-
Notifications
You must be signed in to change notification settings - Fork 0
/
explain.py
executable file
·73 lines (55 loc) · 1.89 KB
/
explain.py
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
#!/usr/local/bin/python3
import subprocess
import sys
import re
DEBUG = False
def get_man_descriptions(flag, man_page):
# Check for correctness
if flag[0] != '-':
return "Invalid flag."
flag_re_prefix = "\W*"
flags = []
if len(flag) > 2:
if flag[1] == '-':
flags.append(flag)
else:
for char in flag:
if char != '-':
flags.append('-' + char)
else:
flags.append(flag)
relevant_lines = []
for f in flags:
flag_re = re.compile(flag_re_prefix + f)
for counter, line in enumerate(man_page):
if re.match(flag_re, line):
current_line = line
current_counter = counter
while current_counter < len(man_page) - 1:
current_counter += 1
if not re.match("\W*", man_page[current_counter]):
current_line += "\n" + man_page[current_counter]
relevant_lines.append(current_line)
continue
return relevant_lines
if __name__ == '__main__':
# Perhaps first scrub input for security? Whitelisted commands?
# Add a check to see if it requires sudo?
if DEBUG:
print(sys.argv)
command = sys.argv[1]
flags = sys.argv[2:]
# TODO: figure out encoding from command line
# Run `man _command_` and capture output
# Split output on double newlines to separate paragraphs
man_page = subprocess.check_output(["man", command]).decode("utf-8").split("\n\n")
# Go through each flag/argument and find each line of the man page that
# contains it.
for flag in flags:
print(flag)
man_descriptions = get_man_descriptions(flag, man_page)
if len(man_descriptions):
for m in man_descriptions:
print(m)
else:
print("No valid flags detected")