remote-bzr: only update workingtree on local repos
[git.git] / contrib / remote-helpers / git-remote-bzr
blob9466cb9de1d0dbe7d6569d01d628eb52f549549a
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 for path, fid, kind in changes.added:
187 modified[path] = fid
188 for path, fid, kind in changes.removed:
189 removed[path] = None
190 for path, fid, kind, mod, _ in changes.modified:
191 modified[path] = fid
192 for oldpath, newpath, fid, kind, mod, _ in changes.renamed:
193 removed[oldpath] = None
194 if kind == 'directory':
195 lst = cur.list_files(from_dir=newpath, recursive=True)
196 for path, file_class, kind, fid, entry in lst:
197 if kind != 'directory':
198 modified[newpath + '/' + path] = fid
199 else:
200 modified[newpath] = fid
202 return modified, removed
204 def export_files(tree, files):
205 global marks, filenodes
207 final = []
208 for path, fid in files.iteritems():
209 kind = tree.kind(fid)
211 h = tree.get_file_sha1(fid)
213 if kind == 'symlink':
214 d = tree.get_symlink_target(fid)
215 mode = '120000'
216 elif kind == 'file':
218 if tree.is_executable(fid):
219 mode = '100755'
220 else:
221 mode = '100644'
223 # is the blog already exported?
224 if h in filenodes:
225 mark = filenodes[h]
226 final.append((mode, mark, path))
227 continue
229 d = tree.get_file_text(fid)
230 elif kind == 'directory':
231 continue
232 else:
233 die("Unhandled kind '%s' for path '%s'" % (kind, path))
235 mark = marks.next_mark()
236 filenodes[h] = mark
238 print "blob"
239 print "mark :%u" % mark
240 print "data %d" % len(d)
241 print d
243 final.append((mode, mark, path))
245 return final
247 def export_branch(branch, name):
248 global prefix, dirname
250 ref = '%s/heads/%s' % (prefix, name)
251 tip = marks.get_tip(name)
253 repo = branch.repository
254 repo.lock_read()
255 revs = branch.iter_merge_sorted_revisions(None, tip, 'exclude', 'forward')
256 count = 0
258 revs = [revid for revid, _, _, _ in revs if not marks.is_marked(revid)]
260 for revid in revs:
262 rev = repo.get_revision(revid)
264 parents = rev.parent_ids
265 time = rev.timestamp
266 tz = rev.timezone
267 committer = rev.committer.encode('utf-8')
268 committer = "%s %u %s" % (fixup_user(committer), time, gittz(tz))
269 authors = rev.get_apparent_authors()
270 if authors:
271 author = authors[0].encode('utf-8')
272 author = "%s %u %s" % (fixup_user(author), time, gittz(tz))
273 else:
274 author = committer
275 msg = rev.message.encode('utf-8')
277 msg += '\n'
279 if len(parents) == 0:
280 parent = bzrlib.revision.NULL_REVISION
281 else:
282 parent = parents[0]
284 cur_tree = repo.revision_tree(revid)
285 prev = repo.revision_tree(parent)
286 modified, removed = get_filechanges(cur_tree, prev)
288 modified_final = export_files(cur_tree, modified)
290 if len(parents) == 0:
291 print 'reset %s' % ref
293 print "commit %s" % ref
294 print "mark :%d" % (marks.get_mark(revid))
295 print "author %s" % (author)
296 print "committer %s" % (committer)
297 print "data %d" % (len(msg))
298 print msg
300 for i, p in enumerate(parents):
301 try:
302 m = rev_to_mark(p)
303 except KeyError:
304 # ghost?
305 continue
306 if i == 0:
307 print "from :%s" % m
308 else:
309 print "merge :%s" % m
311 for f in removed:
312 print "D %s" % (f,)
313 for f in modified_final:
314 print "M %s :%u %s" % f
315 print
317 count += 1
318 if (count % 100 == 0):
319 print "progress revision %s (%d/%d)" % (revid, count, len(revs))
320 print "#############################################################"
322 repo.unlock()
324 revid = branch.last_revision()
326 # make sure the ref is updated
327 print "reset %s" % ref
328 print "from :%u" % rev_to_mark(revid)
329 print
331 marks.set_tip(name, revid)
333 def export_tag(repo, name):
334 global tags
335 try:
336 print "reset refs/tags/%s" % name
337 print "from :%u" % rev_to_mark(tags[name])
338 print
339 except KeyError:
340 warn("TODO: fetch tag '%s'" % name)
342 def do_import(parser):
343 global dirname
345 branch = parser.repo
346 path = os.path.join(dirname, 'marks-git')
348 print "feature done"
349 if os.path.exists(path):
350 print "feature import-marks=%s" % path
351 print "feature export-marks=%s" % path
352 sys.stdout.flush()
354 while parser.check('import'):
355 ref = parser[1]
356 if ref.startswith('refs/heads/'):
357 name = ref[len('refs/heads/'):]
358 export_branch(branch, name)
359 if ref.startswith('refs/tags/'):
360 name = ref[len('refs/tags/'):]
361 export_tag(branch, name)
362 parser.next()
364 print 'done'
366 sys.stdout.flush()
368 def parse_blob(parser):
369 global blob_marks
371 parser.next()
372 mark = parser.get_mark()
373 parser.next()
374 data = parser.get_data()
375 blob_marks[mark] = data
376 parser.next()
378 class CustomTree():
380 def __init__(self, repo, revid, parents, files):
381 global files_cache
383 self.repo = repo
384 self.revid = revid
385 self.parents = parents
386 self.updates = {}
388 def copy_tree(revid):
389 files = files_cache[revid] = {}
390 tree = repo.repository.revision_tree(revid)
391 repo.lock_read()
392 try:
393 for path, entry in tree.iter_entries_by_dir():
394 files[path] = entry.file_id
395 finally:
396 repo.unlock()
397 return files
399 if len(parents) == 0:
400 self.base_id = bzrlib.revision.NULL_REVISION
401 self.base_files = {}
402 else:
403 self.base_id = parents[0]
404 self.base_files = files_cache.get(self.base_id, None)
405 if not self.base_files:
406 self.base_files = copy_tree(self.base_id)
408 self.files = files_cache[revid] = self.base_files.copy()
410 for path, f in files.iteritems():
411 fid = self.files.get(path, None)
412 if not fid:
413 fid = bzrlib.generate_ids.gen_file_id(path)
414 f['path'] = path
415 self.updates[fid] = f
417 def last_revision(self):
418 return self.base_id
420 def iter_changes(self):
421 changes = []
423 def get_parent(dirname, basename):
424 parent_fid = self.base_files.get(dirname, None)
425 if parent_fid:
426 return parent_fid
427 parent_fid = self.files.get(dirname, None)
428 if parent_fid:
429 return parent_fid
430 if basename == '':
431 return None
432 fid = bzrlib.generate_ids.gen_file_id(path)
433 d = add_entry(fid, dirname, 'directory')
434 return fid
436 def add_entry(fid, path, kind, mode = None):
437 dirname, basename = os.path.split(path)
438 parent_fid = get_parent(dirname, basename)
440 executable = False
441 if mode == '100755':
442 executable = True
443 elif mode == '120000':
444 kind = 'symlink'
446 change = (fid,
447 (None, path),
448 True,
449 (False, True),
450 (None, parent_fid),
451 (None, basename),
452 (None, kind),
453 (None, executable))
454 self.files[path] = change[0]
455 changes.append(change)
456 return change
458 def update_entry(fid, path, kind, mode = None):
459 dirname, basename = os.path.split(path)
460 parent_fid = get_parent(dirname, basename)
462 executable = False
463 if mode == '100755':
464 executable = True
465 elif mode == '120000':
466 kind = 'symlink'
468 change = (fid,
469 (path, path),
470 True,
471 (True, True),
472 (None, parent_fid),
473 (None, basename),
474 (None, kind),
475 (None, executable))
476 self.files[path] = change[0]
477 changes.append(change)
478 return change
480 def remove_entry(fid, path, kind):
481 dirname, basename = os.path.split(path)
482 parent_fid = get_parent(dirname, basename)
483 change = (fid,
484 (path, None),
485 True,
486 (True, False),
487 (parent_fid, None),
488 (None, None),
489 (None, None),
490 (None, None))
491 del self.files[path]
492 changes.append(change)
493 return change
495 for fid, f in self.updates.iteritems():
496 path = f['path']
498 if 'deleted' in f:
499 remove_entry(fid, path, 'file')
500 continue
502 if path in self.base_files:
503 update_entry(fid, path, 'file', f['mode'])
504 else:
505 add_entry(fid, path, 'file', f['mode'])
507 return changes
509 def get_file_with_stat(self, file_id, path=None):
510 return (StringIO.StringIO(self.updates[file_id]['data']), None)
512 def get_symlink_target(self, file_id):
513 return self.updates[file_id]['data']
515 def parse_commit(parser):
516 global marks, blob_marks, bmarks, parsed_refs
517 global mode
519 parents = []
521 ref = parser[1]
522 parser.next()
524 if ref != 'refs/heads/master':
525 die("bzr doesn't support multiple branches; use 'master'")
527 commit_mark = parser.get_mark()
528 parser.next()
529 author = parser.get_author()
530 parser.next()
531 committer = parser.get_author()
532 parser.next()
533 data = parser.get_data()
534 parser.next()
535 if parser.check('from'):
536 parents.append(parser.get_mark())
537 parser.next()
538 while parser.check('merge'):
539 parents.append(parser.get_mark())
540 parser.next()
542 files = {}
544 for line in parser:
545 if parser.check('M'):
546 t, m, mark_ref, path = line.split(' ', 3)
547 mark = int(mark_ref[1:])
548 f = { 'mode' : m, 'data' : blob_marks[mark] }
549 elif parser.check('D'):
550 t, path = line.split(' ')
551 f = { 'deleted' : True }
552 else:
553 die('Unknown file command: %s' % line)
554 files[path] = f
556 repo = parser.repo
558 committer, date, tz = committer
559 parents = [str(mark_to_rev(p)) for p in parents]
560 revid = bzrlib.generate_ids.gen_revision_id(committer, date)
561 props = {}
562 props['branch-nick'] = repo.nick
564 mtree = CustomTree(repo, revid, parents, files)
565 changes = mtree.iter_changes()
567 repo.lock_write()
568 try:
569 builder = repo.get_commit_builder(parents, None, date, tz, committer, props, revid)
570 try:
571 list(builder.record_iter_changes(mtree, mtree.last_revision(), changes))
572 builder.finish_inventory()
573 builder.commit(data.decode('utf-8', 'replace'))
574 except Exception, e:
575 builder.abort()
576 raise
577 finally:
578 repo.unlock()
580 parsed_refs[ref] = revid
581 marks.new_mark(revid, commit_mark)
583 def parse_reset(parser):
584 global parsed_refs
586 ref = parser[1]
587 parser.next()
589 if ref != 'refs/heads/master':
590 die("bzr doesn't support multiple branches; use 'master'")
592 # ugh
593 if parser.check('commit'):
594 parse_commit(parser)
595 return
596 if not parser.check('from'):
597 return
598 from_mark = parser.get_mark()
599 parser.next()
601 parsed_refs[ref] = mark_to_rev(from_mark)
603 def do_export(parser):
604 global parsed_refs, dirname, peer
606 parser.next()
608 for line in parser.each_block('done'):
609 if parser.check('blob'):
610 parse_blob(parser)
611 elif parser.check('commit'):
612 parse_commit(parser)
613 elif parser.check('reset'):
614 parse_reset(parser)
615 elif parser.check('tag'):
616 pass
617 elif parser.check('feature'):
618 pass
619 else:
620 die('unhandled export command: %s' % line)
622 repo = parser.repo
624 for ref, revid in parsed_refs.iteritems():
625 if ref == 'refs/heads/master':
626 repo.generate_revision_history(revid, marks.get_tip('master'))
627 revno, revid = repo.last_revision_info()
628 if peer:
629 if hasattr(peer, "import_last_revision_info_and_tags"):
630 peer.import_last_revision_info_and_tags(repo, revno, revid)
631 else:
632 peer.import_last_revision_info(repo.repository, revno, revid)
633 else:
634 wt = repo.bzrdir.open_workingtree()
635 wt.update()
636 print "ok %s" % ref
637 print
639 def do_capabilities(parser):
640 global dirname
642 print "import"
643 print "export"
644 print "refspec refs/heads/*:%s/heads/*" % prefix
646 path = os.path.join(dirname, 'marks-git')
648 if os.path.exists(path):
649 print "*import-marks %s" % path
650 print "*export-marks %s" % path
652 print
654 def do_list(parser):
655 global tags
656 print "? refs/heads/%s" % 'master'
657 for tag, revid in parser.repo.tags.get_tag_dict().items():
658 print "? refs/tags/%s" % tag
659 tags[tag] = revid
660 print "@refs/heads/%s HEAD" % 'master'
661 print
663 def get_repo(url, alias):
664 global dirname, peer
666 origin = bzrlib.bzrdir.BzrDir.open(url)
667 branch = origin.open_branch()
669 if not isinstance(origin.transport, bzrlib.transport.local.LocalTransport):
670 clone_path = os.path.join(dirname, 'clone')
671 remote_branch = branch
672 if os.path.exists(clone_path):
673 # pull
674 d = bzrlib.bzrdir.BzrDir.open(clone_path)
675 branch = d.open_branch()
676 result = branch.pull(remote_branch, [], None, False)
677 else:
678 # clone
679 d = origin.sprout(clone_path, None,
680 hardlink=True, create_tree_if_local=False,
681 source_branch=remote_branch)
682 branch = d.open_branch()
683 branch.bind(remote_branch)
685 peer = remote_branch
686 else:
687 peer = None
689 return branch
691 def main(args):
692 global marks, prefix, dirname
693 global tags, filenodes
694 global blob_marks
695 global parsed_refs
696 global files_cache
698 alias = args[1]
699 url = args[2]
701 prefix = 'refs/bzr/%s' % alias
702 tags = {}
703 filenodes = {}
704 blob_marks = {}
705 parsed_refs = {}
706 files_cache = {}
708 gitdir = os.environ['GIT_DIR']
709 dirname = os.path.join(gitdir, 'bzr', alias)
711 if not os.path.exists(dirname):
712 os.makedirs(dirname)
714 repo = get_repo(url, alias)
716 marks_path = os.path.join(dirname, 'marks-int')
717 marks = Marks(marks_path)
719 parser = Parser(repo)
720 for line in parser:
721 if parser.check('capabilities'):
722 do_capabilities(parser)
723 elif parser.check('list'):
724 do_list(parser)
725 elif parser.check('import'):
726 do_import(parser)
727 elif parser.check('export'):
728 do_export(parser)
729 else:
730 die('unhandled command: %s' % line)
731 sys.stdout.flush()
733 marks.store()
735 sys.exit(main(sys.argv))