diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..a3ed0e6 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, Jared W. Cook +# SPDX-License-Identifier: AGPL-3.0-or-later +# Build context is limited to the files required to install dependencies. +** +!pyproject.toml +!README.md +!LICENSE.md +!hooks/ +!hooks/** +hooks/**/__pycache__/ +hooks/**/*.pyc +!docker/ +!docker/toolchain.Dockerfile +!docker/toolchain-entrypoint.sh +!docker/constraints.txt +!docs/ +!docs/jekyll/ +!docs/jekyll/Gemfile +!docs/jekyll/Gemfile.lock diff --git a/.github/workflows/container-toolchain.yml b/.github/workflows/container-toolchain.yml new file mode 100644 index 0000000..296a056 --- /dev/null +++ b/.github/workflows/container-toolchain.yml @@ -0,0 +1,74 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, Jared W. Cook +# SPDX-License-Identifier: AGPL-3.0-or-later +--- +name: Container Development Toolchain + +on: [push, pull_request, workflow_dispatch] + +permissions: + contents: read + +jobs: + toolchain: + name: Container build and hook acceptance + runs-on: ubuntu-24.04 + timeout-minutes: 30 + steps: + - name: Checkout + uses: actions/checkout@v7 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Build the pinned toolchain + run: make TOOLCHAIN=container python-install + + - name: Test the project without host Python + run: make TOOLCHAIN=container test + + - name: Build documentation and generate the changelog + run: make TOOLCHAIN=container build-docs changelog + + - name: Install and exercise the real Git hooks + run: | + make TOOLCHAIN=container pre-commit-init + git hook run pre-commit + message="$(git rev-parse --git-path COMMIT_EDITMSG)" + printf '%s\n' 'feat: add container toolchain' > "$message" + git hook run commit-msg -- "$message" + printf '%s\n' 'not a conventional commit' > "$message" + if git hook run commit-msg -- "$message" > .git/container-invalid-message.log 2>&1; then + echo "Invalid commit message was accepted." >&2 + exit 1 + fi + cat .git/container-invalid-message.log + grep -E 'Conventional Commit.*Failed' .git/container-invalid-message.log + printf '%s\n' 'feat: add hte toolchain' > "$message" + if git hook run commit-msg -- "$message" > .git/container-invalid-spelling.log 2>&1; then + echo "Misspelled commit message was accepted." >&2 + exit 1 + fi + cat .git/container-invalid-spelling.log + grep -E 'cspell.*Failed' .git/container-invalid-spelling.log + + - name: Reject invalid staged source through the real hook + run: | + fixture=container-hook-invalid-fixture.yaml + test ! -e "$fixture" + printf '%s\n' 'invalid: [' > "$fixture" + git add -- "$fixture" + trap 'git restore --staged -- "$fixture"; rm -- "$fixture"' EXIT + if git hook run pre-commit > .git/container-invalid-hook.log 2>&1; then + echo "Invalid staged YAML was accepted." >&2 + exit 1 + fi + cat .git/container-invalid-hook.log + grep -E 'check yaml.*Failed' .git/container-invalid-hook.log + + - name: Verify failure propagation and file ownership + run: | + if scripts/toolchain.sh run false; then + echo "The toolchain swallowed an error." >&2 + exit 1 + fi + test -z "$(find . -uid 0 -print -quit)" diff --git a/.gitignore b/.gitignore index 51aea69..e39f401 100644 --- a/.gitignore +++ b/.gitignore @@ -28,6 +28,7 @@ __pycache__/ .pytest_cache/ .ruff_cache/ .venv/ +.venv.backup.*/ dist/ # ========================================= ## Default Ignores # diff --git a/.yamllint b/.yamllint index 107f6f9..debf822 100644 --- a/.yamllint +++ b/.yamllint @@ -19,6 +19,8 @@ extends: default ignore: - .venv + - .venv.backup.* + - .git - changelogs - '{{ cookiecutter.project_slug }}' diff --git a/Makefile b/Makefile index 88df35a..6a24ff7 100644 --- a/Makefile +++ b/Makefile @@ -15,6 +15,10 @@ # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . +TOOLCHAIN ?= native +ifeq ($(TOOLCHAIN),container) +include docker/toolchain.mk +else # -------------------------------------------------- # โš™๏ธ Environment Settings # -------------------------------------------------- @@ -130,15 +134,26 @@ DEV_DOCS := .[docs] # ๐Ÿ Python Commands (venv, activate, pip) # -------------------------------------------------- PYTHON_CMD := python3.11 +ifeq ($(TOOLCHAIN_CONTAINER),1) +VENV_DIR := /opt/venv +CI := 1 +RUBY_INSTALL_OVERRIDE := RUBY_INSTALL="bundle check" +else VENV_DIR := $(PROJECT_ROOT)/.venv +endif ACTIVATE := source $(VENV_DIR)/bin/activate PYTHON := $(ACTIVATE) && $(PYTHON_CMD) # -------------------------------------------------- # ๐Ÿ’Ž Ruby Settings # -------------------------------------------------- RUBY_VERSION := 3.3.0 +ifeq ($(TOOLCHAIN_CONTAINER),1) +GEMFILE := /opt/jekyll/Gemfile +BUNDLE_PATH := /opt/bundle +else GEMFILE := $(PROJECT_ROOT)/Gemfile BUNDLE_PATH := $(PROJECT_ROOT)/vendor/bundle +endif # -------------------------------------------------- # ๐Ÿ’Ž Ruby Commands (bundler) # -------------------------------------------------- @@ -217,7 +232,10 @@ BUMPVERSION := $(ACTIVATE) && bump-my-version # Finds files of a given extension or "*" (all files) under a directory, # skipping VENV_DIR and template markers like {{ }}. define get_files_by_extension - find $(1) -name "$(2)" \ + find "$(1)" \ + -type d \( -name ".git" -o -name ".venv" -o -name ".venv.backup.*" \ + -o -name "node_modules" -o -name "_site" \) -prune -o \ + -type f -name "$(2)" \ ! -path "$(VENV_DIR)/*" \ ! -path "$(RENDERED_VENV_DIR)/*" \ ! -path "*{{*" \ @@ -307,7 +325,7 @@ nutrimatic-readme: ## Automated documentation assistant for Jinja and Jekyll tem jekyll-build: ## A Ruby-based static site generator for project documentation. $(AT)echo "Running ๐Ÿš€ Building Jekyll site in $(DOCS_DIR)..." - $(AT)$(JEKYLL) -j1 all + $(AT)$(JEKYLL) -j1 all $(RUBY_INSTALL_OVERRIDE) $(AT)echo "โœ… Jekyll build complete!" jekyll-serve: ## A Ruby-based static site generator for project documentation. @@ -642,7 +660,7 @@ pre-release: # ๐Ÿ“š Documentation (Jekyll + nutrimatic) # -------------------------------------------------- ruby-install: - $(AT)$(MAKE) -C "$(JEKYLL_DIR)" ruby-install + $(AT)$(MAKE) -C "$(JEKYLL_DIR)" ruby-install $(RUBY_INSTALL_OVERRIDE) jekyll: jekyll-build nutrimatic-readme: jekyll-build run-docs: jekyll-serve @@ -663,7 +681,9 @@ clean-build: $(AT)echo "๐Ÿงน Cleaning build artifacts..." $(AT)rm -rf build dist *.egg-info $(AT)for dir in "$(SRC_DIR)" "$(TEST_DIR)"; do if [ -d "$$dir" ]; then find "$$dir" -name "__pycache__" -type d -exec rm -rf {} +; fi; done +ifneq ($(TOOLCHAIN_CONTAINER),1) $(AT)-[ -d "$(VENV_DIR)" ] && rm -r $(VENV_DIR) +endif $(AT)echo "๐Ÿงน Cleaned build artifacts." clean: clean-docs clean-build @@ -707,3 +727,5 @@ help: ## Show this help message. $(AT)printf "\n\033[1mOptions:\033[0m\n" $(AT)printf " \033[36m%-30s\033[0m %s\n" "V=1" "Enable verbose output (show all commands)" $(AT)printf " \033[36m%-30s\033[0m %s\n" "make -s" "Run completely silently (suppress output)" + +endif # TOOLCHAIN diff --git a/changelogs/CHANGELOG.md b/changelogs/CHANGELOG.md index a293fb4..37e180f 100644 --- a/changelogs/CHANGELOG.md +++ b/changelogs/CHANGELOG.md @@ -12,7 +12,6 @@ - Import shared spelling dictionary - Add containerized documentation preview - Generate reviewed Python release preparation -- Prepare reviewed Python generator releases ### ๐Ÿ› Fixed @@ -25,6 +24,7 @@ - Standardize generated CLA workflow configuration - Update shared spelling dictionary - Update shared spelling dictionary +- Keep generated readme paths portable (#31) ### ๐Ÿงช Tests diff --git a/changelogs/releases/v0.1.0.md b/changelogs/releases/v0.1.0.md index db7dc60..a1e7098 100644 --- a/changelogs/releases/v0.1.0.md +++ b/changelogs/releases/v0.1.0.md @@ -12,7 +12,6 @@ - Import shared spelling dictionary - Add containerized documentation preview - Generate reviewed Python release preparation -- Prepare reviewed Python generator releases ### ๐Ÿ› Fixed @@ -25,6 +24,7 @@ - Standardize generated CLA workflow configuration - Update shared spelling dictionary - Update shared spelling dictionary +- Keep generated readme paths portable (#31) ### ๐Ÿงช Tests diff --git a/compose.yml b/compose.yml new file mode 100644 index 0000000..9dbaa46 --- /dev/null +++ b/compose.yml @@ -0,0 +1,31 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, Jared W. Cook +# SPDX-License-Identifier: AGPL-3.0-or-later +--- +services: + toolchain: + build: + context: "." + dockerfile: "docker/toolchain.Dockerfile" + init: true + user: "${LOCAL_UID:?Run scripts/toolchain.sh}:${LOCAL_GID:?Run scripts/toolchain.sh}" + working_dir: "${TOOLCHAIN_ROOT:?Run scripts/toolchain.sh}" + read_only: true + cap_drop: + - "ALL" + security_opt: + - "no-new-privileges:true" + tmpfs: + - "/tmp:exec,mode=1777" + volumes: + - type: "bind" + source: "." + target: "${TOOLCHAIN_ROOT:?Run scripts/toolchain.sh}" + environment: + HOME: "/tmp/toolchain-home" + PRE_COMMIT_HOME: "${TOOLCHAIN_ROOT}/.git/container-toolchain-cache" + TOOLCHAIN: "native" + TOOLCHAIN_CONTAINER: "1" + CI: "1" + BUNDLE_FROZEN: "true" + GIT_TERMINAL_PROMPT: "0" + command: ["make", "test"] diff --git a/docker/constraints.txt b/docker/constraints.txt new file mode 100644 index 0000000..7b2db6d --- /dev/null +++ b/docker/constraints.txt @@ -0,0 +1,174 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Resolved Python 3.11 Linux development and documentation dependencies. +# Regenerate and review against the parent toolchain constraints. +alabaster==1.0.0 +annotated-doc==0.0.7 +annotated-types==0.8.0 +anyio==4.16.0 +arrow==1.4.0 +ast-serialize==0.13.1 +babel==2.19.0 +backports-tarfile==1.2.0 +bandit==1.9.4 +binaryornot==0.6.0 +black==26.10.1 +boolean-py==5.0 +bracex==3.2.4 +build==1.6.1 +bump-my-version==1.8.4 +cachecontrol==0.15.0 +cairocffi==1.7.1 +cairosvg==2.9.1 +certifi==2026.11.20 +cffi==2.1.1 +cfgv==3.5.0 +charset-normalizer==3.5.3 +click==8.5.1 +codespell==2.4.3 +cookiecutter==2.7.1 +cookiecutter-project-upgrader==1.3.1 +coverage==7.17.5 +cryptography==51.0.0 +cssbeautifier==2.0.3 +cssselect2==0.10.1 +cyclonedx-python-lib==11.13.0 +defusedxml==0.7.1 +deprecated==1.3.1 +deptry==0.25.1 +distlib==0.4.4 +djlint==1.54.2 +docutils==0.22.4 +editorconfig==0.17.1 +filelock==4.3.2 +fuzzywuzzy==0.18.0 +git-cliff==2.14.2 +gitdb==4.0.12 +gitpython==3.2.1 +h11==0.16.0 +httpcore2==2.16.2 +httpx2==2.16.2 +id==1.6.1 +identify==2.6.20 +idna==3.20 +imagesize==2.0.1 +importlib-metadata==10.2.0 +iniconfig==2.3.1 +installer==1.1.0 +jaraco-classes==3.4.0 +jaraco-context==6.1.2 +jaraco-functools==4.6.0 +jeepney==0.9.0 +jinja2==3.1.6 +jinja2-cli==1.0.1 +jinja2-time==0.2.0 +jsbeautifier==2.0.3 +json-lint-tools==0.1.2 +json5==0.17.3 +keyring==25.7.0 +lazy-importer==0.1.0 +levenshtein==0.27.5 +librt==0.17.0 +license-expression==30.4.4 +markdown-it-py==4.3.0 +markupsafe==3.0.4 +mdit-py-plugins==0.7.0 +mdurl==0.1.2 +more-itertools==11.2.1 +msgpack==1.2.4 +mypy==2.4.1 +mypy-extensions==1.2.0 +myst-parser==5.2.0 +nab==0.0.32 +nab-index==0.0.32 +nab-markersets==0.0.32 +nab-project==0.0.32 +nab-provider==0.0.32 +nab-resolver==0.0.32 +nameisok==0.1.8 +nh3==0.3.8 +nodeenv==1.12.0 +nutri-matic==0.1.15 +packageurl-python==0.17.6 +packaging==26.4 +pathspec==1.1.1 +pillow==13.0.0 +pip==26.3 +pip-api==0.0.35 +pip-audit==2.10.1 +pip-requirements-parser==32.0.1 +pipdeptree==4.2.18 +platformdirs==4.14.9 +pluggy==1.7.0 +pre-commit==4.7.0 +prompt-toolkit==3.0.53 +py-serializable==2.2.0 +pycparser==3.12 +pydantic==2.14.4 +pydantic-core==2.50.5 +pydantic-settings==2.16.3 +pygments==2.21.0 +pyparsing==3.3.3 +pyproject-hooks==1.3.3 +pytest==9.2.0 +pytest-cookies==0.7.0 +pytest-cov==7.1.0 +python-dateutil==4.0.0 +python-discovery==1.9.8 +python-dotenv==1.2.4 +python-levenshtein==0.27.5 +python-slugify==9.2.0 +pytokens==0.4.1 +pyyaml==6.0.4 +questionary==2.1.1 +rapidfuzz==3.14.6 +readme-renderer==46.0 +regex==2026.11.25 +requests==2.34.2 +requests-toolbelt==1.0.0 +requirements-parser==0.13.1 +rfc3986==2.0.0 +rich==15.0.0 +rich-click==1.9.9 +roman-numerals==4.1.0 +ruff==0.17.6 +secretstorage==3.5.0 +setuptools==84.2.1 +shellingham==1.5.4 +smmap==5.0.3 +snowballstemmer==3.1.1 +sortedcontainers==2.4.0 +sphinx==9.0.4 +sphinx-autodoc-typehints==3.6.1 +sphinx-markdown-builder==0.6.11 +sphinx-rtd-theme==3.1.0 +sphinxcontrib-applehelp==2.0.0 +sphinxcontrib-devhelp==2.0.0 +sphinxcontrib-htmlhelp==2.1.0 +sphinxcontrib-jquery==4.1 +sphinxcontrib-jsmath==2.0.0 +sphinxcontrib-qthelp==2.0.0 +sphinxcontrib-serializinghtml==2.0.0 +stevedore==5.10.0 +tabulate==0.10.0 +text-unidecode==1.3 +tinycss2==1.5.1 +toml==0.10.2 +tomli==2.5.0 +tomli-w==1.2.0 +tomlkit==0.15.3 +tomllint==0.3.6 +truststore==0.10.5 +twine==7.0.0 +typer==0.29.3 +typing-extensions==4.16.0 +typing-inspection==0.4.5 +tzdata==2026.6 +urllib3==2.8.0 +virtualenv==21.15.14 +wcmatch==12.0.4 +wcwidth==0.9.5 +webencodings==0.6.1 +wheel==0.48.0 +wrapt==2.5.2 +yamllint==1.38.0 +zipp==4.1.2 diff --git a/docker/toolchain-entrypoint.sh b/docker/toolchain-entrypoint.sh new file mode 100755 index 0000000..7279525 --- /dev/null +++ b/docker/toolchain-entrypoint.sh @@ -0,0 +1,10 @@ +#!/bin/sh +# SPDX-FileCopyrightText: Copyright (c) 2026, Jared W. Cook +# SPDX-License-Identifier: AGPL-3.0-or-later +set -eu +if [ "$(id -u)" -eq 0 ]; then + echo "Refusing a root toolchain process." >&2 + exit 1 +fi +mkdir -p "$HOME" +exec "$@" diff --git a/docker/toolchain.Dockerfile b/docker/toolchain.Dockerfile new file mode 100644 index 0000000..a679f53 --- /dev/null +++ b/docker/toolchain.Dockerfile @@ -0,0 +1,46 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, Jared W. Cook +# SPDX-License-Identifier: AGPL-3.0-or-later + +FROM ruby:3.3.14-bookworm@sha256:e2bd2e75c5543d79ce392526f3b53ebae08d7004449771fac54d4303ab1ec22d + +ENV LANG=C.UTF-8 \ + PATH="/opt/venv/bin:${PATH}" \ + BUNDLE_PATH=/opt/bundle \ + BUNDLE_GEMFILE=/opt/jekyll/Gemfile \ + BUNDLE_FROZEN=true \ + PIP_DISABLE_PIP_VERSION_CHECK=1 + +RUN apt-get update \ + && apt-get install -y --no-install-recommends \ + python3.11 python3.11-venv python3.11-dev \ + ca-certificates git jq make libmagic1 libcairo2 \ + && rm -rf /var/lib/apt/lists/* \ + && python3.11 -m venv /opt/venv + +WORKDIR /opt/dependency-source +COPY --chmod=0644 pyproject.toml README.md LICENSE.md ./ +COPY hooks/ hooks/ +COPY --chmod=0644 docker/constraints.txt /opt/constraints.txt +RUN umask 022 \ + && python -m pip install --constraint /opt/constraints.txt pip setuptools wheel \ + && python -m pip install --no-build-isolation \ + --constraint /opt/constraints.txt ".[dev,docs]" "git-cliff==2.14.2" \ + && python -m pip check + +WORKDIR /opt/jekyll +COPY --chmod=0644 docs/jekyll/Gemfile docs/jekyll/Gemfile.lock ./ +RUN umask 022 \ + && gem install bundler --version 2.5.23 --no-document \ + && bundle _2.5.23_ install \ + && bundle _2.5.23_ check + +COPY --chmod=0755 docker/toolchain-entrypoint.sh /usr/local/bin/toolchain-entrypoint +USER 65534:65534 +RUN HOME=/tmp python --version \ + && HOME=/tmp pre-commit --version \ + && jq -e -n 'true' \ + && HOME=/tmp git cliff --version \ + && HOME=/tmp bundle _2.5.23_ check + +ENTRYPOINT ["/usr/local/bin/toolchain-entrypoint"] +CMD ["make", "test"] diff --git a/docker/toolchain.mk b/docker/toolchain.mk new file mode 100644 index 0000000..a1770e6 --- /dev/null +++ b/docker/toolchain.mk @@ -0,0 +1,30 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, Jared W. Cook +# SPDX-License-Identifier: AGPL-3.0-or-later + +.DEFAULT_GOAL := all +.PHONY: all build python-install toolchain-build pre-commit-init run-docs jekyll-serve help +.PHONY: test lint-check typecheck spellcheck format-check format-fix dependency-check security +.PHONY: build-docs jekyll readme clean pre-commit changelog + +toolchain-build python-install: + @./scripts/toolchain.sh build + +all build: + @./scripts/toolchain.sh run make lint-check typecheck spellcheck test build-docs + +test lint-check typecheck spellcheck format-check format-fix dependency-check security build-docs jekyll readme clean pre-commit changelog: + @./scripts/toolchain.sh run make $@ + +pre-commit-init: + @./scripts/install-container-hooks.sh + +run-docs jekyll-serve: + @$(MAKE) -C docs/jekyll run + +help: + @printf '%s\n' "Container toolchain (TOOLCHAIN=container)" \ + "make TOOLCHAIN=container python-install Build the toolchain image" \ + "make TOOLCHAIN=container test Run tests" \ + "make TOOLCHAIN=container build Run checks and build docs" \ + "make TOOLCHAIN=container pre-commit-init Install container-backed Git hooks" \ + "make TOOLCHAIN=native help Existing native toolchain" diff --git a/docs/container-toolchain.md b/docs/container-toolchain.md new file mode 100644 index 0000000..f8d6553 --- /dev/null +++ b/docs/container-toolchain.md @@ -0,0 +1,66 @@ +# Container development toolchain + +The root Compose service is separate from the Jekyll website preview. +Use Docker Engine, Docker Compose v2, Git and Make on the host. +No host Python, Ruby or project virtual environment is required for the +container targets. This first release is opt-in while the real container +acceptance checks run. + +## Build and check + +```sh +make TOOLCHAIN=container python-install +make TOOLCHAIN=container test +make TOOLCHAIN=container lint-check +make TOOLCHAIN=container typecheck +make TOOLCHAIN=container build +``` + +The build target runs lint, typing, spelling, tests and the existing +documentation build. The documentation and changelog targets retain the +existing generated-file staging behavior. The website preview remains +`make TOOLCHAIN=container run-docs`. + +The image uses the project's pinned Ruby base image, Debian Python 3.11, +the reviewed Python dependency constraints and the existing Gemfile.lock. +The image uses the locked Gemfile even during temporary README builds. +The build installs dependencies without host credentials. OS security +updates and remote theme content can still vary between builds. + +## Git hooks + +```sh +make TOOLCHAIN=container pre-commit-init +``` + +The installer prepares all configured pre-commit environments before +changing either hook. It recognizes the standard pre-commit wrapper, +preserves the old wrappers in a private directory under .git, and refuses +custom, symlinked or legacy hooks and custom core.hooksPath settings. +The installed hooks run the original pre-commit configuration, including +documentation, changelog, spelling and conventional commit-message checks. +A nonzero exit blocks the normal Git operation. Use ordinary host Git +commands to review, commit and push; the build toolchain never pushes. + +If the installer refuses a hook, review its actual contents before +migrating it. To return to the native workflow, restore the backed-up hooks +after repairing the native environment, or reinstall standard pre-commit +hooks using that environment. Do not skip checks. + +## Runtime boundary + +The service runs as the invoking user's UID and GID with a read-only +container filesystem, a temporary home, dropped Linux capabilities and +no Docker socket or SSH-agent mount. The checkout is mounted writable +at its original absolute path so Git temporary index and message paths +remain valid. Build context excludes .git and the rest of the checkout +except the dependency-installation inputs. + +A normal checkout with a local .git directory is required; linked +worktrees, external index paths and root execution are refused. +The pre-commit cache is isolated per checkout under .git. +Host virtual environments and preserved virtual environment backups are +excluded from source discovery; existing backups are not deleted. +The wrapper ignores implicit Compose dotenv loading. +Public package and hook downloads require network access. +The existing native targets remain available with TOOLCHAIN=native. diff --git a/scripts/git-hooks/container-hook b/scripts/git-hooks/container-hook new file mode 100755 index 0000000..e5e561d --- /dev/null +++ b/scripts/git-hooks/container-hook @@ -0,0 +1,11 @@ +#!/bin/sh +# SPDX-FileCopyrightText: Copyright (c) 2026, Jared W. Cook +# SPDX-License-Identifier: AGPL-3.0-or-later +# Cook's Code container toolchain hook +set -eu +root=$(git rev-parse --show-toplevel) +case "${0##*/}" in + pre-commit|commit-msg) hook="${0##*/}" ;; + *) echo "Unsupported hook type." >&2; exit 1 ;; +esac +exec "$root/scripts/toolchain.sh" hook "$hook" "$@" diff --git a/scripts/install-container-hooks.sh b/scripts/install-container-hooks.sh new file mode 100755 index 0000000..d13c101 --- /dev/null +++ b/scripts/install-container-hooks.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Copyright (c) 2026, Jared W. Cook +# SPDX-License-Identifier: AGPL-3.0-or-later +set -euo pipefail +root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd -P) +cd "$root" +if [[ ! -d .git || -L .git || "$(git rev-parse --absolute-git-dir)" != "$root/.git" ]]; then + echo "The installer requires a normal checkout." >&2 + exit 1 +fi +if [[ "$(id -u)" == 0 ]] || git config --get core.hooksPath >/dev/null; then + echo "Refusing root or a custom core.hooksPath; review existing hooks first." >&2 + exit 1 +fi + +hooks="$root/.git/hooks" +[[ ! -L "$hooks" ]] || { echo "Refusing a symlinked hooks directory." >&2; exit 1; } +mkdir -p "$hooks" +for hook in pre-commit commit-msg; do + path="$hooks/$hook" + if [[ -e "$path.legacy" || -L "$path.legacy" || -L "$path" ]]; then + echo "Refusing to replace a legacy or symlinked hook: $hook" >&2 + exit 1 + fi + if [[ -e "$path" ]] && ! cmp -s "$path" scripts/git-hooks/container-hook; then + # Match the complete standard pre-commit wrapper, ignoring only its + # generated interpreter path. Refuse unknown or edited wrappers. + case "$hook" in + pre-commit) expected=22d4acab4e6eb61a60930bd57beb25215333670589c811f2cd914dc3c21a385e ;; + commit-msg) expected=abf4d1dc4f02630c82108e9e23cae32b6c99f2e265f397890da257236f6adf7a ;; + esac + if [[ ! -f "$path" ]] || [[ "$(sed "s|^INSTALL_PYTHON=.*$|INSTALL_PYTHON=''|" "$path" | sha256sum | cut -d ' ' -f 1)" != "$expected" ]]; then + echo "Refusing to replace a custom hook: $hook" >&2 + exit 1 + fi + fi +done + +# Do not alter existing hooks until the image and all configured hook +# environments have been prepared successfully. +scripts/toolchain.sh run pre-commit install-hooks +backup=$(mktemp -d "$root/.git/container-hook-backup.XXXXXX") +for hook in pre-commit commit-msg; do + path="$hooks/$hook" + if [[ -e "$path" ]]; then + cp -p -- "$path" "$backup/$hook" + fi + temp=$(mktemp "$hooks/.${hook}.XXXXXX") + install -m 0755 scripts/git-hooks/container-hook "$temp" + mv -- "$temp" "$path" +done +printf 'Container hooks installed. Previous hooks (if any): %s\n' "$backup" diff --git a/scripts/toolchain.sh b/scripts/toolchain.sh new file mode 100755 index 0000000..4e6ebdd --- /dev/null +++ b/scripts/toolchain.sh @@ -0,0 +1,59 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Copyright (c) 2026, Jared W. Cook +# SPDX-License-Identifier: AGPL-3.0-or-later +set -euo pipefail + +root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd -P) +cd "$root" + +# Keep absolute paths identical inside and outside the container, including +# Git's temporary index and commit-message files. +if [[ ! -d .git || -L .git || "$(git rev-parse --absolute-git-dir)" != "$root/.git" ]]; then + echo "The toolchain requires a normal checkout with a local .git directory." >&2 + exit 1 +fi + +export LOCAL_UID="$(id -u)" LOCAL_GID="$(id -g)" TOOLCHAIN_ROOT="$root" +if [[ "$LOCAL_UID" == 0 ]]; then + echo "Run the toolchain as your ordinary user, not root." >&2 + exit 1 +fi + +project="cc-toolchain-$(printf '%s' "$root" | sha256sum | cut -c1-12)" +compose=(docker compose --env-file /dev/null --project-name "$project" --project-directory "$root" -f "$root/compose.yml") +environment=() +if [[ -n "${GIT_INDEX_FILE:-}" ]]; then + index=$(realpath -m -- "$GIT_INDEX_FILE") + if [[ "$index" != "$root/.git/"* ]]; then + echo "Refusing a Git index outside the checkout." >&2 + exit 1 + fi + environment+=(-e "GIT_INDEX_FILE=$index") +fi + +case "${1:-}" in + build) + [[ "$#" == 1 ]] + exec "${compose[@]}" build toolchain + ;; + run) + shift + [[ "$#" -gt 0 ]] + exec "${compose[@]}" run --rm --build -T --no-deps "${environment[@]}" toolchain "$@" + ;; + hook) + shift + case "${1:-}" in + pre-commit|commit-msg) hook="$1" ;; + *) echo "Unsupported hook type." >&2; exit 1 ;; + esac + shift + exec "${compose[@]}" run --rm --build -T --no-deps "${environment[@]}" toolchain \ + pre-commit hook-impl --config .pre-commit-config.yaml \ + --hook-type "$hook" --hook-dir "$root/.git/hooks" -- "$@" + ;; + *) + echo "Usage: scripts/toolchain.sh build | run COMMAND [ARGS...] | hook TYPE [ARGS...]" >&2 + exit 2 + ;; +esac diff --git a/tests/test_container_toolchain.py b/tests/test_container_toolchain.py new file mode 100644 index 0000000..ab2f5e3 --- /dev/null +++ b/tests/test_container_toolchain.py @@ -0,0 +1,262 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, Jared W. Cook +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Validate the host-only Compose dispatcher and Git hook migration.""" + +from __future__ import annotations + +import json +import os +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest +import yaml + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture +def checkout(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + """Exercise real host scripts in a disposable checkout with a fake engine.""" + repo = tmp_path / "checkout" + repo.mkdir() + for name in ( + "Makefile", + "compose.yml", + "docker/toolchain.mk", + "scripts/toolchain.sh", + "scripts/install-container-hooks.sh", + "scripts/git-hooks/container-hook", + ): + target = repo / name + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(ROOT / name, target) + + for name in ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_CONFIG_COUNT"): + monkeypatch.delenv(name, raising=False) + monkeypatch.setenv("GIT_CONFIG_GLOBAL", "/dev/null") + monkeypatch.setenv("GIT_CONFIG_SYSTEM", "/dev/null") + subprocess.run(["git", "init", "-q", str(repo)], check=True) + (repo / ".pre-commit-config.yaml").write_text("repos: []\n") + + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + docker = bin_dir / "docker" + docker.write_text( + f"#!{sys.executable}\n" + "import json, os, sys\n" + "with open(os.environ['DOCKER_TEST_LOG'], 'a') as stream:\n" + " stream.write(json.dumps({'args': sys.argv[1:], " + "'uid': os.environ['LOCAL_UID'], 'gid': os.environ['LOCAL_GID'], " + "'root': os.environ['TOOLCHAIN_ROOT']}) + '\\n')\n" + "sys.exit(int(os.environ.get('DOCKER_TEST_EXIT', '0')))\n" + ) + docker.chmod(0o755) + monkeypatch.setenv("PATH", f"{bin_dir}:{os.environ['PATH']}") + monkeypatch.setenv("DOCKER_TEST_LOG", str(repo / ".git/engine.log")) + return repo + + +def invoke(repo: Path, *args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run(args, cwd=repo, capture_output=True, text=True, check=False) + + +def engine_calls(repo: Path) -> list[dict[str, object]]: + log = repo / ".git/engine.log" + return [json.loads(line) for line in log.read_text().splitlines()] + + +def test_compose_boundary() -> None: + config = yaml.safe_load((ROOT / "compose.yml").read_text()) + service = config["services"]["toolchain"] + assert service["read_only"] + assert service["cap_drop"] == ["ALL"] + assert service["security_opt"] == ["no-new-privileges:true"] + assert service["user"].startswith("${LOCAL_UID:") + assert service["environment"]["TOOLCHAIN"] == "native" + assert service["environment"]["CI"] == "1" + assert len(service["volumes"]) == 1 + assert service["volumes"][0]["source"] == "." + assert not service.get("privileged") + assert not service.get("ports") + assert not service.get("env_file") + assert "SSH_AUTH_SOCK" not in service["environment"] + assert "docker.sock" not in (ROOT / "compose.yml").read_text() + dockerfile = (ROOT / "docker/toolchain.Dockerfile").read_text() + assert "BUNDLE_GEMFILE=/opt/jekyll/Gemfile" in dockerfile + assert "BUNDLE_FROZEN=true" in dockerfile + + +def test_host_make_and_failure(checkout: Path, monkeypatch: pytest.MonkeyPatch) -> None: + result = invoke(checkout, "make", "TOOLCHAIN=container", "test") + assert result.returncode == 0, result.stderr + call = engine_calls(checkout)[-1] + assert call["root"] == str(checkout.resolve()) + assert call["uid"] == str(os.getuid()) + assert call["gid"] == str(os.getgid()) + args = call["args"] + assert isinstance(args, list) + assert args[:3] == ["compose", "--env-file", "/dev/null"] + assert args[-8:] == [ + "run", + "--rm", + "--build", + "-T", + "--no-deps", + "toolchain", + "make", + "test", + ] + monkeypatch.setenv("DOCKER_TEST_EXIT", "17") + result = invoke(checkout, "make", "TOOLCHAIN=container", "test") + assert result.returncode != 0 + assert not (checkout / ".venv").exists() + + +def test_make_native_inside_container(checkout: Path) -> None: + result = invoke( + checkout, + "make", + "-n", + "TOOLCHAIN=native", + "TOOLCHAIN_CONTAINER=1", + "test", + "clean-build", + ) + assert result.returncode == 0, result.stderr + assert "source /opt/venv/bin/activate" in result.stdout + assert "rm -r /opt/venv" not in result.stdout + assert "scripts/toolchain.sh" not in result.stdout + + result = invoke( + checkout, + "make", + "-s", + "TOOLCHAIN=native", + "TOOLCHAIN_CONTAINER=1", + "--eval", + "bundle-path-test: ; @printf '%s' '$(BUNDLE_PATH)'", + "bundle-path-test", + ) + assert result.returncode == 0, result.stderr + assert result.stdout == "/opt/bundle" + + +def test_install_and_invoke_hooks( + checkout: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + result = invoke( + checkout, + sys.executable, + "-m", + "pre_commit", + "install", + "--hook-type", + "pre-commit", + "--hook-type", + "commit-msg", + ) + assert result.returncode == 0, result.stderr + hooks = checkout / ".git/hooks" + original = { + name: (hooks / name).read_bytes() for name in ("pre-commit", "commit-msg") + } + result = invoke(checkout, "scripts/install-container-hooks.sh") + assert result.returncode == 0, result.stderr + install_args = engine_calls(checkout)[-1]["args"] + assert isinstance(install_args, list) + assert install_args[-3:] == [ + "toolchain", + "pre-commit", + "install-hooks", + ] + backups = list((checkout / ".git").glob("container-hook-backup.*")) + assert len(backups) == 1 + for name, contents in original.items(): + assert (backups[0] / name).read_bytes() == contents + assert (hooks / name).read_bytes() == ( + checkout / "scripts/git-hooks/container-hook" + ).read_bytes() + message = checkout / ".git/message with spaces" + message.write_text("feat: synthetic change\n") + index = checkout / ".git/index.synthetic" + monkeypatch.setenv("GIT_INDEX_FILE", str(index)) + result = invoke(checkout, str(hooks / "commit-msg"), str(message)) + assert result.returncode == 0, result.stderr + args = engine_calls(checkout)[-1]["args"] + assert isinstance(args, list) + assert f"GIT_INDEX_FILE={index}" in args + assert args[-2:] == ["--", str(message)] + assert args[args.index("--hook-type") + 1] == "commit-msg" + monkeypatch.setenv("DOCKER_TEST_EXIT", "23") + result = invoke(checkout, str(hooks / "pre-commit")) + assert result.returncode == 23 + + +def test_custom_hook_and_failed_setup_are_preserved( + checkout: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + hook = checkout / ".git/hooks/pre-commit" + hook.write_text("#!/bin/sh\necho custom\n") + hook.chmod(0o755) + before = hook.read_bytes() + result = invoke(checkout, "scripts/install-container-hooks.sh") + assert result.returncode != 0 + assert hook.read_bytes() == before + assert not (checkout / ".git/engine.log").exists() + hook.unlink() + monkeypatch.setenv("DOCKER_TEST_EXIT", "9") + result = invoke(checkout, "scripts/install-container-hooks.sh") + assert result.returncode == 9 + assert not hook.exists() + assert not (checkout / ".git/hooks/commit-msg").exists() + + +def test_external_index_and_custom_hook_path_refused( + checkout: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("GIT_INDEX_FILE", str(checkout.parent / "external-index")) + result = invoke(checkout, "scripts/toolchain.sh", "run", "true") + assert result.returncode != 0 + assert "outside" in result.stderr + monkeypatch.delenv("GIT_INDEX_FILE") + subprocess.run( + ["git", "config", "core.hooksPath", "custom-hooks"], cwd=checkout, check=True + ) + result = invoke(checkout, "scripts/install-container-hooks.sh") + assert result.returncode != 0 + assert "core.hooksPath" in result.stderr + assert not (checkout / ".git/engine.log").exists() + + +def test_container_discovery_excludes_host_caches(checkout: Path) -> None: + for name in ( + "pyproject.toml", + ".git/container-toolchain-cache/pyproject.toml", + ".venv/pyproject.toml", + ".venv.backup.123/pyproject.toml", + "node_modules/pyproject.toml", + "_site/pyproject.toml", + "rendered/pyproject.toml", + ): + target = checkout / name + target.parent.mkdir(parents=True, exist_ok=True) + target.touch() + + result = invoke( + checkout, + "make", + "-s", + "TOOLCHAIN=native", + "TOOLCHAIN_CONTAINER=1", + "--eval", + "discovery-test: ; @$(call get_files_by_extension,$(CURDIR),*.toml)", + "discovery-test", + ) + assert result.returncode == 0, result.stderr + assert set(result.stdout.rstrip("\0").split("\0")) == { + str(checkout / "pyproject.toml"), + str(checkout / "rendered/pyproject.toml"), + }