Debian Codegraph @

contrib/testparseutil.py

raw
1 # testparseutil.py - utilities to parse test script for check tools
2 #
3 # Copyright 2018 FUJIWARA Katsunori <[email protected]> and others
4 #
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
7
8
9 import abc
10 import builtins
11 import re
12
13 ####################
14 # for Python3 compatibility (almost comes from mercurial/pycompat.py)
15
16
17 def identity(a):
18 return a
19
20
21 def _rapply(f, xs):
22 if xs is None:
23 # assume None means non-value of optional data
24 return xs
25 if isinstance(xs, (list, set, tuple)):
26 return type(xs)(_rapply(f, x) for x in xs)
27 if isinstance(xs, dict):
28 return type(xs)((_rapply(f, k), _rapply(f, v)) for k, v in xs.items())
29 return f(xs)
30
31
32 def rapply(f, xs):
33 if f is identity:
34 # fast path mainly for py2
35 return xs
36 return _rapply(f, xs)
37
38
39 def bytestr(s):
40 # tiny version of pycompat.bytestr
41 return s.encode('latin1')
42
43
44 def sysstr(s):
45 if isinstance(s, builtins.str):
46 return s
47 return s.decode('latin-1')
48
49
50 def opentext(f):
51 return open(f)
52
53
54 def b2s(x):
55 # convert BYTES elements in "x" to SYSSTR recursively
56 return rapply(sysstr, x)
57
58
59 def writeout(data):
60 # write "data" in BYTES into stdout
61 sys.stdout.write(data)
62
63
64 def writeerr(data):
65 # write "data" in BYTES into stderr
66 sys.stderr.write(data)
67
68
69 ####################
70
71
72 class embeddedmatcher: # pytype: disable=ignored-metaclass
73 """Base class to detect embedded code fragments in *.t test script"""
74
75 __metaclass__ = abc.ABCMeta
76
77 def __init__(self, desc):
78 self.desc = desc
79
80 @abc.abstractmethod
81 def startsat(self, line):
82 """Examine whether embedded code starts at line
83
84 This can return arbitrary object, and it is used as 'ctx' for
85 subsequent method invocations.
86 """
87
88 @abc.abstractmethod
89 def endsat(self, ctx, line):
90 """Examine whether embedded code ends at line"""
91
92 @abc.abstractmethod
93 def isinside(self, ctx, line):
94 """Examine whether line is inside embedded code, if not yet endsat"""
95
96 @abc.abstractmethod
97 def ignores(self, ctx):
98 """Examine whether detected embedded code should be ignored"""
99
100 @abc.abstractmethod
101 def filename(self, ctx):
102 """Return filename of embedded code
103
104 If filename isn't specified for embedded code explicitly, this
105 returns None.
106 """
107
108 @abc.abstractmethod
109 def codeatstart(self, ctx, line):
110 """Return actual code at the start line of embedded code
111
112 This might return None, if the start line doesn't contain
113 actual code.
114 """
115
116 @abc.abstractmethod
117 def codeatend(self, ctx, line):
118 """Return actual code at the end line of embedded code
119
120 This might return None, if the end line doesn't contain actual
121 code.
122 """
123
124 @abc.abstractmethod
125 def codeinside(self, ctx, line):
126 """Return actual code at line inside embedded code"""
127
128
129 def embedded(basefile, lines, errors, matchers):
130 """pick embedded code fragments up from given lines
131
132 This is common parsing logic, which examines specified matchers on
133 given lines.
134
135 :basefile: a name of a file, from which lines to be parsed come.
136 :lines: to be parsed (might be a value returned by "open(basefile)")
137 :errors: an array, into which messages for detected error are stored
138 :matchers: an array of embeddedmatcher objects
139
140 This function yields '(filename, starts, ends, code)' tuple.
141
142 :filename: a name of embedded code, if it is explicitly specified
143 (e.g. "foobar" of "cat >> foobar <<EOF").
144 Otherwise, this is None
145 :starts: line number (1-origin), at which embedded code starts (inclusive)
146 :ends: line number (1-origin), at which embedded code ends (exclusive)
147 :code: extracted embedded code, which is single-stringified
148
149 >>> class ambigmatcher:
150 ... # mock matcher class to examine implementation of
151 ... # "ambiguous matching" corner case
152 ... def __init__(self, desc, matchfunc):
153 ... self.desc = desc
154 ... self.matchfunc = matchfunc
155 ... def startsat(self, line):
156 ... return self.matchfunc(line)
157 >>> ambig1 = ambigmatcher('ambiguous #1',
158 ... lambda l: l.startswith(' $ cat '))
159 >>> ambig2 = ambigmatcher('ambiguous #2',
160 ... lambda l: l.endswith('<< EOF\\n'))
161 >>> lines = [' $ cat > foo.py << EOF\\n']
162 >>> errors = []
163 >>> matchers = [ambig1, ambig2]
164 >>> list(t for t in embedded('<dummy>', lines, errors, matchers))
165 []
166 >>> b2s(errors)
167 ['<dummy>:1: ambiguous line for "ambiguous #1", "ambiguous #2"']
168
169 """
170 matcher = None
171 ctx = filename = code = startline = None # for pyflakes
172
173 for lineno, line in enumerate(lines, 1):
174 if not line.endswith('\n'):
175 line += '\n' # to normalize EOF line
176 if matcher: # now, inside embedded code
177 if matcher.endsat(ctx, line):
178 codeatend = matcher.codeatend(ctx, line)
179 if codeatend is not None:
180 code.append(codeatend)
181 if not matcher.ignores(ctx):
182 yield (filename, startline, lineno, ''.join(code))
183 matcher = None
184 # DO NOT "continue", because line might start next fragment
185 elif not matcher.isinside(ctx, line):
186 # this is an error of basefile
187 # (if matchers are implemented correctly)
188 errors.append(
189 '%s:%d: unexpected line for "%s"'
190 % (basefile, lineno, matcher.desc)
191 )
192 # stop extracting embedded code by current 'matcher',
193 # because appearance of unexpected line might mean
194 # that expected end-of-embedded-code line might never
195 # appear
196 matcher = None
197 # DO NOT "continue", because line might start next fragment
198 else:
199 code.append(matcher.codeinside(ctx, line))
200 continue
201
202 # examine whether current line starts embedded code or not
203 assert not matcher
204
205 matched = []
206 for m in matchers:
207 ctx = m.startsat(line)
208 if ctx:
209 matched.append((m, ctx))
210 if matched:
211 if len(matched) > 1:
212 # this is an error of matchers, maybe
213 errors.append(
214 '%s:%d: ambiguous line for %s'
215 % (
216 basefile,
217 lineno,
218 ', '.join(['"%s"' % m.desc for m, c in matched]),
219 )
220 )
221 # omit extracting embedded code, because choosing
222 # arbitrary matcher from matched ones might fail to
223 # detect the end of embedded code as expected.
224 continue
225 matcher, ctx = matched[0]
226 filename = matcher.filename(ctx)
227 code = []
228 codeatstart = matcher.codeatstart(ctx, line)
229 if codeatstart is not None:
230 code.append(codeatstart)
231 startline = lineno
232 else:
233 startline = lineno + 1
234
235 if matcher:
236 # examine whether EOF ends embedded code, because embedded
237 # code isn't yet ended explicitly
238 if matcher.endsat(ctx, '\n'):
239 codeatend = matcher.codeatend(ctx, '\n')
240 if codeatend is not None:
241 code.append(codeatend)
242 if not matcher.ignores(ctx):
243 yield (filename, startline, lineno + 1, ''.join(code))
244 else:
245 # this is an error of basefile
246 # (if matchers are implemented correctly)
247 errors.append(
248 '%s:%d: unexpected end of file for "%s"'
249 % (basefile, lineno, matcher.desc)
250 )
251
252
253 # heredoc limit mark to ignore embedded code at check-code.py or so
254 heredocignorelimit = 'NO_CHECK_EOF'
255
256 # the pattern to match against cases below, and to return a limit mark
257 # string as 'lname' group
258 #
259 # - << LIMITMARK
260 # - << "LIMITMARK"
261 # - << 'LIMITMARK'
262 heredoclimitpat = r'\s*<<\s*(?P<lquote>["\']?)(?P<limit>\w+)(?P=lquote)'
263
264
265 class fileheredocmatcher(embeddedmatcher):
266 """Detect "cat > FILE << LIMIT" style embedded code
267
268 >>> matcher = fileheredocmatcher('heredoc .py file', r'[^<]+\\.py')
269 >>> b2s(matcher.startsat(' $ cat > file.py << EOF\\n'))
270 ('file.py', ' > EOF\\n')
271 >>> b2s(matcher.startsat(' $ cat >>file.py <<EOF\\n'))
272 ('file.py', ' > EOF\\n')
273 >>> b2s(matcher.startsat(' $ cat> \\x27any file.py\\x27<< "EOF"\\n'))
274 ('any file.py', ' > EOF\\n')
275 >>> b2s(matcher.startsat(" $ cat > file.py << 'ANYLIMIT'\\n"))
276 ('file.py', ' > ANYLIMIT\\n')
277 >>> b2s(matcher.startsat(' $ cat<<ANYLIMIT>"file.py"\\n'))
278 ('file.py', ' > ANYLIMIT\\n')
279 >>> start = ' $ cat > file.py << EOF\\n'
280 >>> ctx = matcher.startsat(start)
281 >>> matcher.codeatstart(ctx, start)
282 >>> b2s(matcher.filename(ctx))
283 'file.py'
284 >>> matcher.ignores(ctx)
285 False
286 >>> inside = ' > foo = 1\\n'
287 >>> matcher.endsat(ctx, inside)
288 False
289 >>> matcher.isinside(ctx, inside)
290 True
291 >>> b2s(matcher.codeinside(ctx, inside))
292 'foo = 1\\n'
293 >>> end = ' > EOF\\n'
294 >>> matcher.endsat(ctx, end)
295 True
296 >>> matcher.codeatend(ctx, end)
297 >>> matcher.endsat(ctx, ' > EOFEOF\\n')
298 False
299 >>> ctx = matcher.startsat(' $ cat > file.py << NO_CHECK_EOF\\n')
300 >>> matcher.ignores(ctx)
301 True
302 """
303
304 _prefix = ' > '
305
306 def __init__(self, desc, namepat):
307 super().__init__(desc)
308
309 # build the pattern to match against cases below (and ">>"
310 # variants), and to return a target filename string as 'name'
311 # group
312 #
313 # - > NAMEPAT
314 # - > "NAMEPAT"
315 # - > 'NAMEPAT'
316 namepat = (
317 r'\s*>>?\s*(?P<nquote>["\']?)(?P<name>%s)(?P=nquote)' % namepat
318 )
319 self._fileres = [
320 # "cat > NAME << LIMIT" case
321 re.compile(r' {2}\$ \s*cat' + namepat + heredoclimitpat),
322 # "cat << LIMIT > NAME" case
323 re.compile(r' {2}\$ \s*cat' + heredoclimitpat + namepat),
324 ]
325
326 def startsat(self, line):
327 # ctx is (filename, END-LINE-OF-EMBEDDED-CODE) tuple
328 for filere in self._fileres:
329 matched = filere.match(line)
330 if matched:
331 return (
332 matched.group('name'),
333 ' > %s\n' % matched.group('limit'),
334 )
335
336 def endsat(self, ctx, line):
337 return ctx[1] == line
338
339 def isinside(self, ctx, line):
340 return line.startswith(self._prefix)
341
342 def ignores(self, ctx):
343 return ' > %s\n' % heredocignorelimit == ctx[1]
344
345 def filename(self, ctx):
346 return ctx[0]
347
348 def codeatstart(self, ctx, line):
349 return None # no embedded code at start line
350
351 def codeatend(self, ctx, line):
352 return None # no embedded code at end line
353
354 def codeinside(self, ctx, line):
355 return line[len(self._prefix) :] # strip prefix
356
357
358 ####
359 # for embedded python script
360
361
362 class pydoctestmatcher(embeddedmatcher):
363 """Detect ">>> code" style embedded python code
364
365 >>> matcher = pydoctestmatcher()
366 >>> startline = ' >>> foo = 1\\n'
367 >>> matcher.startsat(startline)
368 True
369 >>> matcher.startsat(' ... foo = 1\\n')
370 False
371 >>> ctx = matcher.startsat(startline)
372 >>> matcher.filename(ctx)
373 >>> matcher.ignores(ctx)
374 False
375 >>> b2s(matcher.codeatstart(ctx, startline))
376 'foo = 1\\n'
377 >>> inside = ' >>> foo = 1\\n'
378 >>> matcher.endsat(ctx, inside)
379 False
380 >>> matcher.isinside(ctx, inside)
381 True
382 >>> b2s(matcher.codeinside(ctx, inside))
383 'foo = 1\\n'
384 >>> inside = ' ... foo = 1\\n'
385 >>> matcher.endsat(ctx, inside)
386 False
387 >>> matcher.isinside(ctx, inside)
388 True
389 >>> b2s(matcher.codeinside(ctx, inside))
390 'foo = 1\\n'
391 >>> inside = ' expected output\\n'
392 >>> matcher.endsat(ctx, inside)
393 False
394 >>> matcher.isinside(ctx, inside)
395 True
396 >>> b2s(matcher.codeinside(ctx, inside))
397 '\\n'
398 >>> inside = ' \\n'
399 >>> matcher.endsat(ctx, inside)
400 False
401 >>> matcher.isinside(ctx, inside)
402 True
403 >>> b2s(matcher.codeinside(ctx, inside))
404 '\\n'
405 >>> end = ' $ foo bar\\n'
406 >>> matcher.endsat(ctx, end)
407 True
408 >>> matcher.codeatend(ctx, end)
409 >>> end = '\\n'
410 >>> matcher.endsat(ctx, end)
411 True
412 >>> matcher.codeatend(ctx, end)
413 """
414
415 _prefix = ' >>> '
416 _prefixre = re.compile(r' {2}(>>>|\.\.\.) ')
417
418 # If a line matches against not _prefixre but _outputre, that line
419 # is "an expected output line" (= not a part of code fragment).
420 #
421 # Strictly speaking, a line matching against "(#if|#else|#endif)"
422 # is also treated similarly in "inline python code" semantics by
423 # run-tests.py. But "directive line inside inline python code"
424 # should be rejected by Mercurial reviewers. Therefore, this
425 # regexp does not matche against such directive lines.
426 _outputre = re.compile(r' {2}$| {2}[^$]')
427
428 def __init__(self):
429 super().__init__("doctest style python code")
430
431 def startsat(self, line):
432 # ctx is "True"
433 return line.startswith(self._prefix)
434
435 def endsat(self, ctx, line):
436 return not (self._prefixre.match(line) or self._outputre.match(line))
437
438 def isinside(self, ctx, line):
439 return True # always true, if not yet ended
440
441 def ignores(self, ctx):
442 return False # should be checked always
443
444 def filename(self, ctx):
445 return None # no filename
446
447 def codeatstart(self, ctx, line):
448 return line[len(self._prefix) :] # strip prefix ' >>> '/' ... '
449
450 def codeatend(self, ctx, line):
451 return None # no embedded code at end line
452
453 def codeinside(self, ctx, line):
454 if self._prefixre.match(line):
455 return line[len(self._prefix) :] # strip prefix ' >>> '/' ... '
456 return '\n' # an expected output line is treated as an empty line
457
458
459 class pyheredocmatcher(embeddedmatcher):
460 """Detect "python << LIMIT" style embedded python code
461
462 >>> matcher = pyheredocmatcher()
463 >>> b2s(matcher.startsat(' $ python << EOF\\n'))
464 ' > EOF\\n'
465 >>> b2s(matcher.startsat(' $ $PYTHON <<EOF\\n'))
466 ' > EOF\\n'
467 >>> b2s(matcher.startsat(' $ "$PYTHON"<< "EOF"\\n'))
468 ' > EOF\\n'
469 >>> b2s(matcher.startsat(" $ $PYTHON << 'ANYLIMIT'\\n"))
470 ' > ANYLIMIT\\n'
471 >>> matcher.startsat(' $ "$PYTHON" < EOF\\n')
472 >>> start = ' $ python << EOF\\n'
473 >>> ctx = matcher.startsat(start)
474 >>> matcher.codeatstart(ctx, start)
475 >>> matcher.filename(ctx)
476 >>> matcher.ignores(ctx)
477 False
478 >>> inside = ' > foo = 1\\n'
479 >>> matcher.endsat(ctx, inside)
480 False
481 >>> matcher.isinside(ctx, inside)
482 True
483 >>> b2s(matcher.codeinside(ctx, inside))
484 'foo = 1\\n'
485 >>> end = ' > EOF\\n'
486 >>> matcher.endsat(ctx, end)
487 True
488 >>> matcher.codeatend(ctx, end)
489 >>> matcher.endsat(ctx, ' > EOFEOF\\n')
490 False
491 >>> ctx = matcher.startsat(' $ python << NO_CHECK_EOF\\n')
492 >>> matcher.ignores(ctx)
493 True
494 """
495
496 _prefix = ' > '
497
498 _startre = re.compile(
499 r' {2}\$ (\$PYTHON|"\$PYTHON"|python).*' + heredoclimitpat
500 )
501
502 def __init__(self):
503 super().__init__("heredoc python invocation")
504
505 def startsat(self, line):
506 # ctx is END-LINE-OF-EMBEDDED-CODE
507 matched = self._startre.match(line)
508 if matched:
509 return ' > %s\n' % matched.group('limit')
510
511 def endsat(self, ctx, line):
512 return ctx == line
513
514 def isinside(self, ctx, line):
515 return line.startswith(self._prefix)
516
517 def ignores(self, ctx):
518 return ' > %s\n' % heredocignorelimit == ctx
519
520 def filename(self, ctx):
521 return None # no filename
522
523 def codeatstart(self, ctx, line):
524 return None # no embedded code at start line
525
526 def codeatend(self, ctx, line):
527 return None # no embedded code at end line
528
529 def codeinside(self, ctx, line):
530 return line[len(self._prefix) :] # strip prefix
531
532
533 _pymatchers = [
534 pydoctestmatcher(),
535 pyheredocmatcher(),
536 # use '[^<]+' instead of '\S+', in order to match against
537 # paths including whitespaces
538 fileheredocmatcher('heredoc .py file', r'[^<]+\.py'),
539 ]
540
541
542 def pyembedded(basefile, lines, errors):
543 return embedded(basefile, lines, errors, _pymatchers)
544
545
546 ####
547 # for embedded shell script
548
549 _shmatchers = [
550 # use '[^<]+' instead of '\S+', in order to match against
551 # paths including whitespaces
552 fileheredocmatcher('heredoc .sh file', r'[^<]+\.sh'),
553 ]
554
555
556 def shembedded(basefile, lines, errors):
557 return embedded(basefile, lines, errors, _shmatchers)
558
559
560 ####
561 # for embedded hgrc configuration
562
563 _hgrcmatchers = [
564 # use '[^<]+' instead of '\S+', in order to match against
565 # paths including whitespaces
566 fileheredocmatcher(
567 'heredoc hgrc file', r'(([^/<]+/)+hgrc|\$HGRCPATH|\${HGRCPATH})'
568 ),
569 ]
570
571
572 def hgrcembedded(basefile, lines, errors):
573 return embedded(basefile, lines, errors, _hgrcmatchers)
574
575
576 ####
577
578 if __name__ == "__main__":
579 import optparse
580 import sys
581
582 def showembedded(basefile, lines, embeddedfunc, opts):
583 errors = []
584 for name, starts, ends, code in embeddedfunc(basefile, lines, errors):
585 if not name:
586 name = '<anonymous>'
587 writeout("%s:%d: %s starts\n" % (basefile, starts, name))
588 if opts.verbose and code:
589 writeout(" |%s\n" % "\n |".join(l for l in code.splitlines()))
590 writeout("%s:%d: %s ends\n" % (basefile, ends, name))
591 for e in errors:
592 writeerr("%s\n" % e)
593 return len(errors)
594
595 def applyembedded(args, embeddedfunc, opts):
596 ret = 0
597 if args:
598 for f in args:
599 with opentext(f) as fp:
600 if showembedded(f, fp, embeddedfunc, opts):
601 ret = 1
602 else:
603 lines = [l for l in sys.stdin.readlines()]
604 if showembedded('<stdin>', lines, embeddedfunc, opts):
605 ret = 1
606 return ret
607
608 commands = {}
609
610 def command(name, desc):
611 def wrap(func):
612 commands[name] = (desc, func)
613
614 return wrap
615
616 @command("pyembedded", "detect embedded python script")
617 def pyembeddedcmd(args, opts):
618 return applyembedded(args, pyembedded, opts)
619
620 @command("shembedded", "detect embedded shell script")
621 def shembeddedcmd(args, opts):
622 return applyembedded(args, shembedded, opts)
623
624 @command("hgrcembedded", "detect embedded hgrc configuration")
625 def hgrcembeddedcmd(args, opts):
626 return applyembedded(args, hgrcembedded, opts)
627
628 availablecommands = "\n".join(
629 [" - %s: %s" % (key, value[0]) for key, value in commands.items()]
630 )
631
632 parser = optparse.OptionParser(
633 """%prog COMMAND [file ...]
634
635 Pick up embedded code fragments from given file(s) or stdin, and list
636 up start/end lines of them in standard compiler format
637 ("FILENAME:LINENO:").
638
639 Available commands are:
640 """
641 + availablecommands
642 + """
643 """
644 )
645 parser.add_option(
646 "-v",
647 "--verbose",
648 help="enable additional output (e.g. actual code)",
649 action="store_true",
650 )
651 (opts, args) = parser.parse_args()
652
653 if not args or args[0] not in commands:
654 parser.print_help()
655 sys.exit(255)
656
657 sys.exit(commands[args[0]][1](args[1:], opts))