dnd/deadsands/site_tools/cli.py

240 lines
7.1 KiB
Python
Raw Normal View History

2023-07-03 14:14:03 -07:00
import asyncio
import os
2023-07-04 10:59:51 -07:00
import shlex
import shutil
import subprocess
2022-08-02 18:20:45 -07:00
import sys
2023-07-04 10:45:10 -07:00
import termios
2023-07-04 10:59:51 -07:00
import webbrowser
from collections import defaultdict
2022-08-02 18:20:45 -07:00
from enum import Enum
2023-07-04 10:59:51 -07:00
from pathlib import Path
from time import sleep
import click
import typer
from livereload import Server
2022-09-17 16:48:16 -07:00
from livereload.watcher import INotifyWatcher
from pelican import main as pelican_main
2023-07-04 10:59:51 -07:00
from rolltable.tables import RollTable
2023-07-03 14:14:03 -07:00
from typing_extensions import Annotated
2022-09-17 16:48:16 -07:00
2023-07-04 10:59:51 -07:00
import site_tools as st
2022-08-02 22:40:49 -07:00
from site_tools.content_manager import create
2023-07-04 10:45:10 -07:00
from site_tools.shell.interactive_shell import DMShell
2022-08-02 22:49:01 -07:00
2023-07-04 10:45:10 -07:00
CONFIG = defaultdict(dict)
2023-07-04 10:59:51 -07:00
CONFIG.update(
{
"settings_base": st.DEV_SETTINGS_FILE_BASE,
"settings_publish": st.PUB_SETTINGS_FILE_BASE,
# Output path. Can be absolute or relative to tasks.py. Default: 'output'
"deploy_path": st.SETTINGS["OUTPUT_PATH"],
# Remote server configuration
"ssh_user": "greg",
"ssh_host": "froghat.club",
"ssh_port": "22",
"ssh_path": "/usr/local/deploy/deadsands/",
# Host and port for `serve`
"host": "localhost",
"port": 8000,
# content manager config
"templates_path": "markdown-templates",
# directory to watch for new assets
"import_path": "imports",
# where new asseets will be made available
"production_host": "deadsands.froghat.club",
# where to find roll table sources
"table_sources_path": "sources",
}
)
2022-08-02 18:20:45 -07:00
app = typer.Typer()
class ContentType(str, Enum):
2023-07-04 10:59:51 -07:00
post = "post"
lore = "lore"
monster = "monster"
region = "region"
location = "location"
page = "page"
2022-08-02 18:20:45 -07:00
2023-07-03 14:14:03 -07:00
class Die(str, Enum):
2023-07-04 10:59:51 -07:00
d100 = "100"
d20 = "20"
d12 = "12"
d10 = "10"
d6 = "6"
d4 = "4"
2023-07-03 14:14:03 -07:00
def pelican_run(cmd: list = [], publish=False) -> None:
2023-07-04 10:59:51 -07:00
settings = CONFIG["settings_publish" if publish else "settings_base"]
pelican_main(["-s", settings] + cmd)
@app.command()
def clean() -> None:
2023-07-04 10:59:51 -07:00
if os.path.isdir(CONFIG["deploy_path"]):
shutil.rmtree(CONFIG["deploy_path"])
os.makedirs(CONFIG["deploy_path"])
@app.command()
def build() -> None:
2023-07-04 10:59:51 -07:00
subprocess.run(shlex.split("git submodule update --remote --merge"))
pelican_run()
2022-09-17 16:48:16 -07:00
@app.command()
def watch() -> None:
2023-07-04 10:59:51 -07:00
import_path = Path(CONFIG["import_path"])
content_path = Path(st.SETTINGS["PATH"])
2022-09-17 16:48:16 -07:00
def do_import():
assets = []
2023-07-04 10:59:51 -07:00
for src in import_path.rglob("*"):
2022-09-17 16:48:16 -07:00
relpath = src.relative_to(import_path)
target = content_path / relpath
if src.is_dir():
target.mkdir(parents=True, exist_ok=True)
continue
if target.exists():
print(f"{target}: exists; skipping.")
continue
print(f"{target}: importing...")
src.link_to(target)
2023-07-04 10:59:51 -07:00
subprocess.run(shlex.split(f"git add {target}"))
uri = target.relative_to("content")
2022-09-17 16:48:16 -07:00
assets.append(f"https://{CONFIG['production_host']}/{uri}")
src.unlink()
if assets:
publish()
2023-07-04 10:59:51 -07:00
print("\n\t".join(["\nImported Asset URLS:"] + assets))
2022-09-17 16:48:16 -07:00
print("\n")
watcher = INotifyWatcher()
watcher.watch(import_path, do_import)
watcher.start(do_import)
print(f"Watching {import_path}. CTRL+C to exit.")
while True:
watcher.examine()
2023-05-13 13:24:43 -07:00
sleep(5)
2022-09-17 16:48:16 -07:00
@app.command()
def serve() -> None:
2023-07-04 10:59:51 -07:00
url = "http://{host}:{port}/".format(**CONFIG)
def cached_build():
2023-07-04 10:59:51 -07:00
pelican_run(["-ve", "CACHE_CONTENT=true", "LOAD_CONTENT_CACHE=true", "SHOW_DRAFTS=true", f'SITEURL="{url}"'])
clean()
cached_build()
server = Server()
2023-07-04 10:59:51 -07:00
theme_path = st.SETTINGS["THEME"]
watched_globs = [
2023-07-04 10:59:51 -07:00
CONFIG["settings_base"],
"{}/templates/**/*.html".format(theme_path),
]
2023-07-04 10:59:51 -07:00
content_file_extensions = [".md", ".rst"]
for extension in content_file_extensions:
2023-07-04 10:59:51 -07:00
content_glob = "{0}/**/*{1}".format(st.SETTINGS["PATH"], extension)
watched_globs.append(content_glob)
2023-07-04 10:59:51 -07:00
static_file_extensions = [".css", ".js"]
for extension in static_file_extensions:
2023-07-04 10:59:51 -07:00
static_file_glob = "{0}/static/**/*{1}".format(theme_path, extension)
watched_globs.append(static_file_glob)
for glob in watched_globs:
server.watch(glob, cached_build)
2022-08-02 22:49:01 -07:00
if st.OPEN_BROWSER_ON_SERVE:
webbrowser.open(url)
2023-07-04 10:59:51 -07:00
server.serve(host=CONFIG["host"], port=CONFIG["port"], root=CONFIG["deploy_path"])
@app.command()
2022-08-02 22:40:49 -07:00
def publish() -> None:
clean()
pelican_run(publish=True)
2023-07-04 10:59:51 -07:00
subprocess.run(
shlex.split(
'rsync --delete --exclude ".DS_Store" -pthrvz -c '
'-e "ssh -p {ssh_port}" '
"{} {ssh_user}@{ssh_host}:{ssh_path}".format(CONFIG["deploy_path"].rstrip("/") + "/", **CONFIG)
)
2023-07-04 10:59:51 -07:00
)
2023-05-13 13:24:43 -07:00
@app.command()
2023-07-04 10:59:51 -07:00
def restock(
source: str = typer.Argument(..., help="The source file for the store."),
frequency: str = Annotated[str, typer.Option("default", help="use the specified frequency from the source file")],
die: Die = typer.Option(20, help="The size of the die for which to create a table"),
2023-07-03 14:14:03 -07:00
template_dir: str = Annotated[
str,
typer.Argument(
2023-07-04 10:59:51 -07:00
CONFIG["templates_path"],
2023-07-03 14:14:03 -07:00
help="Override the default location for markdown templates.",
2023-07-04 10:59:51 -07:00
),
2023-07-03 14:14:03 -07:00
],
2023-05-13 13:24:43 -07:00
) -> None:
2023-07-04 10:59:51 -07:00
rt = RollTable([Path(source).read_text()], frequency=frequency, die=die, hide_rolls=True)
store = rt.datasources[0].metadata["store"]
click.edit(
filename=create(
content_type="post",
title=store["title"],
template_dir=template_dir,
category="stores",
template="store",
extra_context=dict(inventory=rt.as_markdown, **store),
2023-05-13 13:24:43 -07:00
)
2023-07-04 10:59:51 -07:00
)
2023-05-13 13:24:43 -07:00
2022-08-02 18:20:45 -07:00
@app.command()
def new(
content_type: ContentType = typer.Argument(
...,
help="The type of content to create.",
),
title: str = typer.Argument(
...,
help="The title of the content.",
),
category: str = typer.Argument(
None,
help='Override the default category; required for "post" content.',
),
template: str = typer.Argument(
None,
help="Override the default template for the content_type.",
),
template_dir: str = typer.Argument(
2023-07-04 10:59:51 -07:00
CONFIG["templates_path"],
2022-08-02 18:20:45 -07:00
help="Override the default location for markdown templates.",
2023-07-04 10:59:51 -07:00
),
2022-08-02 18:20:45 -07:00
) -> None:
if not category:
match content_type:
2023-07-04 10:59:51 -07:00
case "post":
2022-08-02 18:20:45 -07:00
print("You must specify a category for 'post' content.")
sys.exit()
2023-07-04 10:59:51 -07:00
case "monster":
category = "bestiary"
case "region":
category = "locations"
case "location":
category = "locations"
case "page":
category = "pages"
2022-08-02 18:20:45 -07:00
case _:
2022-08-04 21:34:47 -07:00
category = content_type.value
2023-07-04 10:59:51 -07:00
click.edit(filename=create(content_type.value, title, template_dir, category, template or content_type.value))
2022-08-02 18:20:45 -07:00
2023-07-03 14:14:03 -07:00
def dmsh():
old_attrs = termios.tcgetattr(sys.stdin)
try:
2023-07-04 10:45:10 -07:00
asyncio.run(DMShell(CONFIG).start())
2023-07-03 14:14:03 -07:00
finally:
termios.tcsetattr(sys.stdin, termios.TCSANOW, old_attrs)
2023-07-04 10:59:51 -07:00
if __name__ == "__main__":
2022-08-02 18:20:45 -07:00
app()