-
-
Save frerich/b6436ec41e29307affc9c39142d21698 to your computer and use it in GitHub Desktop.
Wrapper script for 'hugo server'
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import os | |
import platform | |
import subprocess | |
import sys | |
from http.server import BaseHTTPRequestHandler, HTTPServer | |
from urllib.parse import urlparse, parse_qs | |
SCRIPT_PATH = os.path.abspath(__file__) | |
class RequestHandler(BaseHTTPRequestHandler): | |
def do_POST(self): | |
self.close_connection = True | |
url = urlparse(self.path) | |
if url.path not in ('/open',): | |
self.send_response(400, "Only /open supported") | |
self.end_headers() | |
return | |
query = parse_qs(url.query) | |
if 'path' not in query: | |
self.send_response(400, "Query lacks 'path' field") | |
self.end_headers() | |
return | |
for path in query['path']: | |
if not os.path.exists(path): | |
self.send_response(404, "Not found: %s" % path) | |
self.end_headers() | |
return | |
for path in query['path']: | |
open_file(path) | |
self.send_response(200) | |
self.end_headers() | |
def open_file(path): | |
if os.path.exists("./open_file"): | |
subprocess.call(["./open_file", path]) | |
elif os.path.exists("./open_file.bat"): | |
subprocess.call(["./open_file.bat", path]) | |
elif platform.system() == "Linux": | |
subprocess.call(["xdg-open", path]) | |
elif platform.system() == "Windows": | |
# Nobody is using notepad, let's default to Notepad++. | |
# Power users will know how to adjust this to their liking. | |
subprocess.call(["start", "notepad++", path], shell=True) | |
else: # Fallback, covers macOS | |
subprocess.call(["open", path]) | |
cmd = ["hugo", "server", "--disableFastRender"] | |
cmd.extend(sys.argv[1:]) | |
hugo = subprocess.Popen( | |
cmd, | |
cwd="site", | |
env=dict(os.environ, HUGO_DIR=os.path.join(os.path.dirname(SCRIPT_PATH), "site")) | |
) | |
httpd = HTTPServer(("localhost", 1314), RequestHandler) | |
httpd.serve_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment