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
16 # If you want to specify which branches you want to track (per repo):
17 # % git config remote.origin.bzr-branches 'trunk, devel, test'
19 # Where 'origin' is the name of the repository you want to specify the
26 if hasattr(bzrlib, "initialize"):
30 bzrlib.plugin.load_plugins()
32 import bzrlib.generate_ids
33 import bzrlib.transport
36 import bzrlib.urlutils
50 NAME_RE = re.compile('^([^<>]+)')
51 AUTHOR_RE = re.compile('^([^<>]+?)? ?[<>]([^<>]*)(?:$|>)')
52 EMAIL_RE = re.compile(r'([^ \t<>]+@[^ \t<>]+)')
53 RAW_AUTHOR_RE = re.compile('^(\w+) (.+)? <(.*)> (\d+) ([+-]\d+)')
56 sys.stderr.write('ERROR: %s\n' % (msg % args))
60 sys.stderr.write('WARNING: %s\n' % (msg % args))
63 return '%+03d%02d' % (tz / 3600, tz % 3600 / 60)
65 def get_config(config):
66 cmd = ['git', 'config', '--get', config]
67 process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
68 output, _ = process.communicate()
73 def __init__(self, path):
82 if not os.path.exists(self.path):
85 tmp = json.load(open(self.path))
86 self.tips = tmp['tips']
87 self.marks = tmp['marks']
88 self.last_mark = tmp['last-mark']
90 for rev, mark in self.marks.iteritems():
91 self.rev_marks[mark] = rev
94 return { 'tips': self.tips, 'marks': self.marks, 'last-mark': self.last_mark }
97 json.dump(self.dict(), open(self.path, 'w'))
100 return str(self.dict())
102 def from_rev(self, rev):
103 return self.marks[rev]
105 def to_rev(self, mark):
106 return str(self.rev_marks[mark])
110 return self.last_mark
112 def get_mark(self, rev):
114 self.marks[rev] = self.last_mark
115 return self.last_mark
117 def is_marked(self, rev):
118 return rev in self.marks
120 def new_mark(self, rev, mark):
121 self.marks[rev] = mark
122 self.rev_marks[mark] = rev
123 self.last_mark = mark
125 def get_tip(self, branch):
127 return str(self.tips[branch])
131 def set_tip(self, branch, tip):
132 self.tips[branch] = tip
136 def __init__(self, repo):
138 self.line = self.get_line()
141 return sys.stdin.readline().strip()
143 def __getitem__(self, i):
144 return self.line.split()[i]
146 def check(self, word):
147 return self.line.startswith(word)
149 def each_block(self, separator):
150 while self.line != separator:
152 self.line = self.get_line()
155 return self.each_block('')
158 self.line = self.get_line()
159 if self.line == 'done':
163 i = self.line.index(':') + 1
164 return int(self.line[i:])
167 if not self.check('data'):
169 i = self.line.index(' ') + 1
170 size = int(self.line[i:])
171 return sys.stdin.read(size)
173 def get_author(self):
174 m = RAW_AUTHOR_RE.match(self.line)
177 _, name, email, date, tz = m.groups()
178 name = name.decode('utf-8')
179 committer = '%s <%s>' % (name, email)
181 tz = ((tz / 100) * 3600) + ((tz % 100) * 60)
182 return (committer, int(date), tz)
184 def rev_to_mark(rev):
185 return marks.from_rev(rev)
187 def mark_to_rev(mark):
188 return marks.to_rev(mark)
190 def fixup_user(user):
192 user = user.replace('"', '')
193 m = AUTHOR_RE.match(user)
196 mail = m.group(2).strip()
198 m = EMAIL_RE.match(user)
202 m = NAME_RE.match(user)
204 name = m.group(1).strip()
211 return '%s <%s>' % (name, mail)
213 def get_filechanges(cur, prev):
217 changes = cur.changes_from(prev)
220 return s.encode('utf-8')
222 for path, fid, kind in changes.added:
223 modified[u(path)] = fid
224 for path, fid, kind in changes.removed:
225 removed[u(path)] = None
226 for path, fid, oldkind, newkind in changes.kind_changed:
227 modified[u(path)] = fid
228 for path, fid, kind, mod, _ in changes.modified:
229 modified[u(path)] = fid
230 for oldpath, newpath, fid, kind, mod, _ in changes.renamed:
231 removed[u(oldpath)] = None
232 if kind == 'directory':
233 lst = cur.list_files(from_dir=newpath, recursive=True)
234 for path, file_class, kind, fid, entry in lst:
235 if kind != 'directory':
236 modified[u(newpath + '/' + path)] = fid
238 modified[u(newpath)] = fid
240 return modified, removed
242 def export_files(tree, files):
244 for path, fid in files.iteritems():
245 kind = tree.kind(fid)
247 h = tree.get_file_sha1(fid)
249 if kind == 'symlink':
250 d = tree.get_symlink_target(fid)
254 if tree.is_executable(fid):
259 # is the blob already exported?
262 final.append((mode, mark, path))
265 d = tree.get_file_text(fid)
266 elif kind == 'directory':
269 die("Unhandled kind '%s' for path '%s'" % (kind, path))
271 mark = marks.next_mark()
275 print "mark :%u" % mark
276 print "data %d" % len(d)
279 final.append((mode, mark, path))
283 def export_branch(repo, name):
284 ref = '%s/heads/%s' % (prefix, name)
285 tip = marks.get_tip(name)
287 branch = get_remote_branch(name)
288 repo = branch.repository
291 revs = branch.iter_merge_sorted_revisions(None, tip, 'exclude', 'forward')
293 tip_revno = branch.revision_id_to_revno(tip)
294 last_revno, _ = branch.last_revision_info()
295 total = last_revno - tip_revno
296 except bzrlib.errors.NoSuchRevision:
300 for revid, _, seq, _ in revs:
302 if marks.is_marked(revid):
305 rev = repo.get_revision(revid)
308 parents = rev.parent_ids
311 committer = rev.committer.encode('utf-8')
312 committer = "%s %u %s" % (fixup_user(committer), time, gittz(tz))
313 authors = rev.get_apparent_authors()
315 author = authors[0].encode('utf-8')
316 author = "%s %u %s" % (fixup_user(author), time, gittz(tz))
319 msg = rev.message.encode('utf-8')
323 if rev.properties.has_key('file-info'):
324 from bzrlib import bencode
326 files = bencode.bdecode(rev.properties['file-info'].encode('utf-8'))
328 # protect against repository corruption
329 # (happens in the wild, see MySQL tree)
332 rmsg = msg.rstrip('\r\n ')
335 fmsg = file['message'].rstrip('\r\n ')
336 # Skip empty file comments and file comments identical to the
337 # commit comment (they originate from tools and policies that
338 # require writing per-file comments and users simply copy-paste
339 # revision comment over, these comments add no value as a part of
340 # the commit comment).
341 if fmsg == '' or fmsg == rmsg:
344 file_comments.append(file['path'] + ':')
345 for l in fmsg.split('\n'):
346 file_comments.append(' ' + l)
348 msg += '\n' + '\n'.join(file_comments) + '\n'
350 if len(parents) == 0:
351 parent = bzrlib.revision.NULL_REVISION
355 cur_tree = repo.revision_tree(revid)
356 prev = repo.revision_tree(parent)
357 modified, removed = get_filechanges(cur_tree, prev)
359 modified_final = export_files(cur_tree, modified)
361 if len(parents) == 0:
362 print 'reset %s' % ref
364 print "commit %s" % ref
365 print "mark :%d" % (marks.get_mark(revid))
366 print "author %s" % (author)
367 print "committer %s" % (committer)
368 print "data %d" % (len(msg))
371 for i, p in enumerate(parents):
380 print "merge :%s" % m
384 for f in modified_final:
385 print "M %s :%u %s" % f
389 # let's skip branch revisions from the progress report
392 progress = (revno - tip_revno)
393 if (progress % 100 == 0):
395 print "progress revision %d '%s' (%d/%d)" % (revno, name, progress, total)
397 print "progress revision %d '%s' (%d)" % (revno, name, progress)
401 revid = branch.last_revision()
403 # make sure the ref is updated
404 print "reset %s" % ref
405 print "from :%u" % rev_to_mark(revid)
408 marks.set_tip(name, revid)
410 def export_tag(repo, name):
411 ref = '%s/tags/%s' % (prefix, name)
412 print "reset %s" % ref
413 print "from :%u" % rev_to_mark(tags[name])
416 def export_head(repo):
418 export_branch(repo, name)
420 def do_import(parser):
422 path = os.path.join(dirname, 'marks-git')
425 if os.path.exists(path):
426 print "feature import-marks=%s" % path
427 print "feature export-marks=%s" % path
428 print "feature force"
431 while parser.check('import'):
435 elif ref.startswith('refs/heads/'):
436 name = ref[len('refs/heads/'):]
437 export_branch(repo, name)
438 elif ref.startswith('refs/tags/'):
439 name = ref[len('refs/tags/'):]
440 export_tag(repo, name)
447 def parse_blob(parser):
449 mark = parser.get_mark()
451 data = parser.get_data()
452 blob_marks[mark] = data
457 def __init__(self, branch, revid, parents, files):
461 def copy_tree(revid):
462 files = files_cache[revid] = {}
464 tree = branch.repository.revision_tree(revid)
466 for path, entry in tree.iter_entries_by_dir():
467 files[path] = [entry.file_id, None]
472 if len(parents) == 0:
473 self.base_id = bzrlib.revision.NULL_REVISION
476 self.base_id = parents[0]
477 self.base_files = files_cache.get(self.base_id, None)
478 if not self.base_files:
479 self.base_files = copy_tree(self.base_id)
481 self.files = files_cache[revid] = self.base_files.copy()
484 for path, data in self.files.iteritems():
486 self.rev_files[fid] = [path, mark]
488 for path, f in files.iteritems():
489 fid, mark = self.files.get(path, [None, None])
491 fid = bzrlib.generate_ids.gen_file_id(path)
493 self.rev_files[fid] = [path, mark]
494 self.updates[fid] = f
496 def last_revision(self):
499 def iter_changes(self):
502 def get_parent(dirname, basename):
503 parent_fid, mark = self.base_files.get(dirname, [None, None])
506 parent_fid, mark = self.files.get(dirname, [None, None])
511 fid = bzrlib.generate_ids.gen_file_id(path)
512 add_entry(fid, dirname, 'directory')
515 def add_entry(fid, path, kind, mode=None):
516 dirname, basename = os.path.split(path)
517 parent_fid = get_parent(dirname, basename)
522 elif mode == '120000':
533 self.files[path] = [change[0], None]
534 changes.append(change)
536 def update_entry(fid, path, kind, mode=None):
537 dirname, basename = os.path.split(path)
538 parent_fid = get_parent(dirname, basename)
543 elif mode == '120000':
554 self.files[path] = [change[0], None]
555 changes.append(change)
557 def remove_entry(fid, path, kind):
558 dirname, basename = os.path.split(path)
559 parent_fid = get_parent(dirname, basename)
569 changes.append(change)
571 for fid, f in self.updates.iteritems():
575 remove_entry(fid, path, 'file')
578 if path in self.base_files:
579 update_entry(fid, path, 'file', f['mode'])
581 add_entry(fid, path, 'file', f['mode'])
583 self.files[path][1] = f['mark']
584 self.rev_files[fid][1] = f['mark']
588 def get_content(self, file_id):
589 path, mark = self.rev_files[file_id]
591 return blob_marks[mark]
594 tree = self.branch.repository.revision_tree(self.base_id)
595 return tree.get_file_text(file_id)
597 def get_file_with_stat(self, file_id, path=None):
598 content = self.get_content(file_id)
599 return (StringIO.StringIO(content), None)
601 def get_symlink_target(self, file_id):
602 return self.get_content(file_id)
604 def id2path(self, file_id):
605 path, mark = self.rev_files[file_id]
608 def c_style_unescape(string):
609 if string[0] == string[-1] == '"':
610 return string.decode('string-escape')[1:-1]
613 def parse_commit(parser):
619 if ref.startswith('refs/heads/'):
620 name = ref[len('refs/heads/'):]
621 branch = get_remote_branch(name)
625 commit_mark = parser.get_mark()
627 author = parser.get_author()
629 committer = parser.get_author()
631 data = parser.get_data()
633 if parser.check('from'):
634 parents.append(parser.get_mark())
636 while parser.check('merge'):
637 parents.append(parser.get_mark())
640 # fast-export adds an extra newline
647 if parser.check('M'):
648 t, m, mark_ref, path = line.split(' ', 3)
649 mark = int(mark_ref[1:])
650 f = { 'mode': m, 'mark': mark }
651 elif parser.check('D'):
652 t, path = line.split(' ', 1)
653 f = { 'deleted': True }
655 die('Unknown file command: %s' % line)
656 path = c_style_unescape(path).decode('utf-8')
659 committer, date, tz = committer
660 author, _, _ = author
661 parents = [mark_to_rev(p) for p in parents]
662 revid = bzrlib.generate_ids.gen_revision_id(committer, date)
664 props['branch-nick'] = branch.nick
665 props['authors'] = author
667 mtree = CustomTree(branch, revid, parents, files)
668 changes = mtree.iter_changes()
672 builder = branch.get_commit_builder(parents, None, date, tz, committer, props, revid)
674 list(builder.record_iter_changes(mtree, mtree.last_revision(), changes))
675 builder.finish_inventory()
676 builder.commit(data.decode('utf-8', 'replace'))
683 parsed_refs[ref] = revid
684 marks.new_mark(revid, commit_mark)
686 def parse_reset(parser):
691 if parser.check('commit'):
694 if not parser.check('from'):
696 from_mark = parser.get_mark()
699 parsed_refs[ref] = mark_to_rev(from_mark)
701 def do_export(parser):
704 for line in parser.each_block('done'):
705 if parser.check('blob'):
707 elif parser.check('commit'):
709 elif parser.check('reset'):
711 elif parser.check('tag'):
713 elif parser.check('feature'):
716 die('unhandled export command: %s' % line)
718 for ref, revid in parsed_refs.iteritems():
719 if ref.startswith('refs/heads/'):
720 name = ref[len('refs/heads/'):]
721 branch = get_remote_branch(name)
722 branch.generate_revision_history(revid, marks.get_tip(name))
725 peer = bzrlib.branch.Branch.open(peers[name],
726 possible_transports=transports)
728 peer.bzrdir.push_branch(branch, revision_id=revid,
730 except bzrlib.errors.DivergedBranches:
731 print "error %s non-fast forward" % ref
735 wt = branch.bzrdir.open_workingtree()
737 except bzrlib.errors.NoWorkingTree:
739 elif ref.startswith('refs/tags/'):
740 # TODO: implement tag push
741 print "error %s pushing tags not supported" % ref
744 # transport-helper/fast-export bugs
751 def do_capabilities(parser):
754 print "refspec refs/heads/*:%s/heads/*" % prefix
755 print "refspec refs/tags/*:%s/tags/*" % prefix
757 path = os.path.join(dirname, 'marks-git')
759 if os.path.exists(path):
760 print "*import-marks %s" % path
761 print "*export-marks %s" % path
766 class InvalidOptionValue(Exception):
769 def get_bool_option(val):
775 raise InvalidOptionValue()
777 def do_option(parser):
779 opt, val = parser[1:3]
782 force = get_bool_option(val)
786 except InvalidOptionValue:
787 print "error '%s' is not a valid value for option '%s'" % (val, opt)
789 def ref_is_valid(name):
790 return True not in [c in name for c in '~^: \\']
795 for name in branches:
796 if not master_branch:
798 print "? refs/heads/%s" % name
800 branch = get_remote_branch(master_branch)
802 for tag, revid in branch.tags.get_tag_dict().items():
804 branch.revision_id_to_dotted_revno(revid)
805 except bzrlib.errors.NoSuchRevision:
807 if not ref_is_valid(tag):
809 print "? refs/tags/%s" % tag
813 print "@refs/heads/%s HEAD" % master_branch
816 def clone(path, remote_branch):
818 bdir = bzrlib.bzrdir.BzrDir.create(path, possible_transports=transports)
819 except bzrlib.errors.AlreadyControlDirError:
820 bdir = bzrlib.bzrdir.BzrDir.open(path, possible_transports=transports)
821 repo = bdir.find_repository()
822 repo.fetch(remote_branch.repository)
823 return remote_branch.sprout(bdir, repository=repo)
825 def get_remote_branch(name):
826 remote_branch = bzrlib.branch.Branch.open(branches[name],
827 possible_transports=transports)
828 if isinstance(remote_branch.bzrdir.root_transport, bzrlib.transport.local.LocalTransport):
831 branch_path = os.path.join(dirname, 'clone', name)
834 branch = bzrlib.branch.Branch.open(branch_path,
835 possible_transports=transports)
836 except bzrlib.errors.NotBranchError:
838 branch = clone(branch_path, remote_branch)
842 branch.pull(remote_branch, overwrite=True)
843 except bzrlib.errors.DivergedBranches:
844 # use remote branch for now
849 def find_branches(repo):
850 transport = repo.bzrdir.root_transport
852 for fn in transport.iter_files_recursive():
853 if not fn.endswith('.bzr/branch-format'):
856 name = subdir = fn[:-len('/.bzr/branch-format')]
857 name = name if name != '' else 'master'
858 name = name.replace('/', '+')
861 cur = transport.clone(subdir)
862 branch = bzrlib.branch.Branch.open_from_transport(cur)
863 except (bzrlib.errors.NotBranchError, bzrlib.errors.PermissionDenied):
866 yield name, branch.base
868 def get_repo(url, alias):
869 normal_url = bzrlib.urlutils.normalize_url(url)
870 origin = bzrlib.bzrdir.BzrDir.open(url, possible_transports=transports)
871 is_local = isinstance(origin.transport, bzrlib.transport.local.LocalTransport)
873 shared_path = os.path.join(gitdir, 'bzr')
875 shared_dir = bzrlib.bzrdir.BzrDir.open(shared_path,
876 possible_transports=transports)
877 except bzrlib.errors.NotBranchError:
878 shared_dir = bzrlib.bzrdir.BzrDir.create(shared_path,
879 possible_transports=transports)
881 shared_repo = shared_dir.open_repository()
882 except bzrlib.errors.NoRepositoryPresent:
883 shared_repo = shared_dir.create_repository(shared=True)
886 clone_path = os.path.join(dirname, 'clone')
887 if not os.path.exists(clone_path):
890 # check and remove old organization
892 bdir = bzrlib.bzrdir.BzrDir.open(clone_path,
893 possible_transports=transports)
894 bdir.destroy_repository()
895 except bzrlib.errors.NotBranchError:
897 except bzrlib.errors.NoRepositoryPresent:
900 wanted = get_config('remote.%s.bzr-branches' % alias).rstrip().split(', ')
902 wanted = [e for e in wanted if e]
904 wanted = get_config('remote-bzr.branches').rstrip().split(', ')
906 wanted = [e for e in wanted if e]
910 repo = origin.open_repository()
911 if not repo.bzrdir.root_transport.listable():
912 # this repository is not usable for us
913 raise bzrlib.errors.NoRepositoryPresent(repo.bzrdir)
914 except bzrlib.errors.NoRepositoryPresent:
918 def list_wanted(url, wanted):
920 subdir = name if name != 'master' else ''
921 yield name, bzrlib.urlutils.join(url, subdir)
923 branch_list = list_wanted(url, wanted)
925 branch_list = find_branches(repo)
927 for name, url in branch_list:
934 def fix_path(alias, orig_url):
935 url = urlparse.urlparse(orig_url, 'file')
936 if url.scheme != 'file' or os.path.isabs(url.path):
938 abs_url = urlparse.urljoin("%s/" % os.getcwd(), orig_url)
939 cmd = ['git', 'config', 'remote.%s.url' % alias, "bzr::%s" % abs_url]
943 global marks, prefix, gitdir, dirname
944 global tags, filenodes
949 global branches, peers
957 gitdir = os.environ.get('GIT_DIR', None)
960 die('Not enough arguments.')
963 die('GIT_DIR not set')
980 alias = hashlib.sha1(alias).hexdigest()
982 prefix = 'refs/bzr/%s' % alias
983 dirname = os.path.join(gitdir, 'bzr', alias)
988 if not os.path.exists(dirname):
991 if hasattr(bzrlib.ui.ui_factory, 'be_quiet'):
992 bzrlib.ui.ui_factory.be_quiet(True)
994 repo = get_repo(url, alias)
996 marks_path = os.path.join(dirname, 'marks-int')
997 marks = Marks(marks_path)
999 parser = Parser(repo)
1001 if parser.check('capabilities'):
1002 do_capabilities(parser)
1003 elif parser.check('list'):
1005 elif parser.check('import'):
1007 elif parser.check('export'):
1009 elif parser.check('option'):
1012 die('unhandled command: %s' % line)
1019 shutil.rmtree(dirname)
1021 atexit.register(bye)
1022 sys.exit(main(sys.argv))