|
1 | 1 | import re |
2 | 2 |
|
3 | | -import grep_test as gt # type: ignore[import-not-found] |
4 | | - |
5 | 3 |
|
6 | 4 | def grep(pattern: str, flags: str, files: list[str]) -> str: |
7 | 5 | filename = len(files) > 1 |
8 | 6 | line_numbers = "-n" in flags |
9 | 7 | name_only = "-l" in flags |
10 | 8 |
|
11 | | - pattern_txt = __build_pattern(flags).replace("{}", pattern) |
| 9 | + pattern_txt = _build_pattern(pattern, flags) |
12 | 10 | p = re.compile(rf"{pattern_txt}") |
13 | | - result = [] |
| 11 | + result: list[str] = [] |
14 | 12 |
|
15 | 13 | for f in files: |
16 | | - lines = gt.FILE_TEXT[f].splitlines() |
17 | | - for line_num, line in enumerate(lines): |
18 | | - if not re.search(p, line): |
19 | | - continue |
20 | | - if name_only: |
21 | | - result.append(f) |
22 | | - break |
23 | | - temp = [] |
24 | | - if filename: |
25 | | - temp.append(f"{f}:") |
26 | | - if line_numbers: |
27 | | - temp.append(f"{line_num + 1}:") |
28 | | - temp.append(line) |
29 | | - result.append("".join(temp)) |
| 14 | + with open(f, encoding="UTF-8") as file: |
| 15 | + line_num = -1 |
| 16 | + while line := file.readline().rstrip("\n"): |
| 17 | + line_num += 1 |
| 18 | + if not re.search(p, line): |
| 19 | + continue |
| 20 | + if name_only: |
| 21 | + result.append(f) |
| 22 | + break |
| 23 | + temp = [] |
| 24 | + if filename: |
| 25 | + temp.append(f"{f}:") |
| 26 | + if line_numbers: |
| 27 | + temp.append(f"{line_num + 1}:") |
| 28 | + temp.append(line) |
| 29 | + result.append("".join(temp)) |
30 | 30 |
|
31 | 31 | return ("\n".join(result) + "\n") if result else "" |
32 | 32 |
|
33 | 33 |
|
34 | | -def __build_pattern(flags: str) -> str: |
| 34 | +def _build_pattern(pattern: str, flags: str) -> str: |
35 | 35 | case_insensitive = "-i" in flags |
36 | 36 | invert = "-v" in flags |
37 | 37 | whole_line = invert or "-x" in flags |
38 | 38 |
|
39 | | - xs = [] |
| 39 | + xs: list[str] = [] |
40 | 40 | if case_insensitive: |
41 | 41 | xs.append("(?i)") |
42 | 42 | if whole_line: |
43 | 43 | xs.append("^") |
44 | 44 | if invert: |
45 | 45 | # Negative lookahead. |
46 | 46 | # https://www.regular-expressions.info/lookaround.html |
47 | | - xs.append("(?:(?!{}).)*") |
| 47 | + xs.append(f"(?:(?!{pattern}).)*") |
48 | 48 | else: |
49 | | - xs.append("(?:{})") |
| 49 | + xs.append(f"(?:{pattern})") |
50 | 50 | if whole_line: |
51 | 51 | xs.append("$") |
52 | 52 |
|
|
0 commit comments