Debian Codegraph @

tests/testlifter.py

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