Debian Codegraph @

cvsconvert

raw symbols SCIP
1 #!/usr/bin/env python3
2 """
3 cvsconvert - convert a CVS repo and check against the original
4
5 Convert, and check the tree content of a gitspace conversion against
6 the CVS. The tip state of every branch, and every tag, is checked.
7
8 Will produce spurious errors if any CVS branch name had to be sanitized.
9 """
10 # SPDX-License-Identifier: GPL-2.0+
11 #
12 # The engine for this is the testlifter.py code from the distribution directory.
13 # Modify it there, not here
14 #
15 # This code runs correctly under both Python 2 and Python 3.
16 # Preserve this property!
17 import sys, os, shutil, subprocess, time, filecmp
18
19 try:
20 from pipes import quote
21 except ImportError:
22 from shlex import quote
23
24 DEBUG_STEPS = 1
25 DEBUG_COMMANDS = 2
26 DEBUG_VCS = 3
27 DEBUG_LIFTER = 4
28
29 verbose = 0
30
31 os.putenv("PATH", os.getenv("PATH") + os.pathsep + "..")
32
33 binary_encoding = 'Latin-1' # Preserves high bits in data
34
35 def noisy_run(dcmd, legend=""):
36 "Either execute a command or raise a fatal exception."
37 if legend:
38 legend = " " + legend
39 caller = os.path.basename(sys.argv[0])
40 if verbose >= DEBUG_COMMANDS:
41 sys.stdout.write("%s: executing '%s'%s\n" % (caller, dcmd, legend))
42 try:
43 retcode = subprocess.call(dcmd, shell=True)
44 if retcode < 0:
45 sys.stderr.write("%s: %s was terminated by signal %d.\n" % (-caller, dcmd, retcode))
46 sys.exit(1)
47 elif retcode != 0:
48 sys.stderr.write("%s: %s returned %d.\n" % (caller, dcmd, retcode))
49 return False
50 except (OSError, IOError) as e:
51 sys.stderr.write("%s: execution of %s%s failed: %s\n" % (caller, dcmd, legend, e))
52 return False
53 return True
54
55 def capture_or_die(dcmd, legend=""):
56 "Either execute a command and capture its output or die."
57 if legend:
58 legend = " " + legend
59 caller = os.path.basename(sys.argv[0])
60 if verbose >= DEBUG_COMMANDS:
61 sys.stdout.write("%s: executing '%s'%s\n" % (caller, dcmd, legend))
62 try:
63 return subprocess.Popen(dcmd, shell=True, stdout=subprocess.PIPE).communicate()[0].decode(binary_encoding)
64 except subprocess.CalledProcessError as e:
65 if e.returncode < 0:
66 sys.stderr.write("%s: child was terminated by signal %d." % (caller, -e.returncode))
67 elif e.returncode != 0:
68 sys.stderr.write("%s: child returned %d." % (caller, e.returncode))
69 sys.exit(1)
70
71 class directory_context(object):
72 def __init__(self, target):
73 self.target = target
74 self.source = None
75 def __enter__(self):
76 if verbose >= DEBUG_COMMANDS:
77 sys.stdout.write("In %s: " % os.path.relpath(self.target))
78 self.source = os.getcwd()
79 if os.path.isdir(self.target):
80 os.chdir(self.target)
81 def __exit__(self, extype, value_unused, traceback_unused):
82 os.chdir(self.source)
83
84 class RCSRepository(object):
85 "An RCS file collection."
86 def __init__(self, name):
87 self.name = name
88 self.retain = False
89 self.directory = os.path.join(os.getcwd(), self.name)
90 self.conversions = []
91 def run_with_cleanup(self, cmd):
92 if not noisy_run(cmd):
93 if not self.retain:
94 self.cleanup()
95 sys.exit(1)
96 def do(self, cmd, *args):
97 "Execute a RCS command in context of this repo."
98 if verbose < DEBUG_VCS:
99 mute = '-q'
100 else:
101 mute = ""
102 if not noisy_run("cd %s && %s %s %s" % (self.directory, cmd, mute, " ".join(args))) and not self.retain:
103 self.cleanup()
104 sys.exit(1)
105 def init(self):
106 "Initialize the repository."
107 self.run_with_cleanup("rm -fr {0} && mkdir -p {0}".format(self.directory))
108 def write(self, fn, content):
109 "Create file content in the repository."
110 if verbose >= DEBUG_COMMANDS:
111 sys.stdout.write("%s <- %s" % (fn, content))
112 with directory_context(self.directory):
113 with open(fn, "w") as fp:
114 fp.write(content)
115 def add(self, filename):
116 "Add a file to the version-controlled set."
117 self.do("rcs", "-t-", "-i", filename)
118 def tag(self, filename, name):
119 "Create a tag on a specified file."
120 self.do("rcs", "-n" + name + ":", filename)
121 def checkout(self, filename):
122 "Check out a writeable copy of the specified file."
123 self.do("co", "-l", filename)
124 def checkin(self, filename, message):
125 "Check in changes to the specified file."
126 self.do("ci", "-m'%s' %s" % (message, filename))
127 def stream(self, smodule, _gitdir, outfile, more_opts=''):
128 directory = os.path.join(self.directory, smodule)
129 vopt = "-v " * (verbose - DEBUG_LIFTER + 1)
130 # The -L is necessary to handle proxied directories.
131 self.run_with_cleanup('find -L {0} -name "*,v" | cvs-fast-export {1} {2} >{3}'.format(directory, vopt, more_opts, outfile))
132 def convert(self, smodule, gitdir, more_opts=''):
133 "Convert the repo."
134 streamfile = "%s-%s.git.fi" % (self.name, module)
135 self.stream(smodule, gitdir, streamfile, more_opts)
136 self.run_with_cleanup("rm -fr {0} && mkdir {0} && git init --quiet {0}".format(gitdir))
137 self.run_with_cleanup('cat {1} | (cd {0} >/dev/null; git fast-import --quiet --done && git checkout)'.format(gitdir, streamfile))
138 self.conversions.append(gitdir)
139 if not self.retain:
140 os.remove(streamfile)
141 def cleanup(self):
142 "Clean up the repository conversions."
143 if not self.retain:
144 if self.conversions:
145 os.system("rm -fr %s" % " ".join(self.conversions))
146
147 class CVSRepository(RCSRepository):
148 def __init__(self, name, readonly=False):
149 RCSRepository.__init__(self, name)
150 self.readonly = readonly
151 self.directory = os.path.join(os.getcwd(), self.name)
152 self.checkouts = []
153 self.conversions = []
154 def do(self, *cmd):
155 "Execute a CVS command in context of this repo."
156 if verbose < DEBUG_VCS:
157 mute = '-Q'
158 else:
159 mute = ""
160 if self.readonly:
161 prefix = "CVSREADONLYFS=yes "
162 else:
163 prefix = ""
164 self.run_with_cleanup("%scvs %s -d:local:%s %s" % (prefix, mute,
165 self.directory,
166 " ".join(cmd)))
167 def init(self):
168 RCSRepository.init(self)
169 self.do("init")
170 def module(self, mname):
171 "Create an empty module with a specified name."
172 module = os.path.join(self.directory, mname)
173 if verbose >= DEBUG_COMMANDS:
174 sys.stdout.write("Creating module %s\n" % module)
175 os.mkdir(module)
176 def checkout(self, module, checkout=None):
177 "Create a checkout of this repo."
178 self.checkouts.append(CVSCheckout(self, module, checkout))
179 return self.checkouts[-1]
180 def cleanup(self):
181 "Clean up the repository checkout directories."
182 if not self.retain:
183 RCSRepository.cleanup(self)
184 for checkout in self.checkouts:
185 checkout.cleanup()
186
187 class CVSCheckout(object):
188 PROXYSUFFIX = "-proxy"
189 SUFFIX = ".checkout"
190 def __init__(self, repo, module, checkout=None):
191 self.repo = repo
192 self.module = module or "module"
193 self.name = checkout or "%s-%s%s" % (repo.name, module, CVSCheckout.SUFFIX)
194 # Hack to get around repositories that don't have a CVSROOT & module
195 self.proxy = None
196 if not os.path.exists(self.repo.directory + os.sep + "CVSROOT"):
197 self.proxy = self.repo.name + CVSCheckout.PROXYSUFFIX
198 try:
199 shutil.rmtree(self.proxy)
200 except OSError:
201 pass
202 os.mkdir(self.proxy)
203 os.symlink(self.repo.directory, self.proxy + os.sep + self.module)
204 os.mkdir(self.proxy + os.sep + "CVSROOT")
205 self.repo.name += CVSCheckout.PROXYSUFFIX
206 self.repo.directory += CVSCheckout.PROXYSUFFIX
207 if os.path.exists(self.name):
208 shutil.rmtree(self.name)
209 self.repo.do("co", self.module)
210 os.rename(self.module, self.name)
211 self.directory = os.path.join(os.getcwd(), self.name)
212 def do(self, cmd, *args):
213 "Execute a command in the checkout directory."
214 with directory_context(self.directory):
215 self.repo.do(*([cmd] + list(args)))
216 def outdo(self, cmd):
217 "Execute a command in the checkout directory."
218 with directory_context(self.directory):
219 self.repo.run_with_cleanup(cmd)
220 def add(self, *filenames):
221 "Add a file to the version-controlled set."
222 self.do(*["add"] + list(filenames))
223 def remove(self, *files):
224 "Remove a file from the version-controlled set."
225 self.do(*["remove", "-f"] + list(files))
226 def branch(self, branchname):
227 "Create a new branch."
228 self.do("tag", branchname + "_root")
229 self.do("tag", "-r", branchname + "_root", "-b", branchname)
230 self.do("up", "-r", branchname)
231 def switch(self, branch="HEAD"):
232 "Switch to an existing branch."
233 self.do("up", "-A")
234 if branch != "HEAD":
235 self.do("up", "-r", "'" + branch + "'")
236 def tag(self, name):
237 "Create a tag."
238 self.do("tag", name)
239 def merge(self, branchname):
240 "Merge a branch to trunk."
241 # See https://kb.wisc.edu/middleware/page.php?id=4087
242 self.do("tag", "merge_" + branchname)
243 self.do("up", "-A")
244 self.do("up", "-j", branchname)
245 def commit(self, message):
246 "Commit changes to the repository."
247 # The CVS tools weren't designed to be called in rapid-fire
248 # succession by scripts; they have race conditions. This
249 # presents misbehavior.
250 time.sleep(2)
251 self.do(*["commit", "-m '%s'" % message])
252 def write(self, fn, content):
253 "Create file content in the repository."
254 if verbose >= DEBUG_COMMANDS:
255 sys.stdout.write("%s <- %s" % (fn, content))
256 with directory_context(self.directory):
257 with open(fn, "w") as fp:
258 fp.write(content)
259 def append(self, fn, content):
260 "Append to file content in the repository."
261 if verbose >= DEBUG_COMMANDS:
262 sys.stdout.write("%s <-| %s" % (fn, content))
263 with directory_context(self.directory):
264 with open(fn, "a") as fp:
265 fp.write(content)
266 def update(self, rev):
267 "Update the content to the specified revision or tag."
268 if rev == 'master':
269 rev = "HEAD"
270 self.do("up", "-kb", "-A", "-r", "'" + rev + "'")
271 def cleanup(self):
272 "Clean up the checkout directory."
273 if self.proxy and os.path.exists(self.proxy):
274 shutil.rmtree(self.proxy)
275 if os.path.exists(self.directory):
276 shutil.rmtree(self.directory)
277
278 def expect_same(a, b):
279 "Complain if two files aren't identical"
280 if not os.path.exists(a):
281 sys.stderr.write("%s does not exist in CVS.\n" % a)
282 return
283 if not os.path.exists(b):
284 sys.stderr.write("%s does not exist in the git conversion.\n" % b)
285 return
286 if not filecmp.cmp(a, b, shallow=False):
287 sys.stderr.write("%s and %s are not the same.\n" % (a, b))
288
289 def expect_different(a, b):
290 "Rejoice if two files are unexpectedly identical"
291 if not os.path.exists(a):
292 sys.stderr.write("%s does not exist in CVS.\n" % a)
293 return
294 if not os.path.exists(b):
295 sys.stderr.write("%s does not exist in the git conversion.\n" % b)
296 return
297 if filecmp.cmp(a, b, shallow=False):
298 sys.stderr.write("%s and %s are unexpectedly the same.\n" % (a, b))
299
300 def junkbranch(name):
301 "Is this a synthetic branch generated by cvs-fast-export?"
302 return name.startswith("import-") or name.find("UNNAMED") != -1
303
304 class ConvertComparison(object):
305 "Compare a CVS repository and its conversion for equality."
306 # Needs to stay synchronized with reposurgeon's generic conversion makefile
307 SUFFIX = "-git"
308 def __init__(self, srepo=None, smodule=None, checkout=None, options="", showdiffs=False):
309 self.repo = CVSRepository(srepo, readonly=True)
310 self.checkout = self.repo.checkout(smodule, checkout)
311 self.gitRepoName = "%s-%s%s" % (self.repo.name, self.checkout.module, ConvertComparison.SUFFIX)
312 self.showdiffs = showdiffs
313 self.repo.convert(self.checkout.module, self.gitRepoName, more_opts=options)
314
315 with directory_context(self.gitRepoName):
316 self.branches = [name for name in capture_or_die("git branch -l").split() if name != '*' and not junkbranch(name)]
317 self.tags = [name for name in capture_or_die("git tag -l").split()]
318 self.branches.sort()
319 if "master" in self.branches:
320 self.branches.remove("master")
321 self.branches = ["master"] + self.branches
322 def compare_tree(self, legend, ref, success_expected=True):
323 "Test to see if a tag or branch checkout has the expected content."
324 preamble = "%s %s %s: " % (self.repo.name, legend, ref)
325 if ref not in self.tags and ref not in self.branches:
326 if success_expected:
327 sys.stderr.write(preamble + "%s unexpectedly missing.\n" % ref)
328 return False
329 def ftw(mydir, ignore):
330 for root, _, files in os.walk(mydir):
331 for walkfile in files:
332 path = os.path.join(root, walkfile)
333 if ignore not in path.split(os.sep) and not path.endswith(".cvsignore") and not path.endswith(".gitignore"):
334 yield path
335 self.checkout.update(ref)
336 with directory_context(self.gitRepoName):
337 if not noisy_run("git checkout --quiet %s" % quote(ref)):
338 self.repo.cleanup()
339 sys.exit(1)
340 # with directory_context(self.gitRepoName):
341 # if not noisy_run("git log --format=%H -1"):
342 # self.repo.cleanup()
343 # sys.exit(1)
344 cvspaths = list(ftw(self.checkout.name, ignore="CVS"))
345 cvsfiles = [fn[len(self.checkout.name)+1:] for fn in cvspaths]
346 gitpaths = list(ftw(self.gitRepoName, ignore=".git"))
347 gitfiles = [fn[len(self.gitRepoName)+1:] for fn in gitpaths]
348 cvsfiles.sort()
349 gitfiles.sort()
350 success = True
351 if cvsfiles != gitfiles:
352 if success_expected:
353 sys.stderr.write(preamble + "file manifests don't match.\n")
354 if self.showdiffs:
355 sys.stderr.write(preamble + "common: %d\n" %
356 len([f for f in gitfiles if f in cvsfiles]))
357 gitspace_only = set([f for f in gitfiles if not f in cvsfiles])
358 if gitspace_only:
359 sys.stderr.write(preamble + "gitspace only: %s\n" %
360 gitspace_only)
361 cvs_only = set([f for f in cvsfiles if not f in gitfiles])
362 if cvs_only:
363 sys.stderr.write(preamble + "CVS only: %s\n" %
364 cvs_only)
365 success = False
366 common = [(path, path.replace(CVSCheckout.SUFFIX + "/", ConvertComparison.SUFFIX + "/"))
367 for path in cvspaths if path.replace(CVSCheckout.SUFFIX + "/", ConvertComparison.SUFFIX + "/") in gitpaths]
368 for (a, b) in common:
369 if not filecmp.cmp(a, b, shallow=False):
370 success = False
371 if success_expected:
372 sys.stderr.write("%s %s %s: %s and %s are different.\n" % (self.repo.name, legend, ref, a, b))
373 if self.showdiffs:
374 os.system("diff -u %s %s" % (a, b))
375 if success:
376 if not success_expected:
377 sys.stderr.write(preamble + "trees unexpectedly match\n")
378 elif verbose >= DEBUG_STEPS:
379 sys.stderr.write(preamble + "trees matched as expected\n")
380 elif not success:
381 if not success_expected and verbose >= DEBUG_STEPS:
382 sys.stderr.write(preamble + "trees diverged as expected\n")
383 return success
384 def checkall(self):
385 "Check all named references - branches and tags - expecting matches."
386 for branch in self.branches:
387 if branch.endswith("UNNAMED-BRANCH"):
388 if verbose > 0:
389 sys.stderr.write("%s: skipping %s\n" % (os.path.basename(sys.argv[0]), branch))
390 else:
391 cc.compare_tree("branch", branch)
392 for tag in cc.tags:
393 cc.compare_tree("tag", tag)
394 def command_returns(self, cmd, expected):
395 seen = capture_or_die(cmd)
396 succeeded = (seen.strip() == expected.strip())
397 if not succeeded:
398 sys.stderr.write(cmd + " return was not as expected\n")
399 def cleanup(self):
400 self.checkout.cleanup()
401 shutil.rmtree(self.gitRepoName)
402
403 # End.
404
405 # Copy of testlifter.py ends here
406
407 if __name__ == '__main__':
408 import getopt
409 (opts, arguments) = getopt.getopt(sys.argv[1:], "npqvA:")
410 retain = True
411 engine_opts = ""
412 quiet = False
413 for (opt, arg) in opts:
414 if opt == '-v':
415 verbose += 1
416 elif opt == '-n':
417 retain = False
418 elif opt == '-p':
419 engine_opts += " -p"
420 elif opt == '-q':
421 engine_opts += " -q"
422 elif opt == '-A':
423 engine_opts += " -A " + arg
424
425 if not arguments:
426 sys.stderr.write("cvsconvert: requires a repo/module argument.\n")
427 sys.exit(1)
428 elif "/" in arguments[0]:
429 (repo, module) = arguments[0].split('/', 1)
430 elif not os.path.isdir(arguments[0] + os.sep + "CVSROOT"):
431 (repo, module) = (arguments[0], None)
432 else:
433 candidates = [sub for sub in os.listdir(arguments[0]) if sub != "CVSROOT" and os.path.isdir(os.path.join(arguments[0], sub))]
434 if not candidates:
435 sys.stderr.write("cvsconvert: no modules under %s.\n" % arguments[0])
436 sys.exit(1)
437 elif len(candidates) > 1:
438 sys.stderr.write("cvsconvert: choose one of %s\n" % candidates)
439 sys.exit(1)
440 else:
441 (repo, module) = (arguments[0], candidates[0])
442 if "-q" not in engine_opts:
443 sys.stderr.write("cvsconvert: processing %s/%s\n" % (repo, module))
444 if repo == module:
445 sys.stderr.write("cvsconvert: repo directory and module name cannot be the same.\n")
446 sys.exit(1)
447 if not os.path.exists(repo):
448 sys.stderr.write("cvsconvert: repo %s does not exist.\n" % repo)
449 sys.exit(1)
450 if os.path.realpath(os.path.abspath(".")) == os.path.realpath(os.path.abspath(repo)):
451 sys.stderr.write("cvsconvert: repo directory cannot be the current directory.\n")
452 sys.exit(1)
453 cc = ConvertComparison(srepo=repo, smodule=module,
454 checkout=None,
455 options=engine_opts,
456 showdiffs=True)
457 if verbose == 0 and "-p" in engine_opts:
458 verbose = DEBUG_STEPS
459 cc.repo.retain = retain
460 cc.checkall()
461 cc.checkout.cleanup()
462 if retain:
463 sys.stderr.write("cvsconvert: conversion is in %s\n" % (cc.gitRepoName))
464 else:
465 cc.cleanup()
466
467 # end