-
Notifications
You must be signed in to change notification settings - Fork 6
/
include_snippets.py
executable file
·81 lines (64 loc) · 2.52 KB
/
include_snippets.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
74
75
76
77
78
79
80
81
#!/usr/bin/env python3
import os
FILE_TYPES = {".py": ("python", "[Python]"), ".cpp": ("cpp", "[C++]")}
def run_snippet_cmd(snippets_root, snippet_file, *labels, code_group=None):
lines = [[] for _ in labels]
with open(os.path.join(snippets_root, snippet_file), "r") as f:
idx = None
for line in f:
for i, label in enumerate(labels):
# first match
if idx is None and f"[{label}]" in line.split():
idx = i
break
# secod match
elif idx is not None and f"[{label}]" in line.split():
idx = None
break
else:
if idx is not None:
lines[idx].append(line)
# TODO: strip indent
extension = os.path.splitext(snippet_file)[1]
(ft, _code_group) = FILE_TYPES[extension]
code_group = _code_group if code_group is None else code_group
blocks = "\n\n\n".join("".join(xs).strip() for xs in lines)
return f"```{ft} {code_group}\n{blocks}\n```\n"
def run_snippet_cmd_group(snippets_root, snippet_file, group, *labels):
return run_snippet_cmd(
snippets_root, snippet_file, *labels, code_group=group
)
support_commands = [
("@snippet", run_snippet_cmd),
("@snippet_group", run_snippet_cmd_group),
]
def parse_commands(lines):
for linenum, line in enumerate(lines):
for cmd, _ in support_commands:
if line.startswith(cmd):
yield (linenum, line.strip().split())
def run_commands(snippets_root, filepath):
with open(filepath, "r") as f:
# for small doc files, this is OK
lines = f.readlines()
commands = parse_commands(lines)
for cmd_linenum, cmds in commands:
for support_cmd, fun in support_commands:
if cmds[0] == support_cmd:
new_lines = fun(snippets_root, *cmds[1:])
lines[cmd_linenum] = new_lines
with open(filepath, "w") as f:
f.write("".join(lines))
if __name__ == "__main__":
import argparse
import glob
parser = argparse.ArgumentParser(description="Including Your Snippets")
parser.add_argument(
"--snippets-root", type=str, help="your snippets root dir", default=""
)
parser.add_argument(
"--file-pattern", type=str, help="dest file pattern", required=True
)
args = parser.parse_args()
for file in glob.iglob(args.file_pattern, recursive=True):
run_commands(args.snippets_root, file)