Sync with maint
[git] / contrib / remote-helpers / git-remote-bzr
1 #!/usr/bin/env python
2 #
3 # Copyright (c) 2012 Felipe Contreras
4 #
5
6 #
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
10 #
11 # For example:
12 # % git clone bzr::$HOME/myrepo
13 # or
14 # % git clone bzr::lp:myrepo
15 #
16
17 import sys
18
19 import bzrlib
20 if hasattr(bzrlib, "initialize"):
21     bzrlib.initialize()
22
23 import bzrlib.plugin
24 bzrlib.plugin.load_plugins()
25
26 import bzrlib.generate_ids
27 import bzrlib.transport
28 import bzrlib.errors
29
30 import sys
31 import os
32 import json
33 import re
34 import StringIO
35
36 NAME_RE = re.compile('^([^<>]+)')
37 AUTHOR_RE = re.compile('^([^<>]+?)? ?<([^<>]*)>$')
38 RAW_AUTHOR_RE = re.compile('^(\w+) (.+)? <(.*)> (\d+) ([+-]\d+)')
39
40 def die(msg, *args):
41     sys.stderr.write('ERROR: %s\n' % (msg % args))
42     sys.exit(1)
43
44 def warn(msg, *args):
45     sys.stderr.write('WARNING: %s\n' % (msg % args))
46
47 def gittz(tz):
48     return '%+03d%02d' % (tz / 3600, tz % 3600 / 60)
49
50 class Marks:
51
52     def __init__(self, path):
53         self.path = path
54         self.tips = {}
55         self.marks = {}
56         self.rev_marks = {}
57         self.last_mark = 0
58         self.load()
59
60     def load(self):
61         if not os.path.exists(self.path):
62             return
63
64         tmp = json.load(open(self.path))
65         self.tips = tmp['tips']
66         self.marks = tmp['marks']
67         self.last_mark = tmp['last-mark']
68
69         for rev, mark in self.marks.iteritems():
70             self.rev_marks[mark] = rev
71
72     def dict(self):
73         return { 'tips': self.tips, 'marks': self.marks, 'last-mark' : self.last_mark }
74
75     def store(self):
76         json.dump(self.dict(), open(self.path, 'w'))
77
78     def __str__(self):
79         return str(self.dict())
80
81     def from_rev(self, rev):
82         return self.marks[rev]
83
84     def to_rev(self, mark):
85         return self.rev_marks[mark]
86
87     def next_mark(self):
88         self.last_mark += 1
89         return self.last_mark
90
91     def get_mark(self, rev):
92         self.last_mark += 1
93         self.marks[rev] = self.last_mark
94         return self.last_mark
95
96     def is_marked(self, rev):
97         return self.marks.has_key(rev)
98
99     def new_mark(self, rev, mark):
100         self.marks[rev] = mark
101         self.rev_marks[mark] = rev
102         self.last_mark = mark
103
104     def get_tip(self, branch):
105         return self.tips.get(branch, None)
106
107     def set_tip(self, branch, tip):
108         self.tips[branch] = tip
109
110 class Parser:
111
112     def __init__(self, repo):
113         self.repo = repo
114         self.line = self.get_line()
115
116     def get_line(self):
117         return sys.stdin.readline().strip()
118
119     def __getitem__(self, i):
120         return self.line.split()[i]
121
122     def check(self, word):
123         return self.line.startswith(word)
124
125     def each_block(self, separator):
126         while self.line != separator:
127             yield self.line
128             self.line = self.get_line()
129
130     def __iter__(self):
131         return self.each_block('')
132
133     def next(self):
134         self.line = self.get_line()
135         if self.line == 'done':
136             self.line = None
137
138     def get_mark(self):
139         i = self.line.index(':') + 1
140         return int(self.line[i:])
141
142     def get_data(self):
143         if not self.check('data'):
144             return None
145         i = self.line.index(' ') + 1
146         size = int(self.line[i:])
147         return sys.stdin.read(size)
148
149     def get_author(self):
150         m = RAW_AUTHOR_RE.match(self.line)
151         if not m:
152             return None
153         _, name, email, date, tz = m.groups()
154         committer = '%s <%s>' % (name, email)
155         tz = int(tz)
156         tz = ((tz / 100) * 3600) + ((tz % 100) * 60)
157         return (committer, int(date), tz)
158
159 def rev_to_mark(rev):
160     global marks
161     return marks.from_rev(rev)
162
163 def mark_to_rev(mark):
164     global marks
165     return marks.to_rev(mark)
166
167 def fixup_user(user):
168     name = mail = None
169     user = user.replace('"', '')
170     m = AUTHOR_RE.match(user)
171     if m:
172         name = m.group(1)
173         mail = m.group(2).strip()
174     else:
175         m = NAME_RE.match(user)
176         if m:
177             name = m.group(1).strip()
178
179     return '%s <%s>' % (name, mail)
180
181 def get_filechanges(cur, prev):
182     modified = {}
183     removed = {}
184
185     changes = cur.changes_from(prev)
186
187     def u(s):
188         return s.encode('utf-8')
189
190     for path, fid, kind in changes.added:
191         modified[u(path)] = fid
192     for path, fid, kind in changes.removed:
193         removed[u(path)] = None
194     for path, fid, kind, mod, _ in changes.modified:
195         modified[u(path)] = fid
196     for oldpath, newpath, fid, kind, mod, _ in changes.renamed:
197         removed[u(oldpath)] = None
198         if kind == 'directory':
199             lst = cur.list_files(from_dir=newpath, recursive=True)
200             for path, file_class, kind, fid, entry in lst:
201                 if kind != 'directory':
202                     modified[u(newpath + '/' + path)] = fid
203         else:
204             modified[u(newpath)] = fid
205
206     return modified, removed
207
208 def export_files(tree, files):
209     global marks, filenodes
210
211     final = []
212     for path, fid in files.iteritems():
213         kind = tree.kind(fid)
214
215         h = tree.get_file_sha1(fid)
216
217         if kind == 'symlink':
218             d = tree.get_symlink_target(fid)
219             mode = '120000'
220         elif kind == 'file':
221
222             if tree.is_executable(fid):
223                 mode = '100755'
224             else:
225                 mode = '100644'
226
227             # is the blog already exported?
228             if h in filenodes:
229                 mark = filenodes[h]
230                 final.append((mode, mark, path))
231                 continue
232
233             d = tree.get_file_text(fid)
234         elif kind == 'directory':
235             continue
236         else:
237             die("Unhandled kind '%s' for path '%s'" % (kind, path))
238
239         mark = marks.next_mark()
240         filenodes[h] = mark
241
242         print "blob"
243         print "mark :%u" % mark
244         print "data %d" % len(d)
245         print d
246
247         final.append((mode, mark, path))
248
249     return final
250
251 def export_branch(branch, name):
252     global prefix
253
254     ref = '%s/heads/%s' % (prefix, name)
255     tip = marks.get_tip(name)
256
257     repo = branch.repository
258     repo.lock_read()
259     revs = branch.iter_merge_sorted_revisions(None, tip, 'exclude', 'forward')
260     count = 0
261
262     revs = [revid for revid, _, _, _ in revs if not marks.is_marked(revid)]
263
264     for revid in revs:
265
266         rev = repo.get_revision(revid)
267
268         parents = rev.parent_ids
269         time = rev.timestamp
270         tz = rev.timezone
271         committer = rev.committer.encode('utf-8')
272         committer = "%s %u %s" % (fixup_user(committer), time, gittz(tz))
273         authors = rev.get_apparent_authors()
274         if authors:
275             author = authors[0].encode('utf-8')
276             author = "%s %u %s" % (fixup_user(author), time, gittz(tz))
277         else:
278             author = committer
279         msg = rev.message.encode('utf-8')
280
281         msg += '\n'
282
283         if len(parents) == 0:
284             parent = bzrlib.revision.NULL_REVISION
285         else:
286             parent = parents[0]
287
288         cur_tree = repo.revision_tree(revid)
289         prev = repo.revision_tree(parent)
290         modified, removed = get_filechanges(cur_tree, prev)
291
292         modified_final = export_files(cur_tree, modified)
293
294         if len(parents) == 0:
295             print 'reset %s' % ref
296
297         print "commit %s" % ref
298         print "mark :%d" % (marks.get_mark(revid))
299         print "author %s" % (author)
300         print "committer %s" % (committer)
301         print "data %d" % (len(msg))
302         print msg
303
304         for i, p in enumerate(parents):
305             try:
306                 m = rev_to_mark(p)
307             except KeyError:
308                 # ghost?
309                 continue
310             if i == 0:
311                 print "from :%s" % m
312             else:
313                 print "merge :%s" % m
314
315         for f in removed:
316             print "D %s" % (f,)
317         for f in modified_final:
318             print "M %s :%u %s" % f
319         print
320
321         count += 1
322         if (count % 100 == 0):
323             print "progress revision %s (%d/%d)" % (revid, count, len(revs))
324             print "#############################################################"
325
326     repo.unlock()
327
328     revid = branch.last_revision()
329
330     # make sure the ref is updated
331     print "reset %s" % ref
332     print "from :%u" % rev_to_mark(revid)
333     print
334
335     marks.set_tip(name, revid)
336
337 def export_tag(repo, name):
338     global tags, prefix
339
340     ref = '%s/tags/%s' % (prefix, name)
341     print "reset %s" % ref
342     print "from :%u" % rev_to_mark(tags[name])
343     print
344
345 def do_import(parser):
346     global dirname
347
348     branch = parser.repo
349     path = os.path.join(dirname, 'marks-git')
350
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()
356
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()
366
367     print 'done'
368
369     sys.stdout.flush()
370
371 def parse_blob(parser):
372     global blob_marks
373
374     parser.next()
375     mark = parser.get_mark()
376     parser.next()
377     data = parser.get_data()
378     blob_marks[mark] = data
379     parser.next()
380
381 class CustomTree():
382
383     def __init__(self, repo, revid, parents, files):
384         global files_cache
385
386         self.repo = repo
387         self.revid = revid
388         self.parents = parents
389         self.updates = {}
390
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
401
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)
410
411         self.files = files_cache[revid] = self.base_files.copy()
412
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
419
420     def last_revision(self):
421         return self.base_id
422
423     def iter_changes(self):
424         changes = []
425
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
438
439         def add_entry(fid, path, kind, mode = None):
440             dirname, basename = os.path.split(path)
441             parent_fid = get_parent(dirname, basename)
442
443             executable = False
444             if mode == '100755':
445                 executable = True
446             elif mode == '120000':
447                 kind = 'symlink'
448
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
460
461         def update_entry(fid, path, kind, mode = None):
462             dirname, basename = os.path.split(path)
463             parent_fid = get_parent(dirname, basename)
464
465             executable = False
466             if mode == '100755':
467                 executable = True
468             elif mode == '120000':
469                 kind = 'symlink'
470
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
482
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
497
498         for fid, f in self.updates.iteritems():
499             path = f['path']
500
501             if 'deleted' in f:
502                 remove_entry(fid, path, 'file')
503                 continue
504
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'])
509
510         return changes
511
512     def get_file_with_stat(self, file_id, path=None):
513         return (StringIO.StringIO(self.updates[file_id]['data']), None)
514
515     def get_symlink_target(self, file_id):
516         return self.updates[file_id]['data']
517
518 def c_style_unescape(string):
519     if string[0] == string[-1] == '"':
520         return string.decode('string-escape')[1:-1]
521     return string
522
523 def parse_commit(parser):
524     global marks, blob_marks, bmarks, parsed_refs
525     global mode
526
527     parents = []
528
529     ref = parser[1]
530     parser.next()
531
532     if ref != 'refs/heads/master':
533         die("bzr doesn't support multiple branches; use 'master'")
534
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()
549
550     files = {}
551
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
564
565     repo = parser.repo
566
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
572
573     mtree = CustomTree(repo, revid, parents, files)
574     changes = mtree.iter_changes()
575
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()
588
589     parsed_refs[ref] = revid
590     marks.new_mark(revid, commit_mark)
591
592 def parse_reset(parser):
593     global parsed_refs
594
595     ref = parser[1]
596     parser.next()
597
598     if ref != 'refs/heads/master':
599         die("bzr doesn't support multiple branches; use 'master'")
600
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()
609
610     parsed_refs[ref] = mark_to_rev(from_mark)
611
612 def do_export(parser):
613     global parsed_refs, dirname, peer
614
615     parser.next()
616
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)
630
631     repo = parser.repo
632
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
647
648 def do_capabilities(parser):
649     global dirname
650
651     print "import"
652     print "export"
653     print "refspec refs/heads/*:%s/heads/*" % prefix
654     print "refspec refs/tags/*:%s/tags/*" % prefix
655
656     path = os.path.join(dirname, 'marks-git')
657
658     if os.path.exists(path):
659         print "*import-marks %s" % path
660     print "*export-marks %s" % path
661
662     print
663
664 def ref_is_valid(name):
665     return not True in [c in name for c in '~^: \\']
666
667 def do_list(parser):
668     global tags
669     print "? refs/heads/%s" % 'master'
670
671     branch = parser.repo
672     branch.lock_read()
673     for tag, revid in branch.tags.get_tag_dict().items():
674         try:
675             branch.revision_id_to_dotted_revno(revid)
676         except bzrlib.errors.NoSuchRevision:
677             continue
678         if not ref_is_valid(tag):
679             continue
680         print "? refs/tags/%s" % tag
681         tags[tag] = revid
682     branch.unlock()
683     print "@refs/heads/%s HEAD" % 'master'
684     print
685
686 def get_repo(url, alias):
687     global dirname, peer
688
689     origin = bzrlib.bzrdir.BzrDir.open(url)
690     branch = origin.open_branch()
691
692     if not isinstance(origin.transport, bzrlib.transport.local.LocalTransport):
693         clone_path = os.path.join(dirname, 'clone')
694         remote_branch = branch
695         if os.path.exists(clone_path):
696             # pull
697             d = bzrlib.bzrdir.BzrDir.open(clone_path)
698             branch = d.open_branch()
699             result = branch.pull(remote_branch, [], None, False)
700         else:
701             # clone
702             d = origin.sprout(clone_path, None,
703                     hardlink=True, create_tree_if_local=False,
704                     source_branch=remote_branch)
705             branch = d.open_branch()
706             branch.bind(remote_branch)
707
708         peer = remote_branch
709     else:
710         peer = None
711
712     return branch
713
714 def main(args):
715     global marks, prefix, dirname
716     global tags, filenodes
717     global blob_marks
718     global parsed_refs
719     global files_cache
720
721     alias = args[1]
722     url = args[2]
723
724     prefix = 'refs/bzr/%s' % alias
725     tags = {}
726     filenodes = {}
727     blob_marks = {}
728     parsed_refs = {}
729     files_cache = {}
730
731     gitdir = os.environ['GIT_DIR']
732     dirname = os.path.join(gitdir, 'bzr', alias)
733
734     if not os.path.exists(dirname):
735         os.makedirs(dirname)
736
737     repo = get_repo(url, alias)
738
739     marks_path = os.path.join(dirname, 'marks-int')
740     marks = Marks(marks_path)
741
742     parser = Parser(repo)
743     for line in parser:
744         if parser.check('capabilities'):
745             do_capabilities(parser)
746         elif parser.check('list'):
747             do_list(parser)
748         elif parser.check('import'):
749             do_import(parser)
750         elif parser.check('export'):
751             do_export(parser)
752         else:
753             die('unhandled command: %s' % line)
754         sys.stdout.flush()
755
756     marks.store()
757
758 sys.exit(main(sys.argv))