#!/usr/bin/env run-pandoc.py
# run-pandoc.py
import subprocess
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

# handler: defines what happens when a filesystem event occurs
class PandocHandler(FileSystemEventHandler):
    # called by watchdog when a file has been fully written and closed
    def on_closed(self, event):
        # ignore directory events and non-markdown files
        if not event.is_directory and event.src_path.endswith('.md'):
            mdfile = event.src_path
            htmlfile = mdfile.replace('.md', '.html')
            cmd = 'pandoc %s -o %s' % (mdfile, htmlfile)
            print(cmd)
            subprocess.run(cmd, shell=True)

# observer: background thread, watches for filesystem events
observer = Observer()
observer.schedule(PandocHandler(), path='.', recursive=False)
observer.start()

# keep main thread alive, wait for ctrl+c
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    observer.stop()

# cleanup
observer.join()
