-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprod.py
241 lines (190 loc) · 6.86 KB
/
prod.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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
"""A script to generate static HTML files in production build.
Usage: python -m prod [path_to_md_file]
"""
__author__ = ["Kris Jordan <[email protected]>", "Ezri White <[email protected]"]
import time
import sys
import os
import subprocess
from jinja2 import Environment, FileSystemLoader, select_autoescape
from typing import List, Dict
SITE_DIR = "."
def main() -> None:
"""Entrypoint of Program."""
path = parse_args(sys.argv)
md_file = f'{path}.md'
body: str = capture_pandoc_html(md_file)
top_section, bottom_section = read_arguments(md_file)
globals = convert_to_dict(top_section)
fixed_navbar = choose_navbar(globals)
site_branch = choose_site_branch(globals)
if is_overview(globals):
overview = create_overview(md_file)
generate_html(md_file, globals, body,
fixed_navbar, site_branch, overview)
elif is_columns(globals):
bodies = split_body(body)
generate_html(md_file, globals, bodies, fixed_navbar, site_branch)
elif is_rows(globals):
bodies = split_body(body)
generate_html(md_file, globals, bodies, fixed_navbar, site_branch)
elif is_grid(globals):
bodies = parse_grid(body, globals)
generate_html(md_file, globals, bodies, fixed_navbar, site_branch)
else:
generate_html(md_file, globals, body, fixed_navbar, site_branch)
def choose_navbar(globals):
""""""
if "navbar" in globals:
if globals["navbar"] == "fixed":
return True
return False
def choose_site_branch(globals):
"""Determines which branch of the site."""
if "site-branch" in globals:
return globals["site-branch"]
return "student"
def is_overview(globals):
""""""
if "template" in globals:
return globals["template"] == "overview"
return False
def is_columns(globals):
"""Determines if the page should have a column layout."""
if "template" in globals:
return globals["template"] == "columns"
return False
def is_rows(globals):
"""Determines if the page should have a row layout."""
if "template" in globals:
return globals["template"] == "rows"
return False
def is_grid(globals):
"""Determines if the page should have a row layout."""
if "template" in globals:
return globals["template"] == "grid"
return False
def split_body(body):
""""""
bodies = body.split('//split//')
return bodies
def parse_grid(body, globals):
""""""
row_length = int(globals["row-length"])
items = body.split('//split//')
bodies = []
for i in range(len(items)):
if i % row_length == 0:
bodies.append([])
bodies[int(i / row_length)].append(items[i])
return bodies
def create_overview(source):
""""""
output = subprocess.check_output(
["pandoc", "-t", "html", source, "--standalone", "--toc", "--toc-depth=3"])
cleaned_output = output.decode("utf-8")
cut_output = cleaned_output.split("nav")[1]
return cut_output[26:]
def generate_html(source: str, globals, body, fixed_navbar, site_branch, overview=""):
"""Use globals to determine variables in order to generate html from jinja."""
env = Environment(
loader=FileSystemLoader(SITE_DIR),
autoescape=select_autoescape(["html", "xml"]),
trim_blocks=True,
lstrip_blocks=True
)
base_template = env.get_template(choose_template(globals))
time_stamp = time.time()
path = source.replace("md", "html")
with open(path, "w") as target:
if overview == "":
result = base_template.render(
title=globals["title"], page=globals["page"], author=globals["author"], body=body, fixed_navbar=fixed_navbar, time_stamp=time_stamp, site_branch=site_branch)
else:
result = base_template.render(
title=globals["title"], page=globals["page"], author=globals["author"], body=body, overview=overview, fixed_navbar=fixed_navbar, time_stamp=time_stamp, site_branch=site_branch)
target.write(result)
def choose_template(globals) -> str:
"""Determine which child template to use"""
if "template" in globals:
template_path = f"./templates/{globals['template']}.jinja2"
else:
template_path = "./templates/generic.jinja2"
return template_path
def capture_pandoc_html(source: str) -> str:
"""Generate HTML by shelling out to pandoc.
Args:
- source is the markdown file being transformed
- template is the template HTML file to wrap it in
Returns:
- String containing pandoc output
"""
output = subprocess.check_output(
["pandoc", "-t", "html", source])
cleaned_output = output.decode("utf-8")
return str(cleaned_output)
def read_arguments(target: str):
"""Read in md file and split into top variables and markdown pieces."""
with open(target, 'r') as file:
lines = file.readlines()
lines = lines[1:]
top_section = ""
markdown = ""
finished_top = False
for line in lines:
if "---" in line:
finished_top = True
if finished_top:
markdown += line
else:
top_section += line
return (top_section, markdown)
def convert_to_dict(top_section: str) -> Dict:
"""Make top variable information into a usable format.
Input: String containing all lines in top variable section of md file.
Returns: Converted dictionary version of this information.
"""
list: List[str] = top_section.split("\n")
globals = {}
i = 0
while i < len(list):
if list[i][-1:] == ":":
key = list[i][:-1].strip()
globals[key] = []
while list[i + 1].strip()[0] == "-":
i += 1
globals[key].append(list[i].strip()[2:])
else:
if ":" in list[i]:
pair = list[i].split(":")
globals[pair[0].strip()] = pair[1].strip()
i += 1
return globals
def parse_args(argv: List[str]) -> str:
"""Confirm correct usage of command and parse input.
Args:
- argv are the process's input arguments
Returns:
The path of the markdown file to convert.
"""
if len(argv) != 2:
print("Usage: python -m prod [path_to_md_file]", file=sys.stderr)
exit(1)
else:
return argv[1]
def pandoc_html(source: str, template: str) -> None:
"""Generate HTML by shelling out to pandoc.
Args:
- source is the markdown file being transformed
- template is the template HTML file to wrap it in
Returns:
None. Outputs a file in same path as source but html.
"""
target = f"{source}.html"
source = f"{source}.md"
args = ["pandoc", source, f"-o {target}", "--standalone",
f"--template={template}", "--toc", "--toc-depth=3"]
command = " ".join(args)
os.system(command)
if __name__ == "__main__":
main()