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):
252 global prefix, dirname
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):
339 print "reset refs/tags/%s" % name
340 print "from :%u" % rev_to_mark(tags[name])
343 def do_import(parser):
347 path = os.path.join(dirname, 'marks-git')
350 if os.path.exists(path):
351 print "feature import-marks=%s" % path
352 print "feature export-marks=%s" % path
355 while parser.check('import'):
357 if ref.startswith('refs/heads/'):
358 name = ref[len('refs/heads/'):]
359 export_branch(branch, name)
360 if ref.startswith('refs/tags/'):
361 name = ref[len('refs/tags/'):]
362 export_tag(branch, name)
369 def parse_blob(parser):
373 mark = parser.get_mark()
375 data = parser.get_data()
376 blob_marks[mark] = data
381 def __init__(self, repo, revid, parents, files):
386 self.parents = parents
389 def copy_tree(revid):
390 files = files_cache[revid] = {}
391 tree = repo.repository.revision_tree(revid)
394 for path, entry in tree.iter_entries_by_dir():
395 files[path] = entry.file_id
400 if len(parents) == 0:
401 self.base_id = bzrlib.revision.NULL_REVISION
404 self.base_id = parents[0]
405 self.base_files = files_cache.get(self.base_id, None)
406 if not self.base_files:
407 self.base_files = copy_tree(self.base_id)
409 self.files = files_cache[revid] = self.base_files.copy()
411 for path, f in files.iteritems():
412 fid = self.files.get(path, None)
414 fid = bzrlib.generate_ids.gen_file_id(path)
416 self.updates[fid] = f
418 def last_revision(self):
421 def iter_changes(self):
424 def get_parent(dirname, basename):
425 parent_fid = self.base_files.get(dirname, None)
428 parent_fid = self.files.get(dirname, None)
433 fid = bzrlib.generate_ids.gen_file_id(path)
434 d = add_entry(fid, dirname, 'directory')
437 def add_entry(fid, path, kind, mode = None):
438 dirname, basename = os.path.split(path)
439 parent_fid = get_parent(dirname, basename)
444 elif mode == '120000':
455 self.files[path] = change[0]
456 changes.append(change)
459 def update_entry(fid, path, kind, mode = None):
460 dirname, basename = os.path.split(path)
461 parent_fid = get_parent(dirname, basename)
466 elif mode == '120000':
477 self.files[path] = change[0]
478 changes.append(change)
481 def remove_entry(fid, path, kind):
482 dirname, basename = os.path.split(path)
483 parent_fid = get_parent(dirname, basename)
493 changes.append(change)
496 for fid, f in self.updates.iteritems():
500 remove_entry(fid, path, 'file')
503 if path in self.base_files:
504 update_entry(fid, path, 'file', f['mode'])
506 add_entry(fid, path, 'file', f['mode'])
510 def get_file_with_stat(self, file_id, path=None):
511 return (StringIO.StringIO(self.updates[file_id]['data']), None)
513 def get_symlink_target(self, file_id):
514 return self.updates[file_id]['data']
516 def c_style_unescape(string):
517 if string[0] == string[-1] == '"':
518 return string.decode('string-escape')[1:-1]
521 def parse_commit(parser):
522 global marks, blob_marks, bmarks, parsed_refs
530 if ref != 'refs/heads/master':
531 die("bzr doesn't support multiple branches; use 'master'")
533 commit_mark = parser.get_mark()
535 author = parser.get_author()
537 committer = parser.get_author()
539 data = parser.get_data()
541 if parser.check('from'):
542 parents.append(parser.get_mark())
544 while parser.check('merge'):
545 parents.append(parser.get_mark())
551 if parser.check('M'):
552 t, m, mark_ref, path = line.split(' ', 3)
553 mark = int(mark_ref[1:])
554 f = { 'mode' : m, 'data' : blob_marks[mark] }
555 elif parser.check('D'):
556 t, path = line.split(' ')
557 f = { 'deleted' : True }
559 die('Unknown file command: %s' % line)
560 path = c_style_unescape(path).decode('utf-8')
565 committer, date, tz = committer
566 parents = [str(mark_to_rev(p)) for p in parents]
567 revid = bzrlib.generate_ids.gen_revision_id(committer, date)
569 props['branch-nick'] = repo.nick
571 mtree = CustomTree(repo, revid, parents, files)
572 changes = mtree.iter_changes()
576 builder = repo.get_commit_builder(parents, None, date, tz, committer, props, revid)
578 list(builder.record_iter_changes(mtree, mtree.last_revision(), changes))
579 builder.finish_inventory()
580 builder.commit(data.decode('utf-8', 'replace'))
587 parsed_refs[ref] = revid
588 marks.new_mark(revid, commit_mark)
590 def parse_reset(parser):
596 if ref != 'refs/heads/master':
597 die("bzr doesn't support multiple branches; use 'master'")
600 if parser.check('commit'):
603 if not parser.check('from'):
605 from_mark = parser.get_mark()
608 parsed_refs[ref] = mark_to_rev(from_mark)
610 def do_export(parser):
611 global parsed_refs, dirname, peer
615 for line in parser.each_block('done'):
616 if parser.check('blob'):
618 elif parser.check('commit'):
620 elif parser.check('reset'):
622 elif parser.check('tag'):
624 elif parser.check('feature'):
627 die('unhandled export command: %s' % line)
631 for ref, revid in parsed_refs.iteritems():
632 if ref == 'refs/heads/master':
633 repo.generate_revision_history(revid, marks.get_tip('master'))
634 revno, revid = repo.last_revision_info()
636 if hasattr(peer, "import_last_revision_info_and_tags"):
637 peer.import_last_revision_info_and_tags(repo, revno, revid)
639 peer.import_last_revision_info(repo.repository, revno, revid)
641 wt = repo.bzrdir.open_workingtree()
646 def do_capabilities(parser):
651 print "refspec refs/heads/*:%s/heads/*" % prefix
653 path = os.path.join(dirname, 'marks-git')
655 if os.path.exists(path):
656 print "*import-marks %s" % path
657 print "*export-marks %s" % path
661 def ref_is_valid(name):
662 return not True in [c in name for c in '~^: \\']
666 print "? refs/heads/%s" % 'master'
670 for tag, revid in branch.tags.get_tag_dict().items():
672 branch.revision_id_to_dotted_revno(revid)
673 except bzrlib.errors.NoSuchRevision:
675 if not ref_is_valid(tag):
677 print "? refs/tags/%s" % tag
680 print "@refs/heads/%s HEAD" % 'master'
683 def get_repo(url, alias):
686 origin = bzrlib.bzrdir.BzrDir.open(url)
687 branch = origin.open_branch()
689 if not isinstance(origin.transport, bzrlib.transport.local.LocalTransport):
690 clone_path = os.path.join(dirname, 'clone')
691 remote_branch = branch
692 if os.path.exists(clone_path):
694 d = bzrlib.bzrdir.BzrDir.open(clone_path)
695 branch = d.open_branch()
696 result = branch.pull(remote_branch, [], None, False)
699 d = origin.sprout(clone_path, None,
700 hardlink=True, create_tree_if_local=False,
701 source_branch=remote_branch)
702 branch = d.open_branch()
703 branch.bind(remote_branch)
712 global marks, prefix, dirname
713 global tags, filenodes
721 prefix = 'refs/bzr/%s' % alias
728 gitdir = os.environ['GIT_DIR']
729 dirname = os.path.join(gitdir, 'bzr', alias)
731 if not os.path.exists(dirname):
734 repo = get_repo(url, alias)
736 marks_path = os.path.join(dirname, 'marks-int')
737 marks = Marks(marks_path)
739 parser = Parser(repo)
741 if parser.check('capabilities'):
742 do_capabilities(parser)
743 elif parser.check('list'):
745 elif parser.check('import'):
747 elif parser.check('export'):
750 die('unhandled command: %s' % line)
755 sys.exit(main(sys.argv))