/
tree-checksum.py
executable file
·313 lines (254 loc) · 9.43 KB
/
tree-checksum.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
#!/usr/bin/env python
"""
Usage: tree-checksum.py [--all-git|--all-svn] DIRECTORY > LISTING
tree-checksum.py --compare ORIGINAL CONVERTED
Compute a checksum for a directory (or for svn-all-fast-export / SVN items).
"""
import optparse
import tempfile
import sys
import os
import re
import hashlib
import shutil
import subprocess
import fnmatch
def main():
p = optparse.OptionParser(usage=__doc__.strip())
p.add_option("--all-git", action="store_true")
p.add_option("--all-svn", action="store_true")
p.add_option("--start-rev", action="store", type="int")
p.add_option("--end-rev", action="store", type="int")
p.add_option("--compare", action="store_true")
p.add_option("--skip", action="append", type="string", dest="skip",
default=[], help="items to skip")
options, args = p.parse_args()
if options.compare:
if len(args) != 2:
p.error("invalid number of arguments")
equal = do_compare(args[0], args[1])
sys.exit(0 if equal else 1)
if len(args) != 1:
p.error("invalid number of arguments")
path = args[0]
if options.all_git:
do_git(path, start_rev=options.start_rev, end_rev=options.end_rev, skip=options.skip)
elif options.all_svn:
do_svn(path, start_rev=options.start_rev, end_rev=options.end_rev, skip=options.skip)
else:
print path_checksum(path, skip=options.skip)
sys.exit(0)
def _with_workdir(func):
def wrapper(*a, **kw):
tmpdir = os.path.abspath(tempfile.mkdtemp())
try:
a = a + (tmpdir,)
func(*a, **kw)
finally:
shutil.rmtree(tmpdir)
return wrapper
def do_compare(original_filename, converted_filename, start_rev=None):
original = _read_listing(original_filename)
converted = _read_listing(converted_filename)
states = original.keys()
states.sort()
converted_checksums = {}
for (rev, branch), checksum in converted.items():
converted_checksums[checksum] = True
equal = True
for state in states:
if state in converted:
if original[state] != converted[state]:
equal = False
print "MISMATCH ", state[0], state[1]
else:
# The converted repo contains commits only for those SVN commits
# that actually change something. So report missing states
# only if the tree checksum does not appear at all in the converted
# repo.
if original[state] not in converted_checksums:
print "MISSING ", state[0], state[1]
states = converted.keys()
states.sort()
for state in states:
if state not in original:
print "spurious ", state[0], state[1]
return equal
def _read_listing(filename):
listing = {}
f = open(filename, 'r')
try:
for line in f:
if not line.strip():
continue
parts = line.strip().split()
if len(parts) != 3:
raise ValueError("Invalid line '%s'" % line)
listing[(int(parts[0]), parts[1])] = parts[2]
finally:
f.close()
return listing
@_with_workdir
def do_git(path, workdir, start_rev=None, end_rev=None, skip=None):
repo = os.path.join(workdir, 'repo')
git('clone', '--quiet', path, repo)
os.chdir(repo)
git('fetch', '--quiet', 'origin', 'refs/*:refs/remotes/origin/*')
for commit in git.readlines('log', '--format=%H', '--all'):
msg = git.readlines('cat-file', 'commit', commit)
m = re.match(r'svn path=/(.*)/; revision=(\d+)', msg[-1].strip())
assert m is not None, commit
if start_rev is not None and int(m.group(2)) > start_rev:
continue
if end_rev is not None and int(m.group(2)) <= end_rev:
break
git('checkout', '--quiet', commit)
checksum = path_checksum(repo, skip=skip)
print m.group(2), m.group(1), checksum
sys.stdout.flush()
@_with_workdir
def do_svn(path, workdir, start_rev=None, end_rev=None, skip=None):
if '://' in path:
url = path
else:
url = ("file://" +
os.path.normpath(os.path.abspath(path)).replace(os.path.sep, '/').rstrip('/'))
checkoutdir = os.path.join(workdir, 'repo')
for commit, branch in svn_logreader(url):
if start_rev is not None and commit > start_rev:
continue
if end_rev is not None and commit <= end_rev:
break
commiturl = url + '/' + branch + ("@%s" % commit)
if not os.path.isdir(checkoutdir):
svn('checkout', '--ignore-externals', '-q', '-r', str(commit),
commiturl, checkoutdir)
os.chdir(checkoutdir)
else:
os.chdir(checkoutdir)
svn('switch', '--force', '--ignore-externals', '-q', commiturl)
checksum = path_checksum(checkoutdir, skip=skip)
print commit, branch, checksum
sys.stdout.flush()
def svn_logreader(url):
"""
Read commit+branch information from SVN log.
"""
log = svn.pipe('log', '-v', url)
seen = {}
while log:
line = log.readline()
if line.startswith('-'*50):
line = log.readline().strip()
if not line:
break
m = re.match('^r(\d+) .*', line)
commit = int(m.group(1))
line = log.readline().strip()
assert line.startswith('Changed paths:')
while log:
line = log.readline().strip()
if not line:
break
m = re.match(r'^[MARD]\s+/(.*)', line)
pth = m.group(1)
m = re.match(r'^(branches/[^/ ]+|tags/[^/ ]+|trunk).*?', pth)
if m:
branch = m.group(1)
key = (commit, branch)
if key not in seen:
seen[key] = True
if line != "D /%s" % m.group(1):
# skip whole-branch deletions
yield commit, m.group(1)
def path_checksum(path, skip=None):
digest = hashlib.sha1()
if skip is None:
skip = []
def feed_file(filename):
f = open(filename, 'rb')
try:
while True:
chunk = f.read(65536)
if not chunk:
break
digest.update(chunk)
finally:
f.close()
def feed_string(s):
digest.update(s)
for dirpath, dirnames, filenames in os.walk(path, topdown=True):
dirnames.sort()
for name in ('.svn', '.git'):
try:
dirnames.remove(name)
except ValueError:
pass
filenames.sort()
for fn in filenames:
fullpath = os.path.join(dirpath, fn)
if any(fnmatch.fnmatch(fullpath, pat) for pat in skip):
continue
feed_string(fn)
seen = {}
while os.path.islink(fullpath) and fullpath not in seen:
seen[fullpath] = True
fullpath = os.path.join(os.path.dirname(fullpath),
os.readlink(fullpath))
svnpath = os.path.join(os.path.dirname(fullpath), '.svn', 'text-base',
os.path.basename(fullpath) + '.svn-base')
if os.path.isfile(svnpath):
feed_file(svnpath)
else:
feed_file(fullpath)
return digest.hexdigest()
#------------------------------------------------------------------------------
# Communicating with Git/SVN
#------------------------------------------------------------------------------
class Cmd(object):
executable = None
def __init__(self, executable):
self.executable = executable
def _call(self, command, args, kw, repository=None, call=False):
cmd = [self.executable, command] + list(args)
cwd = None
if repository is not None:
cwd = os.getcwd()
os.chdir(repository)
try:
if call:
return subprocess.call(cmd, **kw)
else:
return subprocess.Popen(cmd, **kw)
finally:
if cwd is not None:
os.chdir(cwd)
def __call__(self, command, *a, **kw):
ret = self._call(command, a, {}, call=True, **kw)
if ret != 0:
raise RuntimeError("%s failed" % self.executable)
def pipe(self, command, *a, **kw):
stdin = kw.pop('stdin', None)
p = self._call(command, a, dict(stdin=stdin, stdout=subprocess.PIPE),
call=False, **kw)
return p.stdout
def read(self, command, *a, **kw):
p = self._call(command, a, dict(stdout=subprocess.PIPE),
call=False, **kw)
out, err = p.communicate()
if p.returncode != 0:
raise RuntimeError("%s failed" % self.executable)
return out
def readlines(self, command, *a, **kw):
out = self.read(command, *a, **kw)
return out.rstrip("\n").split("\n")
def test(self, command, *a, **kw):
ret = self._call(command, a, dict(stdout=subprocess.PIPE,
stderr=subprocess.PIPE),
call=True, **kw)
return (ret == 0)
git = Cmd("git")
svn = Cmd("svn")
#------------------------------------------------------------------------------
if __name__ == "__main__":
main()