Skip to content

Instantly share code, notes, and snippets.

@frerich

frerich/serve.py Secret

Created December 10, 2020 20:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frerich/b6436ec41e29307affc9c39142d21698 to your computer and use it in GitHub Desktop.
Save frerich/b6436ec41e29307affc9c39142d21698 to your computer and use it in GitHub Desktop.
Wrapper script for 'hugo server'
#!/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