all repos — py-vite @ 181a63cdd863e461c679c8f8c6a94abe39c1d032

the original vite, written in python

vite/vite.py (view raw)

  1#!/usr/bin/env python3
  2
  3"""
  4Vite - A simple and minimal static site generator.
  5"""
  6
  7import sys
  8import pathlib
  9import os
 10import jinja2
 11import time
 12import http.server
 13import socketserver
 14
 15from markdown2 import markdown_path
 16from huepy import *
 17from distutils.dir_util import copy_tree
 18from vite import vite
 19
 20
 21# constants
 22PAGES_PATH = 'pages/'
 23BUILD_PATH = 'build/'
 24TEMPL_PATH = 'templates/'
 25TEMPL_FILE = ''
 26PORT = 1911
 27
 28
 29def import_config():
 30    try:
 31        sys.path.append(os.getcwd())
 32        globals()['config'] = __import__('config') 
 33        global TEMPL_FILE
 34        TEMPL_FILE = os.path.join(TEMPL_PATH, config.template)
 35    except ImportError:
 36        print(bad('Error: config.py not found.'))
 37        print(que('Are you sure you\'re in a project directory?'))
 38        sys.exit(1)
 39
 40
 41def create_project(path):
 42    try:
 43        abs_path = pathlib.Path(path).resolve()
 44        cur_path = pathlib.Path('.').resolve()
 45        os.makedirs(os.path.join(path, 'build'))
 46        os.mkdir(os.path.join(path, 'pages'))
 47        os.mkdir(os.path.join(path, 'templates'))
 48        os.mkdir(os.path.join(path, 'static'))
 49        create_config(path)
 50        create_template(path)
 51        print(good('Created project directory at %s.' % (abs_path)))
 52    except FileExistsError:
 53        print(bad('Error: specified path exists.'))
 54
 55
 56def create_config(path):
 57    with open(os.path.join(path, 'config.py'), 'w') as f:
 58        f.write("""# config.py - Vite's configuration script
 59
 60title = ''
 61author = ''
 62header = ''
 63footer = '' 
 64template = 'index.html'  # default is index.html
 65               """)
 66
 67
 68def create_template(path):
 69    with open(os.path.join(path, 'templates', 'index.html'), 'w') as f:
 70        f.write("""<!DOCTYPE html>
 71<html>
 72<header>
 73	{{ header }}
 74	<title>
 75		{{ title }}	
 76	</title>
 77</header>
 78
 79<body>
 80	{{ body }}
 81</body>
 82
 83<footer>
 84	{{ footer }}
 85	<p> {{ author }} </p>
 86<footer>
 87
 88                """)
 89
 90# jinja2
 91def jinja_render(html_text, TEMPL_FILE):
 92    template_loader = jinja2.FileSystemLoader('./')
 93    env = jinja2.Environment(loader=template_loader)
 94    template = env.get_template(TEMPL_FILE)
 95    output = template.render(title=config.title,
 96                             author=config.author,
 97                             header=config.header,
 98                             footer=config.footer,
 99                             body=html_text)
100    return output
101
102
103def markdown_render(filename):
104    html_text = markdown_path(PAGES_PATH + filename)
105    return html_text
106
107
108def html_gen():
109    for page in os.listdir(PAGES_PATH):
110        if page == '_index.md':
111            index_html = markdown_render(page)
112            output = jinja_render(index_html, TEMPL_FILE)
113            with open(os.path.join(BUILD_PATH, 'index.html'), 'w') as f:
114                f.write(output)
115                print(run('Rendered _index.md'))
116        else:
117            html_text = markdown_render(page)
118            html_file = os.path.splitext(os.path.join(BUILD_PATH, page))[0]
119            if not os.path.exists(html_file):
120                os.mkdir(html_file)
121            output = jinja_render(html_text, TEMPL_FILE)
122            with open(os.path.join(html_file, 'index.html'), 'w') as f:
123                f.write(output)
124                print(run('Rendered %s.' % (page)))
125
126
127def server():
128    handler = http.server.SimpleHTTPRequestHandler
129    os.chdir(os.path.join(os.getcwd(), BUILD_PATH))
130    try:
131        with socketserver.TCPServer(('', PORT), handler) as httpd:
132            print(run(f'Serving the {italic("build")} directory at http://localhost:{PORT}'))
133            print(white('Ctrl+C') + ' to stop.')
134            httpd.serve_forever()
135    except KeyboardInterrupt:
136        print(info('Stopping server.'))
137        httpd.socket.close()
138        sys.exit(1)
139
140def builder():
141    path = os.getcwd()
142    start = time.process_time()
143    if not os.listdir(os.path.join(path, PAGES_PATH)):
144        print(info(italic('pages') + ' directory is empty. Nothing to build.'))
145        sys.exit(1)
146    else:
147        try:
148            html_gen()
149            if not os.path.exists(os.path.join(path, BUILD_PATH, 'static')):
150                os.mkdir(os.path.join(path, BUILD_PATH, 'static'))
151            copy_tree('static', os.path.join(path, BUILD_PATH, 'static'))
152            print(good('Done in %0.5fs.' % (time.process_time() - start)))
153        except jinja2.exceptions.TemplateNotFound:
154            print(bad('Error: specified template not found: %s' % TEMPL_FILE))
155