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
35 NAME_RE = re.compile('^([^<>]+)')
36 AUTHOR_RE = re.compile('^([^<>]+?)? ?<([^<>]*)>$')
37 RAW_AUTHOR_RE = re.compile('^(\w+) (.+)? <(.*)> (\d+) ([+-]\d+)')
40 sys.stderr.write('ERROR: %s\n' % (msg % args))
44 sys.stderr.write('WARNING: %s\n' % (msg % args))
47 return '%+03d%02d' % (tz / 3600, tz % 3600 / 60)
51 def __init__(self, path):
60 if not os.path.exists(self.path):
63 tmp = json.load(open(self.path))
64 self.tips = tmp['tips']
65 self.marks = tmp['marks']
66 self.last_mark = tmp['last-mark']
68 for rev, mark in self.marks.iteritems():
69 self.rev_marks[mark] = rev
72 return { 'tips': self.tips, 'marks': self.marks, 'last-mark' : self.last_mark }
75 json.dump(self.dict(), open(self.path, 'w'))
78 return str(self.dict())
80 def from_rev(self, rev):
81 return self.marks[rev]
83 def to_rev(self, mark):
84 return self.rev_marks[mark]
90 def get_mark(self, rev):
92 self.marks[rev] = self.last_mark
95 def is_marked(self, rev):
96 return self.marks.has_key(rev)
98 def new_mark(self, rev, mark):
99 self.marks[rev] = mark
100 self.rev_marks[mark] = rev
101 self.last_mark = mark
103 def get_tip(self, branch):
104 return self.tips.get(branch, None)
106 def set_tip(self, branch, tip):
107 self.tips[branch] = tip
111 def __init__(self, repo):
113 self.line = self.get_line()
116 return sys.stdin.readline().strip()
118 def __getitem__(self, i):
119 return self.line.split()[i]
121 def check(self, word):
122 return self.line.startswith(word)
124 def each_block(self, separator):
125 while self.line != separator:
127 self.line = self.get_line()
130 return self.each_block('')
133 self.line = self.get_line()
134 if self.line == 'done':
138 i = self.line.index(':') + 1
139 return int(self.line[i:])
142 if not self.check('data'):
144 i = self.line.index(' ') + 1
145 size = int(self.line[i:])
146 return sys.stdin.read(size)
148 def get_author(self):
149 m = RAW_AUTHOR_RE.match(self.line)
152 _, name, email, date, tz = m.groups()
153 committer = '%s <%s>' % (name, email)
155 tz = ((tz / 100) * 3600) + ((tz % 100) * 60)
156 return (committer, int(date), tz)
158 def rev_to_mark(rev):
160 return marks.from_rev(rev)
162 def mark_to_rev(mark):
164 return marks.to_rev(mark)
166 def fixup_user(user):
168 user = user.replace('"', '')
169 m = AUTHOR_RE.match(user)
172 mail = m.group(2).strip()
174 m = NAME_RE.match(user)
176 name = m.group(1).strip()
178 return '%s <%s>' % (name, mail)
180 def get_filechanges(cur, prev):
184 changes = cur.changes_from(prev)
186 for path, fid, kind in changes.added:
188 for path, fid, kind in changes.removed:
190 for path, fid, kind, mod, _ in changes.modified:
192 for oldpath, newpath, fid, kind, mod, _ in changes.renamed:
193 removed[oldpath] = None
194 modified[newpath] = fid
196 return modified, removed
198 def export_files(tree, files):
199 global marks, filenodes
202 for path, fid in files.iteritems():
203 kind = tree.kind(fid)
205 h = tree.get_file_sha1(fid)
207 if kind == 'symlink':
208 d = tree.get_symlink_target(fid)
212 if tree.is_executable(fid):
217 # is the blog already exported?
220 final.append((mode, mark, path))
223 d = tree.get_file_text(fid)
224 elif kind == 'directory':
227 die("Unhandled kind '%s' for path '%s'" % (kind, path))
229 mark = marks.next_mark()
233 print "mark :%u" % mark
234 print "data %d" % len(d)
237 final.append((mode, mark, path))
241 def export_branch(branch, name):
242 global prefix, dirname
244 ref = '%s/heads/%s' % (prefix, name)
245 tip = marks.get_tip(name)
247 repo = branch.repository
249 revs = branch.iter_merge_sorted_revisions(None, tip, 'exclude', 'forward')
252 revs = [revid for revid, _, _, _ in revs if not marks.is_marked(revid)]
256 rev = repo.get_revision(revid)
258 parents = rev.parent_ids
261 committer = rev.committer.encode('utf-8')
262 committer = "%s %u %s" % (fixup_user(committer), time, gittz(tz))
264 msg = rev.message.encode('utf-8')
268 if len(parents) == 0:
269 parent = bzrlib.revision.NULL_REVISION
273 cur_tree = repo.revision_tree(revid)
274 prev = repo.revision_tree(parent)
275 modified, removed = get_filechanges(cur_tree, prev)
277 modified_final = export_files(cur_tree, modified)
279 if len(parents) == 0:
280 print 'reset %s' % ref
282 print "commit %s" % ref
283 print "mark :%d" % (marks.get_mark(revid))
284 print "author %s" % (author)
285 print "committer %s" % (committer)
286 print "data %d" % (len(msg))
289 for i, p in enumerate(parents):
298 print "merge :%s" % m
300 for f in modified_final:
301 print "M %s :%u %s" % f
307 if (count % 100 == 0):
308 print "progress revision %s (%d/%d)" % (revid, count, len(revs))
309 print "#############################################################"
313 revid = branch.last_revision()
315 # make sure the ref is updated
316 print "reset %s" % ref
317 print "from :%u" % rev_to_mark(revid)
320 marks.set_tip(name, revid)
322 def export_tag(repo, name):
325 print "reset refs/tags/%s" % name
326 print "from :%u" % rev_to_mark(tags[name])
329 warn("TODO: fetch tag '%s'" % name)
331 def do_import(parser):
335 path = os.path.join(dirname, 'marks-git')
338 if os.path.exists(path):
339 print "feature import-marks=%s" % path
340 print "feature export-marks=%s" % path
343 while parser.check('import'):
345 if ref.startswith('refs/heads/'):
346 name = ref[len('refs/heads/'):]
347 export_branch(branch, name)
348 if ref.startswith('refs/tags/'):
349 name = ref[len('refs/tags/'):]
350 export_tag(branch, name)
357 def parse_blob(parser):
361 mark = parser.get_mark()
363 data = parser.get_data()
364 blob_marks[mark] = data
369 def __init__(self, repo, revid, parents, files):
374 self.parents = parents
377 def copy_tree(revid):
378 files = files_cache[revid] = {}
379 tree = repo.repository.revision_tree(revid)
382 for path, entry in tree.iter_entries_by_dir():
383 files[path] = entry.file_id
388 if len(parents) == 0:
389 self.base_id = bzrlib.revision.NULL_REVISION
392 self.base_id = parents[0]
393 self.base_files = files_cache.get(self.base_id, None)
394 if not self.base_files:
395 self.base_files = copy_tree(self.base_id)
397 self.files = files_cache[revid] = self.base_files.copy()
399 for path, f in files.iteritems():
400 fid = self.files.get(path, None)
402 fid = bzrlib.generate_ids.gen_file_id(path)
404 self.updates[fid] = f
406 def last_revision(self):
409 def iter_changes(self):
412 def get_parent(dirname, basename):
413 parent_fid = self.base_files.get(dirname, None)
416 parent_fid = self.files.get(dirname, None)
421 fid = bzrlib.generate_ids.gen_file_id(path)
422 d = add_entry(fid, dirname, 'directory')
425 def add_entry(fid, path, kind, mode = None):
426 dirname, basename = os.path.split(path)
427 parent_fid = get_parent(dirname, basename)
432 elif mode == '120000':
443 self.files[path] = change[0]
444 changes.append(change)
447 def update_entry(fid, path, kind, mode = None):
448 dirname, basename = os.path.split(path)
449 parent_fid = get_parent(dirname, basename)
454 elif mode == '120000':
465 self.files[path] = change[0]
466 changes.append(change)
469 def remove_entry(fid, path, kind):
470 dirname, basename = os.path.split(path)
471 parent_fid = get_parent(dirname, basename)
481 changes.append(change)
484 for fid, f in self.updates.iteritems():
488 remove_entry(fid, path, 'file')
491 if path in self.base_files:
492 update_entry(fid, path, 'file', f['mode'])
494 add_entry(fid, path, 'file', f['mode'])
498 def get_file_with_stat(self, file_id, path=None):
499 return (StringIO.StringIO(self.updates[file_id]['data']), None)
501 def get_symlink_target(self, file_id):
502 return self.updates[file_id]['data']
504 def parse_commit(parser):
505 global marks, blob_marks, bmarks, parsed_refs
513 if ref != 'refs/heads/master':
514 die("bzr doesn't support multiple branches; use 'master'")
516 commit_mark = parser.get_mark()
518 author = parser.get_author()
520 committer = parser.get_author()
522 data = parser.get_data()
524 if parser.check('from'):
525 parents.append(parser.get_mark())
527 while parser.check('merge'):
528 parents.append(parser.get_mark())
534 if parser.check('M'):
535 t, m, mark_ref, path = line.split(' ', 3)
536 mark = int(mark_ref[1:])
537 f = { 'mode' : m, 'data' : blob_marks[mark] }
538 elif parser.check('D'):
539 t, path = line.split(' ')
540 f = { 'deleted' : True }
542 die('Unknown file command: %s' % line)
547 committer, date, tz = committer
548 parents = [str(mark_to_rev(p)) for p in parents]
549 revid = bzrlib.generate_ids.gen_revision_id(committer, date)
551 props['branch-nick'] = repo.nick
553 mtree = CustomTree(repo, revid, parents, files)
554 changes = mtree.iter_changes()
558 builder = repo.get_commit_builder(parents, None, date, tz, committer, props, revid)
560 list(builder.record_iter_changes(mtree, mtree.last_revision(), changes))
561 builder.finish_inventory()
562 builder.commit(data.decode('utf-8', 'replace'))
569 parsed_refs[ref] = revid
570 marks.new_mark(revid, commit_mark)
572 def parse_reset(parser):
578 if ref != 'refs/heads/master':
579 die("bzr doesn't support multiple branches; use 'master'")
582 if parser.check('commit'):
585 if not parser.check('from'):
587 from_mark = parser.get_mark()
590 parsed_refs[ref] = mark_to_rev(from_mark)
592 def do_export(parser):
593 global parsed_refs, dirname, peer
597 for line in parser.each_block('done'):
598 if parser.check('blob'):
600 elif parser.check('commit'):
602 elif parser.check('reset'):
604 elif parser.check('tag'):
606 elif parser.check('feature'):
609 die('unhandled export command: %s' % line)
613 for ref, revid in parsed_refs.iteritems():
614 if ref == 'refs/heads/master':
615 repo.generate_revision_history(revid, marks.get_tip('master'))
616 revno, revid = repo.last_revision_info()
618 if hasattr(peer, "import_last_revision_info_and_tags"):
619 peer.import_last_revision_info_and_tags(repo, revno, revid)
621 peer.import_last_revision_info(repo.repository, revno, revid)
622 wt = peer.bzrdir.open_workingtree()
624 wt = repo.bzrdir.open_workingtree()
629 def do_capabilities(parser):
634 print "refspec refs/heads/*:%s/heads/*" % prefix
636 path = os.path.join(dirname, 'marks-git')
638 if os.path.exists(path):
639 print "*import-marks %s" % path
640 print "*export-marks %s" % path
646 print "? refs/heads/%s" % 'master'
647 for tag, revid in parser.repo.tags.get_tag_dict().items():
648 print "? refs/tags/%s" % tag
650 print "@refs/heads/%s HEAD" % 'master'
653 def get_repo(url, alias):
656 origin = bzrlib.bzrdir.BzrDir.open(url)
657 branch = origin.open_branch()
659 if not isinstance(origin.transport, bzrlib.transport.local.LocalTransport):
660 clone_path = os.path.join(dirname, 'clone')
661 remote_branch = branch
662 if os.path.exists(clone_path):
664 d = bzrlib.bzrdir.BzrDir.open(clone_path)
665 branch = d.open_branch()
666 result = branch.pull(remote_branch, [], None, False)
669 d = origin.sprout(clone_path, None,
670 hardlink=True, create_tree_if_local=False,
671 source_branch=remote_branch)
672 branch = d.open_branch()
673 branch.bind(remote_branch)
682 global marks, prefix, dirname
683 global tags, filenodes
691 prefix = 'refs/bzr/%s' % alias
698 gitdir = os.environ['GIT_DIR']
699 dirname = os.path.join(gitdir, 'bzr', alias)
701 if not os.path.exists(dirname):
704 repo = get_repo(url, alias)
706 marks_path = os.path.join(dirname, 'marks-int')
707 marks = Marks(marks_path)
709 parser = Parser(repo)
711 if parser.check('capabilities'):
712 do_capabilities(parser)
713 elif parser.check('list'):
715 elif parser.check('import'):
717 elif parser.check('export'):
720 die('unhandled command: %s' % line)
725 sys.exit(main(sys.argv))