This repository was archived by the owner on Jul 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathinclude_snippets.py
executable file
·71 lines (56 loc) · 2.15 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
#!/usr/bin/env python3
import os
FILE_TYPES = {".py": "python", "cpp": "cpp"}
def run_snippet_cmd(snippets_root, snippet_file, *labels):
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 = FILE_TYPES[extension]
blocks = "\n\n\n".join("".join(xs).strip() for xs in lines)
return f"```{ft}\n{blocks}\n```\n"
support_commands = [("@snippet", run_snippet_cmd)]
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):
run_commands(args.snippets_root, file)