make.py (view raw)
1#!/usr/bin/env python3
2
3import os
4import sys
5import jinja2
6import time
7import argparse
8import http.server
9import socketserver
10
11from markdown2 import markdown_path
12from huepy import *
13
14desc = green('Script to build and serve Vite projects.')
15usage = lightblue('make.py') + ' [serve]'
16help_txt = 'Serve pages from the ' + italic('build') + ' directory.'
17parser = argparse.ArgumentParser(description=desc, usage=usage)
18parser.add_argument('serve', nargs='*', help=help_txt)
19
20args = parser.parse_args()
21
22# import config file
23try:
24 sys.path.append(os.getcwd())
25 import config
26except ModuleNotFoundError:
27 print(bad('Error: config.py not found.'))
28 print(que('Are you sure you\'re in a project directory?'))
29 parser.print_help()
30 sys.exit(1)
31
32# constants
33PAGES_PATH = 'pages/'
34BUILD_PATH = 'build/'
35TEMPL_PATH = 'templates/'
36TEMPL_FILE = TEMPL_PATH + config.template
37PORT = 1911
38
39
40# jinja2
41def jinja_render(html_text, TEMPL_FILE):
42 template_loader = jinja2.FileSystemLoader('./')
43 env = jinja2.Environment(loader=template_loader)
44 template = env.get_template(TEMPL_FILE)
45 output = template.render(title=config.title,
46 author=config.author,
47 header=config.header,
48 footer=config.footer,
49 body=html_text)
50 return output
51
52
53def markdown_render(filename):
54 html_text = markdown_path(PAGES_PATH + filename)
55 return html_text
56
57
58def html_gen():
59 for page in os.listdir(PAGES_PATH):
60 html_text = markdown_render(page)
61 html_file= os.path.splitext(os.path.join(BUILD_PATH, page))[0]
62 if not os.path.exists(html_file):
63 os.mkdir(html_file)
64 output = jinja_render(html_text, TEMPL_FILE)
65 with open(os.path.join(html_file, 'index.html'), 'w') as f:
66 f.write(output)
67 print(run('Rendered %s.' % (page)))
68
69
70def server():
71 handler = http.server.SimpleHTTPRequestHandler
72 os.chdir(BUILD_PATH)
73 print(os.getcwd())
74 try:
75 with socketserver.TCPServer(('', PORT), handler) as httpd:
76 print(run(f'Serving the {italic("build")} directory at http://localhost:{PORT}'))
77 print(white('Ctrl+C') + ' to stop.')
78 httpd.serve_forever()
79 except KeyboardInterrupt:
80 print(info('Stopping server.'))
81 httpd.server_close()
82 sys.exit(1)
83
84def main():
85 if args.serve:
86 server()
87 start = time.process_time()
88 TEMPL_FILE = TEMPL_PATH + config.template
89 if not os.listdir(PAGES_PATH):
90 print(info(italic('pages') + ' directory is empty. Nothing to build.'))
91 sys.exit(1)
92 else:
93 try:
94 html_gen()
95 print(good('Done in %0.5fs.' % (time.process_time() - start)))
96 except jinja2.exceptions.TemplateNotFound:
97 print(bad('Error: specified template not found: %s' % (TEMPL_FILE)))
98
99
100if __name__ == "__main__":
101 main()