website/build.py

81 lines
2.2 KiB
Python
Raw Normal View History

2023-09-16 13:12:45 +03:00
import os
import shutil
2024-05-03 21:18:46 +03:00
import json
2023-09-16 13:12:45 +03:00
import mistune
render = mistune.create_markdown(
plugins=['math', 'strikethrough', 'footnotes', 'table', 'url', 'task_lists', 'abbr', 'mark', 'subscript', 'spoiler']
2024-05-03 21:18:46 +03:00
)
2023-09-16 13:12:45 +03:00
try:
shutil.rmtree("build")
except:
pass
os.mkdir("build")
template_file = open('template.html', "r")
template_text = template_file.read()
template_file.close()
2024-05-03 21:18:46 +03:00
base_meta_file = open('meta.json', "r")
base_meta = json.loads(base_meta_file.read())
base_meta_file.close()
def parse_meta(data):
result = ""
for key, value in data['tags'].items():
result += f'<meta name="{key}" content="{value}">\n'
for key, value in data['og'].items():
result += f'<meta property="og:{key}" content="{value}">\n'
2023-09-16 13:12:45 +03:00
2024-05-03 21:18:46 +03:00
return result
def gen_file(directory, filename):
file = open(directory + filename, "r")
2023-09-16 13:12:45 +03:00
md_text = file.read()
file.close()
2024-05-03 21:18:46 +03:00
try:
file = open(directory + 'meta.json', "r")
meta = json.loads(file.read())
file.close()
except:
meta = base_meta
meta_data = parse_meta(meta)
return template_text.replace("{{%CONTENT%}}", render(md_text)).replace("{{%TITLE%}}", meta['title']).replace("{{%META%}}", meta_data)
2023-09-16 13:12:45 +03:00
def go_through(directory):
for filename in os.listdir(directory):
2023-12-26 10:51:21 +03:00
_, _, fier = directory.partition('/')
if len(fier) != 0: fier += "/"
2023-12-26 10:51:21 +03:00
if len(filename.split(".")) == 1:
os.makedirs(f'build/{fier}{filename}')
go_through(directory + "/" + filename)
else:
2024-05-03 21:18:46 +03:00
if filename.split(".")[1] == "json":
continue
2023-12-26 11:20:24 +03:00
for ofn in os.listdir("static"):
2024-05-03 21:18:46 +03:00
try:
if len(ofn.split(".")) == 1:
shutil.copytree(f"{os.getcwd()}/static/{ofn}", f"{os.getcwd()}/build/{fier}{ofn}")
else:
shutil.copy(f"{os.getcwd()}/static/{ofn}", f"{os.getcwd()}/build/{fier}{ofn}")
except:
pass
2023-12-26 11:20:24 +03:00
2024-05-03 21:18:46 +03:00
content = gen_file(f"{os.getcwd()}/{directory}/", filename)
2023-12-26 10:51:21 +03:00
loc = fier + filename.split(".")[0] + '.html'
2023-12-26 10:51:21 +03:00
file = open(f"{os.getcwd()}/build/{loc}", "a")
file.write(content)
file.close()
go_through("content")