Debian Codegraph @

cvsstrip

raw symbols SCIP
1 #!/usr/bin/env python3
2 # Runs under both Python 2 and Python 3: preserve this property!
3 # SPDX-License-Identifier: GPL-2.0+
4 """
5 cvsstrip - skeletonize CVS master files
6
7 Called as a filter, skeletonizes a CVS master presented on standard input
8 and write it to standard output. If an argument is specified, it must be
9 the name of a directory containing CVS master files; in that case a
10 corresponding directory of stripped files is created.
11
12 Options:
13 -o dir Set name of output directory. Defaults to the input dirname
14 with the suffix '-reduced'.
15 -t Suppress stripping of (non-sticky) tags. Sticky tags are
16 always preserved.
17 -l Suppress replacement of log content with a hash.
18 -c Suppress replacement of revision content.
19 -v Enable progress messages.
20
21 Default behavior is to strip non-sticky tags, replace each version
22 of content with a unique string including the revision ID, and
23 replace log text with its MD5 hash in hex.
24
25 The only identifying information left in the tree is filenames and CVS
26 user IDs.
27
28 The intent is to discard bulky content but preserve all metadata
29 relevant to changeset collation. A collection of stripped files should
30 imply the same changeset DAG as the unstripped originals, but be
31 easier to pass around, faster to process, and not reveal potentially
32 sensitive data.
33 """
34 import os, sys, getopt, hashlib, io, shutil
35
36 strip_tags = True
37 strip_logs = True
38 strip_content = True
39 verbose = 0
40
41 # Any encoding that preserves 0x80...0x8f through round-tripping from byte
42 # streams to Unicode and back would do, latin-1 is the best known of these.
43
44 binary_encoding = 'latin-1'
45
46 if str is bytes: # Python 2
47
48 polystr = str
49 polybytes = bytes
50 polyord = ord
51 polychr = str
52
53 else: # Python 3
54
55 def polystr(o):
56 if isinstance(o, str):
57 return o
58 if isinstance(o, bytes):
59 return str(o, encoding=binary_encoding)
60 raise ValueError
61
62 def polybytes(o):
63 if isinstance(o, bytes):
64 return o
65 if isinstance(o, str):
66 return bytes(o, encoding=binary_encoding)
67 raise ValueError
68
69 def polyord(c):
70 "Polymorphic ord() function"
71 if isinstance(c, str):
72 return ord(c)
73 return c
74
75 def polychr(c):
76 "Polymorphic chr() function"
77 if isinstance(c, int):
78 return chr(c)
79 return c
80
81 def make_std_wrapper(stream):
82 "Standard input/output wrapper factory function"
83 # This ensures that the encoding of standard output and standard
84 # error on Python 3 matches the binary encoding we use to turn
85 # bytes to Unicode in polystr above
86
87 # newline="\n" ensures that Python 3 won't mangle line breaks
88 # line_buffering=True ensures that interactive command sessions work as expected
89 return io.TextIOWrapper(stream.buffer, encoding=binary_encoding, newline="\n", line_buffering=True)
90
91 sys.stdin = make_std_wrapper(sys.stdin)
92 sys.stdout = make_std_wrapper(sys.stdout)
93 sys.stderr = make_std_wrapper(sys.stderr)
94
95 def replace_escaped_text(inputf, replacement, outputf):
96 "Replace text between @ delimiters with a specified string."
97 leader = polystr(inputf.read(1))
98 if leader != '@':
99 sys.stderr.write("cvsstrip: fatal error, @ leader not where expected.\n")
100 sys.exit(1)
101 else:
102 outputf.write('@' + replacement.replace("@", r'@@'))
103 while True:
104 nxt = inputf.read(1)
105 if nxt == '@':
106 nxt2 = inputf.read(1)
107 if nxt2 == '@':
108 continue
109 else:
110 break
111 if nxt2 == '\n':
112 outputf.write("@\n")
113 else:
114 sys.stderr.write("cvsstrip: fatal error, @ trailer not followed by newline (%s).\n" % nxt2)
115 sys.exit(1)
116
117 def hash_escaped_text(inputf, outputf):
118 "Replace text between @ delimiters with its MD5 hash."
119 leader = polystr(inputf.read(1))
120 if leader != '@':
121 sys.stderr.write("cvsstrip: fatal error, @ leader not where expected.\n")
122 sys.exit(1)
123 txt = ""
124 while True:
125 nxt = polystr(inputf.read(1))
126 if nxt == '@':
127 nxt2 = inputf.read(1)
128 if nxt2 == '@':
129 txt += "@"
130 continue
131 else:
132 break
133 txt += nxt
134 if nxt2 == '\n':
135 m = hashlib.md5()
136 m.update(polybytes(txt))
137 outputf.write("@%s\n@\n" % m.hexdigest())
138 else:
139 sys.stderr.write("cvsstrip: fatal error, @ trailer not followed by newline (%s).\n" % nxt2)
140 sys.exit(1)
141
142 def skeletonize(inputf, outputf):
143 "Skeletonize a CVS master, discarding content but leaving metadata."
144 state = "ini"
145 last_version = None
146 deltacount = 0
147 lineno = 0
148 while True:
149 lineno += 1
150 line = polystr(inputf.readline())
151 if not line:
152 break
153 if verbose > 1:
154 sys.stderr.write(b"%s: %s\n" % (state, line.strip()))
155 if state == 'ini':
156 if line.startswith("symbols"):
157 state = "sym"
158 elif line[0].isdigit():
159 last_version = line.strip()
160 elif line.startswith("log"):
161 if strip_logs:
162 outputf.write(polystr(line))
163 hash_escaped_text(inputf, outputf)
164 continue
165 elif line.startswith("text"):
166 if strip_content:
167 outputf.write(polystr(line))
168 txt = "%s content for %s\n" % (inputf.name, last_version)
169 if deltacount > 0:
170 txt = "d1 1\na1 1\n" + txt
171 deltacount += 1
172 replace_escaped_text(inputf, txt, outputf)
173 continue
174 elif state == "sym":
175 if not line[0] in (' ', '\t') or line.strip() == ';':
176 state = "ini"
177 elif strip_tags and '0' not in line.split(":")[1]:
178 if line.endswith(";\n"):
179 outputf.write("\t;\n")
180 continue
181 outputf.write(polystr(line))
182
183 if __name__ == '__main__':
184 (opts, arguments) = getopt.getopt(sys.argv[1:], "ctlo:v")
185 outdir = None
186 for (opt, arg) in opts:
187 if opt == '-t':
188 strip_tags = False
189 elif opt == '-l':
190 strip_logs = False
191 elif opt == '-c':
192 strip_content = False
193 elif opt == '-o':
194 outdir = arg
195 elif opt == '-v':
196 verbose += 1
197
198 if not arguments:
199 skeletonize(sys.stdin, sys.stdout)
200 sys.exit(0)
201 elif not os.path.isdir(arguments[0]):
202 sys.stderr.write("cvsstrip: argument must be a directory.\n")
203 sys.exit(1)
204
205 originals = arguments[0]
206 if not outdir:
207 outdir = originals + "-reduced"
208 if os.path.exists(outdir):
209 sys.stderr.write("cvsstrip: refusing to step on %s.\n" % outdir)
210 sys.exit(1)
211
212 # Directory traversal
213 for dirName, subdirList, fileList in os.walk(originals):
214 path_parts = list(dirName.split(os.sep))
215 path_parts.pop(0)
216 newparts = [outdir] + path_parts
217 for i in range(len(newparts)):
218 newdir = os.path.join(*newparts[:i+1])
219 if not os.path.exists(newdir):
220 if verbose:
221 print("Directory creation: %s" % newdir)
222 os.mkdir(newdir)
223 for fname in fileList:
224 oldname = os.path.join(dirName, fname)
225 newpath = newparts + [fname]
226 newname = os.path.join(*newpath)
227 if verbose > 0:
228 print('%s -> %s' % (oldname, newname))
229 if oldname.endswith(',v'):
230 old = open(oldname, "rb")
231 new = open(newname, "wb")
232 skeletonize(old, new)
233 old.close()
234 new.close()
235 else:
236 sys.stderr.write("cvsstrip: %s isn't a CVS master.\n" % oldname)
237 shutil.copyfile(oldname, newname)
238
239 # end