1#!/usr/bin/env python
2#
3# Copyright (c) 2012 Felipe Contreras
4#
5
6#
7# Just copy to your ~/bin, or anywhere in your $PATH.
8# Then you can clone with:
9# % git clone bzr::/path/to/bzr/repo/or/url
10#
11# For example:
12# % git clone bzr::$HOME/myrepo
13# or
14# % git clone bzr::lp:myrepo
15#
16
17import sys
18
19import bzrlib
20if hasattr(bzrlib, "initialize"):
21 bzrlib.initialize()
22
23import bzrlib.plugin
24bzrlib.plugin.load_plugins()
25
26import bzrlib.generate_ids
27import bzrlib.transport
28
29import sys
30import os
31import json
32import re
33import StringIO
34
35NAME_RE = re.compile('^([^<>]+)')
36AUTHOR_RE = re.compile('^([^<>]+?)? ?<([^<>]*)>$')
37RAW_AUTHOR_RE = re.compile('^(\w+) (.+)? <(.*)> (\d+) ([+-]\d+)')
38
39def die(msg, *args):
40 sys.stderr.write('ERROR: %s\n' % (msg % args))
41 sys.exit(1)
42
43def warn(msg, *args):
44 sys.stderr.write('WARNING: %s\n' % (msg % args))
45
46def gittz(tz):
47 return '%+03d%02d' % (tz / 3600, tz % 3600 / 60)
48
49class Marks:
50
51 def __init__(self, path):
52 self.path = path
53 self.tips = {}
54 self.marks = {}
55 self.rev_marks = {}
56 self.last_mark = 0
57 self.load()
58
59 def load(self):
60 if not os.path.exists(self.path):
61 return
62
63 tmp = json.load(open(self.path))
64 self.tips = tmp['tips']
65 self.marks = tmp['marks']
66 self.last_mark = tmp['last-mark']
67
68 for rev, mark in self.marks.iteritems():
69 self.rev_marks[mark] = rev
70
71 def dict(self):
72 return { 'tips': self.tips, 'marks': self.marks, 'last-mark' : self.last_mark }
73
74 def store(self):
75 json.dump(self.dict(), open(self.path, 'w'))
76
77 def __str__(self):
78 return str(self.dict())
79
80 def from_rev(self, rev):
81 return self.marks[rev]
82
83 def to_rev(self, mark):
84 return self.rev_marks[mark]
85
86 def next_mark(self):
87 self.last_mark += 1
88 return self.last_mark
89
90 def get_mark(self, rev):
91 self.last_mark += 1
92 self.marks[rev] = self.last_mark
93 return self.last_mark
94
95 def is_marked(self, rev):
96 return self.marks.has_key(rev)
97
98 def new_mark(self, rev, mark):
99 self.marks[rev] = mark
100 self.rev_marks[mark] = rev
101 self.last_mark = mark
102
103 def get_tip(self, branch):
104 return self.tips.get(branch, None)
105
106 def set_tip(self, branch, tip):
107 self.tips[branch] = tip
108
109class Parser:
110
111 def __init__(self, repo):
112 self.repo = repo
113 self.line = self.get_line()
114
115 def get_line(self):
116 return sys.stdin.readline().strip()
117
118 def __getitem__(self, i):
119 return self.line.split()[i]
120
121 def check(self, word):
122 return self.line.startswith(word)
123
124 def each_block(self, separator):
125 while self.line != separator:
126 yield self.line
127 self.line = self.get_line()
128
129 def __iter__(self):
130 return self.each_block('')
131
132 def next(self):
133 self.line = self.get_line()
134 if self.line == 'done':
135 self.line = None
136
137 def get_mark(self):
138 i = self.line.index(':') + 1
139 return int(self.line[i:])
140
141 def get_data(self):
142 if not self.check('data'):
143 return None
144 i = self.line.index(' ') + 1
145 size = int(self.line[i:])
146 return sys.stdin.read(size)
147
148 def get_author(self):
149 m = RAW_AUTHOR_RE.match(self.line)
150 if not m:
151 return None
152 _, name, email, date, tz = m.groups()
153 committer = '%s <%s>' % (name, email)
154 tz = int(tz)
155 tz = ((tz / 100) * 3600) + ((tz % 100) * 60)
156 return (committer, int(date), tz)
157
158def rev_to_mark(rev):
159 global marks
160 return marks.from_rev(rev)
161
162def mark_to_rev(mark):
163 global marks
164 return marks.to_rev(mark)
165
166def fixup_user(user):
167 name = mail = None
168 user = user.replace('"', '')
169 m = AUTHOR_RE.match(user)
170 if m:
171 name = m.group(1)
172 mail = m.group(2).strip()
173 else:
174 m = NAME_RE.match(user)
175 if m:
176 name = m.group(1).strip()
177
178 return '%s <%s>' % (name, mail)
179
180def get_filechanges(cur, prev):
181 modified = {}
182 removed = {}
183
184 changes = cur.changes_from(prev)
185
186 for path, fid, kind in changes.added:
187 modified[path] = fid
188 for path, fid, kind in changes.removed:
189 removed[path] = None
190 for path, fid, kind, mod, _ in changes.modified:
191 modified[path] = fid
192 for oldpath, newpath, fid, kind, mod, _ in changes.renamed:
193 removed[oldpath] = None
194 if kind == 'directory':
195 lst = cur.list_files(from_dir=newpath, recursive=True)
196 for path, file_class, kind, fid, entry in lst:
197 if kind != 'directory':
198 modified[newpath + '/' + path] = fid
199 else:
200 modified[newpath] = fid
201
202 return modified, removed
203
204def export_files(tree, files):
205 global marks, filenodes
206
207 final = []
208 for path, fid in files.iteritems():
209 kind = tree.kind(fid)
210
211 h = tree.get_file_sha1(fid)
212
213 if kind == 'symlink':
214 d = tree.get_symlink_target(fid)
215 mode = '120000'
216 elif kind == 'file':
217
218 if tree.is_executable(fid):
219 mode = '100755'
220 else:
221 mode = '100644'
222
223 # is the blog already exported?
224 if h in filenodes:
225 mark = filenodes[h]
226 final.append((mode, mark, path))
227 continue
228
229 d = tree.get_file_text(fid)
230 elif kind == 'directory':
231 continue
232 else:
233 die("Unhandled kind '%s' for path '%s'" % (kind, path))
234
235 mark = marks.next_mark()
236 filenodes[h] = mark
237
238 print "blob"
239 print "mark :%u" % mark
240 print "data %d" % len(d)
241 print d
242
243 final.append((mode, mark, path))
244
245 return final
246
247def export_branch(branch, name):
248 global prefix, dirname
249
250 ref = '%s/heads/%s' % (prefix, name)
251 tip = marks.get_tip(name)
252
253 repo = branch.repository
254 repo.lock_read()
255 revs = branch.iter_merge_sorted_revisions(None, tip, 'exclude', 'forward')
256 count = 0
257
258 revs = [revid for revid, _, _, _ in revs if not marks.is_marked(revid)]
259
260 for revid in revs:
261
262 rev = repo.get_revision(revid)
263
264 parents = rev.parent_ids
265 time = rev.timestamp
266 tz = rev.timezone
267 committer = rev.committer.encode('utf-8')
268 committer = "%s %u %s" % (fixup_user(committer), time, gittz(tz))
269 author = committer
270 msg = rev.message.encode('utf-8')
271
272 msg += '\n'
273
274 if len(parents) == 0:
275 parent = bzrlib.revision.NULL_REVISION
276 else:
277 parent = parents[0]
278
279 cur_tree = repo.revision_tree(revid)
280 prev = repo.revision_tree(parent)
281 modified, removed = get_filechanges(cur_tree, prev)
282
283 modified_final = export_files(cur_tree, modified)
284
285 if len(parents) == 0:
286 print 'reset %s' % ref
287
288 print "commit %s" % ref
289 print "mark :%d" % (marks.get_mark(revid))
290 print "author %s" % (author)
291 print "committer %s" % (committer)
292 print "data %d" % (len(msg))
293 print msg
294
295 for i, p in enumerate(parents):
296 try:
297 m = rev_to_mark(p)
298 except KeyError:
299 # ghost?
300 continue
301 if i == 0:
302 print "from :%s" % m
303 else:
304 print "merge :%s" % m
305
306 for f in modified_final:
307 print "M %s :%u %s" % f
308 for f in removed:
309 print "D %s" % (f)
310 print
311
312 count += 1
313 if (count % 100 == 0):
314 print "progress revision %s (%d/%d)" % (revid, count, len(revs))
315 print "#############################################################"
316
317 repo.unlock()
318
319 revid = branch.last_revision()
320
321 # make sure the ref is updated
322 print "reset %s" % ref
323 print "from :%u" % rev_to_mark(revid)
324 print
325
326 marks.set_tip(name, revid)
327
328def export_tag(repo, name):
329 global tags
330 try:
331 print "reset refs/tags/%s" % name
332 print "from :%u" % rev_to_mark(tags[name])
333 print
334 except KeyError:
335 warn("TODO: fetch tag '%s'" % name)
336
337def do_import(parser):
338 global dirname
339
340 branch = parser.repo
341 path = os.path.join(dirname, 'marks-git')
342
343 print "feature done"
344 if os.path.exists(path):
345 print "feature import-marks=%s" % path
346 print "feature export-marks=%s" % path
347 sys.stdout.flush()
348
349 while parser.check('import'):
350 ref = parser[1]
351 if ref.startswith('refs/heads/'):
352 name = ref[len('refs/heads/'):]
353 export_branch(branch, name)
354 if ref.startswith('refs/tags/'):
355 name = ref[len('refs/tags/'):]
356 export_tag(branch, name)
357 parser.next()
358
359 print 'done'
360
361 sys.stdout.flush()
362
363def parse_blob(parser):
364 global blob_marks
365
366 parser.next()
367 mark = parser.get_mark()
368 parser.next()
369 data = parser.get_data()
370 blob_marks[mark] = data
371 parser.next()
372
373class CustomTree():
374
375 def __init__(self, repo, revid, parents, files):
376 global files_cache
377
378 self.repo = repo
379 self.revid = revid
380 self.parents = parents
381 self.updates = {}
382
383 def copy_tree(revid):
384 files = files_cache[revid] = {}
385 tree = repo.repository.revision_tree(revid)
386 repo.lock_read()
387 try:
388 for path, entry in tree.iter_entries_by_dir():
389 files[path] = entry.file_id
390 finally:
391 repo.unlock()
392 return files
393
394 if len(parents) == 0:
395 self.base_id = bzrlib.revision.NULL_REVISION
396 self.base_files = {}
397 else:
398 self.base_id = parents[0]
399 self.base_files = files_cache.get(self.base_id, None)
400 if not self.base_files:
401 self.base_files = copy_tree(self.base_id)
402
403 self.files = files_cache[revid] = self.base_files.copy()
404
405 for path, f in files.iteritems():
406 fid = self.files.get(path, None)
407 if not fid:
408 fid = bzrlib.generate_ids.gen_file_id(path)
409 f['path'] = path
410 self.updates[fid] = f
411
412 def last_revision(self):
413 return self.base_id
414
415 def iter_changes(self):
416 changes = []
417
418 def get_parent(dirname, basename):
419 parent_fid = self.base_files.get(dirname, None)
420 if parent_fid:
421 return parent_fid
422 parent_fid = self.files.get(dirname, None)
423 if parent_fid:
424 return parent_fid
425 if basename == '':
426 return None
427 fid = bzrlib.generate_ids.gen_file_id(path)
428 d = add_entry(fid, dirname, 'directory')
429 return fid
430
431 def add_entry(fid, path, kind, mode = None):
432 dirname, basename = os.path.split(path)
433 parent_fid = get_parent(dirname, basename)
434
435 executable = False
436 if mode == '100755':
437 executable = True
438 elif mode == '120000':
439 kind = 'symlink'
440
441 change = (fid,
442 (None, path),
443 True,
444 (False, True),
445 (None, parent_fid),
446 (None, basename),
447 (None, kind),
448 (None, executable))
449 self.files[path] = change[0]
450 changes.append(change)
451 return change
452
453 def update_entry(fid, path, kind, mode = None):
454 dirname, basename = os.path.split(path)
455 parent_fid = get_parent(dirname, basename)
456
457 executable = False
458 if mode == '100755':
459 executable = True
460 elif mode == '120000':
461 kind = 'symlink'
462
463 change = (fid,
464 (path, path),
465 True,
466 (True, True),
467 (None, parent_fid),
468 (None, basename),
469 (None, kind),
470 (None, executable))
471 self.files[path] = change[0]
472 changes.append(change)
473 return change
474
475 def remove_entry(fid, path, kind):
476 dirname, basename = os.path.split(path)
477 parent_fid = get_parent(dirname, basename)
478 change = (fid,
479 (path, None),
480 True,
481 (True, False),
482 (parent_fid, None),
483 (None, None),
484 (None, None),
485 (None, None))
486 del self.files[path]
487 changes.append(change)
488 return change
489
490 for fid, f in self.updates.iteritems():
491 path = f['path']
492
493 if 'deleted' in f:
494 remove_entry(fid, path, 'file')
495 continue
496
497 if path in self.base_files:
498 update_entry(fid, path, 'file', f['mode'])
499 else:
500 add_entry(fid, path, 'file', f['mode'])
501
502 return changes
503
504 def get_file_with_stat(self, file_id, path=None):
505 return (StringIO.StringIO(self.updates[file_id]['data']), None)
506
507 def get_symlink_target(self, file_id):
508 return self.updates[file_id]['data']
509
510def parse_commit(parser):
511 global marks, blob_marks, bmarks, parsed_refs
512 global mode
513
514 parents = []
515
516 ref = parser[1]
517 parser.next()
518
519 if ref != 'refs/heads/master':
520 die("bzr doesn't support multiple branches; use 'master'")
521
522 commit_mark = parser.get_mark()
523 parser.next()
524 author = parser.get_author()
525 parser.next()
526 committer = parser.get_author()
527 parser.next()
528 data = parser.get_data()
529 parser.next()
530 if parser.check('from'):
531 parents.append(parser.get_mark())
532 parser.next()
533 while parser.check('merge'):
534 parents.append(parser.get_mark())
535 parser.next()
536
537 files = {}
538
539 for line in parser:
540 if parser.check('M'):
541 t, m, mark_ref, path = line.split(' ', 3)
542 mark = int(mark_ref[1:])
543 f = { 'mode' : m, 'data' : blob_marks[mark] }
544 elif parser.check('D'):
545 t, path = line.split(' ')
546 f = { 'deleted' : True }
547 else:
548 die('Unknown file command: %s' % line)
549 files[path] = f
550
551 repo = parser.repo
552
553 committer, date, tz = committer
554 parents = [str(mark_to_rev(p)) for p in parents]
555 revid = bzrlib.generate_ids.gen_revision_id(committer, date)
556 props = {}
557 props['branch-nick'] = repo.nick
558
559 mtree = CustomTree(repo, revid, parents, files)
560 changes = mtree.iter_changes()
561
562 repo.lock_write()
563 try:
564 builder = repo.get_commit_builder(parents, None, date, tz, committer, props, revid)
565 try:
566 list(builder.record_iter_changes(mtree, mtree.last_revision(), changes))
567 builder.finish_inventory()
568 builder.commit(data.decode('utf-8', 'replace'))
569 except Exception, e:
570 builder.abort()
571 raise
572 finally:
573 repo.unlock()
574
575 parsed_refs[ref] = revid
576 marks.new_mark(revid, commit_mark)
577
578def parse_reset(parser):
579 global parsed_refs
580
581 ref = parser[1]
582 parser.next()
583
584 if ref != 'refs/heads/master':
585 die("bzr doesn't support multiple branches; use 'master'")
586
587 # ugh
588 if parser.check('commit'):
589 parse_commit(parser)
590 return
591 if not parser.check('from'):
592 return
593 from_mark = parser.get_mark()
594 parser.next()
595
596 parsed_refs[ref] = mark_to_rev(from_mark)
597
598def do_export(parser):
599 global parsed_refs, dirname, peer
600
601 parser.next()
602
603 for line in parser.each_block('done'):
604 if parser.check('blob'):
605 parse_blob(parser)
606 elif parser.check('commit'):
607 parse_commit(parser)
608 elif parser.check('reset'):
609 parse_reset(parser)
610 elif parser.check('tag'):
611 pass
612 elif parser.check('feature'):
613 pass
614 else:
615 die('unhandled export command: %s' % line)
616
617 repo = parser.repo
618
619 for ref, revid in parsed_refs.iteritems():
620 if ref == 'refs/heads/master':
621 repo.generate_revision_history(revid, marks.get_tip('master'))
622 revno, revid = repo.last_revision_info()
623 if peer:
624 if hasattr(peer, "import_last_revision_info_and_tags"):
625 peer.import_last_revision_info_and_tags(repo, revno, revid)
626 else:
627 peer.import_last_revision_info(repo.repository, revno, revid)
628 wt = peer.bzrdir.open_workingtree()
629 else:
630 wt = repo.bzrdir.open_workingtree()
631 wt.update()
632 print "ok %s" % ref
633 print
634
635def do_capabilities(parser):
636 global dirname
637
638 print "import"
639 print "export"
640 print "refspec refs/heads/*:%s/heads/*" % prefix
641
642 path = os.path.join(dirname, 'marks-git')
643
644 if os.path.exists(path):
645 print "*import-marks %s" % path
646 print "*export-marks %s" % path
647
648 print
649
650def do_list(parser):
651 global tags
652 print "? refs/heads/%s" % 'master'
653 for tag, revid in parser.repo.tags.get_tag_dict().items():
654 print "? refs/tags/%s" % tag
655 tags[tag] = revid
656 print "@refs/heads/%s HEAD" % 'master'
657 print
658
659def get_repo(url, alias):
660 global dirname, peer
661
662 origin = bzrlib.bzrdir.BzrDir.open(url)
663 branch = origin.open_branch()
664
665 if not isinstance(origin.transport, bzrlib.transport.local.LocalTransport):
666 clone_path = os.path.join(dirname, 'clone')
667 remote_branch = branch
668 if os.path.exists(clone_path):
669 # pull
670 d = bzrlib.bzrdir.BzrDir.open(clone_path)
671 branch = d.open_branch()
672 result = branch.pull(remote_branch, [], None, False)
673 else:
674 # clone
675 d = origin.sprout(clone_path, None,
676 hardlink=True, create_tree_if_local=False,
677 source_branch=remote_branch)
678 branch = d.open_branch()
679 branch.bind(remote_branch)
680
681 peer = remote_branch
682 else:
683 peer = None
684
685 return branch
686
687def main(args):
688 global marks, prefix, dirname
689 global tags, filenodes
690 global blob_marks
691 global parsed_refs
692 global files_cache
693
694 alias = args[1]
695 url = args[2]
696
697 prefix = 'refs/bzr/%s' % alias
698 tags = {}
699 filenodes = {}
700 blob_marks = {}
701 parsed_refs = {}
702 files_cache = {}
703
704 gitdir = os.environ['GIT_DIR']
705 dirname = os.path.join(gitdir, 'bzr', alias)
706
707 if not os.path.exists(dirname):
708 os.makedirs(dirname)
709
710 repo = get_repo(url, alias)
711
712 marks_path = os.path.join(dirname, 'marks-int')
713 marks = Marks(marks_path)
714
715 parser = Parser(repo)
716 for line in parser:
717 if parser.check('capabilities'):
718 do_capabilities(parser)
719 elif parser.check('list'):
720 do_list(parser)
721 elif parser.check('import'):
722 do_import(parser)
723 elif parser.check('export'):
724 do_export(parser)
725 else:
726 die('unhandled command: %s' % line)
727 sys.stdout.flush()
728
729 marks.store()
730
731sys.exit(main(sys.argv))