vite/vite.py (view raw)
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 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 |
# vite - a simple and minimal static site generator, that JustWorks™ # Copyright (c) 2020 Anirudh Oppiliappan <x@icyphox.sh> # Licensed under the MIT license import sys import pathlib import os import jinja2 import time import http.server import socketserver import shutil import datetime import re from markdown2 import markdown_path from huepy import * from livereload import Server from subprocess import call # constants PAGES_PATH = "pages/" BUILD_PATH = "build/" TEMPL_PATH = "templates/" TEMPL_FILE = "" PORT = 1911 def import_config(): try: sys.path.append(os.getcwd()) globals()["config"] = __import__("config") global TEMPL_FILE TEMPL_FILE = os.path.join(TEMPL_PATH, config.template) except ImportError: print(bad("Error: config.py not found.")) print(que("Are you sure you're in a project directory?")) sys.exit(1) def create_project(path): try: abs_path = pathlib.Path(path).resolve() cur_path = pathlib.Path(".").resolve() os.makedirs(os.path.join(path, "build")) os.mkdir(os.path.join(path, "pages")) os.mkdir(os.path.join(path, "templates")) os.mkdir(os.path.join(path, "static")) create_config(path) create_template(path) print(good("Created project directory at %s." % (abs_path))) except FileExistsError: print(bad("Error: specified path exists.")) def create_path(path): head, tail = os.path.split(path) now = datetime.datetime.now() today = now.strftime("%Y-%m-%d") url = os.path.splitext(os.path.basename(path))[0] try: os.makedirs(os.path.join(PAGES_PATH, head)) except FileExistsError: pass if os.path.exists(os.path.join(PAGES_PATH, head, tail)): print(bad("Error: specified path exists.")) else: with open(os.path.join(PAGES_PATH, head, tail), "w") as f: to_write = ( """--- template: url: {u} title: subtitle: date: {t} ---\n""" ).format(t=today, u=url) f.write(to_write) print(good("Created %s.") % (os.path.join(PAGES_PATH, head, tail))) def create_config(path): with open(os.path.join(path, "config.py"), "w") as f: f.write( """# config.py - Vite's configuration script title = '' author = '' header = '' footer = '' pre_build = [] post_build = [] template = 'index.html' # default is index.html\n""" ) def create_template(path): with open(os.path.join(path, "templates", "index.html"), "w") as f: f.write( """<!DOCTYPE html> <html> <header> {{ header }} <title> {{ title }} </title> </header> <body> {{ body }} </body> <footer> {{ footer }} <p> {{ author }} </p> <footer> """ ) # jinja2 def jinja_render(html, tmpl): template_loader = jinja2.FileSystemLoader("./") env = jinja2.Environment(loader=template_loader) try: template = env.get_template(tmpl) except jinja2.exceptions.TemplateNotFound: template = env.get_template(TEMPL_FILE) meta = html.metadata output = template.render( title=meta["title"] if "title" in meta else config.title, author=meta["author"] if "author" in meta else config.author, header=meta["header"] if "header" in meta else config.header, url=meta["url"] if "url" in meta else "", footer=meta["footer"] if "footer" in meta else config.footer, date=meta["date"] if "date" in meta else "", subtitle=meta["subtitle"] if "subtitle" in meta else "", body=html, ) return output def fm_template(metadata): try: page_template = os.path.join(os.path.join(TEMPL_PATH, metadata["template"])) except KeyError: page_template = TEMPL_FILE return page_template def markdown_render(filename): html = markdown_path( os.path.join(PAGES_PATH, filename), extras=[ "metadata", "fenced-code-blocks", "header-ids", "footnotes", "smarty-pants", "tables", "link-patterns", ], link_patterns=[ ( re.compile( r"((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+(:[0-9]+)?|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)" ), r"\1", ) ], ) return html def html_gen(): def index_render(f, d=""): index_html = markdown_render(os.path.join(d, f)) output = jinja_render(index_html, fm_template(index_html.metadata)) with open(os.path.join(BUILD_PATH, d, "index.html"), "w") as ff: ff.write(output) if d: print(run("Rendered " + white("%s/%s") % (d, f))) else: print(run("Rendered " + white("%s") % (f))) def normal_render(f, d=""): html_text = markdown_render(os.path.join(d, f)) html_file = os.path.splitext(os.path.join(BUILD_PATH, d, f))[0] os.mkdir(html_file) output = jinja_render(html_text, fm_template(html_text.metadata)) with open(os.path.join(html_file, "index.html"), "w") as ff: ff.write(output) if d: print(run("Rendered " + white("%s/%s") % (d, f))) else: print(run("Rendered " + white("%s") % (f))) for root, dirs, files in os.walk(PAGES_PATH): for d in dirs: os.mkdir(os.path.join(BUILD_PATH, d)) for f in os.listdir(os.path.join(PAGES_PATH, d)): if os.path.splitext(f)[1] != ".md": shutil.copyfile( os.path.join(PAGES_PATH, d, f), os.path.join(BUILD_PATH, d, f) ) print(run("Copied " + white("%s/%s") % (d, f))) elif f == "_index.md": index_render(f, d) else: normal_render(f, d) for f in os.listdir(PAGES_PATH): if os.path.isfile(os.path.join(PAGES_PATH, f)): if os.path.splitext(f)[1] != ".md": shutil.copyfile( os.path.join(PAGES_PATH, f), os.path.join(BUILD_PATH, f) ) print(run("Copied " + white("%s") % (f))) elif f == "_index.md": index_render(f) else: normal_render(f) def server(): # handler = http.server.SimpleHTTPRequestHandler # os.chdir(os.path.join(os.getcwd(), BUILD_PATH)) server = Server() try: print( run( f'Serving the {italic(yellow("build"))} directory at {white(f"http://localhost:{PORT}")}' ) ) print(white("Ctrl+C") + " to stop.") server.serve(port=PORT, root="build/") except KeyboardInterrupt: print(info("Stopping server.")) sys.exit(1) def clean(): for root, dirs, files in os.walk(BUILD_PATH): for f in files: os.unlink(os.path.join(root, f)) for d in dirs: shutil.rmtree(os.path.join(root, d)) def builder(): path = os.getcwd() start = time.process_time() if not os.listdir(os.path.join(path, PAGES_PATH)): print(info(italic("pages") + " directory is empty. Nothing to build.")) sys.exit(1) else: try: if config.pre_build != "": print(run("Running pre-build actions...")) for s in config.pre_build: print(info(f"{s}")) call([s]) except AttributeError: pass clean() html_gen() if os.path.exists(os.path.join(os.getcwd(), "static")): shutil.copytree( os.path.join(os.getcwd(), "static"), os.path.join(BUILD_PATH, "static") ) print(good("Done in %0.5fs." % (time.process_time() - start))) try: if config.post_build != "": print(run("Running post-build actions...")) for s in config.post_build: print(info(f"{s}")) call([s]) except AttributeError: pass |