comparison lib/hg/hggit_sync.py @ 295:e40cdce29e5a

Hacky hg-git sync script.
author Ludovic Chabant <ludovic@chabant.com>
date Thu, 02 Apr 2015 08:00:57 -0700
parents
children e7fe049b7f8b
comparison
equal deleted inserted replaced
294:8bc056d80c39 295:e40cdce29e5a
1 import os
2 import os.path
3 import sys
4 import subprocess
5
6
7 class CommitInfo(object):
8 def __init__(self):
9 self.nodeid = None
10 self.timestamp = None
11 self.description = None
12
13
14 def parse_commits(text):
15 commits = []
16 cur_commit = None
17 for line in text.split('\n'):
18 if line == '':
19 if cur_commit:
20 commits.append(cur_commit)
21 cur_commit = None
22 continue
23 if cur_commit is None:
24 cur_commit = CommitInfo()
25 if cur_commit.nodeid is None:
26 id_and_date = line.split(' ', 1)
27 cur_commit.nodeid = id_and_date[0]
28 cur_commit.timestamp = int(id_and_date[1].split('.')[0])
29 else:
30 cur_commit.description = line
31 return commits
32
33
34 def build_commit_map(commits1, commits2):
35 commits1 = sorted(commits1, key=lambda c: c.timestamp)
36 commits2 = sorted(commits2, key=lambda c: c.timestamp)
37 commit_map = dict(map(lambda c: (c.timestamp, (c, None)), commits1))
38 for c in commits2:
39 entry = commit_map.get(c.timestamp, (None, None))
40 entry = (entry[0], c)
41 commit_map[c.timestamp] = entry
42 return commit_map
43
44
45 def main():
46 hg_repo = os.getcwd()
47 if not os.path.exists(os.path.join(hg_repo, '.hg')):
48 print "You must run this in the root of a Mercurial repository."
49 return 1
50
51 git_repo = os.path.join(hg_repo, '.hg', 'git')
52 if not os.path.exists(git_repo):
53 print ("This Mercurial repository doesn't seem to have any Git mirror "
54 "to sync with.")
55 return 1
56
57 hg_output = subprocess.check_output([
58 'hg', 'log',
59 '--template', "{node} {date}\n{firstline(desc)}\n\n"])
60 hg_commits = parse_commits(hg_output)
61
62 os.chdir(git_repo)
63 git_output = subprocess.check_output([
64 'git', 'log', '--format=%H %ct%n%s%n%n'])
65 git_commits = parse_commits(git_output)
66 os.chdir(hg_repo)
67
68 commit_map = build_commit_map(git_commits, hg_commits)
69 for key, val in commit_map.iteritems():
70 if val[0] is None:
71 print ("Mercurial commit '%s' (%s) has no Git mirror yet: %s" %
72 (val[1].nodeid, val[1].timestamp, val[1].description))
73 if val[1] is None:
74 print ("Git commit '%s' (%s) is new: %s" %
75 (val[0].nodeid, val[0].timestamp, val[0].description))
76
77 map_file = os.path.join(hg_repo, '.hg', 'git-mapfile')
78 if len(sys.argv) > 1:
79 map_file = sys.argv[1]
80 print "Saving map file: %s" % map_file
81 with open(map_file, 'w') as fp:
82 for key, val in commit_map.iteritems():
83 if val[0] is None or val[1] is None:
84 continue
85 fp.write(val[0].nodeid)
86 fp.write(' ')
87 fp.write(val[1].nodeid)
88 fp.write('\n')
89
90
91 if __name__ == '__main__':
92 res = main()
93 sys.exit(res)
94