#!/usr/bin/env python3 import sys import time import shutil from pathlib import Path from jinja2 import Template from markdown import markdown from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler src_dir = Path('src') out_dir = Path('www') with open('template.html') as f: template = Template(f.read()); # Creates the directory tree for the out directory based on the src directory def create_dir_tree(path): out_dir.mkdir(exist_ok=True) for child in path.iterdir(): if(child.is_dir()): (out_dir / child.relative_to(src_dir)).mkdir(exist_ok=True) create_dir_tree(child) # generates html from a md file and a jinja template def generate_html(md): return template.render(md=markdown(text=md, extensions=['codehilite'])); # takes a md file and puts it in a html file using generate_html def process_md(path): new_path = (out_dir / path.relative_to(src_dir)).with_suffix('.html') with path.open(mode='r') as md_file: md = md_file.read() html = generate_html(md) with new_path.open('w') as html_file: html_file.write(html) # Every css file is appended to a file named style.css. def process_css(path): with open(str(path), 'rb') as src: with open(str(out_dir/'assets/style.css'), 'ab') as dst: shutil.copyfileobj(src, dst) # Every js file is just copied over to its destination def process_js(path): new_path = (out_dir / path.relative_to(src_dir)) shutil.copyfile(str(path), str(new_path)) def process_any(path): new_path = (out_dir / path.relative_to(src_dir)) shutil.copyfile(str(path), str(new_path)) def execute(): shutil.rmtree(out_dir) create_dir_tree(src_dir) for path in Path(src_dir).rglob('*'): if path.suffix == '.draft': print('wont parse {} because is a draft'.format(path)) continue elif path.suffix == '.md': print('parsing {} as md'.format(path)) process_md(path) elif path.suffix == '.css': print('parsing {} as css'.format(path)) process_css(path) elif path.suffix == '.js': print('parsing {} as js'.format(path)) process_js(path) elif not path.is_dir(): print('parsing {} as any'.format(path)) process_any(path) class WatchHandler(PatternMatchingEventHandler): patterns = ["*.py", "*.md", "*.css", "*.js"] def process(self, event): execute() def on_modified(self, event): self.process(event) def on_created(self, event): self.process(event) if __name__ == '__main__': if len(sys.argv) > 1 and sys.argv[1] == '--watch': observer = Observer() observer.schedule(WatchHandler(), str(src_dir)) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join() else: execute()