-
Notifications
You must be signed in to change notification settings - Fork 0
/
gen.py
150 lines (118 loc) · 4.21 KB
/
gen.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
import logging
import os
import time
import shutil
import jinja2
import click
import yaml
import markdown
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import config
_logger = logging.getLogger(__name__)
def _render_to_file(filepath, template, ctx):
fp = os.path.join(config.BUILD_ROOT, filepath)
with open(fp, "wt") as f:
f.write(template.render(**ctx))
def _load_data(no_wip):
fp = os.path.join(config.SRC_ROOT, config.DATA_FILE)
with open(fp) as stream:
data = yaml.safe_load(stream)
for m in data["machines"]:
m["url_id"] = m["name"].strip().replace(" ", "_").lower()
if no_wip:
data["questions"] = list(filter(lambda x: "wip" not in x or x["wip"] == False, data["questions"]))
for q in data["questions"]:
q["url_id"] = q["title"].strip().replace(" ", "_").lower()
if "machine" in q:
q["machine_url_id"] = q["machine"].strip().replace(" ", "_").lower()
num_q = len(data["questions"])
for i in range(num_q):
data["questions"][i]["next_url_id"] = data["questions"][(i + 1) % num_q]["url_id"]
return data
def _compile_once(no_wip):
env = jinja2.Environment(
loader=jinja2.FileSystemLoader(config.SRC_ROOT),
autoescape=jinja2.select_autoescape,
)
ctx = _load_data(no_wip)
os.makedirs(config.BUILD_ROOT, exist_ok=True)
_logger.info("Generating index.html file")
template = env.get_template(config.INDEX_PAGE)
_render_to_file("index.html", template, ctx)
_logger.info("Generating browse.html file")
template = env.get_template(config.BROWSE_PAGE)
_render_to_file("browse.html", template, ctx)
_logger.info("Generating challenge.html file")
template = env.get_template(config.CHALLENGE_PAGE)
_render_to_file("challenge.html", template, ctx)
_logger.info("Generating faq.html file")
template = env.get_template(config.FAQ_PAGE)
_render_to_file("faq.html", template, ctx)
_logger.info("Generating single question .html files")
template = env.get_template(config.SINGLE_Q_PAGE)
base_path = os.path.join(config.BUILD_ROOT, "q")
os.makedirs(base_path, exist_ok=True)
for q in ctx["questions"]:
q["explain_md"] = markdown.markdown(q["explain"])
_render_to_file(
os.path.join("q", f"{q['url_id']}.html"),
template,
{
"q": q,
**ctx,
},
)
_logger.info("Generating single machine .html files")
template = env.get_template(config.SINGLE_M_PAGE)
os.makedirs(os.path.join(config.BUILD_ROOT, "m"), exist_ok=True)
for m in ctx["machines"]:
_render_to_file(
os.path.join("m", f"{m['url_id']}.html"),
template,
{
"m": m,
**ctx,
},
)
_logger.info("Copy static files")
os.makedirs(os.path.join(config.BUILD_ROOT, "static"), exist_ok=True)
shutil.copytree(
os.path.join(config.SRC_ROOT, config.STATIC_DIR),
os.path.join(config.BUILD_ROOT, "static"),
dirs_exist_ok=True,
)
@click.command()
@click.option("--watch", is_flag=True)
@click.option("--no_wip", is_flag=True)
def main(watch, no_wip):
_compile_once(no_wip)
if not watch:
_logger.info("Run below command to run a test server")
_logger.info(
f"cd {os.path.abspath(config.BUILD_ROOT)} && python3 -m http.server"
)
_logger.info("Done.")
else:
observer = Observer()
_logger.info(f"Watching directory {config.BUILD_ROOT}")
class EventHandler(FileSystemEventHandler):
def on_modified(self, event):
_compile_once(no_wip)
event_handler = EventHandler()
observer.schedule(event_handler, config.SRC_ROOT, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
finally:
observer.stop()
observer.join()
if __name__ == "__main__":
logging.basicConfig(
encoding="utf-8",
level=logging.INFO,
format="%(asctime)s %(levelname)s [%(module)s:%(lineno)d] %(message)s",
datefmt="%Y%m%d %H:%M:%S",
)
main()