Skip to content

Commit

Permalink
Add pre-commit checking generate pages
Browse files Browse the repository at this point in the history
  • Loading branch information
CoolCat467 committed Oct 5, 2024
1 parent 8b8bc61 commit 29816d4
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 31 deletions.
11 changes: 10 additions & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ ci:
autoupdate_commit_msg: "[pre-commit.ci] pre-commit autoupdate"
autoupdate_schedule: quarterly
submodules: false
skip: [badgie]
skip: [badgie, regenerate-files]

repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
Expand Down Expand Up @@ -37,6 +37,7 @@ repos:
- id: ruff
types: [file]
types_or: [python, pyi, toml]
args: ["--show-fixes"]
- repo: https://github.com/CoolCat467/badgie
rev: v0.9.5
hooks:
Expand All @@ -47,3 +48,11 @@ repos:
- id: codespell
additional_dependencies:
- tomli
- repo: local
hooks:
- id: regenerate-files
name: regenerate generated files
language: system
entry: python src/sanescansrv/generate_pages.py
pass_filenames: false
files: ^src\/sanescansrv\/(((htmlgen|generate_pages)\.py)|((static|templates)\/.+\.\w+))$
107 changes: 77 additions & 30 deletions src/sanescansrv/generate_pages.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,51 +23,45 @@
__license__ = "GNU General Public License Version 3"


import pathlib
import argparse
import sys
from pathlib import Path
from typing import TYPE_CHECKING, Final

from sanescansrv import htmlgen, server

if TYPE_CHECKING:
from collections.abc import Callable

TEMPLATE_FOLDER: Final = pathlib.Path("templates")
SOURCE_ROOT: Final = Path.cwd()
CORE: Final = SOURCE_ROOT / "src" / "sanescansrv"

TEMPLATE_FOLDER: Final = CORE / "templates"
TEMPLATE_FUNCTIONS: dict[str, Callable[[], str]] = {}
STATIC_FOLDER: Final = pathlib.Path("static")
STATIC_FOLDER: Final = CORE / "static"
STATIC_FUNCTIONS: dict[str, Callable[[], str]] = {}


def save_template(name: str, content: str) -> None:
"""Save content as new template "{name}"."""
assert TEMPLATE_FOLDER is not None
template_path = TEMPLATE_FOLDER / f"{name}.html.jinja"
with open(template_path, "w", encoding="utf-8") as template_file:
template_file.write(content)
template_file.write("\n")
print(f"Saved content to {template_path}")


def save_static(filename: str, content: str) -> None:
"""Save content as new static file "{filename}"."""
assert STATIC_FOLDER is not None
static_path = STATIC_FOLDER / filename
with open(static_path, "w", encoding="utf-8") as static_file:
static_file.write(content)
static_file.write("\n")
print(f"Saved content to {static_path}")
def save_content(path: str, content: str) -> None:
"""Save content to given path."""
with open(path, "w", encoding="utf-8") as fp:
fp.write(content)
fp.write("\n")
print(f"Saved content to {path}")


def save_template_as(
filename: str,
) -> Callable[[Callable[[], str]], Callable[[], str]]:
"""Save generated template as filename."""
path = TEMPLATE_FOLDER / f"{filename}.html.jinja"

def function_wrapper(function: Callable[[], str]) -> Callable[[], str]:
if filename in TEMPLATE_FUNCTIONS:
if path in TEMPLATE_FUNCTIONS:
raise NameError(
f"{filename!r} already exists as template filename",
)
TEMPLATE_FUNCTIONS[filename] = function
TEMPLATE_FUNCTIONS[path] = function
return function

return function_wrapper
Expand All @@ -77,11 +71,12 @@ def save_static_as(
filename: str,
) -> Callable[[Callable[[], str]], Callable[[], str]]:
"""Save generated static file as filename."""
path = STATIC_FOLDER / filename

def function_wrapper(function: Callable[[], str]) -> Callable[[], str]:
if filename in STATIC_FUNCTIONS:
if path in STATIC_FUNCTIONS:
raise NameError(f"{filename!r} already exists as static filename")
STATIC_FUNCTIONS[filename] = function
STATIC_FUNCTIONS[path] = function
return function

return function_wrapper
Expand Down Expand Up @@ -485,14 +480,66 @@ def generate_scan_status_get() -> str:
return template(title, body, head=head)


def run() -> None:
"""Generate all page templates and static files."""
def matches_disk_files(new_files: dict[str, str]) -> bool:
"""Return if all new file contents match old file contents.
Copied from src/trio/_tools/gen_exports.py, dual licensed under
MIT and APACHE2.
"""
for path, new_source in new_files.items():
path_obj = Path(path)
if not path_obj.exists():
return False
# Strip trailing newline `save_content` adds.
old_source = path_obj.read_text(encoding="utf-8")[:-1]
if old_source != new_source:
return False
return True


def process(do_test: bool) -> int:
"""Generate all page templates and static files. Return exit code."""
new_files: dict[str, str] = {}
for filename, function in TEMPLATE_FUNCTIONS.items():
save_template(filename, function())
new_files[filename] = function()
for filename, function in STATIC_FUNCTIONS.items():
save_static(filename, function())
new_files[filename] = function()

matches_disk = matches_disk_files(new_files)

if do_test:
if not matches_disk:
print("Generated sources are outdated. Please regenerate.")
return 1
elif not matches_disk:
for path, new_source in new_files.items():
save_content(path, new_source)
print("Regenerated sources successfully.")
# With pre-commit integration, show that we edited files.
return 1
print("Generated sources are up to date.")
return 0


def run() -> int:
"""Regenerate all generated files."""
parser = argparse.ArgumentParser(
description="Generate static and template files",
)
parser.add_argument(
"--test",
"-t",
action="store_true",
help="test if code is still up to date",
)
parsed_args = parser.parse_args()

# Double-check we found the right directory
assert (SOURCE_ROOT / "LICENSE").exists()

return process(do_test=parsed_args.test)


if __name__ == "__main__":
print(f"{__title__}\nProgrammed by {__author__}.\n")
run()
sys.exit(run())

0 comments on commit 29816d4

Please sign in to comment.