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, kind, mod, _ in changes.modified:
227 modified[u(path)] = fid
228 for oldpath, newpath, fid, kind, mod, _ in changes.renamed:
229 removed[u(oldpath)] = None
230 if kind == 'directory':
231 lst = cur.list_files(from_dir=newpath, recursive=True)
232 for path, file_class, kind, fid, entry in lst:
233 if kind != 'directory':
234 modified[u(newpath + '/' + path)] = fid
236 modified[u(newpath)] = fid
238 return modified, removed
240 def export_files(tree, files):
242 for path, fid in files.iteritems():
243 kind = tree.kind(fid)
245 h = tree.get_file_sha1(fid)
247 if kind == 'symlink':
248 d = tree.get_symlink_target(fid)
252 if tree.is_executable(fid):
257 # is the blob already exported?
260 final.append((mode, mark, path))
263 d = tree.get_file_text(fid)
264 elif kind == 'directory':
267 die("Unhandled kind '%s' for path '%s'" % (kind, path))
269 mark = marks.next_mark()
273 print "mark :%u" % mark
274 print "data %d" % len(d)
277 final.append((mode, mark, path))
281 def export_branch(repo, name):
282 ref = '%s/heads/%s' % (prefix, name)
283 tip = marks.get_tip(name)
285 branch = get_remote_branch(name)
286 repo = branch.repository
289 revs = branch.iter_merge_sorted_revisions(None, tip, 'exclude', 'forward')
291 tip_revno = branch.revision_id_to_revno(tip)
292 last_revno, _ = branch.last_revision_info()
293 total = last_revno - tip_revno
294 except bzrlib.errors.NoSuchRevision:
298 for revid, _, seq, _ in revs:
300 if marks.is_marked(revid):
303 rev = repo.get_revision(revid)
306 parents = rev.parent_ids
309 committer = rev.committer.encode('utf-8')
310 committer = "%s %u %s" % (fixup_user(committer), time, gittz(tz))
311 authors = rev.get_apparent_authors()
313 author = authors[0].encode('utf-8')
314 author = "%s %u %s" % (fixup_user(author), time, gittz(tz))
317 msg = rev.message.encode('utf-8')
321 if len(parents) == 0:
322 parent = bzrlib.revision.NULL_REVISION
326 cur_tree = repo.revision_tree(revid)
327 prev = repo.revision_tree(parent)
328 modified, removed = get_filechanges(cur_tree, prev)
330 modified_final = export_files(cur_tree, modified)
332 if len(parents) == 0:
333 print 'reset %s' % ref
335 print "commit %s" % ref
336 print "mark :%d" % (marks.get_mark(revid))
337 print "author %s" % (author)
338 print "committer %s" % (committer)
339 print "data %d" % (len(msg))
342 for i, p in enumerate(parents):
351 print "merge :%s" % m
355 for f in modified_final:
356 print "M %s :%u %s" % f
360 # let's skip branch revisions from the progress report
363 progress = (revno - tip_revno)
364 if (progress % 100 == 0):
366 print "progress revision %d '%s' (%d/%d)" % (revno, name, progress, total)
368 print "progress revision %d '%s' (%d)" % (revno, name, progress)
372 revid = branch.last_revision()
374 # make sure the ref is updated
375 print "reset %s" % ref
376 print "from :%u" % rev_to_mark(revid)
379 marks.set_tip(name, revid)
381 def export_tag(repo, name):
382 ref = '%s/tags/%s' % (prefix, name)
383 print "reset %s" % ref
384 print "from :%u" % rev_to_mark(tags[name])
387 def do_import(parser):
389 path = os.path.join(dirname, 'marks-git')
392 if os.path.exists(path):
393 print "feature import-marks=%s" % path
394 print "feature export-marks=%s" % path
395 print "feature force"
398 while parser.check('import'):
400 if ref.startswith('refs/heads/'):
401 name = ref[len('refs/heads/'):]
402 export_branch(repo, name)
403 if ref.startswith('refs/tags/'):
404 name = ref[len('refs/tags/'):]
405 export_tag(repo, name)
412 def parse_blob(parser):
414 mark = parser.get_mark()
416 data = parser.get_data()
417 blob_marks[mark] = data
422 def __init__(self, branch, revid, parents, files):
426 def copy_tree(revid):
427 files = files_cache[revid] = {}
429 tree = branch.repository.revision_tree(revid)
431 for path, entry in tree.iter_entries_by_dir():
432 files[path] = [entry.file_id, None]
437 if len(parents) == 0:
438 self.base_id = bzrlib.revision.NULL_REVISION
441 self.base_id = parents[0]
442 self.base_files = files_cache.get(self.base_id, None)
443 if not self.base_files:
444 self.base_files = copy_tree(self.base_id)
446 self.files = files_cache[revid] = self.base_files.copy()
449 for path, data in self.files.iteritems():
451 self.rev_files[fid] = [path, mark]
453 for path, f in files.iteritems():
454 fid, mark = self.files.get(path, [None, None])
456 fid = bzrlib.generate_ids.gen_file_id(path)
458 self.rev_files[fid] = [path, mark]
459 self.updates[fid] = f
461 def last_revision(self):
464 def iter_changes(self):
467 def get_parent(dirname, basename):
468 parent_fid, mark = self.base_files.get(dirname, [None, None])
471 parent_fid, mark = self.files.get(dirname, [None, None])
476 fid = bzrlib.generate_ids.gen_file_id(path)
477 add_entry(fid, dirname, 'directory')
480 def add_entry(fid, path, kind, mode=None):
481 dirname, basename = os.path.split(path)
482 parent_fid = get_parent(dirname, basename)
487 elif mode == '120000':
498 self.files[path] = [change[0], None]
499 changes.append(change)
501 def update_entry(fid, path, kind, mode=None):
502 dirname, basename = os.path.split(path)
503 parent_fid = get_parent(dirname, basename)
508 elif mode == '120000':
519 self.files[path] = [change[0], None]
520 changes.append(change)
522 def remove_entry(fid, path, kind):
523 dirname, basename = os.path.split(path)
524 parent_fid = get_parent(dirname, basename)
534 changes.append(change)
536 for fid, f in self.updates.iteritems():
540 remove_entry(fid, path, 'file')
543 if path in self.base_files:
544 update_entry(fid, path, 'file', f['mode'])
546 add_entry(fid, path, 'file', f['mode'])
548 self.files[path][1] = f['mark']
549 self.rev_files[fid][1] = f['mark']
553 def get_content(self, file_id):
554 path, mark = self.rev_files[file_id]
556 return blob_marks[mark]
559 tree = self.branch.repository.revision_tree(self.base_id)
560 return tree.get_file_text(file_id)
562 def get_file_with_stat(self, file_id, path=None):
563 content = self.get_content(file_id)
564 return (StringIO.StringIO(content), None)
566 def get_symlink_target(self, file_id):
567 return self.get_content(file_id)
569 def id2path(self, file_id):
570 path, mark = self.rev_files[file_id]
573 def c_style_unescape(string):
574 if string[0] == string[-1] == '"':
575 return string.decode('string-escape')[1:-1]
578 def parse_commit(parser):
584 if ref.startswith('refs/heads/'):
585 name = ref[len('refs/heads/'):]
586 branch = get_remote_branch(name)
590 commit_mark = parser.get_mark()
592 author = parser.get_author()
594 committer = parser.get_author()
596 data = parser.get_data()
598 if parser.check('from'):
599 parents.append(parser.get_mark())
601 while parser.check('merge'):
602 parents.append(parser.get_mark())
605 # fast-export adds an extra newline
612 if parser.check('M'):
613 t, m, mark_ref, path = line.split(' ', 3)
614 mark = int(mark_ref[1:])
615 f = { 'mode': m, 'mark': mark }
616 elif parser.check('D'):
617 t, path = line.split(' ', 1)
618 f = { 'deleted': True }
620 die('Unknown file command: %s' % line)
621 path = c_style_unescape(path).decode('utf-8')
624 committer, date, tz = committer
625 author, _, _ = author
626 parents = [mark_to_rev(p) for p in parents]
627 revid = bzrlib.generate_ids.gen_revision_id(committer, date)
629 props['branch-nick'] = branch.nick
630 props['authors'] = author
632 mtree = CustomTree(branch, revid, parents, files)
633 changes = mtree.iter_changes()
637 builder = branch.get_commit_builder(parents, None, date, tz, committer, props, revid)
639 list(builder.record_iter_changes(mtree, mtree.last_revision(), changes))
640 builder.finish_inventory()
641 builder.commit(data.decode('utf-8', 'replace'))
648 parsed_refs[ref] = revid
649 marks.new_mark(revid, commit_mark)
651 def parse_reset(parser):
656 if parser.check('commit'):
659 if not parser.check('from'):
661 from_mark = parser.get_mark()
664 parsed_refs[ref] = mark_to_rev(from_mark)
666 def do_export(parser):
669 for line in parser.each_block('done'):
670 if parser.check('blob'):
672 elif parser.check('commit'):
674 elif parser.check('reset'):
676 elif parser.check('tag'):
678 elif parser.check('feature'):
681 die('unhandled export command: %s' % line)
683 for ref, revid in parsed_refs.iteritems():
684 if ref.startswith('refs/heads/'):
685 name = ref[len('refs/heads/'):]
686 branch = get_remote_branch(name)
687 branch.generate_revision_history(revid, marks.get_tip(name))
690 peer = bzrlib.branch.Branch.open(peers[name],
691 possible_transports=transports)
693 peer.bzrdir.push_branch(branch, revision_id=revid)
694 except bzrlib.errors.DivergedBranches:
695 print "error %s non-fast forward" % ref
699 wt = branch.bzrdir.open_workingtree()
701 except bzrlib.errors.NoWorkingTree:
703 elif ref.startswith('refs/tags/'):
704 # TODO: implement tag push
705 print "error %s pushing tags not supported" % ref
708 # transport-helper/fast-export bugs
715 def do_capabilities(parser):
718 print "refspec refs/heads/*:%s/heads/*" % prefix
719 print "refspec refs/tags/*:%s/tags/*" % prefix
721 path = os.path.join(dirname, 'marks-git')
723 if os.path.exists(path):
724 print "*import-marks %s" % path
725 print "*export-marks %s" % path
729 def ref_is_valid(name):
730 return True not in [c in name for c in '~^: \\']
735 for name in branches:
736 if not master_branch:
738 print "? refs/heads/%s" % name
740 branch = get_remote_branch(master_branch)
742 for tag, revid in branch.tags.get_tag_dict().items():
744 branch.revision_id_to_dotted_revno(revid)
745 except bzrlib.errors.NoSuchRevision:
747 if not ref_is_valid(tag):
749 print "? refs/tags/%s" % tag
753 print "@refs/heads/%s HEAD" % master_branch
756 def clone(path, remote_branch):
758 bdir = bzrlib.bzrdir.BzrDir.create(path, possible_transports=transports)
759 except bzrlib.errors.AlreadyControlDirError:
760 bdir = bzrlib.bzrdir.BzrDir.open(path, possible_transports=transports)
761 repo = bdir.find_repository()
762 repo.fetch(remote_branch.repository)
763 return remote_branch.sprout(bdir, repository=repo)
765 def get_remote_branch(name):
766 remote_branch = bzrlib.branch.Branch.open(branches[name],
767 possible_transports=transports)
768 if isinstance(remote_branch.bzrdir.root_transport, bzrlib.transport.local.LocalTransport):
771 branch_path = os.path.join(dirname, 'clone', name)
774 branch = bzrlib.branch.Branch.open(branch_path,
775 possible_transports=transports)
776 except bzrlib.errors.NotBranchError:
778 branch = clone(branch_path, remote_branch)
782 branch.pull(remote_branch, overwrite=True)
783 except bzrlib.errors.DivergedBranches:
784 # use remote branch for now
789 def find_branches(repo):
790 transport = repo.bzrdir.root_transport
792 for fn in transport.iter_files_recursive():
793 if not fn.endswith('.bzr/branch-format'):
796 name = subdir = fn[:-len('/.bzr/branch-format')]
797 name = name if name != '' else 'master'
798 name = name.replace('/', '+')
801 cur = transport.clone(subdir)
802 branch = bzrlib.branch.Branch.open_from_transport(cur)
803 except bzrlib.errors.NotBranchError:
806 yield name, branch.base
808 def get_repo(url, alias):
809 normal_url = bzrlib.urlutils.normalize_url(url)
810 origin = bzrlib.bzrdir.BzrDir.open(url, possible_transports=transports)
811 is_local = isinstance(origin.transport, bzrlib.transport.local.LocalTransport)
813 shared_path = os.path.join(gitdir, 'bzr')
815 shared_dir = bzrlib.bzrdir.BzrDir.open(shared_path,
816 possible_transports=transports)
817 except bzrlib.errors.NotBranchError:
818 shared_dir = bzrlib.bzrdir.BzrDir.create(shared_path,
819 possible_transports=transports)
821 shared_repo = shared_dir.open_repository()
822 except bzrlib.errors.NoRepositoryPresent:
823 shared_repo = shared_dir.create_repository(shared=True)
826 clone_path = os.path.join(dirname, 'clone')
827 if not os.path.exists(clone_path):
830 # check and remove old organization
832 bdir = bzrlib.bzrdir.BzrDir.open(clone_path,
833 possible_transports=transports)
834 bdir.destroy_repository()
835 except bzrlib.errors.NotBranchError:
837 except bzrlib.errors.NoRepositoryPresent:
840 wanted = get_config('remote.%s.bzr-branches' % alias).rstrip().split(', ')
842 wanted = [e for e in wanted if e]
844 wanted = get_config('remote-bzr.branches').rstrip().split(', ')
846 wanted = [e for e in wanted if e]
850 repo = origin.open_repository()
851 if not repo.bzrdir.root_transport.listable():
852 # this repository is not usable for us
853 raise bzrlib.errors.NoRepositoryPresent(repo.bzrdir)
854 except bzrlib.errors.NoRepositoryPresent:
858 def list_wanted(url, wanted):
860 subdir = name if name != 'master' else ''
861 yield name, bzrlib.urlutils.join(url, subdir)
863 branch_list = list_wanted(url, wanted)
865 branch_list = find_branches(repo)
867 for name, url in branch_list:
874 def fix_path(alias, orig_url):
875 url = urlparse.urlparse(orig_url, 'file')
876 if url.scheme != 'file' or os.path.isabs(url.path):
878 abs_url = urlparse.urljoin("%s/" % os.getcwd(), orig_url)
879 cmd = ['git', 'config', 'remote.%s.url' % alias, "bzr::%s" % abs_url]
883 global marks, prefix, gitdir, dirname
884 global tags, filenodes
889 global branches, peers
894 gitdir = os.environ.get('GIT_DIR', None)
897 die('Not enough arguments.')
900 die('GIT_DIR not set')
916 alias = hashlib.sha1(alias).hexdigest()
918 prefix = 'refs/bzr/%s' % alias
919 dirname = os.path.join(gitdir, 'bzr', alias)
924 if not os.path.exists(dirname):
927 if hasattr(bzrlib.ui.ui_factory, 'be_quiet'):
928 bzrlib.ui.ui_factory.be_quiet(True)
930 repo = get_repo(url, alias)
932 marks_path = os.path.join(dirname, 'marks-int')
933 marks = Marks(marks_path)
935 parser = Parser(repo)
937 if parser.check('capabilities'):
938 do_capabilities(parser)
939 elif parser.check('list'):
941 elif parser.check('import'):
943 elif parser.check('export'):
946 die('unhandled command: %s' % line)
953 shutil.rmtree(dirname)
956 sys.exit(main(sys.argv))