3 """ hg-to-git.py - A Mercurial to GIT converter
5 Copyright (C)2007 Stelian Pop <stelian@popies.net>
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 import os
, os
.path
, sys
23 import tempfile
, pickle
, getopt
26 if sys
.hexversion
< 0x02030000:
27 # The behavior of the pickle module changed significantly in 2.3
28 sys
.stderr
.write("hg-to-git.py: requires Python 2.3 or later.\n")
31 # Maps hg version -> git version
33 # List of children for each hg revision
35 # List of parents for each hg revision
37 # Current branch for each hg revision
39 # Number of new changesets converted from hg
42 #------------------------------------------------------------------------------
50 -s, --gitstate=FILE: name of the state to be saved/read
52 -n, --nrepack=INT: number of changesets that will trigger
53 a repack (default=0, -1 to deactivate)
54 -v, --verbose: be verbose
57 hgprj: name of the HG project to import (directory)
60 #------------------------------------------------------------------------------
62 def getgitenv(user
, date
):
64 elems
= re
.compile('(.*?)\s+<(.*)>').match(user
)
66 env
+= 'export GIT_AUTHOR_NAME="%s" ;' % elems
.group(1)
67 env
+= 'export GIT_COMMITTER_NAME="%s" ;' % elems
.group(1)
68 env
+= 'export GIT_AUTHOR_EMAIL="%s" ;' % elems
.group(2)
69 env
+= 'export GIT_COMMITTER_EMAIL="%s" ;' % elems
.group(2)
71 env
+= 'export GIT_AUTHOR_NAME="%s" ;' % user
72 env
+= 'export GIT_COMMITTER_NAME="%s" ;' % user
73 env
+= 'export GIT_AUTHOR_EMAIL= ;'
74 env
+= 'export GIT_COMMITTER_EMAIL= ;'
76 env
+= 'export GIT_AUTHOR_DATE="%s" ;' % date
77 env
+= 'export GIT_COMMITTER_DATE="%s" ;' % date
80 #------------------------------------------------------------------------------
87 opts
, args
= getopt
.getopt(sys
.argv
[1:], 's:t:n:v', ['gitstate=', 'tempdir=', 'nrepack=', 'verbose'])
89 if o
in ('-s', '--gitstate'):
91 state
= os
.path
.abspath(state
)
92 if o
in ('-n', '--nrepack'):
94 if o
in ('-v', '--verbose'):
97 raise Exception('params')
106 if os
.path
.exists(state
):
108 print 'State does exist, reading'
110 hgvers
= pickle
.load(f
)
112 print 'State does not exist, first run'
114 sock
= os
.popen('hg tip --template "{rev}"')
121 # Calculate the branches
123 print 'analysing the branches...'
125 hgparents
["0"] = (None, None)
126 hgbranch
["0"] = "master"
127 for cset
in range(1, int(tip
) + 1):
128 hgchildren
[str(cset
)] = ()
129 prnts
= os
.popen('hg log -r %d --template "{parents}"' % cset
).read().strip().split(' ')
130 prnts
= map(lambda x
: x
[:x
.find(':')], prnts
)
132 parent
= prnts
[0].strip()
134 parent
= str(cset
- 1)
135 hgchildren
[parent
] += ( str(cset
), )
137 mparent
= prnts
[1].strip()
138 hgchildren
[mparent
] += ( str(cset
), )
142 hgparents
[str(cset
)] = (parent
, mparent
)
145 # For merge changesets, take either one, preferably the 'master' branch
146 if hgbranch
[mparent
] == 'master':
147 hgbranch
[str(cset
)] = 'master'
149 hgbranch
[str(cset
)] = hgbranch
[parent
]
152 # For first children, take the parent branch, for the others create a new branch
153 if hgchildren
[parent
][0] == str(cset
):
154 hgbranch
[str(cset
)] = hgbranch
[parent
]
156 hgbranch
[str(cset
)] = "branch-" + str(cset
)
158 if not hgvers
.has_key("0"):
159 print 'creating repository'
160 os
.system('git init')
162 # loop through every hg changeset
163 for cset
in range(int(tip
) + 1):
165 # incremental, already seen
166 if hgvers
.has_key(str(cset
)):
171 log_data
= os
.popen('hg log -r %d --template "{tags}\n{date|date}\n{author}\n"' % cset
).readlines()
172 tag
= log_data
[0].strip()
173 date
= log_data
[1].strip()
174 user
= log_data
[2].strip()
175 parent
= hgparents
[str(cset
)][0]
176 mparent
= hgparents
[str(cset
)][1]
179 (fdcomment
, filecomment
) = tempfile
.mkstemp()
180 csetcomment
= os
.popen('hg log -r %d --template "{desc}"' % cset
).read().strip()
181 os
.write(fdcomment
, csetcomment
)
184 print '-----------------------------------------'
186 print 'branch:', hgbranch
[str(cset
)]
189 print 'comment:', csetcomment
191 print 'parent:', parent
193 print 'mparent:', mparent
196 print '-----------------------------------------'
198 # checkout the parent if necessary
200 if hgbranch
[str(cset
)] == "branch-" + str(cset
):
201 print 'creating new branch', hgbranch
[str(cset
)]
202 os
.system('git checkout -b %s %s' % (hgbranch
[str(cset
)], hgvers
[parent
]))
204 print 'checking out branch', hgbranch
[str(cset
)]
205 os
.system('git checkout %s' % hgbranch
[str(cset
)])
209 if hgbranch
[parent
] == hgbranch
[str(cset
)]:
210 otherbranch
= hgbranch
[mparent
]
212 otherbranch
= hgbranch
[parent
]
213 print 'merging', otherbranch
, 'into', hgbranch
[str(cset
)]
214 os
.system(getgitenv(user
, date
) + 'git merge --no-commit -s ours "" %s %s' % (hgbranch
[str(cset
)], otherbranch
))
216 # remove everything except .git and .hg directories
217 os
.system('find . \( -path "./.hg" -o -path "./.git" \) -prune -o ! -name "." -print | xargs rm -rf')
219 # repopulate with checkouted files
220 os
.system('hg update -C %d' % cset
)
223 os
.system('git ls-files -x .hg --others | git update-index --add --stdin')
224 # delete removed files
225 os
.system('git ls-files -x .hg --deleted | git update-index --remove --stdin')
228 os
.system(getgitenv(user
, date
) + 'git commit --allow-empty --allow-empty-message -a -F %s' % filecomment
)
229 os
.unlink(filecomment
)
232 if tag
and tag
!= 'tip':
233 os
.system(getgitenv(user
, date
) + 'git tag %s' % tag
)
235 # delete branch if not used anymore...
236 if mparent
and len(hgchildren
[str(cset
)]):
237 print "Deleting unused branch:", otherbranch
238 os
.system('git branch -d %s' % otherbranch
)
240 # retrieve and record the version
241 vvv
= os
.popen('git show --quiet --pretty=format:%H').read()
242 print 'record', cset
, '->', vvv
243 hgvers
[str(cset
)] = vvv
245 if hgnewcsets
>= opt_nrepack
and opt_nrepack
!= -1:
246 os
.system('git repack -a -d')
248 # write the state for incrementals
251 print 'Writing state'
253 pickle
.dump(hgvers
, f
)
255 # vim: et ts=8 sw=4 sts=4