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
30 import bzrlib
.urlutils
37 import atexit
, shutil
, hashlib
, urlparse
, subprocess
39 NAME_RE
= re
.compile('^([^<>]+)')
40 AUTHOR_RE
= re
.compile('^([^<>]+?)? ?<([^<>]*)>$')
41 EMAIL_RE
= re
.compile('^([^<>]+[^ \\\t<>])?\\b(?:[ \\t<>]*?)\\b([^ \\t<>]+@[^ \\t<>]+)')
42 RAW_AUTHOR_RE
= re
.compile('^(\w+) (.+)? <(.*)> (\d+) ([+-]\d+)')
45 sys
.stderr
.write('ERROR: %s\n' % (msg
% args
))
49 sys
.stderr
.write('WARNING: %s\n' % (msg
% args
))
52 return '%+03d%02d' % (tz
/ 3600, tz
% 3600 / 60)
56 def __init__(self
, path
):
65 if not os
.path
.exists(self
.path
):
68 tmp
= json
.load(open(self
.path
))
69 self
.tips
= tmp
['tips']
70 self
.marks
= tmp
['marks']
71 self
.last_mark
= tmp
['last-mark']
73 for rev
, mark
in self
.marks
.iteritems():
74 self
.rev_marks
[mark
] = rev
77 return { 'tips': self
.tips
, 'marks': self
.marks
, 'last-mark' : self
.last_mark
}
80 json
.dump(self
.dict(), open(self
.path
, 'w'))
83 return str(self
.dict())
85 def from_rev(self
, rev
):
86 return self
.marks
[rev
]
88 def to_rev(self
, mark
):
89 return self
.rev_marks
[mark
]
95 def get_mark(self
, rev
):
97 self
.marks
[rev
] = self
.last_mark
100 def is_marked(self
, rev
):
101 return rev
in self
.marks
103 def new_mark(self
, rev
, mark
):
104 self
.marks
[rev
] = mark
105 self
.rev_marks
[mark
] = rev
106 self
.last_mark
= mark
108 def get_tip(self
, branch
):
109 return self
.tips
.get(branch
, None)
111 def set_tip(self
, branch
, tip
):
112 self
.tips
[branch
] = tip
116 def __init__(self
, repo
):
118 self
.line
= self
.get_line()
121 return sys
.stdin
.readline().strip()
123 def __getitem__(self
, i
):
124 return self
.line
.split()[i
]
126 def check(self
, word
):
127 return self
.line
.startswith(word
)
129 def each_block(self
, separator
):
130 while self
.line
!= separator
:
132 self
.line
= self
.get_line()
135 return self
.each_block('')
138 self
.line
= self
.get_line()
139 if self
.line
== 'done':
143 i
= self
.line
.index(':') + 1
144 return int(self
.line
[i
:])
147 if not self
.check('data'):
149 i
= self
.line
.index(' ') + 1
150 size
= int(self
.line
[i
:])
151 return sys
.stdin
.read(size
)
153 def get_author(self
):
154 m
= RAW_AUTHOR_RE
.match(self
.line
)
157 _
, name
, email
, date
, tz
= m
.groups()
158 committer
= '%s <%s>' % (name
, email
)
160 tz
= ((tz
/ 100) * 3600) + ((tz
% 100) * 60)
161 return (committer
, int(date
), tz
)
163 def rev_to_mark(rev
):
165 return marks
.from_rev(rev
)
167 def mark_to_rev(mark
):
169 return marks
.to_rev(mark
)
171 def fixup_user(user
):
173 user
= user
.replace('"', '')
174 m
= AUTHOR_RE
.match(user
)
177 mail
= m
.group(2).strip()
179 m
= EMAIL_RE
.match(user
)
184 m
= NAME_RE
.match(user
)
186 name
= m
.group(1).strip()
193 return '%s <%s>' % (name
, mail
)
195 def get_filechanges(cur
, prev
):
199 changes
= cur
.changes_from(prev
)
202 return s
.encode('utf-8')
204 for path
, fid
, kind
in changes
.added
:
205 modified
[u(path
)] = fid
206 for path
, fid
, kind
in changes
.removed
:
207 removed
[u(path
)] = None
208 for path
, fid
, kind
, mod
, _
in changes
.modified
:
209 modified
[u(path
)] = fid
210 for oldpath
, newpath
, fid
, kind
, mod
, _
in changes
.renamed
:
211 removed
[u(oldpath
)] = None
212 if kind
== 'directory':
213 lst
= cur
.list_files(from_dir
=newpath
, recursive
=True)
214 for path
, file_class
, kind
, fid
, entry
in lst
:
215 if kind
!= 'directory':
216 modified
[u(newpath
+ '/' + path
)] = fid
218 modified
[u(newpath
)] = fid
220 return modified
, removed
222 def export_files(tree
, files
):
223 global marks
, filenodes
226 for path
, fid
in files
.iteritems():
227 kind
= tree
.kind(fid
)
229 h
= tree
.get_file_sha1(fid
)
231 if kind
== 'symlink':
232 d
= tree
.get_symlink_target(fid
)
236 if tree
.is_executable(fid
):
241 # is the blob already exported?
244 final
.append((mode
, mark
, path
))
247 d
= tree
.get_file_text(fid
)
248 elif kind
== 'directory':
251 die("Unhandled kind '%s' for path '%s'" % (kind
, path
))
253 mark
= marks
.next_mark()
257 print "mark :%u" % mark
258 print "data %d" % len(d
)
261 final
.append((mode
, mark
, path
))
265 def export_branch(repo
, name
):
268 ref
= '%s/heads/%s' % (prefix
, name
)
269 tip
= marks
.get_tip(name
)
271 branch
= branches
[name
]
272 repo
= branch
.repository
275 revs
= branch
.iter_merge_sorted_revisions(None, tip
, 'exclude', 'forward')
278 revs
= [revid
for revid
, _
, _
, _
in revs
if not marks
.is_marked(revid
)]
282 rev
= repo
.get_revision(revid
)
284 parents
= rev
.parent_ids
287 committer
= rev
.committer
.encode('utf-8')
288 committer
= "%s %u %s" % (fixup_user(committer
), time
, gittz(tz
))
289 authors
= rev
.get_apparent_authors()
291 author
= authors
[0].encode('utf-8')
292 author
= "%s %u %s" % (fixup_user(author
), time
, gittz(tz
))
295 msg
= rev
.message
.encode('utf-8')
299 if len(parents
) == 0:
300 parent
= bzrlib
.revision
.NULL_REVISION
304 cur_tree
= repo
.revision_tree(revid
)
305 prev
= repo
.revision_tree(parent
)
306 modified
, removed
= get_filechanges(cur_tree
, prev
)
308 modified_final
= export_files(cur_tree
, modified
)
310 if len(parents
) == 0:
311 print 'reset %s' % ref
313 print "commit %s" % ref
314 print "mark :%d" % (marks
.get_mark(revid
))
315 print "author %s" % (author
)
316 print "committer %s" % (committer
)
317 print "data %d" % (len(msg
))
320 for i
, p
in enumerate(parents
):
329 print "merge :%s" % m
333 for f
in modified_final
:
334 print "M %s :%u %s" % f
338 if (count
% 100 == 0):
339 print "progress revision %s '%s' (%d/%d)" % (revid
, name
, count
, len(revs
))
340 print "#############################################################"
344 revid
= branch
.last_revision()
346 # make sure the ref is updated
347 print "reset %s" % ref
348 print "from :%u" % rev_to_mark(revid
)
351 marks
.set_tip(name
, revid
)
353 def export_tag(repo
, name
):
356 ref
= '%s/tags/%s' % (prefix
, name
)
357 print "reset %s" % ref
358 print "from :%u" % rev_to_mark(tags
[name
])
361 def do_import(parser
):
365 path
= os
.path
.join(dirname
, 'marks-git')
368 if os
.path
.exists(path
):
369 print "feature import-marks=%s" % path
370 print "feature export-marks=%s" % path
371 print "feature force"
374 while parser
.check('import'):
376 if ref
.startswith('refs/heads/'):
377 name
= ref
[len('refs/heads/'):]
378 export_branch(repo
, name
)
379 if ref
.startswith('refs/tags/'):
380 name
= ref
[len('refs/tags/'):]
381 export_tag(repo
, name
)
388 def parse_blob(parser
):
392 mark
= parser
.get_mark()
394 data
= parser
.get_data()
395 blob_marks
[mark
] = data
400 def __init__(self
, branch
, revid
, parents
, files
):
406 def copy_tree(revid
):
407 files
= files_cache
[revid
] = {}
409 tree
= branch
.repository
.revision_tree(revid
)
411 for path
, entry
in tree
.iter_entries_by_dir():
412 files
[path
] = [entry
.file_id
, None]
417 if len(parents
) == 0:
418 self
.base_id
= bzrlib
.revision
.NULL_REVISION
421 self
.base_id
= parents
[0]
422 self
.base_files
= files_cache
.get(self
.base_id
, None)
423 if not self
.base_files
:
424 self
.base_files
= copy_tree(self
.base_id
)
426 self
.files
= files_cache
[revid
] = self
.base_files
.copy()
429 for path
, data
in self
.files
.iteritems():
431 self
.rev_files
[fid
] = [path
, mark
]
433 for path
, f
in files
.iteritems():
434 fid
, mark
= self
.files
.get(path
, [None, None])
436 fid
= bzrlib
.generate_ids
.gen_file_id(path
)
438 self
.rev_files
[fid
] = [path
, mark
]
439 self
.updates
[fid
] = f
441 def last_revision(self
):
444 def iter_changes(self
):
447 def get_parent(dirname
, basename
):
448 parent_fid
, mark
= self
.base_files
.get(dirname
, [None, None])
451 parent_fid
, mark
= self
.files
.get(dirname
, [None, None])
456 fid
= bzrlib
.generate_ids
.gen_file_id(path
)
457 add_entry(fid
, dirname
, 'directory')
460 def add_entry(fid
, path
, kind
, mode
= None):
461 dirname
, basename
= os
.path
.split(path
)
462 parent_fid
= get_parent(dirname
, basename
)
467 elif mode
== '120000':
478 self
.files
[path
] = [change
[0], None]
479 changes
.append(change
)
481 def update_entry(fid
, path
, kind
, mode
= None):
482 dirname
, basename
= os
.path
.split(path
)
483 parent_fid
= get_parent(dirname
, basename
)
488 elif mode
== '120000':
499 self
.files
[path
] = [change
[0], None]
500 changes
.append(change
)
502 def remove_entry(fid
, path
, kind
):
503 dirname
, basename
= os
.path
.split(path
)
504 parent_fid
= get_parent(dirname
, basename
)
514 changes
.append(change
)
516 for fid
, f
in self
.updates
.iteritems():
520 remove_entry(fid
, path
, 'file')
523 if path
in self
.base_files
:
524 update_entry(fid
, path
, 'file', f
['mode'])
526 add_entry(fid
, path
, 'file', f
['mode'])
528 self
.files
[path
][1] = f
['mark']
529 self
.rev_files
[fid
][1] = f
['mark']
533 def get_content(self
, file_id
):
534 path
, mark
= self
.rev_files
[file_id
]
536 return blob_marks
[mark
]
539 tree
= self
.branch
.repository
.revision_tree(self
.base_id
)
540 return tree
.get_file_text(file_id
)
542 def get_file_with_stat(self
, file_id
, path
=None):
543 content
= self
.get_content(file_id
)
544 return (StringIO
.StringIO(content
), None)
546 def get_symlink_target(self
, file_id
):
547 return self
.get_content(file_id
)
549 def id2path(self
, file_id
):
550 path
, mark
= self
.rev_files
[file_id
]
553 def c_style_unescape(string
):
554 if string
[0] == string
[-1] == '"':
555 return string
.decode('string-escape')[1:-1]
558 def parse_commit(parser
):
559 global marks
, blob_marks
, parsed_refs
567 if ref
.startswith('refs/heads/'):
568 name
= ref
[len('refs/heads/'):]
569 branch
= branches
[name
]
573 commit_mark
= parser
.get_mark()
575 author
= parser
.get_author()
577 committer
= parser
.get_author()
579 data
= parser
.get_data()
581 if parser
.check('from'):
582 parents
.append(parser
.get_mark())
584 while parser
.check('merge'):
585 parents
.append(parser
.get_mark())
588 # fast-export adds an extra newline
595 if parser
.check('M'):
596 t
, m
, mark_ref
, path
= line
.split(' ', 3)
597 mark
= int(mark_ref
[1:])
598 f
= { 'mode' : m
, 'mark' : mark
}
599 elif parser
.check('D'):
600 t
, path
= line
.split(' ')
601 f
= { 'deleted' : True }
603 die('Unknown file command: %s' % line
)
604 path
= c_style_unescape(path
).decode('utf-8')
607 committer
, date
, tz
= committer
608 parents
= [str(mark_to_rev(p
)) for p
in parents
]
609 revid
= bzrlib
.generate_ids
.gen_revision_id(committer
, date
)
611 props
['branch-nick'] = branch
.nick
613 mtree
= CustomTree(branch
, revid
, parents
, files
)
614 changes
= mtree
.iter_changes()
618 builder
= branch
.get_commit_builder(parents
, None, date
, tz
, committer
, props
, revid
)
620 list(builder
.record_iter_changes(mtree
, mtree
.last_revision(), changes
))
621 builder
.finish_inventory()
622 builder
.commit(data
.decode('utf-8', 'replace'))
629 parsed_refs
[ref
] = revid
630 marks
.new_mark(revid
, commit_mark
)
632 def parse_reset(parser
):
639 if parser
.check('commit'):
642 if not parser
.check('from'):
644 from_mark
= parser
.get_mark()
647 parsed_refs
[ref
] = mark_to_rev(from_mark
)
649 def do_export(parser
):
650 global parsed_refs
, dirname
654 for line
in parser
.each_block('done'):
655 if parser
.check('blob'):
657 elif parser
.check('commit'):
659 elif parser
.check('reset'):
661 elif parser
.check('tag'):
663 elif parser
.check('feature'):
666 die('unhandled export command: %s' % line
)
668 for ref
, revid
in parsed_refs
.iteritems():
669 name
= ref
[len('refs/heads/'):]
670 branch
= branches
[name
]
671 branch
.generate_revision_history(revid
, marks
.get_tip(name
))
676 peer
.bzrdir
.push_branch(branch
, revision_id
=revid
)
677 except bzrlib
.errors
.DivergedBranches
:
678 print "error %s non-fast forward" % ref
682 wt
= branch
.bzrdir
.open_workingtree()
684 except bzrlib
.errors
.NoWorkingTree
:
691 def do_capabilities(parser
):
696 print "refspec refs/heads/*:%s/heads/*" % prefix
697 print "refspec refs/tags/*:%s/tags/*" % prefix
699 path
= os
.path
.join(dirname
, 'marks-git')
701 if os
.path
.exists(path
):
702 print "*import-marks %s" % path
703 print "*export-marks %s" % path
707 def ref_is_valid(name
):
708 return not True in [c
in name
for c
in '~^: \\']
715 for name
in branches
:
716 if not master_branch
:
718 print "? refs/heads/%s" % name
720 branch
= branches
[master_branch
]
722 for tag
, revid
in branch
.tags
.get_tag_dict().items():
724 branch
.revision_id_to_dotted_revno(revid
)
725 except bzrlib
.errors
.NoSuchRevision
:
727 if not ref_is_valid(tag
):
729 print "? refs/tags/%s" % tag
733 print "@refs/heads/%s HEAD" % master_branch
736 def get_remote_branch(origin
, remote_branch
, name
):
737 global dirname
, peers
739 branch_path
= os
.path
.join(dirname
, 'clone', name
)
740 if os
.path
.exists(branch_path
):
742 d
= bzrlib
.bzrdir
.BzrDir
.open(branch_path
)
743 branch
= d
.open_branch()
745 branch
.pull(remote_branch
, [], None, False)
746 except bzrlib
.errors
.DivergedBranches
:
747 # use remote branch for now
751 d
= origin
.sprout(branch_path
, None,
752 hardlink
=True, create_tree_if_local
=False,
753 force_new_repo
=False,
754 source_branch
=remote_branch
)
755 branch
= d
.open_branch()
759 def get_repo(url
, alias
):
760 global dirname
, peer
, branches
762 normal_url
= bzrlib
.urlutils
.normalize_url(url
)
763 origin
= bzrlib
.bzrdir
.BzrDir
.open(url
)
764 is_local
= isinstance(origin
.transport
, bzrlib
.transport
.local
.LocalTransport
)
766 shared_path
= os
.path
.join(gitdir
, 'bzr')
768 shared_dir
= bzrlib
.bzrdir
.BzrDir
.open(shared_path
)
769 except bzrlib
.errors
.NotBranchError
:
770 shared_dir
= bzrlib
.bzrdir
.BzrDir
.create(shared_path
)
772 shared_repo
= shared_dir
.open_repository()
773 except bzrlib
.errors
.NoRepositoryPresent
:
774 shared_repo
= shared_dir
.create_repository(shared
=True)
777 clone_path
= os
.path
.join(dirname
, 'clone')
778 if not os
.path
.exists(clone_path
):
782 repo
= origin
.open_repository()
783 except bzrlib
.errors
.NoRepositoryPresent
:
787 branch
= origin
.open_branch()
791 branches
[name
] = get_remote_branch(origin
, branch
, name
)
793 branches
[name
] = branch
795 return branch
.repository
799 for branch
in repo
.find_branches():
801 name
= repo
.user_transport
.relpath(branch
.base
)
802 name
= name
if name
!= '' else 'master'
803 name
= name
.replace('/', '+')
807 branches
[name
] = get_remote_branch(origin
, branch
, name
)
809 branches
[name
] = branch
813 def fix_path(alias
, orig_url
):
814 url
= urlparse
.urlparse(orig_url
, 'file')
815 if url
.scheme
!= 'file' or os
.path
.isabs(url
.path
):
817 abs_url
= urlparse
.urljoin("%s/" % os
.getcwd(), orig_url
)
818 cmd
= ['git', 'config', 'remote.%s.url' % alias
, "bzr::%s" % abs_url
]
822 global marks
, prefix
, gitdir
, dirname
823 global tags
, filenodes
828 global branches
, peers
844 alias
= hashlib
.sha1(alias
).hexdigest()
848 prefix
= 'refs/bzr/%s' % alias
849 gitdir
= os
.environ
['GIT_DIR']
850 dirname
= os
.path
.join(gitdir
, 'bzr', alias
)
855 if not os
.path
.exists(dirname
):
858 bzrlib
.ui
.ui_factory
.be_quiet(True)
860 repo
= get_repo(url
, alias
)
862 marks_path
= os
.path
.join(dirname
, 'marks-int')
863 marks
= Marks(marks_path
)
865 parser
= Parser(repo
)
867 if parser
.check('capabilities'):
868 do_capabilities(parser
)
869 elif parser
.check('list'):
871 elif parser
.check('import'):
873 elif parser
.check('export'):
876 die('unhandled command: %s' % line
)
885 shutil
.rmtree(dirname
)
888 sys
.exit(main(sys
.argv
))