-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathijgrep
More file actions
executable file
·78 lines (66 loc) · 2.28 KB
/
ijgrep
File metadata and controls
executable file
·78 lines (66 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env python3
import sys
import linecache
import glob
import os
def default_files():
search_path = os.getenv("IJGREP_DIR", "~/documents/intentionjournal*.txt")
return list(sorted(glob.glob(os.path.expanduser(search_path))))
def get_level(s):
PREFIXES = ["\t", " "]
l = 0
changed = True
while changed:
changed = False
for p in PREFIXES:
while s.startswith(p):
l, s, changed = l+1, s.removeprefix(p), True
return l
def lines(file):
file.seek(0, 0)
ancestry = []
last_level = 0
for lineno, line in enumerate(file):
level = get_level(line)
if line.strip() == "": # Empty lines maintain indentation
level = last_level
# If we indented more than one level at once, add dummy ancestors for the missing levels
for _ in range(level - last_level - 1):
ancestry.append(None)
# If we dedented, pop ancestors
ancestry = ancestry[:level]
# We are now an ancestor
last_level = level
ancestry.append(lineno)
yield ancestry, line
last_file=None
def print_line(line, lineno, filename, search, is_match):
"""Figure out your magical custom formatting here"""
out = f"{filename}:{line.removesuffix("\n")}"
global last_file
if filename != last_file and last_file is not None:
print()
last_file = filename
print(out)
def grep(search, file, filename):
print_all = set()
print_direct = set()
# Queue up print tasks
for ancestry, line in lines(file):
if search.casefold() in line.casefold():
print_all.add(ancestry[-1])
print_direct.update(ancestry)
print_direct.discard(None)
# Print
for ancestry, line in lines(file):
if ( any(x in print_all for x in ancestry) or
ancestry[-1] in print_direct or
len(ancestry) > 1 and ancestry[-2] in print_direct):
print_line(line, lineno=ancestry[-1], filename=filename, search=search,
is_match=(search.casefold() in line.casefold()))
if __name__ == "__main__":
files = sys.argv[2:] or default_files()
search = sys.argv[1]
for file in files:
with open(file, "r", encoding="utf8") as f:
grep(search, f, filename=file)