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 track (per repo):
17 # git config remote-bzr.branches 'trunk, devel, test'
23 if hasattr(bzrlib
, "initialize"):
27 bzrlib
.plugin
.load_plugins()
29 import bzrlib
.generate_ids
30 import bzrlib
.transport
33 import bzrlib
.urlutils
40 import atexit
, shutil
, hashlib
, urlparse
, subprocess
42 NAME_RE
= re
.compile('^([^<>]+)')
43 AUTHOR_RE
= re
.compile('^([^<>]+?)? ?<([^<>]*)>$')
44 EMAIL_RE
= re
.compile('^([^<>]+[^ \\\t<>])?\\b(?:[ \\t<>]*?)\\b([^ \\t<>]+@[^ \\t<>]+)')
45 RAW_AUTHOR_RE
= re
.compile('^(\w+) (.+)? <(.*)> (\d+) ([+-]\d+)')
48 sys
.stderr
.write('ERROR: %s\n' % (msg
% args
))
52 sys
.stderr
.write('WARNING: %s\n' % (msg
% args
))
55 return '%+03d%02d' % (tz
/ 3600, tz
% 3600 / 60)
57 def get_config(config
):
58 cmd
= ['git', 'config', '--get', config
]
59 process
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
)
60 output
, _
= process
.communicate()
65 def __init__(self
, path
):
74 if not os
.path
.exists(self
.path
):
77 tmp
= json
.load(open(self
.path
))
78 self
.tips
= tmp
['tips']
79 self
.marks
= tmp
['marks']
80 self
.last_mark
= tmp
['last-mark']
82 for rev
, mark
in self
.marks
.iteritems():
83 self
.rev_marks
[mark
] = rev
86 return { 'tips': self
.tips
, 'marks': self
.marks
, 'last-mark' : self
.last_mark
}
89 json
.dump(self
.dict(), open(self
.path
, 'w'))
92 return str(self
.dict())
94 def from_rev(self
, rev
):
95 return self
.marks
[rev
]
97 def to_rev(self
, mark
):
98 return str(self
.rev_marks
[mark
])
102 return self
.last_mark
104 def get_mark(self
, rev
):
106 self
.marks
[rev
] = self
.last_mark
107 return self
.last_mark
109 def is_marked(self
, rev
):
110 return rev
in self
.marks
112 def new_mark(self
, rev
, mark
):
113 self
.marks
[rev
] = mark
114 self
.rev_marks
[mark
] = rev
115 self
.last_mark
= mark
117 def get_tip(self
, branch
):
118 return self
.tips
.get(branch
, None)
120 def set_tip(self
, branch
, tip
):
121 self
.tips
[branch
] = tip
125 def __init__(self
, repo
):
127 self
.line
= self
.get_line()
130 return sys
.stdin
.readline().strip()
132 def __getitem__(self
, i
):
133 return self
.line
.split()[i
]
135 def check(self
, word
):
136 return self
.line
.startswith(word
)
138 def each_block(self
, separator
):
139 while self
.line
!= separator
:
141 self
.line
= self
.get_line()
144 return self
.each_block('')
147 self
.line
= self
.get_line()
148 if self
.line
== 'done':
152 i
= self
.line
.index(':') + 1
153 return int(self
.line
[i
:])
156 if not self
.check('data'):
158 i
= self
.line
.index(' ') + 1
159 size
= int(self
.line
[i
:])
160 return sys
.stdin
.read(size
)
162 def get_author(self
):
163 m
= RAW_AUTHOR_RE
.match(self
.line
)
166 _
, name
, email
, date
, tz
= m
.groups()
167 committer
= '%s <%s>' % (name
, email
)
169 tz
= ((tz
/ 100) * 3600) + ((tz
% 100) * 60)
170 return (committer
, int(date
), tz
)
172 def rev_to_mark(rev
):
174 return marks
.from_rev(rev
)
176 def mark_to_rev(mark
):
178 return marks
.to_rev(mark
)
180 def fixup_user(user
):
182 user
= user
.replace('"', '')
183 m
= AUTHOR_RE
.match(user
)
186 mail
= m
.group(2).strip()
188 m
= EMAIL_RE
.match(user
)
193 m
= NAME_RE
.match(user
)
195 name
= m
.group(1).strip()
202 return '%s <%s>' % (name
, mail
)
204 def get_filechanges(cur
, prev
):
208 changes
= cur
.changes_from(prev
)
211 return s
.encode('utf-8')
213 for path
, fid
, kind
in changes
.added
:
214 modified
[u(path
)] = fid
215 for path
, fid
, kind
in changes
.removed
:
216 removed
[u(path
)] = None
217 for path
, fid
, kind
, mod
, _
in changes
.modified
:
218 modified
[u(path
)] = fid
219 for oldpath
, newpath
, fid
, kind
, mod
, _
in changes
.renamed
:
220 removed
[u(oldpath
)] = None
221 if kind
== 'directory':
222 lst
= cur
.list_files(from_dir
=newpath
, recursive
=True)
223 for path
, file_class
, kind
, fid
, entry
in lst
:
224 if kind
!= 'directory':
225 modified
[u(newpath
+ '/' + path
)] = fid
227 modified
[u(newpath
)] = fid
229 return modified
, removed
231 def export_files(tree
, files
):
232 global marks
, filenodes
235 for path
, fid
in files
.iteritems():
236 kind
= tree
.kind(fid
)
238 h
= tree
.get_file_sha1(fid
)
240 if kind
== 'symlink':
241 d
= tree
.get_symlink_target(fid
)
245 if tree
.is_executable(fid
):
250 # is the blob already exported?
253 final
.append((mode
, mark
, path
))
256 d
= tree
.get_file_text(fid
)
257 elif kind
== 'directory':
260 die("Unhandled kind '%s' for path '%s'" % (kind
, path
))
262 mark
= marks
.next_mark()
266 print "mark :%u" % mark
267 print "data %d" % len(d
)
270 final
.append((mode
, mark
, path
))
274 def export_branch(repo
, name
):
277 ref
= '%s/heads/%s' % (prefix
, name
)
278 tip
= marks
.get_tip(name
)
280 branch
= bzrlib
.branch
.Branch
.open(branches
[name
])
281 repo
= branch
.repository
284 revs
= branch
.iter_merge_sorted_revisions(None, tip
, 'exclude', 'forward')
286 tip_revno
= branch
.revision_id_to_revno(tip
)
287 last_revno
, _
= branch
.last_revision_info()
288 total
= last_revno
- tip_revno
289 except bzrlib
.errors
.NoSuchRevision
:
293 for revid
, _
, seq
, _
in revs
:
295 if marks
.is_marked(revid
):
298 rev
= repo
.get_revision(revid
)
301 parents
= rev
.parent_ids
304 committer
= rev
.committer
.encode('utf-8')
305 committer
= "%s %u %s" % (fixup_user(committer
), time
, gittz(tz
))
306 authors
= rev
.get_apparent_authors()
308 author
= authors
[0].encode('utf-8')
309 author
= "%s %u %s" % (fixup_user(author
), time
, gittz(tz
))
312 msg
= rev
.message
.encode('utf-8')
316 if len(parents
) == 0:
317 parent
= bzrlib
.revision
.NULL_REVISION
321 cur_tree
= repo
.revision_tree(revid
)
322 prev
= repo
.revision_tree(parent
)
323 modified
, removed
= get_filechanges(cur_tree
, prev
)
325 modified_final
= export_files(cur_tree
, modified
)
327 if len(parents
) == 0:
328 print 'reset %s' % ref
330 print "commit %s" % ref
331 print "mark :%d" % (marks
.get_mark(revid
))
332 print "author %s" % (author
)
333 print "committer %s" % (committer
)
334 print "data %d" % (len(msg
))
337 for i
, p
in enumerate(parents
):
346 print "merge :%s" % m
350 for f
in modified_final
:
351 print "M %s :%u %s" % f
355 # let's skip branch revisions from the progress report
358 progress
= (revno
- tip_revno
)
359 if (progress
% 100 == 0):
361 print "progress revision %d '%s' (%d/%d)" % (revno
, name
, progress
, total
)
363 print "progress revision %d '%s' (%d)" % (revno
, name
, progress
)
367 revid
= branch
.last_revision()
369 # make sure the ref is updated
370 print "reset %s" % ref
371 print "from :%u" % rev_to_mark(revid
)
374 marks
.set_tip(name
, revid
)
376 def export_tag(repo
, name
):
379 ref
= '%s/tags/%s' % (prefix
, name
)
380 print "reset %s" % ref
381 print "from :%u" % rev_to_mark(tags
[name
])
384 def do_import(parser
):
388 path
= os
.path
.join(dirname
, 'marks-git')
391 if os
.path
.exists(path
):
392 print "feature import-marks=%s" % path
393 print "feature export-marks=%s" % path
394 print "feature force"
397 while parser
.check('import'):
399 if ref
.startswith('refs/heads/'):
400 name
= ref
[len('refs/heads/'):]
401 export_branch(repo
, name
)
402 if ref
.startswith('refs/tags/'):
403 name
= ref
[len('refs/tags/'):]
404 export_tag(repo
, name
)
411 def parse_blob(parser
):
415 mark
= parser
.get_mark()
417 data
= parser
.get_data()
418 blob_marks
[mark
] = data
423 def __init__(self
, branch
, revid
, parents
, files
):
429 def copy_tree(revid
):
430 files
= files_cache
[revid
] = {}
432 tree
= branch
.repository
.revision_tree(revid
)
434 for path
, entry
in tree
.iter_entries_by_dir():
435 files
[path
] = [entry
.file_id
, None]
440 if len(parents
) == 0:
441 self
.base_id
= bzrlib
.revision
.NULL_REVISION
444 self
.base_id
= parents
[0]
445 self
.base_files
= files_cache
.get(self
.base_id
, None)
446 if not self
.base_files
:
447 self
.base_files
= copy_tree(self
.base_id
)
449 self
.files
= files_cache
[revid
] = self
.base_files
.copy()
452 for path
, data
in self
.files
.iteritems():
454 self
.rev_files
[fid
] = [path
, mark
]
456 for path
, f
in files
.iteritems():
457 fid
, mark
= self
.files
.get(path
, [None, None])
459 fid
= bzrlib
.generate_ids
.gen_file_id(path
)
461 self
.rev_files
[fid
] = [path
, mark
]
462 self
.updates
[fid
] = f
464 def last_revision(self
):
467 def iter_changes(self
):
470 def get_parent(dirname
, basename
):
471 parent_fid
, mark
= self
.base_files
.get(dirname
, [None, None])
474 parent_fid
, mark
= self
.files
.get(dirname
, [None, None])
479 fid
= bzrlib
.generate_ids
.gen_file_id(path
)
480 add_entry(fid
, dirname
, 'directory')
483 def add_entry(fid
, path
, kind
, mode
= None):
484 dirname
, basename
= os
.path
.split(path
)
485 parent_fid
= get_parent(dirname
, basename
)
490 elif mode
== '120000':
501 self
.files
[path
] = [change
[0], None]
502 changes
.append(change
)
504 def update_entry(fid
, path
, kind
, mode
= None):
505 dirname
, basename
= os
.path
.split(path
)
506 parent_fid
= get_parent(dirname
, basename
)
511 elif mode
== '120000':
522 self
.files
[path
] = [change
[0], None]
523 changes
.append(change
)
525 def remove_entry(fid
, path
, kind
):
526 dirname
, basename
= os
.path
.split(path
)
527 parent_fid
= get_parent(dirname
, basename
)
537 changes
.append(change
)
539 for fid
, f
in self
.updates
.iteritems():
543 remove_entry(fid
, path
, 'file')
546 if path
in self
.base_files
:
547 update_entry(fid
, path
, 'file', f
['mode'])
549 add_entry(fid
, path
, 'file', f
['mode'])
551 self
.files
[path
][1] = f
['mark']
552 self
.rev_files
[fid
][1] = f
['mark']
556 def get_content(self
, file_id
):
557 path
, mark
= self
.rev_files
[file_id
]
559 return blob_marks
[mark
]
562 tree
= self
.branch
.repository
.revision_tree(self
.base_id
)
563 return tree
.get_file_text(file_id
)
565 def get_file_with_stat(self
, file_id
, path
=None):
566 content
= self
.get_content(file_id
)
567 return (StringIO
.StringIO(content
), None)
569 def get_symlink_target(self
, file_id
):
570 return self
.get_content(file_id
)
572 def id2path(self
, file_id
):
573 path
, mark
= self
.rev_files
[file_id
]
576 def c_style_unescape(string
):
577 if string
[0] == string
[-1] == '"':
578 return string
.decode('string-escape')[1:-1]
581 def parse_commit(parser
):
582 global marks
, blob_marks
, parsed_refs
590 if ref
.startswith('refs/heads/'):
591 name
= ref
[len('refs/heads/'):]
592 branch
= bzrlib
.branch
.Branch
.open(branches
[name
])
596 commit_mark
= parser
.get_mark()
598 author
= parser
.get_author()
600 committer
= parser
.get_author()
602 data
= parser
.get_data()
604 if parser
.check('from'):
605 parents
.append(parser
.get_mark())
607 while parser
.check('merge'):
608 parents
.append(parser
.get_mark())
611 # fast-export adds an extra newline
618 if parser
.check('M'):
619 t
, m
, mark_ref
, path
= line
.split(' ', 3)
620 mark
= int(mark_ref
[1:])
621 f
= { 'mode' : m
, 'mark' : mark
}
622 elif parser
.check('D'):
623 t
, path
= line
.split(' ')
624 f
= { 'deleted' : True }
626 die('Unknown file command: %s' % line
)
627 path
= c_style_unescape(path
).decode('utf-8')
630 committer
, date
, tz
= committer
631 parents
= [mark_to_rev(p
) for p
in parents
]
632 revid
= bzrlib
.generate_ids
.gen_revision_id(committer
, date
)
634 props
['branch-nick'] = branch
.nick
636 mtree
= CustomTree(branch
, revid
, parents
, files
)
637 changes
= mtree
.iter_changes()
641 builder
= branch
.get_commit_builder(parents
, None, date
, tz
, committer
, props
, revid
)
643 list(builder
.record_iter_changes(mtree
, mtree
.last_revision(), changes
))
644 builder
.finish_inventory()
645 builder
.commit(data
.decode('utf-8', 'replace'))
652 parsed_refs
[ref
] = revid
653 marks
.new_mark(revid
, commit_mark
)
655 def parse_reset(parser
):
662 if parser
.check('commit'):
665 if not parser
.check('from'):
667 from_mark
= parser
.get_mark()
670 parsed_refs
[ref
] = mark_to_rev(from_mark
)
672 def do_export(parser
):
673 global parsed_refs
, dirname
677 for line
in parser
.each_block('done'):
678 if parser
.check('blob'):
680 elif parser
.check('commit'):
682 elif parser
.check('reset'):
684 elif parser
.check('tag'):
686 elif parser
.check('feature'):
689 die('unhandled export command: %s' % line
)
691 for ref
, revid
in parsed_refs
.iteritems():
692 if ref
.startswith('refs/heads/'):
693 name
= ref
[len('refs/heads/'):]
694 branch
= bzrlib
.branch
.Branch
.open(branches
[name
])
695 branch
.generate_revision_history(revid
, marks
.get_tip(name
))
698 peer
= bzrlib
.branch
.Branch
.open(peers
[name
])
700 peer
.bzrdir
.push_branch(branch
, revision_id
=revid
)
701 except bzrlib
.errors
.DivergedBranches
:
702 print "error %s non-fast forward" % ref
706 wt
= branch
.bzrdir
.open_workingtree()
708 except bzrlib
.errors
.NoWorkingTree
:
710 elif ref
.startswith('refs/tags/'):
711 # TODO: implement tag push
712 print "error %s pushing tags not supported" % ref
715 # transport-helper/fast-export bugs
722 def do_capabilities(parser
):
727 print "refspec refs/heads/*:%s/heads/*" % prefix
728 print "refspec refs/tags/*:%s/tags/*" % prefix
730 path
= os
.path
.join(dirname
, 'marks-git')
732 if os
.path
.exists(path
):
733 print "*import-marks %s" % path
734 print "*export-marks %s" % path
738 def ref_is_valid(name
):
739 return not True in [c
in name
for c
in '~^: \\']
746 for name
in branches
:
747 if not master_branch
:
749 print "? refs/heads/%s" % name
751 branch
= bzrlib
.branch
.Branch
.open(branches
[master_branch
])
753 for tag
, revid
in branch
.tags
.get_tag_dict().items():
755 branch
.revision_id_to_dotted_revno(revid
)
756 except bzrlib
.errors
.NoSuchRevision
:
758 if not ref_is_valid(tag
):
760 print "? refs/tags/%s" % tag
764 print "@refs/heads/%s HEAD" % master_branch
767 def get_remote_branch(origin
, remote_branch
, name
):
768 global dirname
, peers
770 branch_path
= os
.path
.join(dirname
, 'clone', name
)
771 if os
.path
.exists(branch_path
):
773 d
= bzrlib
.bzrdir
.BzrDir
.open(branch_path
)
774 branch
= d
.open_branch()
776 branch
.pull(remote_branch
, [], None, False)
777 except bzrlib
.errors
.DivergedBranches
:
778 # use remote branch for now
782 d
= origin
.sprout(branch_path
, None,
783 hardlink
=True, create_tree_if_local
=False,
784 force_new_repo
=False,
785 source_branch
=remote_branch
)
786 branch
= d
.open_branch()
790 def find_branches(repo
, wanted
):
791 transport
= repo
.user_transport
793 for fn
in transport
.iter_files_recursive():
794 if not fn
.endswith('.bzr/branch-format'):
797 name
= subdir
= fn
[:-len('/.bzr/branch-format')]
798 name
= name
if name
!= '' else 'master'
799 name
= name
.replace('/', '+')
801 if wanted
and not name
in wanted
:
805 cur
= transport
.clone(subdir
)
806 branch
= bzrlib
.branch
.Branch
.open_from_transport(cur
)
807 except bzrlib
.errors
.NotBranchError
:
812 def get_repo(url
, alias
):
813 global dirname
, peer
, branches
815 normal_url
= bzrlib
.urlutils
.normalize_url(url
)
816 origin
= bzrlib
.bzrdir
.BzrDir
.open(url
)
817 is_local
= isinstance(origin
.transport
, bzrlib
.transport
.local
.LocalTransport
)
819 shared_path
= os
.path
.join(gitdir
, 'bzr')
821 shared_dir
= bzrlib
.bzrdir
.BzrDir
.open(shared_path
)
822 except bzrlib
.errors
.NotBranchError
:
823 shared_dir
= bzrlib
.bzrdir
.BzrDir
.create(shared_path
)
825 shared_repo
= shared_dir
.open_repository()
826 except bzrlib
.errors
.NoRepositoryPresent
:
827 shared_repo
= shared_dir
.create_repository(shared
=True)
830 clone_path
= os
.path
.join(dirname
, 'clone')
831 if not os
.path
.exists(clone_path
):
834 # check and remove old organization
836 bdir
= bzrlib
.bzrdir
.BzrDir
.open(clone_path
)
837 bdir
.destroy_repository()
838 except bzrlib
.errors
.NotBranchError
:
840 except bzrlib
.errors
.NoRepositoryPresent
:
844 repo
= origin
.open_repository()
845 if not repo
.user_transport
.listable():
846 # this repository is not usable for us
847 raise bzrlib
.errors
.NoRepositoryPresent(repo
.bzrdir
)
848 except bzrlib
.errors
.NoRepositoryPresent
:
852 remote_branch
= origin
.open_branch()
855 peers
[name
] = remote_branch
.base
856 branch
= get_remote_branch(origin
, remote_branch
, name
)
858 branch
= remote_branch
860 branches
[name
] = branch
.base
862 return branch
.repository
866 wanted
= get_config('remote-bzr.branches').rstrip().split(', ')
868 wanted
= [e
for e
in wanted
if e
]
870 for name
, remote_branch
in find_branches(repo
, wanted
):
873 peers
[name
] = remote_branch
.base
874 branch
= get_remote_branch(origin
, remote_branch
, name
)
876 branch
= remote_branch
878 branches
[name
] = branch
.base
882 def fix_path(alias
, orig_url
):
883 url
= urlparse
.urlparse(orig_url
, 'file')
884 if url
.scheme
!= 'file' or os
.path
.isabs(url
.path
):
886 abs_url
= urlparse
.urljoin("%s/" % os
.getcwd(), orig_url
)
887 cmd
= ['git', 'config', 'remote.%s.url' % alias
, "bzr::%s" % abs_url
]
891 global marks
, prefix
, gitdir
, dirname
892 global tags
, filenodes
897 global branches
, peers
913 alias
= hashlib
.sha1(alias
).hexdigest()
917 prefix
= 'refs/bzr/%s' % alias
918 gitdir
= os
.environ
['GIT_DIR']
919 dirname
= os
.path
.join(gitdir
, 'bzr', alias
)
924 if not os
.path
.exists(dirname
):
927 bzrlib
.ui
.ui_factory
.be_quiet(True)
929 repo
= get_repo(url
, alias
)
931 marks_path
= os
.path
.join(dirname
, 'marks-int')
932 marks
= Marks(marks_path
)
934 parser
= Parser(repo
)
936 if parser
.check('capabilities'):
937 do_capabilities(parser
)
938 elif parser
.check('list'):
940 elif parser
.check('import'):
942 elif parser
.check('export'):
945 die('unhandled command: %s' % line
)
954 shutil
.rmtree(dirname
)
957 sys
.exit(main(sys
.argv
))