remote-bzr: fix utf-8 support for fetching
[git/jnareb-git.git] / contrib / remote-helpers / git-remote-bzr
blob55ebf195bebc18bc4afd98e17e6fb96af5510fab
1 #!/usr/bin/env python
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
11 # For example:
12 # % git clone bzr::$HOME/myrepo
13 # or
14 # % git clone bzr::lp:myrepo
17 import sys
19 import bzrlib
20 if hasattr(bzrlib, "initialize"):
21 bzrlib.initialize()
23 import bzrlib.plugin
24 bzrlib.plugin.load_plugins()
26 import bzrlib.generate_ids
27 import bzrlib.transport
29 import sys
30 import os
31 import json
32 import re
33 import StringIO
35 NAME_RE = re.compile('^([^<>]+)')
36 AUTHOR_RE = re.compile('^([^<>]+?)? ?<([^<>]*)>$')
37 RAW_AUTHOR_RE = re.compile('^(\w+) (.+)? <(.*)> (\d+) ([+-]\d+)')
39 def die(msg, *args):
40 sys.stderr.write('ERROR: %s\n' % (msg % args))
41 sys.exit(1)
43 def warn(msg, *args):
44 sys.stderr.write('WARNING: %s\n' % (msg % args))
46 def gittz(tz):
47 return '%+03d%02d' % (tz / 3600, tz % 3600 / 60)
49 class Marks:
51 def __init__(self, path):
52 self.path = path
53 self.tips = {}
54 self.marks = {}
55 self.rev_marks = {}
56 self.last_mark = 0
57 self.load()
59 def load(self):
60 if not os.path.exists(self.path):
61 return
63 tmp = json.load(open(self.path))
64 self.tips = tmp['tips']
65 self.marks = tmp['marks']
66 self.last_mark = tmp['last-mark']
68 for rev, mark in self.marks.iteritems():
69 self.rev_marks[mark] = rev
71 def dict(self):
72 return { 'tips': self.tips, 'marks': self.marks, 'last-mark' : self.last_mark }
74 def store(self):
75 json.dump(self.dict(), open(self.path, 'w'))
77 def __str__(self):
78 return str(self.dict())
80 def from_rev(self, rev):
81 return self.marks[rev]
83 def to_rev(self, mark):
84 return self.rev_marks[mark]
86 def next_mark(self):
87 self.last_mark += 1
88 return self.last_mark
90 def get_mark(self, rev):
91 self.last_mark += 1
92 self.marks[rev] = self.last_mark
93 return self.last_mark
95 def is_marked(self, rev):
96 return self.marks.has_key(rev)
98 def new_mark(self, rev, mark):
99 self.marks[rev] = mark
100 self.rev_marks[mark] = rev
101 self.last_mark = mark
103 def get_tip(self, branch):
104 return self.tips.get(branch, None)
106 def set_tip(self, branch, tip):
107 self.tips[branch] = tip
109 class Parser:
111 def __init__(self, repo):
112 self.repo = repo
113 self.line = self.get_line()
115 def get_line(self):
116 return sys.stdin.readline().strip()
118 def __getitem__(self, i):
119 return self.line.split()[i]
121 def check(self, word):
122 return self.line.startswith(word)
124 def each_block(self, separator):
125 while self.line != separator:
126 yield self.line
127 self.line = self.get_line()
129 def __iter__(self):
130 return self.each_block('')
132 def next(self):
133 self.line = self.get_line()
134 if self.line == 'done':
135 self.line = None
137 def get_mark(self):
138 i = self.line.index(':') + 1
139 return int(self.line[i:])
141 def get_data(self):
142 if not self.check('data'):
143 return None
144 i = self.line.index(' ') + 1
145 size = int(self.line[i:])
146 return sys.stdin.read(size)
148 def get_author(self):
149 m = RAW_AUTHOR_RE.match(self.line)
150 if not m:
151 return None
152 _, name, email, date, tz = m.groups()
153 committer = '%s <%s>' % (name, email)
154 tz = int(tz)
155 tz = ((tz / 100) * 3600) + ((tz % 100) * 60)
156 return (committer, int(date), tz)
158 def rev_to_mark(rev):
159 global marks
160 return marks.from_rev(rev)
162 def mark_to_rev(mark):
163 global marks
164 return marks.to_rev(mark)
166 def fixup_user(user):
167 name = mail = None
168 user = user.replace('"', '')
169 m = AUTHOR_RE.match(user)
170 if m:
171 name = m.group(1)
172 mail = m.group(2).strip()
173 else:
174 m = NAME_RE.match(user)
175 if m:
176 name = m.group(1).strip()
178 return '%s <%s>' % (name, mail)
180 def get_filechanges(cur, prev):
181 modified = {}
182 removed = {}
184 changes = cur.changes_from(prev)
186 def u(s):
187 return s.encode('utf-8')
189 for path, fid, kind in changes.added:
190 modified[u(path)] = fid
191 for path, fid, kind in changes.removed:
192 removed[u(path)] = None
193 for path, fid, kind, mod, _ in changes.modified:
194 modified[u(path)] = fid
195 for oldpath, newpath, fid, kind, mod, _ in changes.renamed:
196 removed[u(oldpath)] = None
197 if kind == 'directory':
198 lst = cur.list_files(from_dir=newpath, recursive=True)
199 for path, file_class, kind, fid, entry in lst:
200 if kind != 'directory':
201 modified[u(newpath + '/' + path)] = fid
202 else:
203 modified[u(newpath)] = fid
205 return modified, removed
207 def export_files(tree, files):
208 global marks, filenodes
210 final = []
211 for path, fid in files.iteritems():
212 kind = tree.kind(fid)
214 h = tree.get_file_sha1(fid)
216 if kind == 'symlink':
217 d = tree.get_symlink_target(fid)
218 mode = '120000'
219 elif kind == 'file':
221 if tree.is_executable(fid):
222 mode = '100755'
223 else:
224 mode = '100644'
226 # is the blog already exported?
227 if h in filenodes:
228 mark = filenodes[h]
229 final.append((mode, mark, path))
230 continue
232 d = tree.get_file_text(fid)
233 elif kind == 'directory':
234 continue
235 else:
236 die("Unhandled kind '%s' for path '%s'" % (kind, path))
238 mark = marks.next_mark()
239 filenodes[h] = mark
241 print "blob"
242 print "mark :%u" % mark
243 print "data %d" % len(d)
244 print d
246 final.append((mode, mark, path))
248 return final
250 def export_branch(branch, name):
251 global prefix, dirname
253 ref = '%s/heads/%s' % (prefix, name)
254 tip = marks.get_tip(name)
256 repo = branch.repository
257 repo.lock_read()
258 revs = branch.iter_merge_sorted_revisions(None, tip, 'exclude', 'forward')
259 count = 0
261 revs = [revid for revid, _, _, _ in revs if not marks.is_marked(revid)]
263 for revid in revs:
265 rev = repo.get_revision(revid)
267 parents = rev.parent_ids
268 time = rev.timestamp
269 tz = rev.timezone
270 committer = rev.committer.encode('utf-8')
271 committer = "%s %u %s" % (fixup_user(committer), time, gittz(tz))
272 authors = rev.get_apparent_authors()
273 if authors:
274 author = authors[0].encode('utf-8')
275 author = "%s %u %s" % (fixup_user(author), time, gittz(tz))
276 else:
277 author = committer
278 msg = rev.message.encode('utf-8')
280 msg += '\n'
282 if len(parents) == 0:
283 parent = bzrlib.revision.NULL_REVISION
284 else:
285 parent = parents[0]
287 cur_tree = repo.revision_tree(revid)
288 prev = repo.revision_tree(parent)
289 modified, removed = get_filechanges(cur_tree, prev)
291 modified_final = export_files(cur_tree, modified)
293 if len(parents) == 0:
294 print 'reset %s' % ref
296 print "commit %s" % ref
297 print "mark :%d" % (marks.get_mark(revid))
298 print "author %s" % (author)
299 print "committer %s" % (committer)
300 print "data %d" % (len(msg))
301 print msg
303 for i, p in enumerate(parents):
304 try:
305 m = rev_to_mark(p)
306 except KeyError:
307 # ghost?
308 continue
309 if i == 0:
310 print "from :%s" % m
311 else:
312 print "merge :%s" % m
314 for f in removed:
315 print "D %s" % (f,)
316 for f in modified_final:
317 print "M %s :%u %s" % f
318 print
320 count += 1
321 if (count % 100 == 0):
322 print "progress revision %s (%d/%d)" % (revid, count, len(revs))
323 print "#############################################################"
325 repo.unlock()
327 revid = branch.last_revision()
329 # make sure the ref is updated
330 print "reset %s" % ref
331 print "from :%u" % rev_to_mark(revid)
332 print
334 marks.set_tip(name, revid)
336 def export_tag(repo, name):
337 global tags
338 try:
339 print "reset refs/tags/%s" % name
340 print "from :%u" % rev_to_mark(tags[name])
341 print
342 except KeyError:
343 warn("TODO: fetch tag '%s'" % name)
345 def do_import(parser):
346 global dirname
348 branch = parser.repo
349 path = os.path.join(dirname, 'marks-git')
351 print "feature done"
352 if os.path.exists(path):
353 print "feature import-marks=%s" % path
354 print "feature export-marks=%s" % path
355 sys.stdout.flush()
357 while parser.check('import'):
358 ref = parser[1]
359 if ref.startswith('refs/heads/'):
360 name = ref[len('refs/heads/'):]
361 export_branch(branch, name)
362 if ref.startswith('refs/tags/'):
363 name = ref[len('refs/tags/'):]
364 export_tag(branch, name)
365 parser.next()
367 print 'done'
369 sys.stdout.flush()
371 def parse_blob(parser):
372 global blob_marks
374 parser.next()
375 mark = parser.get_mark()
376 parser.next()
377 data = parser.get_data()
378 blob_marks[mark] = data
379 parser.next()
381 class CustomTree():
383 def __init__(self, repo, revid, parents, files):
384 global files_cache
386 self.repo = repo
387 self.revid = revid
388 self.parents = parents
389 self.updates = {}
391 def copy_tree(revid):
392 files = files_cache[revid] = {}
393 tree = repo.repository.revision_tree(revid)
394 repo.lock_read()
395 try:
396 for path, entry in tree.iter_entries_by_dir():
397 files[path] = entry.file_id
398 finally:
399 repo.unlock()
400 return files
402 if len(parents) == 0:
403 self.base_id = bzrlib.revision.NULL_REVISION
404 self.base_files = {}
405 else:
406 self.base_id = parents[0]
407 self.base_files = files_cache.get(self.base_id, None)
408 if not self.base_files:
409 self.base_files = copy_tree(self.base_id)
411 self.files = files_cache[revid] = self.base_files.copy()
413 for path, f in files.iteritems():
414 fid = self.files.get(path, None)
415 if not fid:
416 fid = bzrlib.generate_ids.gen_file_id(path)
417 f['path'] = path
418 self.updates[fid] = f
420 def last_revision(self):
421 return self.base_id
423 def iter_changes(self):
424 changes = []
426 def get_parent(dirname, basename):
427 parent_fid = self.base_files.get(dirname, None)
428 if parent_fid:
429 return parent_fid
430 parent_fid = self.files.get(dirname, None)
431 if parent_fid:
432 return parent_fid
433 if basename == '':
434 return None
435 fid = bzrlib.generate_ids.gen_file_id(path)
436 d = add_entry(fid, dirname, 'directory')
437 return fid
439 def add_entry(fid, path, kind, mode = None):
440 dirname, basename = os.path.split(path)
441 parent_fid = get_parent(dirname, basename)
443 executable = False
444 if mode == '100755':
445 executable = True
446 elif mode == '120000':
447 kind = 'symlink'
449 change = (fid,
450 (None, path),
451 True,
452 (False, True),
453 (None, parent_fid),
454 (None, basename),
455 (None, kind),
456 (None, executable))
457 self.files[path] = change[0]
458 changes.append(change)
459 return change
461 def update_entry(fid, path, kind, mode = None):
462 dirname, basename = os.path.split(path)
463 parent_fid = get_parent(dirname, basename)
465 executable = False
466 if mode == '100755':
467 executable = True
468 elif mode == '120000':
469 kind = 'symlink'
471 change = (fid,
472 (path, path),
473 True,
474 (True, True),
475 (None, parent_fid),
476 (None, basename),
477 (None, kind),
478 (None, executable))
479 self.files[path] = change[0]
480 changes.append(change)
481 return change
483 def remove_entry(fid, path, kind):
484 dirname, basename = os.path.split(path)
485 parent_fid = get_parent(dirname, basename)
486 change = (fid,
487 (path, None),
488 True,
489 (True, False),
490 (parent_fid, None),
491 (None, None),
492 (None, None),
493 (None, None))
494 del self.files[path]
495 changes.append(change)
496 return change
498 for fid, f in self.updates.iteritems():
499 path = f['path']
501 if 'deleted' in f:
502 remove_entry(fid, path, 'file')
503 continue
505 if path in self.base_files:
506 update_entry(fid, path, 'file', f['mode'])
507 else:
508 add_entry(fid, path, 'file', f['mode'])
510 return changes
512 def get_file_with_stat(self, file_id, path=None):
513 return (StringIO.StringIO(self.updates[file_id]['data']), None)
515 def get_symlink_target(self, file_id):
516 return self.updates[file_id]['data']
518 def c_style_unescape(string):
519 if string[0] == string[-1] == '"':
520 return string.decode('string-escape')[1:-1]
521 return string
523 def parse_commit(parser):
524 global marks, blob_marks, bmarks, parsed_refs
525 global mode
527 parents = []
529 ref = parser[1]
530 parser.next()
532 if ref != 'refs/heads/master':
533 die("bzr doesn't support multiple branches; use 'master'")
535 commit_mark = parser.get_mark()
536 parser.next()
537 author = parser.get_author()
538 parser.next()
539 committer = parser.get_author()
540 parser.next()
541 data = parser.get_data()
542 parser.next()
543 if parser.check('from'):
544 parents.append(parser.get_mark())
545 parser.next()
546 while parser.check('merge'):
547 parents.append(parser.get_mark())
548 parser.next()
550 files = {}
552 for line in parser:
553 if parser.check('M'):
554 t, m, mark_ref, path = line.split(' ', 3)
555 mark = int(mark_ref[1:])
556 f = { 'mode' : m, 'data' : blob_marks[mark] }
557 elif parser.check('D'):
558 t, path = line.split(' ')
559 f = { 'deleted' : True }
560 else:
561 die('Unknown file command: %s' % line)
562 path = c_style_unescape(path).decode('utf-8')
563 files[path] = f
565 repo = parser.repo
567 committer, date, tz = committer
568 parents = [str(mark_to_rev(p)) for p in parents]
569 revid = bzrlib.generate_ids.gen_revision_id(committer, date)
570 props = {}
571 props['branch-nick'] = repo.nick
573 mtree = CustomTree(repo, revid, parents, files)
574 changes = mtree.iter_changes()
576 repo.lock_write()
577 try:
578 builder = repo.get_commit_builder(parents, None, date, tz, committer, props, revid)
579 try:
580 list(builder.record_iter_changes(mtree, mtree.last_revision(), changes))
581 builder.finish_inventory()
582 builder.commit(data.decode('utf-8', 'replace'))
583 except Exception, e:
584 builder.abort()
585 raise
586 finally:
587 repo.unlock()
589 parsed_refs[ref] = revid
590 marks.new_mark(revid, commit_mark)
592 def parse_reset(parser):
593 global parsed_refs
595 ref = parser[1]
596 parser.next()
598 if ref != 'refs/heads/master':
599 die("bzr doesn't support multiple branches; use 'master'")
601 # ugh
602 if parser.check('commit'):
603 parse_commit(parser)
604 return
605 if not parser.check('from'):
606 return
607 from_mark = parser.get_mark()
608 parser.next()
610 parsed_refs[ref] = mark_to_rev(from_mark)
612 def do_export(parser):
613 global parsed_refs, dirname, peer
615 parser.next()
617 for line in parser.each_block('done'):
618 if parser.check('blob'):
619 parse_blob(parser)
620 elif parser.check('commit'):
621 parse_commit(parser)
622 elif parser.check('reset'):
623 parse_reset(parser)
624 elif parser.check('tag'):
625 pass
626 elif parser.check('feature'):
627 pass
628 else:
629 die('unhandled export command: %s' % line)
631 repo = parser.repo
633 for ref, revid in parsed_refs.iteritems():
634 if ref == 'refs/heads/master':
635 repo.generate_revision_history(revid, marks.get_tip('master'))
636 revno, revid = repo.last_revision_info()
637 if peer:
638 if hasattr(peer, "import_last_revision_info_and_tags"):
639 peer.import_last_revision_info_and_tags(repo, revno, revid)
640 else:
641 peer.import_last_revision_info(repo.repository, revno, revid)
642 else:
643 wt = repo.bzrdir.open_workingtree()
644 wt.update()
645 print "ok %s" % ref
646 print
648 def do_capabilities(parser):
649 global dirname
651 print "import"
652 print "export"
653 print "refspec refs/heads/*:%s/heads/*" % prefix
655 path = os.path.join(dirname, 'marks-git')
657 if os.path.exists(path):
658 print "*import-marks %s" % path
659 print "*export-marks %s" % path
661 print
663 def do_list(parser):
664 global tags
665 print "? refs/heads/%s" % 'master'
667 history = parser.repo.revision_history()
668 for tag, revid in parser.repo.tags.get_tag_dict().items():
669 if revid not in history:
670 continue
671 print "? refs/tags/%s" % tag
672 tags[tag] = revid
673 print "@refs/heads/%s HEAD" % 'master'
674 print
676 def get_repo(url, alias):
677 global dirname, peer
679 origin = bzrlib.bzrdir.BzrDir.open(url)
680 branch = origin.open_branch()
682 if not isinstance(origin.transport, bzrlib.transport.local.LocalTransport):
683 clone_path = os.path.join(dirname, 'clone')
684 remote_branch = branch
685 if os.path.exists(clone_path):
686 # pull
687 d = bzrlib.bzrdir.BzrDir.open(clone_path)
688 branch = d.open_branch()
689 result = branch.pull(remote_branch, [], None, False)
690 else:
691 # clone
692 d = origin.sprout(clone_path, None,
693 hardlink=True, create_tree_if_local=False,
694 source_branch=remote_branch)
695 branch = d.open_branch()
696 branch.bind(remote_branch)
698 peer = remote_branch
699 else:
700 peer = None
702 return branch
704 def main(args):
705 global marks, prefix, dirname
706 global tags, filenodes
707 global blob_marks
708 global parsed_refs
709 global files_cache
711 alias = args[1]
712 url = args[2]
714 prefix = 'refs/bzr/%s' % alias
715 tags = {}
716 filenodes = {}
717 blob_marks = {}
718 parsed_refs = {}
719 files_cache = {}
721 gitdir = os.environ['GIT_DIR']
722 dirname = os.path.join(gitdir, 'bzr', alias)
724 if not os.path.exists(dirname):
725 os.makedirs(dirname)
727 repo = get_repo(url, alias)
729 marks_path = os.path.join(dirname, 'marks-int')
730 marks = Marks(marks_path)
732 parser = Parser(repo)
733 for line in parser:
734 if parser.check('capabilities'):
735 do_capabilities(parser)
736 elif parser.check('list'):
737 do_list(parser)
738 elif parser.check('import'):
739 do_import(parser)
740 elif parser.check('export'):
741 do_export(parser)
742 else:
743 die('unhandled command: %s' % line)
744 sys.stdout.flush()
746 marks.store()
748 sys.exit(main(sys.argv))