3 # Copyright (c) 2012 Felipe Contreras
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
12 # % git clone bzr::$HOME/myrepo
14 # % git clone bzr::lp:myrepo
20 if hasattr(bzrlib, "initialize"):
24 bzrlib.plugin.load_plugins()
26 import bzrlib.generate_ids
27 import bzrlib.transport
36 NAME_RE = re.compile('^([^<>]+)')
37 AUTHOR_RE = re.compile('^([^<>]+?)? ?<([^<>]*)>$')
38 RAW_AUTHOR_RE = re.compile('^(\w+) (.+)? <(.*)> (\d+) ([+-]\d+)')
41 sys.stderr.write('ERROR: %s\n' % (msg % args))
45 sys.stderr.write('WARNING: %s\n' % (msg % args))
48 return '%+03d%02d' % (tz / 3600, tz % 3600 / 60)
52 def __init__(self, path):
61 if not os.path.exists(self.path):
64 tmp = json.load(open(self.path))
65 self.tips = tmp['tips']
66 self.marks = tmp['marks']
67 self.last_mark = tmp['last-mark']
69 for rev, mark in self.marks.iteritems():
70 self.rev_marks[mark] = rev
73 return { 'tips': self.tips, 'marks': self.marks, 'last-mark' : self.last_mark }
76 json.dump(self.dict(), open(self.path, 'w'))
79 return str(self.dict())
81 def from_rev(self, rev):
82 return self.marks[rev]
84 def to_rev(self, mark):
85 return self.rev_marks[mark]
91 def get_mark(self, rev):
93 self.marks[rev] = self.last_mark
96 def is_marked(self, rev):
97 return self.marks.has_key(rev)
99 def new_mark(self, rev, mark):
100 self.marks[rev] = mark
101 self.rev_marks[mark] = rev
102 self.last_mark = mark
104 def get_tip(self, branch):
105 return self.tips.get(branch, None)
107 def set_tip(self, branch, tip):
108 self.tips[branch] = tip
112 def __init__(self, repo):
114 self.line = self.get_line()
117 return sys.stdin.readline().strip()
119 def __getitem__(self, i):
120 return self.line.split()[i]
122 def check(self, word):
123 return self.line.startswith(word)
125 def each_block(self, separator):
126 while self.line != separator:
128 self.line = self.get_line()
131 return self.each_block('')
134 self.line = self.get_line()
135 if self.line == 'done':
139 i = self.line.index(':') + 1
140 return int(self.line[i:])
143 if not self.check('data'):
145 i = self.line.index(' ') + 1
146 size = int(self.line[i:])
147 return sys.stdin.read(size)
149 def get_author(self):
150 m = RAW_AUTHOR_RE.match(self.line)
153 _, name, email, date, tz = m.groups()
154 committer = '%s <%s>' % (name, email)
156 tz = ((tz / 100) * 3600) + ((tz % 100) * 60)
157 return (committer, int(date), tz)
159 def rev_to_mark(rev):
161 return marks.from_rev(rev)
163 def mark_to_rev(mark):
165 return marks.to_rev(mark)
167 def fixup_user(user):
169 user = user.replace('"', '')
170 m = AUTHOR_RE.match(user)
173 mail = m.group(2).strip()
175 m = NAME_RE.match(user)
177 name = m.group(1).strip()
179 return '%s <%s>' % (name, mail)
181 def get_filechanges(cur, prev):
185 changes = cur.changes_from(prev)
188 return s.encode('utf-8')
190 for path, fid, kind in changes.added:
191 modified[u(path)] = fid
192 for path, fid, kind in changes.removed:
193 removed[u(path)] = None
194 for path, fid, kind, mod, _ in changes.modified:
195 modified[u(path)] = fid
196 for oldpath, newpath, fid, kind, mod, _ in changes.renamed:
197 removed[u(oldpath)] = None
198 if kind == 'directory':
199 lst = cur.list_files(from_dir=newpath, recursive=True)
200 for path, file_class, kind, fid, entry in lst:
201 if kind != 'directory':
202 modified[u(newpath + '/' + path)] = fid
204 modified[u(newpath)] = fid
206 return modified, removed
208 def export_files(tree, files):
209 global marks, filenodes
212 for path, fid in files.iteritems():
213 kind = tree.kind(fid)
215 h = tree.get_file_sha1(fid)
217 if kind == 'symlink':
218 d = tree.get_symlink_target(fid)
222 if tree.is_executable(fid):
227 # is the blog already exported?
230 final.append((mode, mark, path))
233 d = tree.get_file_text(fid)
234 elif kind == 'directory':
237 die("Unhandled kind '%s' for path '%s'" % (kind, path))
239 mark = marks.next_mark()
243 print "mark :%u" % mark
244 print "data %d" % len(d)
247 final.append((mode, mark, path))
251 def export_branch(branch, name):
254 ref = '%s/heads/%s' % (prefix, name)
255 tip = marks.get_tip(name)
257 repo = branch.repository
259 revs = branch.iter_merge_sorted_revisions(None, tip, 'exclude', 'forward')
262 revs = [revid for revid, _, _, _ in revs if not marks.is_marked(revid)]
266 rev = repo.get_revision(revid)
268 parents = rev.parent_ids
271 committer = rev.committer.encode('utf-8')
272 committer = "%s %u %s" % (fixup_user(committer), time, gittz(tz))
273 authors = rev.get_apparent_authors()
275 author = authors[0].encode('utf-8')
276 author = "%s %u %s" % (fixup_user(author), time, gittz(tz))
279 msg = rev.message.encode('utf-8')
283 if len(parents) == 0:
284 parent = bzrlib.revision.NULL_REVISION
288 cur_tree = repo.revision_tree(revid)
289 prev = repo.revision_tree(parent)
290 modified, removed = get_filechanges(cur_tree, prev)
292 modified_final = export_files(cur_tree, modified)
294 if len(parents) == 0:
295 print 'reset %s' % ref
297 print "commit %s" % ref
298 print "mark :%d" % (marks.get_mark(revid))
299 print "author %s" % (author)
300 print "committer %s" % (committer)
301 print "data %d" % (len(msg))
304 for i, p in enumerate(parents):
313 print "merge :%s" % m
317 for f in modified_final:
318 print "M %s :%u %s" % f
322 if (count % 100 == 0):
323 print "progress revision %s (%d/%d)" % (revid, count, len(revs))
324 print "#############################################################"
328 revid = branch.last_revision()
330 # make sure the ref is updated
331 print "reset %s" % ref
332 print "from :%u" % rev_to_mark(revid)
335 marks.set_tip(name, revid)
337 def export_tag(repo, name):
340 ref = '%s/tags/%s' % (prefix, name)
341 print "reset %s" % ref
342 print "from :%u" % rev_to_mark(tags[name])
345 def do_import(parser):
349 path = os.path.join(dirname, 'marks-git')
352 if os.path.exists(path):
353 print "feature import-marks=%s" % path
354 print "feature export-marks=%s" % path
357 while parser.check('import'):
359 if ref.startswith('refs/heads/'):
360 name = ref[len('refs/heads/'):]
361 export_branch(branch, name)
362 if ref.startswith('refs/tags/'):
363 name = ref[len('refs/tags/'):]
364 export_tag(branch, name)
371 def parse_blob(parser):
375 mark = parser.get_mark()
377 data = parser.get_data()
378 blob_marks[mark] = data
383 def __init__(self, repo, revid, parents, files):
388 self.parents = parents
391 def copy_tree(revid):
392 files = files_cache[revid] = {}
393 tree = repo.repository.revision_tree(revid)
396 for path, entry in tree.iter_entries_by_dir():
397 files[path] = entry.file_id
402 if len(parents) == 0:
403 self.base_id = bzrlib.revision.NULL_REVISION
406 self.base_id = parents[0]
407 self.base_files = files_cache.get(self.base_id, None)
408 if not self.base_files:
409 self.base_files = copy_tree(self.base_id)
411 self.files = files_cache[revid] = self.base_files.copy()
413 for path, f in files.iteritems():
414 fid = self.files.get(path, None)
416 fid = bzrlib.generate_ids.gen_file_id(path)
418 self.updates[fid] = f
420 def last_revision(self):
423 def iter_changes(self):
426 def get_parent(dirname, basename):
427 parent_fid = self.base_files.get(dirname, None)
430 parent_fid = self.files.get(dirname, None)
435 fid = bzrlib.generate_ids.gen_file_id(path)
436 d = add_entry(fid, dirname, 'directory')
439 def add_entry(fid, path, kind, mode = None):
440 dirname, basename = os.path.split(path)
441 parent_fid = get_parent(dirname, basename)
446 elif mode == '120000':
457 self.files[path] = change[0]
458 changes.append(change)
461 def update_entry(fid, path, kind, mode = None):
462 dirname, basename = os.path.split(path)
463 parent_fid = get_parent(dirname, basename)
468 elif mode == '120000':
479 self.files[path] = change[0]
480 changes.append(change)
483 def remove_entry(fid, path, kind):
484 dirname, basename = os.path.split(path)
485 parent_fid = get_parent(dirname, basename)
495 changes.append(change)
498 for fid, f in self.updates.iteritems():
502 remove_entry(fid, path, 'file')
505 if path in self.base_files:
506 update_entry(fid, path, 'file', f['mode'])
508 add_entry(fid, path, 'file', f['mode'])
512 def get_file_with_stat(self, file_id, path=None):
513 return (StringIO.StringIO(self.updates[file_id]['data']), None)
515 def get_symlink_target(self, file_id):
516 return self.updates[file_id]['data']
518 def c_style_unescape(string):
519 if string[0] == string[-1] == '"':
520 return string.decode('string-escape')[1:-1]
523 def parse_commit(parser):
524 global marks, blob_marks, bmarks, parsed_refs
532 if ref != 'refs/heads/master':
533 die("bzr doesn't support multiple branches; use 'master'")
535 commit_mark = parser.get_mark()
537 author = parser.get_author()
539 committer = parser.get_author()
541 data = parser.get_data()
543 if parser.check('from'):
544 parents.append(parser.get_mark())
546 while parser.check('merge'):
547 parents.append(parser.get_mark())
553 if parser.check('M'):
554 t, m, mark_ref, path = line.split(' ', 3)
555 mark = int(mark_ref[1:])
556 f = { 'mode' : m, 'data' : blob_marks[mark] }
557 elif parser.check('D'):
558 t, path = line.split(' ')
559 f = { 'deleted' : True }
561 die('Unknown file command: %s' % line)
562 path = c_style_unescape(path).decode('utf-8')
567 committer, date, tz = committer
568 parents = [str(mark_to_rev(p)) for p in parents]
569 revid = bzrlib.generate_ids.gen_revision_id(committer, date)
571 props['branch-nick'] = repo.nick
573 mtree = CustomTree(repo, revid, parents, files)
574 changes = mtree.iter_changes()
578 builder = repo.get_commit_builder(parents, None, date, tz, committer, props, revid)
580 list(builder.record_iter_changes(mtree, mtree.last_revision(), changes))
581 builder.finish_inventory()
582 builder.commit(data.decode('utf-8', 'replace'))
589 parsed_refs[ref] = revid
590 marks.new_mark(revid, commit_mark)
592 def parse_reset(parser):
598 if ref != 'refs/heads/master':
599 die("bzr doesn't support multiple branches; use 'master'")
602 if parser.check('commit'):
605 if not parser.check('from'):
607 from_mark = parser.get_mark()
610 parsed_refs[ref] = mark_to_rev(from_mark)
612 def do_export(parser):
613 global parsed_refs, dirname, peer
617 for line in parser.each_block('done'):
618 if parser.check('blob'):
620 elif parser.check('commit'):
622 elif parser.check('reset'):
624 elif parser.check('tag'):
626 elif parser.check('feature'):
629 die('unhandled export command: %s' % line)
633 for ref, revid in parsed_refs.iteritems():
634 if ref == 'refs/heads/master':
635 repo.generate_revision_history(revid, marks.get_tip('master'))
636 revno, revid = repo.last_revision_info()
638 if hasattr(peer, "import_last_revision_info_and_tags"):
639 peer.import_last_revision_info_and_tags(repo, revno, revid)
641 peer.import_last_revision_info(repo.repository, revno, revid)
643 wt = repo.bzrdir.open_workingtree()
648 def do_capabilities(parser):
653 print "refspec refs/heads/*:%s/heads/*" % prefix
654 print "refspec refs/tags/*:%s/tags/*" % prefix
656 path = os.path.join(dirname, 'marks-git')
658 if os.path.exists(path):
659 print "*import-marks %s" % path
660 print "*export-marks %s" % path
664 def ref_is_valid(name):
665 return not True in [c in name for c in '~^: \\']
669 print "? refs/heads/%s" % 'master'
673 for tag, revid in branch.tags.get_tag_dict().items():
675 branch.revision_id_to_dotted_revno(revid)
676 except bzrlib.errors.NoSuchRevision:
678 if not ref_is_valid(tag):
680 print "? refs/tags/%s" % tag
683 print "@refs/heads/%s HEAD" % 'master'
686 def get_repo(url, alias):
689 origin = bzrlib.bzrdir.BzrDir.open(url)
690 branch = origin.open_branch()
692 if not isinstance(origin.transport, bzrlib.transport.local.LocalTransport):
693 clone_path = os.path.join(dirname, 'clone')
694 remote_branch = branch
695 if os.path.exists(clone_path):
697 d = bzrlib.bzrdir.BzrDir.open(clone_path)
698 branch = d.open_branch()
699 result = branch.pull(remote_branch, [], None, False)
702 d = origin.sprout(clone_path, None,
703 hardlink=True, create_tree_if_local=False,
704 source_branch=remote_branch)
705 branch = d.open_branch()
706 branch.bind(remote_branch)
715 global marks, prefix, dirname
716 global tags, filenodes
724 prefix = 'refs/bzr/%s' % alias
731 gitdir = os.environ['GIT_DIR']
732 dirname = os.path.join(gitdir, 'bzr', alias)
734 if not os.path.exists(dirname):
737 repo = get_repo(url, alias)
739 marks_path = os.path.join(dirname, 'marks-int')
740 marks = Marks(marks_path)
742 parser = Parser(repo)
744 if parser.check('capabilities'):
745 do_capabilities(parser)
746 elif parser.check('list'):
748 elif parser.check('import'):
750 elif parser.check('export'):
753 die('unhandled command: %s' % line)
758 sys.exit(main(sys.argv))