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