Debian Codegraph @

texk/web2c/tests/fix-changefile-lines.py

raw
1 #!/usr/bin/env python3
2 # $Id: fix-changefile-lines.py 74543 2025-03-09 09:22:22Z ascherer $
3 # Applied to tex.ch and mf.ch on 2024-06-03, following the request at:
4 # https://tug.org/pipermail/tex-k/2024-June/004064.html
5 """
6 Reads a WEB file and a change file and writes a change file to stdout with
7 potentially corrected part, section and line numbers.
8 Written by Tyge Tiessen, 2024. Public domain.
9 """
10
11 import getopt, os, re, sys
12
13 USAGE = f"""
14 Usage: {os.path.basename(sys.argv[0])} [-i|--init] <web file> <change file>
15
16 Reads a WEB file and a change file and writes a change file to stdout with
17 potentially corrected part, section and line numbers.
18
19 The option '-i' ('--init') forces a '[part.section] l.line' tag after each
20 '@x'; this is useful for untagged change files.
21
22 Written by Tyge Tiessen, 2024. Public domain.
23 """.strip()
24
25
26 def main():
27 # Handle command-line options
28 opt_handler = OptHandler()
29
30 # Read WEB file
31 web_reader = WebReader(opt_handler.args[0])
32
33 # Read change file
34 ch_reader = ChangeReader(opt_handler.args[1])
35
36 # Run through the two files in parallel
37 ch_reader.traverse(web_reader, opt_handler)
38
39 for line in ch_reader.get_lines():
40 print(line)
41
42
43 class WebReader:
44 """An iterator that produces the lines of a WEB file while keeping track
45 of the current part and section number.
46 """
47
48 def __init__(self, web_file):
49 self._pos = 0
50 self.part_cnt = 0
51 self.section_cnt = 0
52 try:
53 with open(web_file, "r") as file:
54 self._web_lines = [line.rstrip() for line in file]
55 except OSError:
56 eprint(f"Could not open {web_file}")
57 print(USAGE)
58 sys.exit(1)
59
60 def next_line(self):
61 """Returns the triple of current part, section and line numbers,
62 as well as the next line. Updates part and section numbers.
63 """
64 if self._pos >= len(self._web_lines):
65 return None
66 line = self._web_lines[self._pos]
67
68 # Look for starred section == part
69 if line.startswith("@*"):
70 self.part_cnt += 1
71 self.section_cnt += 1
72
73 # Look for unstarred section
74 if line.startswith("@ ") or line == "@":
75 self.section_cnt += 1
76
77 # Prepare return values
78 part = self.part_cnt
79 section = self.section_cnt
80 line_number = self._pos = self._pos + 1
81
82 # Look for '@i'nclude line
83 result = re.match("^@i \"?(\\w+(\\.\\w+)?)\"?", line)
84 if result:
85 inc_reader = WebReader(result[1])
86 while inc_reader.next_line():
87 pass
88 self.part_cnt += inc_reader.part_cnt
89 self.section_cnt += inc_reader.section_cnt
90 # Do not increase 'part' and 'section' just yet
91 # Ignore line count in include file; we're only one step beyond
92
93 return (part, section, line_number), line
94
95
96 class ChangeReader:
97 """Reads the lines of a change file while updating the tags with
98 information from the corresponding WEB file.
99 """
100
101 def __init__(self, change_file):
102 self._pos = 0
103 self._chunk_start = None
104 self._match_lines = None
105 try:
106 with open(change_file, "r") as file:
107 self._lines = [line.rstrip() for line in file]
108 except OSError:
109 eprint(f"Could not open {change_file}")
110 print(USAGE)
111 sys.exit(1)
112
113 def advance_to_next_chunk(self):
114 """Find the next change chunk. Store where it starts and
115 the lines to be matched.
116 """
117
118 while self._pos < len(self._lines):
119 line = self._lines[self._pos]
120 if line.startswith("@x"):
121 self._chunk_start = self._pos
122 while True:
123 self._pos += 1
124 if self._pos >= len(self._lines):
125 eprint(f"! Change file ended before @y. " +
126 f"(l. {self._pos+1} of change file)")
127 sys.exit(1)
128 line = self._lines[self._pos]
129 if line.startswith("@y"):
130 self._match_lines = self._lines[
131 self._chunk_start + 1 : self._pos
132 ]
133 return True
134 elif line.startswith("@x") or line.startswith("@z"):
135 eprint(f"! Where is the matching @y?. " +
136 f"(l. {self._pos+1} of change file)")
137 eprint(line)
138 sys.exit(1)
139 self._pos += 1
140 return False
141
142 def find_match_in_web(self, web_reader):
143 """Find the match for the current change chunk in the WEB file.
144 Returns the part, section, and line number of the first match line
145 in the WEB file.
146 """
147 while True:
148 try:
149 (part, section, line_number), tex_line = web_reader.next_line()
150 except:
151 eprint(f"! Change file entry did not match. " +
152 f"(l. {self._chunk_start+2} of change file)")
153 eprint(self._match_lines[0])
154 sys.exit(1)
155 if tex_line == self._match_lines[0]:
156 for i in range(1, len(self._match_lines)):
157 try:
158 _, tex_line = web_reader.next_line()
159 except:
160 tex_line = None
161 if tex_line is None or tex_line != self._match_lines[i]:
162 eprint(f"! Change file entry did not match. " +
163 f"(l. {self._chunk_start+2+i} of change file)")
164 eprint(self._match_lines[i])
165 sys.exit(1)
166
167 return part, section, line_number
168
169 def traverse(self, web_reader, opt_handler):
170 """Go through all individual change chunks while updating their tags."""
171 while self.advance_to_next_chunk():
172 part, section, line_number = self.find_match_in_web(web_reader)
173
174 # Replace '@x' line with updated information.
175 new_line = self._lines[self._chunk_start]
176
177 new_line = re.sub(
178 "\\[\\d+\\.\\d+\\]", f"[{part}.{section}]",
179 new_line, count=1)
180 new_line = re.sub(
181 "^@x \\[\\d+\\]", f"@x [{section}]",
182 new_line, count=1)
183 new_line = re.sub(
184 "l\\.\\d+", f"l.{line_number}",
185 new_line, count=1)
186
187 # Force '[part.section] l.line' tag after '@x'; useful for untagged
188 # change files, e.g., CWEB's '*-w2c.ch' monsters.
189 if opt_handler.init_b:
190 new_line = re.sub(
191 "^@x", f"@x [{part}.{section}] l.{line_number}",
192 new_line, count=1)
193
194 ch_line = self._lines[self._chunk_start]
195 if new_line[:10] != ch_line[:10]:
196 eprint("Old:")
197 eprint(f" {ch_line}")
198 eprint("New:")
199 eprint(f" {new_line}")
200 eprint()
201
202 self._lines[self._chunk_start] = new_line
203
204 def get_lines(self):
205 return self._lines
206
207
208 class OptHandler:
209 """Parses the invocation line and extracts the options.
210 Returns the remaining arguments, i.e., the WEB and Change File names.
211 """
212
213 def __init__(self):
214 # Should we insert tag '[{part}.{section}] l.{line}' after '@x'?
215 self.init_b = False
216
217 try:
218 opts, self.args = getopt.getopt(sys.argv[1:], "i", ["init"])
219 except getopt.GetoptError as err:
220 eprint(f"\n{os.path.basename(sys.argv[0])}: {err}!\n")
221 print(USAGE)
222 sys.exit(1)
223
224 for opt, _ in opts:
225 if opt in ("-i", "--init"):
226 self.init_b = True
227 else:
228 assert False, f"Unhandled option {opt}"
229
230 if len(self.args) != 2:
231 print(USAGE)
232 sys.exit(1)
233
234
235 def eprint(*args, **kwargs):
236 """Print to stderr."""
237 print(*args, file=sys.stderr, **kwargs)
238
239
240 if __name__ == "__main__":
241 main()