ยปCore Development>Code coverage>Tools/scripts/rgrep.py

Python code coverage for Tools/scripts/rgrep.py

#countcontent
1n/a#! /usr/bin/env python3
2n/a
3n/a"""Reverse grep.
4n/a
5n/aUsage: rgrep [-i] pattern file
6n/a"""
7n/a
8n/aimport sys
9n/aimport re
10n/aimport getopt
11n/a
12n/a
13n/adef main():
14n/a bufsize = 64 * 1024
15n/a reflags = 0
16n/a opts, args = getopt.getopt(sys.argv[1:], "i")
17n/a for o, a in opts:
18n/a if o == '-i':
19n/a reflags = reflags | re.IGNORECASE
20n/a if len(args) < 2:
21n/a usage("not enough arguments")
22n/a if len(args) > 2:
23n/a usage("exactly one file argument required")
24n/a pattern, filename = args
25n/a try:
26n/a prog = re.compile(pattern, reflags)
27n/a except re.error as msg:
28n/a usage("error in regular expression: %s" % msg)
29n/a try:
30n/a f = open(filename)
31n/a except IOError as msg:
32n/a usage("can't open %r: %s" % (filename, msg), 1)
33n/a f.seek(0, 2)
34n/a pos = f.tell()
35n/a leftover = None
36n/a while pos > 0:
37n/a size = min(pos, bufsize)
38n/a pos = pos - size
39n/a f.seek(pos)
40n/a buffer = f.read(size)
41n/a lines = buffer.split("\n")
42n/a del buffer
43n/a if leftover is None:
44n/a if not lines[-1]:
45n/a del lines[-1]
46n/a else:
47n/a lines[-1] = lines[-1] + leftover
48n/a if pos > 0:
49n/a leftover = lines[0]
50n/a del lines[0]
51n/a else:
52n/a leftover = None
53n/a for line in reversed(lines):
54n/a if prog.search(line):
55n/a print(line)
56n/a
57n/a
58n/adef usage(msg, code=2):
59n/a sys.stdout = sys.stderr
60n/a print(msg)
61n/a print(__doc__)
62n/a sys.exit(code)
63n/a
64n/a
65n/aif __name__ == '__main__':
66n/a main()