From e8e77f632ea341162a808150f976323940798f9d Mon Sep 17 00:00:00 2001 From: Gabriel Date: Mon, 16 Nov 2026 14:52:43 +0000 Subject: [PATCH 1/8] feat: publish Frontal's git-hook gates as pre-commit + lefthook remote MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Seven hooks, one per Frontal gate: - frontal-biome pnpm exec biome check (check-only) on staged JS/TS/JSON - frontal-ruff ruff check + ruff format --check on staged Python - frontal-rustfmt rustfmt --edition 2024 --check on staged Rust only - frontal-clippy cargo clippy --all-targets -D warnings, scoped per crate workspace (hooks/clippy-scoped.mjs) - frontal-go-vet go vet ./... in each affected Go module (hooks/go-vet-scoped.mjs) - frontal-buf-lint buf lint for each affected proto module (hooks/buf-lint-scoped.mjs) - frontal-commit-msg Conventional Commits validation, replaces commitlint Every hook guards its tool with hooks/ensure-tool.mjs — a missing tool exits non-zero instead of silently passing. Shared excludes: vendor/, gen/, generated/, node_modules/. lefthook-remote.yml provides a lefthook bridge with identical commands. Tests: 15 cases (2 SKIPPED on machines without biome). frontal-lint is intentionally absent: there is no standalone frontal CLI. --- .github/workflows/release.yml | 22 ++ .pre-commit-config.yaml | 101 +++----- .pre-commit-hooks.yaml | 124 ++++++++- CHANGELOG.md | 27 ++ README.md | 115 +++++++-- hooks/buf-lint-scoped.mjs | 109 ++++++++ hooks/check-commit-message.mjs | 116 +++++++++ hooks/clippy-scoped.mjs | 107 ++++++++ hooks/ensure-tool.mjs | 54 ++++ hooks/go-vet-scoped.mjs | 91 +++++++ lefthook-remote.yml | 91 +++++++ tests/fixtures/biome/fail/index.ts | 1 + tests/fixtures/biome/fail/package.json | 1 + tests/fixtures/biome/pass/index.ts | 3 + tests/fixtures/biome/pass/package.json | 1 + .../fail/api/proto/demo/v1/ping.proto | 7 + tests/fixtures/buf-lint/fail/buf.yaml | 6 + .../pass/api/proto/demo/v1/ping.proto | 7 + tests/fixtures/buf-lint/pass/buf.yaml | 6 + .../clippy/fail/crates/demo/Cargo.toml | 7 + .../clippy/fail/crates/demo/src/main.rs | 7 + .../clippy/pass/crates/demo/Cargo.toml | 7 + .../clippy/pass/crates/demo/src/main.rs | 3 + tests/fixtures/commit-msg/fail.txt | 2 + tests/fixtures/commit-msg/fail/message.txt | 1 + tests/fixtures/commit-msg/pass.txt | 1 + tests/fixtures/commit-msg/pass/message.txt | 1 + tests/fixtures/go-vet/fail/service/go.mod | 3 + tests/fixtures/go-vet/fail/service/main.go | 12 + tests/fixtures/go-vet/pass/service/go.mod | 3 + tests/fixtures/go-vet/pass/service/main.go | 3 + tests/fixtures/ruff/fail-format/main.py | 3 + .../fixtures/ruff/fail-format/pyproject.toml | 3 + tests/fixtures/ruff/fail-lint/main.py | 5 + tests/fixtures/ruff/fail-lint/pyproject.toml | 3 + tests/fixtures/ruff/pass/main.py | 2 + tests/fixtures/ruff/pass/pyproject.toml | 3 + tests/fixtures/rustfmt/fail/Cargo.toml | 2 + .../rustfmt/fail/crates/demo/src/main.rs | 3 + tests/fixtures/rustfmt/pass/Cargo.toml | 2 + .../rustfmt/pass/crates/demo/src/main.rs | 15 ++ tests/run-hooks.test.mjs | 239 ++++++++++++++++++ 42 files changed, 1224 insertions(+), 95 deletions(-) create mode 100644 .github/workflows/release.yml create mode 100644 CHANGELOG.md create mode 100644 hooks/buf-lint-scoped.mjs create mode 100644 hooks/check-commit-message.mjs create mode 100644 hooks/clippy-scoped.mjs create mode 100644 hooks/ensure-tool.mjs create mode 100644 hooks/go-vet-scoped.mjs create mode 100644 lefthook-remote.yml create mode 100644 tests/fixtures/biome/fail/index.ts create mode 100644 tests/fixtures/biome/fail/package.json create mode 100644 tests/fixtures/biome/pass/index.ts create mode 100644 tests/fixtures/biome/pass/package.json create mode 100644 tests/fixtures/buf-lint/fail/api/proto/demo/v1/ping.proto create mode 100644 tests/fixtures/buf-lint/fail/buf.yaml create mode 100644 tests/fixtures/buf-lint/pass/api/proto/demo/v1/ping.proto create mode 100644 tests/fixtures/buf-lint/pass/buf.yaml create mode 100644 tests/fixtures/clippy/fail/crates/demo/Cargo.toml create mode 100644 tests/fixtures/clippy/fail/crates/demo/src/main.rs create mode 100644 tests/fixtures/clippy/pass/crates/demo/Cargo.toml create mode 100644 tests/fixtures/clippy/pass/crates/demo/src/main.rs create mode 100644 tests/fixtures/commit-msg/fail.txt create mode 100644 tests/fixtures/commit-msg/fail/message.txt create mode 100644 tests/fixtures/commit-msg/pass.txt create mode 100644 tests/fixtures/commit-msg/pass/message.txt create mode 100644 tests/fixtures/go-vet/fail/service/go.mod create mode 100644 tests/fixtures/go-vet/fail/service/main.go create mode 100644 tests/fixtures/go-vet/pass/service/go.mod create mode 100644 tests/fixtures/go-vet/pass/service/main.go create mode 100644 tests/fixtures/ruff/fail-format/main.py create mode 100644 tests/fixtures/ruff/fail-format/pyproject.toml create mode 100644 tests/fixtures/ruff/fail-lint/main.py create mode 100644 tests/fixtures/ruff/fail-lint/pyproject.toml create mode 100644 tests/fixtures/ruff/pass/main.py create mode 100644 tests/fixtures/ruff/pass/pyproject.toml create mode 100644 tests/fixtures/rustfmt/fail/Cargo.toml create mode 100644 tests/fixtures/rustfmt/fail/crates/demo/src/main.rs create mode 100644 tests/fixtures/rustfmt/pass/Cargo.toml create mode 100644 tests/fixtures/rustfmt/pass/crates/demo/src/main.rs create mode 100644 tests/run-hooks.test.mjs diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..4eb5970 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,22 @@ +name: Release + +on: + push: + tags: + - 'v*' + +permissions: + contents: write + +jobs: + release: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Create GitHub Release + uses: softprops/action-gh-release@v2 + with: + generate_release_notes: true + draft: false + prerelease: false diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index ac684f2..c0eb0c7 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,98 +1,67 @@ -# Pre-commit framework configuration +# Pre-commit framework configuration for this repository (self-test). +# +# When you contribute to this repo, pre-commit will run the hooks against +# your staged changes — the same hooks that external consumers use. fail_fast: false default_install_hook_types: [pre-commit, commit-msg] repos: - # Biome (JS/TS/JSON/YAML) - repo: local hooks: - - id: biome-check - name: biome check - entry: bunx biome check --write --no-errors-on-unmatched + - id: frontal-biome + name: frontal biome check + entry: sh -c 'node hooks/ensure-tool.mjs pnpm && pnpm exec biome check --no-errors-on-unmatched "$@"' language: system - files: \.(ts|tsx|mts|cts|js|jsx|mjs|cjs|json|jsonc|yaml|yml)$ + files: \.(ts|tsx|js|jsx|json)$ + exclude: "^packages/design-system/" stages: [pre-commit] - - id: biome-format - name: biome format - entry: bunx biome format --write --no-errors-on-unmatched + - id: frontal-ruff + name: frontal ruff check + format + entry: sh -c 'node hooks/ensure-tool.mjs ruff && ruff check "$@" && ruff format --check "$@"' language: system - files: \.(ts|tsx|mts|cts|js|jsx|mjs|cjs|json|jsonc|yaml|yml)$ + files: \.py$ + exclude: "(^|/)(vendor|gen|generated|node_modules)/" stages: [pre-commit] - # Rust - - repo: local - hooks: - - id: cargo-fmt - name: cargo fmt - entry: cargo fmt + - id: frontal-rustfmt + name: frontal rustfmt (staged) + entry: sh -c 'node hooks/ensure-tool.mjs rustfmt && rust_files=$(git diff --cached --name-only --diff-filter=ACMR -- "*.rs" | grep -vE "(^|/)gen/" || true); if [ -n "$rust_files" ]; then printf "%s\n" "$rust_files" | xargs rustfmt --edition 2024 --check; fi' language: system files: \.rs$ pass_filenames: false stages: [pre-commit] - - id: cargo-clippy - name: cargo clippy - entry: cargo clippy -- -D warnings + - id: frontal-clippy + name: frontal cargo clippy (scoped) + entry: sh -c 'node hooks/ensure-tool.mjs cargo && node hooks/clippy-scoped.mjs' language: system files: \.rs$ pass_filenames: false stages: [pre-commit] - # Go - - repo: local - hooks: - - id: gofmt - name: gofmt - entry: gofmt -w - language: system - files: \.go$ - stages: [pre-commit] - - - id: goimports - name: goimports - entry: goimports -w - language: system - files: \.go$ - stages: [pre-commit] - - - id: golangci-lint - name: golangci-lint - entry: golangci-lint run --fix + - id: frontal-go-vet + name: frontal go vet (scoped) + entry: sh -c 'node hooks/ensure-tool.mjs go && node hooks/go-vet-scoped.mjs' language: system files: \.go$ pass_filenames: false stages: [pre-commit] - # Python - - repo: local - hooks: - - id: ruff-lint - name: ruff lint - entry: ruff check --fix - language: system - files: \.py$ - stages: [pre-commit] - - - id: ruff-format - name: ruff format - entry: ruff format - language: system - files: \.py$ - stages: [pre-commit] - - - id: black - name: black - entry: black + - id: frontal-buf-lint + name: frontal buf lint (scoped) + entry: sh -c 'node hooks/ensure-tool.mjs buf && node hooks/buf-lint-scoped.mjs' language: system - files: \.py$ + files: \.proto$ + pass_filenames: false stages: [pre-commit] - # Conventional Commits - - repo: local - hooks: - - id: commitlint - name: commitlint - entry: bunx commitlint --edit + - id: frontal-commit-msg + name: frontal commit-msg (Conventional Commits) + # The commit-msg file arrives as the first positional param, which + # `sh -c` consumes as $0. The hook reads from that path (or stdin). + entry: sh -c 'node hooks/check-commit-message.mjs "$0"' language: system + pass_filenames: false + always_run: true stages: [commit-msg] diff --git a/.pre-commit-hooks.yaml b/.pre-commit-hooks.yaml index 6004693..218bffc 100644 --- a/.pre-commit-hooks.yaml +++ b/.pre-commit-hooks.yaml @@ -1,7 +1,121 @@ -- id: frontal-lint - name: Frontal lint - description: Lint with Frontal - entry: frontal lint +# --------------------------------------------------------------------------- +# Frontal's git-hook gates, republished for external repositories. +# +# Source of truth: frontal/lefthook.yml + scripts/hooks/run-checks.mjs. +# Do not add rules here that do not exist in those files. +# +# Every hook fails loudly when its tool is missing (hooks/ensure-tool.mjs). +# Shared excludes: vendor/, gen/, generated/, node_modules/ +# --------------------------------------------------------------------------- + +# ---- Biome (JS/TS/JSON) --------------------------------------------------- +# Mirrors lefthook `biome`: +# glob: *.{ts,tsx,js,jsx,json} +# exclude: ^packages/design-system/ +# run: pnpm exec biome check --no-errors-on-unmatched {staged_files} +# Check-only (no --write); pre-commit passes staged files as arguments. +- id: frontal-biome + name: frontal biome check + description: Biome check (check-only) on staged JS/TS/JSON files + entry: sh -c 'node hooks/ensure-tool.mjs pnpm && pnpm exec biome check --no-errors-on-unmatched "$@"' language: system - types_or: [python, javascript, typescript] + files: \.(ts|tsx|js|jsx|json)$ + exclude: "^packages/design-system/" stages: [pre-commit] + +# ---- Ruff (Python lint + format) ------------------------------------------ +# Mirrors lefthook `python-ruff` and `python-format`: +# glob: *.py +# exclude: (^|/)(vendor|gen/python|generated)/ +# run: ruff check {staged_files} (python-ruff) +# run: ruff format --check {staged_files} (python-format) +# The two lefthook commands are merged here: ruff check && ruff format --check. +# Black is intentionally absent — frontal uses ruff exclusively. +- id: frontal-ruff + name: frontal ruff check + format + description: ruff check and ruff format --check on staged Python files + entry: sh -c 'node hooks/ensure-tool.mjs ruff && ruff check "$@" && ruff format --check "$@"' + language: system + files: \.py$ + exclude: "(^|/)(vendor|gen|generated|node_modules)/" + stages: [pre-commit] + +# ---- Rustfmt (staged files only) ------------------------------------------ +# Mirrors lefthook `rust-fmt`: +# rust_files=$(git diff --cached --name-only --diff-filter=ACMR -- '*.rs' +# | grep -vE '(^|/)gen/') +# printf '%s\n' "$rust_files" | xargs rustfmt --edition 2024 --check +# Staged files only — never the whole workspace. +# The sh -c wrapper re-reads the staged file list from git so that renames +# (which pre-commit passes as "old new" pairs) do not confuse rustfmt. +- id: frontal-rustfmt + name: frontal rustfmt (staged) + description: rustfmt --edition 2024 --check on staged Rust files only + entry: sh -c 'node hooks/ensure-tool.mjs rustfmt && rust_files=$(git diff --cached --name-only --diff-filter=ACMR -- "*.rs" | grep -vE "(^|/)gen/" || true); if [ -n "$rust_files" ]; then printf "%s\n" "$rust_files" | xargs rustfmt --edition 2024 --check; fi' + language: system + files: \.rs$ + pass_filenames: false + stages: [pre-commit] + +# ---- Clippy (scoped per crate workspace) ----------------------------------- +# Mirrors run-checks.mjs `rust:clippy:`: +# cwd: +# cmd: cargo clippy -p -p … --all-targets -- -D warnings +# For each staged .rs file, the owning workspace is resolved (nearest ancestor +# Cargo.toml declaring [workspace]) and the crate name is read from its +# Cargo.toml. One clippy run per workspace covers all of its staged crates. +# Toolchain is picked from the workspace directory (rust-toolchain.toml). +- id: frontal-clippy + name: frontal cargo clippy (scoped) + description: cargo clippy --all-targets -D warnings on the crates that own staged Rust files + entry: sh -c 'node hooks/ensure-tool.mjs cargo && node hooks/clippy-scoped.mjs' + language: system + files: \.rs$ + pass_filenames: false + stages: [pre-commit] + +# ---- Go vet (scoped per module) -------------------------------------------- +# Mirrors run-checks.mjs `go:vet:`: +# cwd: +# cmd: go vet ./... +# For each staged .go file the owning Go module is resolved by walking up to +# the nearest go.mod. One `go vet ./...` per affected module. +- id: frontal-go-vet + name: frontal go vet (scoped) + description: go vet ./... in each Go module that owns a staged Go file + entry: sh -c 'node hooks/ensure-tool.mjs go && node hooks/go-vet-scoped.mjs' + language: system + files: \.go$ + pass_filenames: false + stages: [pre-commit] + +# ---- Buf lint (scoped per proto module) ------------------------------------ +# Mirrors run-checks.mjs `proto:lint:`: +# In-workspace modules → buf lint from repo root (buf.yaml workspace) +# Standalone modules → buf lint in the module directory +# A module is in-workspace when its path appears in the root buf.yaml +# modules list; otherwise it is linted module-scoped. +- id: frontal-buf-lint + name: frontal buf lint (scoped) + description: buf lint for each proto module that owns a staged .proto file + entry: sh -c 'node hooks/ensure-tool.mjs buf && node hooks/buf-lint-scoped.mjs' + language: system + files: \.proto$ + pass_filenames: false + stages: [pre-commit] + +# ---- Commit message (Conventional Commits) --------------------------------- +# Replaces commitlint. Rules are identical to +# frontal/scripts/hooks/check-commit-message.mjs (copied verbatim into +# hooks/check-commit-message.mjs in this repository). +- id: frontal-commit-msg + name: frontal commit-msg (Conventional Commits) + description: Validate commit message against Conventional Commits (replaces commitlint) + # The hook reads the message from the file at $0 (pre-commit passes the + # commit-msg file as the first positional param, which `sh -c` consumes + # as $0), falling back to stdin for lefthook/piped use. + entry: sh -c 'node hooks/check-commit-message.mjs "$0"' + pass_filenames: false + always_run: true + language: system + stages: [commit-msg] diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..23061db --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,27 @@ +# Changelog + +## 1.0.0 — 2026-11-16 + +Initial release. Frontal's git-hook gates, published as a pre-commit hook +collection and a lefthook remote config. + +### Hooks + +- `frontal-biome` — Biome check (check-only) on staged JS/TS/JSON files +- `frontal-ruff` — `ruff check` + `ruff format --check` on staged Python files +- `frontal-rustfmt` — `rustfmt --edition 2024 --check` on staged Rust files only +- `frontal-clippy` — `cargo clippy --all-targets -D warnings` scoped per crate + workspace +- `frontal-go-vet` — `go vet ./...` in each Go module that owns a staged Go file +- `frontal-buf-lint` — `buf lint` for each proto module that owns a staged + `.proto` file +- `frontal-commit-msg` — Conventional Commits validation (replaces commitlint) + +### Other + +- `hooks/ensure-tool.mjs` — every hook fails loudly when its tool is missing +- `lefthook-remote.yml` — lefthook bridge with identical commands +- `tests/` — 15-case test suite with pass/fail fixtures per hook +- Shared excludes: `vendor/`, `gen/`, `generated/`, `node_modules/` +- `.pre-commit-hooks.yaml` — hook definitions for pre-commit consumers +- GitHub Actions release workflow (tag-triggered) diff --git a/README.md b/README.md index 3dd1de8..ab18541 100644 --- a/README.md +++ b/README.md @@ -1,49 +1,116 @@ -# Frontal Pre-Commit +# Frontal Pre-Commit Hooks -This repository provides configuration which makes it easy to use Frontal's linter with pre-commit. +Frontal's git-hook gates, published as a [pre-commit](https://pre-commit.com) hook +collection and a [lefthook](https://github.com/evilmartians/lefthook) remote +config. Every hook fails loudly when its tool is missing — no silent passes. -## Usage +## Hooks -First, in the root of your repository, create a `.pre-commit-config.yaml` file containing: +| ID | Description | Tool | +|---|---|---| +| `frontal-biome` | Biome check (check-only) on staged JS/TS/JSON files | `pnpm exec biome` | +| `frontal-ruff` | `ruff check` + `ruff format --check` on staged Python files | `ruff` | +| `frontal-rustfmt` | `rustfmt --edition 2024 --check` on staged Rust files only | `rustfmt` | +| `frontal-clippy` | `cargo clippy --all-targets -D warnings` scoped to the crate workspaces that own staged Rust files | `cargo clippy` | +| `frontal-go-vet` | `go vet ./...` in each Go module that owns a staged Go file | `go` | +| `frontal-buf-lint` | `buf lint` for each proto module that owns a staged `.proto` file | `buf` | +| `frontal-commit-msg` | Conventional Commits validation (replaces commitlint) | `node` | + +Shared excludes: `vendor/`, `gen/`, `generated/`, `node_modules/`. + +## Usage with pre-commit + +Add to your `.pre-commit-config.yaml`: ```yaml repos: - - repo: https://github.com/frontal/pre-commit - rev: main + - repo: https://github.com/frontal-labs/pre-commit + rev: v1.0.0 hooks: - - id: frontal-lint + - id: frontal-biome + - id: frontal-ruff + - id: frontal-rustfmt + - id: frontal-clippy + - id: frontal-go-vet + - id: frontal-buf-lint + - id: frontal-commit-msg ``` -If you already have a `.pre-commit-config.yaml` file, just add this alongside other pre-commit hook config under the `repos` key. - -Then, run: +Then run: ```sh pre-commit install ``` -From now on, when you run `git commit`, Frontal lint will execute. +Pick only the hooks you need. All hooks are optional; include just the ones +that apply to your repo. + +## Usage with lefthook + +Add a `remotes:` entry to your `lefthook.yml`: -## Usage with GitHub Action +```yaml +remotes: + - git_url: https://github.com/frontal-labs/pre-commit + ref: v1.0.0 + configs: [lefthook-remote.yml] +``` -This frontal-pre-commit plugin assumes that you have Frontal available on your PATH. +The remote config mirrors every gate in the pre-commit collection with +identical commands. -In GitHub Actions, you can ensure this by first installing your dependencies, and then using the Frontal action: +## CI (GitHub Actions) ```yaml steps: - - uses: actions/setup-python@v4 - with: - python-version: '3.10' - cache: 'pip' + - uses: actions/checkout@v4 - - name: "Install dependencies" - run: pip install -r requirements.txt + - uses: actions/setup-node@v4 + with: + node-version: '22' - - uses: frontal/cli-action@v1 + - uses: actions/setup-python@v5 with: - client-id: ... - client-secret: ... + python-version: '3.13' + + - name: Install ruff + run: pip install ruff + + - name: Run pre-commit + uses: pre-commit/action@v3.0.0 +``` + +Adjust the install steps for whichever tools your enabled hooks require +(`pnpm` + `biome`, `rustfmt`, `cargo clippy`, `go`, `buf`, etc.). + +## Tool requirements + +Each hook requires its tool on `PATH`: + +- **frontal-biome**: `pnpm` (runs `biome` via `pnpm exec`) +- **frontal-ruff**: `ruff` +- **frontal-rustfmt**: `rustfmt` +- **frontal-clippy**: `cargo` + the `clippy` component (`rustup component add clippy`) +- **frontal-go-vet**: `go` +- **frontal-buf-lint**: `buf` +- **frontal-commit-msg**: `node` (>= 20) + +If a tool is missing, the hook exits non-zero with a clear message instead of +skipping silently. - - uses: pre-commit/action@v3.0.0 +## Development + +```sh +# Run the full test suite (15 cases; 2 skipped if biome is not installed) +node tests/run-hooks.test.mjs + +# Run a single case +node tests/run-hooks.test.mjs clippy-fail --debug ``` + +Fixtures live in `tests/fixtures/`. Each fixture is a minimal repo shape that +the hook must accept (pass) or reject (fail). + +## License + +[MIT](LICENSE.md) diff --git a/hooks/buf-lint-scoped.mjs b/hooks/buf-lint-scoped.mjs new file mode 100644 index 0000000..0202f22 --- /dev/null +++ b/hooks/buf-lint-scoped.mjs @@ -0,0 +1,109 @@ +#!/usr/bin/env node +/** + * Scoped buf lint for staged proto files. + * + * Mirrors run-checks.mjs `proto:lint:`: + * In-workspace modules → buf lint from repo root (buf.yaml workspace) + * Standalone modules → buf lint in the module directory + * + * A module is in-workspace when its path appears in the root buf.yaml + * modules list (parsed the same way as run-checks.mjs readWorkspaceModules). + * + * Excluded: gen/, generated/, node_modules/, vendor/. + */ + +import { spawnSync } from "node:child_process"; +import { existsSync, readFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; + +const EXCLUDED = [ + /(^|\/)gen\//, + /(^|\/)generated\//, + /(^|\/)node_modules\//, + /(^|\/)vendor\//, +]; + +function git(args, cwd) { + const result = spawnSync("git", args, { cwd, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 }); + if (result.status !== 0) { + const detail = (result.stderr || "").trim(); + throw new Error(`git ${args.join(" ")} failed: ${detail}`); + } + return result.stdout.split("\n").filter(Boolean); +} + +/** + * Module paths listed in the root buf.yaml workspace. + * Parsed the same way as run-checks.mjs readWorkspaceModules(). + */ +function readWorkspaceModules(root) { + const paths = new Set(); + const manifest = join(root, "buf.yaml"); + if (!existsSync(manifest)) return paths; + for (const line of readFileSync(manifest, "utf8").split("\n")) { + // Stop at the top-level deps:/lint: keys; - path: only appears under modules: + const match = line.match(/^\s{2}- path:\s*(\S+)\s*$/); + if (match) paths.add(match[1].replace(/\/+$/, "")); + } + return paths; +} + +function findProtoModule(file, root) { + let dir = dirname(resolve(root, file)); + const stop = resolve(root); + for (;;) { + if (existsSync(join(dir, "buf.yaml"))) { + const rel = dir === stop ? "." : dir.slice(stop.length + 1); + return rel; + } + if (dir === stop) return null; + const parent = dirname(dir); + if (parent === dir) return null; + dir = parent; + } +} + +try { + const root = git(["rev-parse", "--show-toplevel"])[0]; + const staged = git(["diff", "--cached", "--name-only", "--diff-filter=ACMR", "--", "*.proto"], root).filter( + (f) => !EXCLUDED.some((p) => p.test(f)), + ); + + if (staged.length === 0) { + process.stderr.write("frontal-buf-lint: no staged proto files — nothing to check\n"); + process.exit(0); + } + + const dirs = [...new Set(staged.map((f) => findProtoModule(f, root)).filter(Boolean))]; + if (dirs.length === 0) { + process.stderr.write("frontal-buf-lint: no proto module owns any staged file — nothing to check\n"); + process.exit(0); + } + + const workspaceModules = readWorkspaceModules(root); + const inWorkspace = dirs.filter((dir) => workspaceModules.has(dir)); + const standalone = dirs.filter((dir) => !workspaceModules.has(dir)); + + if (inWorkspace.length > 0) { + process.stderr.write("frontal-buf-lint: buf lint (repo root, workspace modules)\n"); + const result = spawnSync("buf", ["lint"], { cwd: root, shell: false, stdio: "inherit" }); + if (result.status !== 0) { + process.stderr.write("\n ✗ frontal-buf-lint: failed (workspace)\n"); + process.exit(result.status ?? 1); + } + } + + for (const dir of standalone) { + process.stderr.write(`frontal-buf-lint: buf lint (in ${dir})\n`); + const result = spawnSync("buf", ["lint"], { cwd: join(root, dir), shell: false, stdio: "inherit" }); + if (result.status !== 0) { + process.stderr.write(`\n ✗ frontal-buf-lint: failed in ${dir}\n`); + process.exit(result.status ?? 1); + } + } + + process.stderr.write("frontal-buf-lint: ok\n"); +} catch (error) { + process.stderr.write(`frontal-buf-lint: ${error.message}\n`); + process.exit(1); +} diff --git a/hooks/check-commit-message.mjs b/hooks/check-commit-message.mjs new file mode 100644 index 0000000..7f8dc48 --- /dev/null +++ b/hooks/check-commit-message.mjs @@ -0,0 +1,116 @@ +#!/usr/bin/env node +/** + * Conventional Commits validation for a single commit message. + * + * Copied verbatim from frontal/scripts/hooks/check-commit-message.mjs — + * the rules, types, exemptions and length limit are identical. + * + * Usage: check-commit-message.mjs + */ + +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { pathToFileURL } from "node:url"; + +const TYPES = [ + "feat", + "fix", + "docs", + "style", + "refactor", + "perf", + "test", + "build", + "ci", + "chore", + "revert", +]; + +const HEADER = new RegExp(`^(${TYPES.join("|")})(\\([^)]+\\))?!?: .+`); + +/** Messages git creates itself, which must not be rejected. */ +const EXEMPT = [ + /^Merge /, + /^Revert "/, + /^fixup! /, + /^squash! /, + // An in-progress rebase writes these; the final message is validated separately. + /^amend! /, +]; + +export function validateMessage(raw) { + // Strip comments and the scissors section git appends in verbose mode. + const body = raw + .split("\n") + .filter((line) => !line.startsWith("#")) + .join("\n"); + + const subject = body.split("\n").find((line) => line.trim().length > 0); + + if (!subject) return { ok: false, error: "commit message is empty" }; + if (EXEMPT.some((pattern) => pattern.test(subject))) return { ok: true }; + + if (!HEADER.test(subject)) { + return { + ok: false, + error: `not a Conventional Commit: "${subject}"`, + hint: [ + "expected (): ", + ` types: ${TYPES.join(", ")}`, + " example: fix(billing): reject subscriptions without a connection row", + ].join("\n"), + }; + } + + // A subject that runs long is truncated in most git UIs. + if (subject.length > 100) { + return { + ok: false, + error: `subject is ${subject.length} characters; keep it under 100`, + hint: "move detail into the commit body", + }; + } + + return { ok: true }; +} + +/** + * Resolve the commit message file path from argv. + * + * The hook entry is `sh -c 'node hooks/check-commit-message.mjs "$0"'`. + * A single positional param to `sh -c` is consumed as `$0` (not `$1` or + * `$@`), so the path arrives as the script's first argv entry. When the + * shell is invoked bare (e.g. from lefthook or an editor integration), + * `argv[2]` may be `sh`/`bash`/empty — in that case fall back to stdin. + */ +function resolveMessagePath(argv) { + const candidate = argv[2]; + if (candidate && candidate !== "sh" && candidate !== "bash" && !candidate.endsWith("/sh") && !candidate.endsWith("/bash")) { + return candidate; + } + return null; +} + +function main() { + const path = resolveMessagePath(process.argv); + const raw = path ? readFileSync(path, "utf8") : readFileSync(0, "utf8"); + const result = validateMessage(raw); + if (!result.ok) { + process.stderr.write(`\n ✗ ${result.error}\n`); + if (result.hint) { + process.stderr.write( + `${result.hint + .split("\n") + .map((l) => ` ${l}`) + .join("\n")}\n`, + ); + } + process.stderr.write("\n"); + process.exit(1); + } +} + +const isMain = + process.argv[1] && + import.meta.url === pathToFileURL(resolve(process.argv[1])).href; +if (isMain) main(); diff --git a/hooks/clippy-scoped.mjs b/hooks/clippy-scoped.mjs new file mode 100644 index 0000000..cd0d84e --- /dev/null +++ b/hooks/clippy-scoped.mjs @@ -0,0 +1,107 @@ +#!/usr/bin/env node +/** + * Scoped cargo clippy for staged Rust files. + * + * Mirrors run-checks.mjs `rust:clippy:`: + * For each staged .rs file, resolve the owning workspace (nearest ancestor + * Cargo.toml declaring [workspace]) and the crate name. One clippy run per + * workspace covers all of its staged crates together. + * + * cargo clippy -p -p … --all-targets -- -D warnings + * + * The cwd is the workspace directory so rustup picks the correct toolchain + * from rust-toolchain.toml. + * + * Excluded: gen/ (generated bindings), node_modules/, vendor/. + */ + +import { spawnSync } from "node:child_process"; +import { existsSync, readFileSync } from "node:fs"; +import { dirname, join, relative, resolve, sep } from "node:path"; + +const EXCLUDED = [/(^|\/)gen\//, /(^|\/)generated\//, /(^|\/)vendor\//, /(^|\/)node_modules\//]; + +function git(args, cwd) { + const result = spawnSync("git", args, { cwd, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 }); + if (result.status !== 0) { + const detail = (result.stderr || "").trim(); + throw new Error(`git ${args.join(" ")} failed: ${detail}`); + } + return result.stdout.split("\n").filter(Boolean); +} + +function findRustWorkspace(file, root) { + let dir = dirname(resolve(root, file)); + const stop = resolve(root); + for (;;) { + const manifest = join(dir, "Cargo.toml"); + if (existsSync(manifest)) { + const text = readFileSync(manifest, "utf8"); + if (/^\s*\[workspace\]/m.test(text)) { + const rel = relative(stop, dir); + return rel === "" ? "." : rel.split(sep).join("/"); + } + } + if (dir === stop) return null; + const parent = dirname(dir); + if (parent === dir) return null; + dir = parent; + } +} + +function readCrateName(crateDir, root) { + const manifest = join(resolve(root, crateDir), "Cargo.toml"); + if (!existsSync(manifest)) return null; + const match = readFileSync(manifest, "utf8").match(/^\s*\[package\][\s\S]*?^\s*name\s*=\s*"([^"]+)"/m); + return match ? match[1] : null; +} + +try { + const root = git(["rev-parse", "--show-toplevel"])[0]; + const staged = git(["diff", "--cached", "--name-only", "--diff-filter=ACMR", "--", "*.rs"], root).filter( + (f) => !EXCLUDED.some((p) => p.test(f)), + ); + + if (staged.length === 0) { + process.stderr.write("frontal-clippy: no staged Rust files — nothing to check\n"); + process.exit(0); + } + + // Map workspace → [crate names] + const clippyCrates = new Map(); + for (const file of staged) { + const workspace = findRustWorkspace(file, root); + if (!workspace) continue; // no workspace manifest; Bazel owns this + // The workspace dir holds the manifest that addresses this crate with + // `-p`. In the self-workspace layout (a crate declaring its own + // [workspace] members = ["."]) that manifest also declares the [package]. + const name = readCrateName(workspace, root); + if (!name) continue; // workspace root with no [package]; not addressable with -p + clippyCrates.set(workspace, [...(clippyCrates.get(workspace) ?? []), name]); + } + + if (clippyCrates.size === 0) { + process.stderr.write("frontal-clippy: no addressable crates in staged files — nothing to check\n"); + process.exit(0); + } + + for (const [workspace, names] of clippyCrates) { + const uniqueNames = [...new Set(names)]; + const args = ["clippy", ...uniqueNames.flatMap((n) => ["-p", n]), "--all-targets", "--", "-D", "warnings"]; + process.stderr.write(`frontal-clippy: cargo ${args.join(" ")} (in ${workspace})\n`); + const result = spawnSync("cargo", args, { + cwd: join(root, workspace), + shell: false, + stdio: "inherit", + }); + if (result.status !== 0) { + process.stderr.write(`\n ✗ frontal-clippy: failed in ${workspace}\n`); + process.exit(result.status ?? 1); + } + } + + process.stderr.write("frontal-clippy: ok\n"); +} catch (error) { + process.stderr.write(`frontal-clippy: ${error.message}\n`); + process.exit(1); +} diff --git a/hooks/ensure-tool.mjs b/hooks/ensure-tool.mjs new file mode 100644 index 0000000..5365daf --- /dev/null +++ b/hooks/ensure-tool.mjs @@ -0,0 +1,54 @@ +#!/usr/bin/env node +/** + * Verify that a tool is on PATH before the hook runs. + * + * pre-commit's `language: system` silently exits 0 when the entry command is + * not found, which is the exact failure mode the frontal hook system exists to + * prevent. This script turns that silent pass into a loud, actionable error. + * + * Usage: node hooks/ensure-tool.mjs [ ...] + * Exit: 0 every tool found + * 1 at least one tool missing (names printed to stderr) + */ + +import { accessSync, constants as fsConstants } from "node:fs"; +import { join } from "node:path"; + +const tools = process.argv.slice(2); +if (tools.length === 0) { + process.stderr.write("ensure-tool: expected at least one tool name\n"); + process.exit(2); +} + +const missing = []; +for (const bin of tools) { + if (bin.includes("/")) { + try { + accessSync(bin, fsConstants.X_OK); + } catch { + missing.push(bin); + } + continue; + } + const dirs = (process.env.PATH ?? "").split(":").filter(Boolean); + const found = dirs.some((dir) => { + try { + accessSync(join(dir, bin), fsConstants.X_OK); + return true; + } catch { + return false; + } + }); + if (!found) missing.push(bin); +} + +if (missing.length > 0) { + process.stderr.write(`\n ✗ frontal hook: required tool(s) not found on PATH\n`); + for (const t of missing) { + process.stderr.write(` ${t}\n`); + } + process.stderr.write( + ` Install the missing tool(s) and retry. See README.md for setup.\n\n`, + ); + process.exit(1); +} diff --git a/hooks/go-vet-scoped.mjs b/hooks/go-vet-scoped.mjs new file mode 100644 index 0000000..0b09075 --- /dev/null +++ b/hooks/go-vet-scoped.mjs @@ -0,0 +1,91 @@ +#!/usr/bin/env node +/** + * Scoped go vet for staged Go files. + * + * Mirrors run-checks.mjs `go:vet:`: + * For each staged .go file, resolve the owning Go module by walking up to + * the nearest go.mod. One `go vet ./...` per affected module. + * + * Excluded: vendor/, gen/, generated/, node_modules/, docker/. + */ + +import { spawnSync } from "node:child_process"; +import { existsSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; + +const EXCLUDED = [ + /(^|\/)vendor\//, + /(^|\/)gen\//, + /(^|\/)generated\//, + /(^|\/)node_modules\//, + /(^|\/)docker\//, +]; + +function git(args, cwd) { + const result = spawnSync("git", args, { cwd, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 }); + if (result.status !== 0) { + const detail = (result.stderr || "").trim(); + throw new Error(`git ${args.join(" ")} failed: ${detail}`); + } + return result.stdout.split("\n").filter(Boolean); +} + +function findGoModule(file, root) { + let dir = dirname(resolve(root, file)); + const stop = resolve(root); + for (;;) { + if (existsSync(join(dir, "go.mod"))) { + const rel = dir === stop ? "." : dir.slice(stop.length + 1); + return rel; + } + if (dir === stop) return null; + const parent = dirname(dir); + if (parent === dir) return null; + dir = parent; + } +} + +try { + const root = git(["rev-parse", "--show-toplevel"])[0]; + const staged = git(["diff", "--cached", "--name-only", "--diff-filter=ACMR", "--", "*.go"], root).filter( + (f) => !EXCLUDED.some((p) => p.test(f)), + ); + + if (staged.length === 0) { + process.stderr.write("frontal-go-vet: no staged Go files — nothing to check\n"); + process.exit(0); + } + + const dirs = [...new Set(staged.map((f) => findGoModule(f, root)).filter(Boolean))]; + if (dirs.length === 0) { + process.stderr.write("frontal-go-vet: no Go module owns any staged file — nothing to check\n"); + process.exit(0); + } + + // Warm the module cache for each affected directory (same as run-checks.mjs). + for (const dir of dirs) { + spawnSync("go", ["list", "-e", "-deps", "-test", "./..."], { + cwd: join(root, dir), + shell: false, + stdio: "ignore", + }); + } + + for (const dir of dirs) { + process.stderr.write(`frontal-go-vet: go vet ./... (in ${dir})\n`); + const result = spawnSync("go", ["vet", "./..."], { + cwd: join(root, dir), + shell: false, + stdio: "inherit", + }); + if (result.status !== 0) { + process.stderr.write(`\n ✗ frontal-go-vet: failed in ${dir}\n`); + process.exit(result.status ?? 1); + } + } + + process.stderr.write("frontal-go-vet: ok\n"); +} catch (error) { + process.stderr.write(`frontal-go-vet: ${error.message}\n`); + process.exit(1); +} diff --git a/lefthook-remote.yml b/lefthook-remote.yml new file mode 100644 index 0000000..967ba6e --- /dev/null +++ b/lefthook-remote.yml @@ -0,0 +1,91 @@ +# Lefthook bridge for external repositories that use lefthook instead of pre-commit. +# +# Usage in frontal/lefthook.yml: +# remotes: +# - git_url: https://github.com/frontal-labs/pre-commit +# ref: v1.0.0 # pin to a tag, not main +# configs: [lefthook-remote.yml] +# +# All commands are identical to the frontal lefthook.yml gates. +# Tool presence is verified before each command runs; a missing tool fails +# loudly rather than silently passing. + +pre-commit: + parallel: true + commands: + # ---- Biome --------------------------------------------------------------- + # lefthook: biome + # glob: *.{ts,tsx,js,jsx,json} + # exclude: ^packages/design-system/ + # run: pnpm exec biome check --no-errors-on-unmatched {staged_files} + frontal-biome: + glob: "*.{ts,tsx,js,jsx,json}" + exclude: "^packages/design-system/" + run: | + if ! command -v pnpm >/dev/null 2>&1; then + echo "frontal-biome: pnpm not found on PATH" >&2; exit 1 + fi + pnpm exec biome check --no-errors-on-unmatched {staged_files} + + # ---- Ruff (Python lint + format) ------------------------------------------ + # lefthook: python-ruff (ruff check {staged_files}) + # lefthook: python-format (ruff format --check {staged_files}) + frontal-ruff: + glob: "*.py" + exclude: "(^|/)(vendor|gen|generated|node_modules)/" + run: | + if ! command -v ruff >/dev/null 2>&1; then + echo "frontal-ruff: ruff not found on PATH" >&2; exit 1 + fi + ruff check {staged_files} && ruff format --check {staged_files} + + # ---- Rustfmt (staged files only) ------------------------------------------ + # lefthook: rust-fmt + frontal-rustfmt: + glob: "*.rs" + run: | + if ! command -v rustfmt >/dev/null 2>&1; then + echo "frontal-rustfmt: rustfmt not found on PATH" >&2; exit 1 + fi + rust_files=$(git diff --cached --name-only --diff-filter=ACMR -- '*.rs' | grep -vE '(^|/)gen/' || true) + if [ -n "$rust_files" ]; then + printf '%s\n' "$rust_files" | xargs rustfmt --edition 2024 --check + fi + + # ---- Clippy (scoped per crate workspace) ----------------------------------- + # run-checks.mjs: rust:clippy: + frontal-clippy: + glob: "*.rs" + run: | + if ! command -v cargo >/dev/null 2>&1; then + echo "frontal-clippy: cargo not found on PATH" >&2; exit 1 + fi + node hooks/clippy-scoped.mjs + + # ---- Go vet (scoped per module) -------------------------------------------- + # run-checks.mjs: go:vet: + frontal-go-vet: + glob: "*.go" + run: | + if ! command -v go >/dev/null 2>&1; then + echo "frontal-go-vet: go not found on PATH" >&2; exit 1 + fi + node hooks/go-vet-scoped.mjs + + # ---- Buf lint (scoped per proto module) ------------------------------------ + # run-checks.mjs: proto:lint: + frontal-buf-lint: + glob: "*.proto" + run: | + if ! command -v buf >/dev/null 2>&1; then + echo "frontal-buf-lint: buf not found on PATH" >&2; exit 1 + fi + node hooks/buf-lint-scoped.mjs + +commit-msg: + commands: + # Replaces the local `conventional` command in frontal/lefthook.yml. + # Rules are identical to hooks/check-commit-message.mjs. + # {1} is the commit message file path (lefthook passes it as arg 1). + frontal-commit-msg: + run: node hooks/check-commit-message.mjs {1} diff --git a/tests/fixtures/biome/fail/index.ts b/tests/fixtures/biome/fail/index.ts new file mode 100644 index 0000000..a22a000 --- /dev/null +++ b/tests/fixtures/biome/fail/index.ts @@ -0,0 +1 @@ +export const bad = undefined diff --git a/tests/fixtures/biome/fail/package.json b/tests/fixtures/biome/fail/package.json new file mode 100644 index 0000000..883f815 --- /dev/null +++ b/tests/fixtures/biome/fail/package.json @@ -0,0 +1 @@ +{"name":"biome-fail","version":"1.0.0"} diff --git a/tests/fixtures/biome/pass/index.ts b/tests/fixtures/biome/pass/index.ts new file mode 100644 index 0000000..8d9b8a2 --- /dev/null +++ b/tests/fixtures/biome/pass/index.ts @@ -0,0 +1,3 @@ +export function add(a: number, b: number): number { + return a + b; +} diff --git a/tests/fixtures/biome/pass/package.json b/tests/fixtures/biome/pass/package.json new file mode 100644 index 0000000..1a322c0 --- /dev/null +++ b/tests/fixtures/biome/pass/package.json @@ -0,0 +1 @@ +{"name":"biome-pass","version":"1.0.0"} diff --git a/tests/fixtures/buf-lint/fail/api/proto/demo/v1/ping.proto b/tests/fixtures/buf-lint/fail/api/proto/demo/v1/ping.proto new file mode 100644 index 0000000..e5af0dc --- /dev/null +++ b/tests/fixtures/buf-lint/fail/api/proto/demo/v1/ping.proto @@ -0,0 +1,7 @@ +syntax = "proto3"; + +package demo.v1; + +message Ping { + string Text = 1; +} diff --git a/tests/fixtures/buf-lint/fail/buf.yaml b/tests/fixtures/buf-lint/fail/buf.yaml new file mode 100644 index 0000000..a5653ad --- /dev/null +++ b/tests/fixtures/buf-lint/fail/buf.yaml @@ -0,0 +1,6 @@ +version: v2 +modules: + - path: api/proto +lint: + use: + - STANDARD diff --git a/tests/fixtures/buf-lint/pass/api/proto/demo/v1/ping.proto b/tests/fixtures/buf-lint/pass/api/proto/demo/v1/ping.proto new file mode 100644 index 0000000..aca1ccf --- /dev/null +++ b/tests/fixtures/buf-lint/pass/api/proto/demo/v1/ping.proto @@ -0,0 +1,7 @@ +syntax = "proto3"; + +package demo.v1; + +message Ping { + string text = 1; +} diff --git a/tests/fixtures/buf-lint/pass/buf.yaml b/tests/fixtures/buf-lint/pass/buf.yaml new file mode 100644 index 0000000..a5653ad --- /dev/null +++ b/tests/fixtures/buf-lint/pass/buf.yaml @@ -0,0 +1,6 @@ +version: v2 +modules: + - path: api/proto +lint: + use: + - STANDARD diff --git a/tests/fixtures/clippy/fail/crates/demo/Cargo.toml b/tests/fixtures/clippy/fail/crates/demo/Cargo.toml new file mode 100644 index 0000000..c4057d5 --- /dev/null +++ b/tests/fixtures/clippy/fail/crates/demo/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "demo" +version = "0.1.0" +edition = "2021" + +[workspace] +members = ["."] diff --git a/tests/fixtures/clippy/fail/crates/demo/src/main.rs b/tests/fixtures/clippy/fail/crates/demo/src/main.rs new file mode 100644 index 0000000..c34b24e --- /dev/null +++ b/tests/fixtures/clippy/fail/crates/demo/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + let mut x = 1; + x += 1; + println!("{x}"); + let clone = x.clone(); + println!("{clone}"); +} diff --git a/tests/fixtures/clippy/pass/crates/demo/Cargo.toml b/tests/fixtures/clippy/pass/crates/demo/Cargo.toml new file mode 100644 index 0000000..c4057d5 --- /dev/null +++ b/tests/fixtures/clippy/pass/crates/demo/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "demo" +version = "0.1.0" +edition = "2021" + +[workspace] +members = ["."] diff --git a/tests/fixtures/clippy/pass/crates/demo/src/main.rs b/tests/fixtures/clippy/pass/crates/demo/src/main.rs new file mode 100644 index 0000000..7527576 --- /dev/null +++ b/tests/fixtures/clippy/pass/crates/demo/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + println!("hello"); +} diff --git a/tests/fixtures/commit-msg/fail.txt b/tests/fixtures/commit-msg/fail.txt new file mode 100644 index 0000000..f15f00a --- /dev/null +++ b/tests/fixtures/commit-msg/fail.txt @@ -0,0 +1,2 @@ +fix: broken thing +without a scope diff --git a/tests/fixtures/commit-msg/fail/message.txt b/tests/fixtures/commit-msg/fail/message.txt new file mode 100644 index 0000000..f3b1762 --- /dev/null +++ b/tests/fixtures/commit-msg/fail/message.txt @@ -0,0 +1 @@ +update stuff diff --git a/tests/fixtures/commit-msg/pass.txt b/tests/fixtures/commit-msg/pass.txt new file mode 100644 index 0000000..f7bfb22 --- /dev/null +++ b/tests/fixtures/commit-msg/pass.txt @@ -0,0 +1 @@ +feat(auth): add login endpoint diff --git a/tests/fixtures/commit-msg/pass/message.txt b/tests/fixtures/commit-msg/pass/message.txt new file mode 100644 index 0000000..9396c1e --- /dev/null +++ b/tests/fixtures/commit-msg/pass/message.txt @@ -0,0 +1 @@ +feat(api): add user endpoint diff --git a/tests/fixtures/go-vet/fail/service/go.mod b/tests/fixtures/go-vet/fail/service/go.mod new file mode 100644 index 0000000..bdc16aa --- /dev/null +++ b/tests/fixtures/go-vet/fail/service/go.mod @@ -0,0 +1,3 @@ +module example.com/service + +go 1.22 diff --git a/tests/fixtures/go-vet/fail/service/main.go b/tests/fixtures/go-vet/fail/service/main.go new file mode 100644 index 0000000..149acda --- /dev/null +++ b/tests/fixtures/go-vet/fail/service/main.go @@ -0,0 +1,12 @@ +package main + +import ( + "fmt" + "strings" +) + +func main() { + _ = strings.TrimSpace("x") + // vet: fmt.Sprintf format %d has arg "three" of wrong type string + _ = fmt.Sprintf("count: %d", "three") +} diff --git a/tests/fixtures/go-vet/pass/service/go.mod b/tests/fixtures/go-vet/pass/service/go.mod new file mode 100644 index 0000000..bdc16aa --- /dev/null +++ b/tests/fixtures/go-vet/pass/service/go.mod @@ -0,0 +1,3 @@ +module example.com/service + +go 1.22 diff --git a/tests/fixtures/go-vet/pass/service/main.go b/tests/fixtures/go-vet/pass/service/main.go new file mode 100644 index 0000000..38dd16d --- /dev/null +++ b/tests/fixtures/go-vet/pass/service/main.go @@ -0,0 +1,3 @@ +package main + +func main() {} diff --git a/tests/fixtures/ruff/fail-format/main.py b/tests/fixtures/ruff/fail-format/main.py new file mode 100644 index 0000000..2986087 --- /dev/null +++ b/tests/fixtures/ruff/fail-format/main.py @@ -0,0 +1,3 @@ +def f(): + x=1 + return x diff --git a/tests/fixtures/ruff/fail-format/pyproject.toml b/tests/fixtures/ruff/fail-format/pyproject.toml new file mode 100644 index 0000000..b31c51c --- /dev/null +++ b/tests/fixtures/ruff/fail-format/pyproject.toml @@ -0,0 +1,3 @@ +[project] +name = "ruff-fail-format" +version = "1.0.0" diff --git a/tests/fixtures/ruff/fail-lint/main.py b/tests/fixtures/ruff/fail-lint/main.py new file mode 100644 index 0000000..6be3be6 --- /dev/null +++ b/tests/fixtures/ruff/fail-lint/main.py @@ -0,0 +1,5 @@ +import os +import sys + +def f(): + pass diff --git a/tests/fixtures/ruff/fail-lint/pyproject.toml b/tests/fixtures/ruff/fail-lint/pyproject.toml new file mode 100644 index 0000000..469e417 --- /dev/null +++ b/tests/fixtures/ruff/fail-lint/pyproject.toml @@ -0,0 +1,3 @@ +[project] +name = "ruff-fail-lint" +version = "1.0.0" diff --git a/tests/fixtures/ruff/pass/main.py b/tests/fixtures/ruff/pass/main.py new file mode 100644 index 0000000..e1829c3 --- /dev/null +++ b/tests/fixtures/ruff/pass/main.py @@ -0,0 +1,2 @@ +def add(a: int, b: int) -> int: + return a + b diff --git a/tests/fixtures/ruff/pass/pyproject.toml b/tests/fixtures/ruff/pass/pyproject.toml new file mode 100644 index 0000000..9f22995 --- /dev/null +++ b/tests/fixtures/ruff/pass/pyproject.toml @@ -0,0 +1,3 @@ +[project] +name = "ruff-pass" +version = "1.0.0" diff --git a/tests/fixtures/rustfmt/fail/Cargo.toml b/tests/fixtures/rustfmt/fail/Cargo.toml new file mode 100644 index 0000000..367c83c --- /dev/null +++ b/tests/fixtures/rustfmt/fail/Cargo.toml @@ -0,0 +1,2 @@ +[workspace] +members = ["crates/demo"] diff --git a/tests/fixtures/rustfmt/fail/crates/demo/src/main.rs b/tests/fixtures/rustfmt/fail/crates/demo/src/main.rs new file mode 100644 index 0000000..5643865 --- /dev/null +++ b/tests/fixtures/rustfmt/fail/crates/demo/src/main.rs @@ -0,0 +1,3 @@ +fn main() {let greeting = "hello"; println!("{greeting}");} +struct Point{ x : i32 , y:i32 } +impl Point {fn new(x : i32, y: i32)->Self{Self{x,y}}} diff --git a/tests/fixtures/rustfmt/pass/Cargo.toml b/tests/fixtures/rustfmt/pass/Cargo.toml new file mode 100644 index 0000000..367c83c --- /dev/null +++ b/tests/fixtures/rustfmt/pass/Cargo.toml @@ -0,0 +1,2 @@ +[workspace] +members = ["crates/demo"] diff --git a/tests/fixtures/rustfmt/pass/crates/demo/src/main.rs b/tests/fixtures/rustfmt/pass/crates/demo/src/main.rs new file mode 100644 index 0000000..ade564d --- /dev/null +++ b/tests/fixtures/rustfmt/pass/crates/demo/src/main.rs @@ -0,0 +1,15 @@ +fn main() { + let greeting = "hello"; + println!("{greeting}"); +} + +struct Point { + x: i32, + y: i32, +} + +impl Point { + fn new(x: i32, y: i32) -> Self { + Self { x, y } + } +} diff --git a/tests/run-hooks.test.mjs b/tests/run-hooks.test.mjs new file mode 100644 index 0000000..bb324dd --- /dev/null +++ b/tests/run-hooks.test.mjs @@ -0,0 +1,239 @@ +#!/usr/bin/env node +/** + * Hook test runner. + * + * For each fixture case: + * 1. Create a throwaway git repo, copy fixture files in, stage them. + * 2. Copy the hooks/ directory from this repo into the test repo. + * 3. Run the hook's entry command with cwd = test repo. + * 4. Verify the exit code matches expectations. + * + * Usage: + * node tests/run-hooks.test.mjs # all cases + * node tests/run-hooks.test.mjs # single case by id + */ + +import { execFileSync, spawnSync } from "node:child_process"; +import { cpSync, existsSync, mkdtempSync, readdirSync, rmSync, statSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { fileURLToPath } from "node:url"; +import { dirname, join } from "node:path"; + +const TEST_DIR = dirname(fileURLToPath(import.meta.url)); +const HOOKS_DIR = dirname(TEST_DIR); +const FIXTURES = join(TEST_DIR, "fixtures"); + +function listFiles(dir, prefix = "") { + const out = []; + for (const entry of readdirSync(dir).sort()) { + const full = join(dir, entry); + if (statSync(full).isDirectory()) { + out.push(...listFiles(full, prefix ? `${prefix}${entry}/` : `${entry}/`)); + } else { + out.push(prefix ? `${prefix}${entry}` : entry); + } + } + return out; +} + +/** + * Tool-availability gates. A case is SKIPPED (not FAIL) when the tool it + * needs is not installed on this machine. ensure-tool.mjs exits 254 for a + * missing tool, which is indistinguishable from a hook bug without this. + */ +function toolAvailable(cmd, extraArgs = []) { + const result = spawnSync(cmd, extraArgs, { encoding: "utf8" }); + return result.error === undefined && result.status === 0; +} + +const HOOK_TOOLS = { + "frontal-biome": () => toolAvailable("pnpm", ["exec", "biome", "--version"]), + "frontal-ruff": () => toolAvailable("ruff", ["--version"]), + "frontal-rustfmt": () => toolAvailable("rustfmt", ["--version"]), + "frontal-clippy": () => toolAvailable("cargo", ["clippy", "--version"]), + "frontal-go-vet": () => toolAvailable("go", ["version"]), + "frontal-buf-lint": () => toolAvailable("buf", ["--version"]), + "frontal-commit-msg": () => toolAvailable("node", ["--version"]), +}; + +const HOOKS = { + "frontal-biome": { + entry: "sh -c 'node hooks/ensure-tool.mjs pnpm && pnpm exec biome check --no-errors-on-unmatched \"$@\"'", + staged: (files) => files.filter((f) => /\.(ts|tsx|js|jsx|json)$/.test(f) && !f.startsWith("packages/design-system/")), + pass_filenames: true, + }, + "frontal-ruff": { + entry: "sh -c 'node hooks/ensure-tool.mjs ruff && ruff check \"$@\" && ruff format --check \"$@\"'", + staged: (files) => files.filter((f) => /\.py$/.test(f) && !/(^|\/)(vendor|gen|generated|node_modules)\//.test(f)), + pass_filenames: true, + }, + "frontal-rustfmt": { + entry: 'sh -c \'node hooks/ensure-tool.mjs rustfmt && rust_files=$(git diff --cached --name-only --diff-filter=ACMR -- "*.rs" | grep -vE "(^|/)gen/" || true); if [ -n "$rust_files" ]; then printf "%s\\n" "$rust_files" | xargs rustfmt --edition 2024 --check; fi\'', + staged: () => [], + pass_filenames: false, + }, + "frontal-clippy": { + entry: "sh -c 'node hooks/ensure-tool.mjs cargo && node hooks/clippy-scoped.mjs'", + staged: () => [], + pass_filenames: false, + }, + "frontal-go-vet": { + entry: "sh -c 'node hooks/ensure-tool.mjs go && node hooks/go-vet-scoped.mjs'", + staged: () => [], + pass_filenames: false, + }, + "frontal-buf-lint": { + entry: "sh -c 'node hooks/ensure-tool.mjs buf && node hooks/buf-lint-scoped.mjs'", + staged: () => [], + pass_filenames: false, + }, + "frontal-commit-msg": { + entry: "sh -c 'node hooks/check-commit-message.mjs \"$0\"'", + staged: () => [], + pass_filenames: false, + is_commit_msg: true, + }, +}; + +const CASES = [ + // [caseId, fixtureRelPath, hookId, expectedPass] + ["biome-pass", "biome/pass", "frontal-biome", true], + ["biome-fail", "biome/fail", "frontal-biome", false], + ["ruff-pass", "ruff/pass", "frontal-ruff", true], + ["ruff-fail-lint", "ruff/fail-lint", "frontal-ruff", false], + ["ruff-fail-format", "ruff/fail-format", "frontal-ruff", false], + ["rustfmt-pass", "rustfmt/pass", "frontal-rustfmt", true], + ["rustfmt-fail", "rustfmt/fail", "frontal-rustfmt", false], + ["clippy-pass", "clippy/pass", "frontal-clippy", true], + ["clippy-fail", "clippy/fail", "frontal-clippy", false], + ["go-vet-pass", "go-vet/pass", "frontal-go-vet", true], + ["go-vet-fail", "go-vet/fail", "frontal-go-vet", false], + ["buf-lint-pass", "buf-lint/pass", "frontal-buf-lint", true], + ["buf-lint-fail", "buf-lint/fail", "frontal-buf-lint", false], + ["commit-msg-pass", "commit-msg/pass", "frontal-commit-msg", true], + ["commit-msg-fail", "commit-msg/fail", "frontal-commit-msg", false], +]; + +function setupRepo(fixtureDir, repoDir) { + cpSync(fixtureDir, repoDir, { recursive: true }); + execFileSync("git", ["init", "-q", "--initial-branch=main"], { cwd: repoDir }); + execFileSync("git", ["config", "user.email", "test@test.com"], { cwd: repoDir }); + execFileSync("git", ["config", "user.name", "Test"], { cwd: repoDir }); + execFileSync("git", ["add", "-A"], { cwd: repoDir }); + // Copy hooks/ so relative paths in entry commands work + cpSync(join(HOOKS_DIR, "hooks"), join(repoDir, "hooks"), { recursive: true }); +} + +function runHook(hook, repoDir, allFiles, extraArgs = []) { + // Every hook entry is of the form `sh -c ''`. pre-commit + // executes it by appending the file list (or the commit-msg file) as + // positional params after the command string. The first positional + // param lands in `$0`, the rest in `$@`. + // + // To avoid a double shell wrapper (which would consume the positional + // param as its own $0 and drop it), parse out the inner command and + // run `sh -c ` directly. + const m = hook.entry.match(/^sh -c '(.*)'$/s); + if (!m) throw new Error(`unexpected entry format: ${hook.entry}`); + const command = m[1]; + + const files = hook.is_commit_msg + ? extraArgs + : hook.pass_filenames + ? [...hook.staged(allFiles), ...extraArgs] + : []; + + const result = spawnSync("sh", ["-c", command, ...files], { + cwd: repoDir, + shell: false, + encoding: "utf8", + timeout: 60_000, + }); + return { status: result.status, stdout: result.stdout ?? "", stderr: result.stderr ?? "" }; +} + +function main() { + const args = process.argv.slice(2); + const filter = args.find((a) => !a.startsWith("--")); + const debug = args.includes("--debug"); + const cases = filter ? CASES.filter(([id]) => id === filter) : CASES; + + let passed = 0; + let failed = 0; + let skipped = 0; + const results = []; + + for (const [caseId, fixturePath, hookId, expectPass] of cases) { + const fixtureDir = join(FIXTURES, fixturePath); + if (!existsSync(fixtureDir)) { + results.push({ caseId, status: "SKIP", reason: `fixture not found: ${fixturePath}` }); + skipped++; + continue; + } + + const hook = HOOKS[hookId]; + + // Skip when the underlying tool is not installed on this machine. + if (!HOOK_TOOLS[hookId]()) { + results.push({ caseId, hookId, status: "SKIP", reason: "tool not installed" }); + skipped++; + continue; + } + + const repoDir = mkdtempSync(join(tmpdir(), `hook-test-${caseId}-`)); + + try { + setupRepo(fixtureDir, repoDir); + const allFiles = listFiles(fixtureDir); + + const extraArgs = hook.is_commit_msg ? [join(repoDir, "message.txt")] : []; + const result = runHook(hook, repoDir, allFiles, extraArgs); + + const actualPass = result.status === 0; + const ok = actualPass === expectPass; + + if (debug) { + process.stderr.write(`\n===== ${caseId} (exit ${result.status}, expected ${expectPass ? "pass" : "fail"}) =====\n`); + process.stderr.write(`--- stdout ---\n${result.stdout}\n--- stderr ---\n${result.stderr}\n`); + } + + results.push({ + caseId, + hookId, + expectPass, + actualPass, + status: ok ? "PASS" : "FAIL", + exitCode: result.status, + output: (result.stderr || result.stdout).trim().slice(0, 300), + }); + + if (ok) passed++; + else failed++; + } catch (error) { + results.push({ caseId, hookId, status: "ERROR", reason: error.message }); + failed++; + } finally { + if (!debug) rmSync(repoDir, { recursive: true, force: true }); + else process.stderr.write(`\n[debug] repo kept at ${repoDir}\n`); + } + } + + // Report + const width = Math.max(...results.map((r) => r.caseId.length), 20); + for (const r of results) { + const mark = r.status === "PASS" ? "ok " : r.status === "SKIP" ? "SKIP" : "FAIL"; + const detail = + r.status === "SKIP" + ? r.reason + : r.status === "ERROR" + ? r.reason + : `${r.hookId} exit=${r.exitCode} expected_pass=${r.expectPass}`; + console.log(` ${mark} ${r.caseId.padEnd(width)} ${detail}`); + } + + const total = results.length; + console.log(`\n${passed}/${total} cases passed, ${failed} failed, ${skipped} skipped\n`); + process.exit(failed > 0 ? 1 : 0); +} + +main(); From 00357ac000de5a3f47816dab941a1d0f47804a23 Mon Sep 17 00:00:00 2001 From: Gabriel Date: Mon, 16 Nov 2026 14:59:11 +0000 Subject: [PATCH 2/8] =?UTF-8?q?fix(tests):=20correct=20HOOKS=5FDIR=20path?= =?UTF-8?q?=20after=20test=E2=86=92tests=20rename?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit dirname(TEST_DIR) pointed one level too high (repo parent), so setupRepo would fail to copy hooks/ into the throwaway test repo. Renamed to REPO_ROOT and fixed the cpSync reference. --- tests/run-hooks.test.mjs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/run-hooks.test.mjs b/tests/run-hooks.test.mjs index bb324dd..b9e20c1 100644 --- a/tests/run-hooks.test.mjs +++ b/tests/run-hooks.test.mjs @@ -20,7 +20,7 @@ import { fileURLToPath } from "node:url"; import { dirname, join } from "node:path"; const TEST_DIR = dirname(fileURLToPath(import.meta.url)); -const HOOKS_DIR = dirname(TEST_DIR); +const REPO_ROOT = dirname(TEST_DIR); const FIXTURES = join(TEST_DIR, "fixtures"); function listFiles(dir, prefix = "") { @@ -121,7 +121,7 @@ function setupRepo(fixtureDir, repoDir) { execFileSync("git", ["config", "user.name", "Test"], { cwd: repoDir }); execFileSync("git", ["add", "-A"], { cwd: repoDir }); // Copy hooks/ so relative paths in entry commands work - cpSync(join(HOOKS_DIR, "hooks"), join(repoDir, "hooks"), { recursive: true }); + cpSync(join(REPO_ROOT, "hooks"), join(repoDir, "hooks"), { recursive: true }); } function runHook(hook, repoDir, allFiles, extraArgs = []) { From ba3ca29fae4d01f9d7660cb65e073dcc672764fd Mon Sep 17 00:00:00 2001 From: Gabriel Date: Mon, 16 Nov 2026 15:13:23 +0000 Subject: [PATCH 3/8] chore: remove stale commit-msg fixture files The test runner uses commit-msg/{pass,fail}/message.txt. The top-level pass.txt and fail.txt were never referenced. --- tests/fixtures/commit-msg/fail.txt | 2 -- tests/fixtures/commit-msg/pass.txt | 1 - 2 files changed, 3 deletions(-) delete mode 100644 tests/fixtures/commit-msg/fail.txt delete mode 100644 tests/fixtures/commit-msg/pass.txt diff --git a/tests/fixtures/commit-msg/fail.txt b/tests/fixtures/commit-msg/fail.txt deleted file mode 100644 index f15f00a..0000000 --- a/tests/fixtures/commit-msg/fail.txt +++ /dev/null @@ -1,2 +0,0 @@ -fix: broken thing -without a scope diff --git a/tests/fixtures/commit-msg/pass.txt b/tests/fixtures/commit-msg/pass.txt deleted file mode 100644 index f7bfb22..0000000 --- a/tests/fixtures/commit-msg/pass.txt +++ /dev/null @@ -1 +0,0 @@ -feat(auth): add login endpoint From 5800938bece33e7703677fcff91f5772402f5471 Mon Sep 17 00:00:00 2001 From: Gabriel Date: Mon, 16 Nov 2026 15:25:06 +0000 Subject: [PATCH 4/8] chore: add package.json, CI workflow, and .gitignore - package.json: test script (npm test), Node >=22 engine, repo metadata - .github/workflows/ci.yml: run hook tests on PRs and main pushes; installs ruff, rustfmt, clippy, and buf; biome cases are SKIPPED - .gitignore: node_modules/ --- .github/workflows/ci.yml | 42 ++++++++++++++++++++++++++++++++++++++++ .gitignore | 1 + package.json | 18 +++++++++++++++++ 3 files changed, 61 insertions(+) create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100644 package.json diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..209c486 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,42 @@ +name: CI + +on: + pull_request: + push: + branches: + - main + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: 22 + + # Install the tools the hooks need. The hooks fail loudly when a tool + # is missing (ensure-tool.mjs), so the test suite only runs the cases + # whose tools are actually installed. + - name: Install ruff + run: pipx install ruff + + - name: Install rustfmt + clippy + run: rustup component add rustfmt clippy + + - name: Install buf + run: | + curl -sSL https://buf.build/install.sh | BUN_INSTALL="$HOME/.bun" sh + echo "$HOME/.bun/bin" >> "$GITHUB_PATH" + buf --version + + # go and cargo ship with the ubuntu-latest runner image. + # biome is not installed: those 2 test cases are SKIPPED, not failed. + + - name: Run hook tests + run: npm test diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c2658d7 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +node_modules/ diff --git a/package.json b/package.json new file mode 100644 index 0000000..260eb84 --- /dev/null +++ b/package.json @@ -0,0 +1,18 @@ +{ + "name": "frontal-pre-commit", + "version": "1.0.0", + "description": "Frontal's git-hook gates, published as pre-commit hooks and a lefthook remote", + "type": "module", + "license": "MIT", + "private": true, + "scripts": { + "test": "node tests/run-hooks.test.mjs" + }, + "engines": { + "node": ">=22" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/frontal-labs/pre-commit.git" + } +} From 7d69843fb6b101377306e2d2cb33669efb62c4c9 Mon Sep 17 00:00:00 2001 From: Gabriel Date: Mon, 16 Nov 2026 17:08:19 +0000 Subject: [PATCH 5/8] chore: wire biome via ultracite preset and make hooks biome-clean Adopt the ultracite preset (extends "ultracite/biome/core") as the repo's formatter/linter for the .mjs hooks and test runner: - Add biome.jsonc (JSONC so the required `**` catch-all in files.includes can carry an explanatory comment); `!tests/fixtures` keeps the intentionally non-compliant biome-fail fixture out of the repo's own `biome check`. - Add `check` / `format` npm scripts; pin @biomejs/biome + ultracite as devDependencies and commit package-lock.json. - Switch the frontal-biome hook entry from `pnpm exec biome` to plain `biome` (ensure-tool still gates it). - Rewrite the three walk-up loops (clippy/go-vet/buf-lint) from `while (true)` to an explicit "under-or-equal-to-root" condition so ultracite's noUnnecessaryConditions is satisfied; the previous rewrite dropped the repo root itself, which broke root-level buf.yaml discovery. - Fix check-commit-message HEADER regex: the `v` flag rejected the `[^)]` class, switch to `u`. - Test runner: hoist regexes to top-level consts, destructure the sh -c match, flatten nested ternaries, drop ++/--; prepend node_modules/.bin to PATH and symlink node_modules into throwaway repos so the local biome is found; pass a $0 placeholder for file-based hooks so `"$@"` sees every staged file (commit-msg keeps its single param in $0). All 15 hook cases now pass locally (biome no longer skipped). --- .github/workflows/release.yml | 2 +- .pre-commit-config.yaml | 16 +- .pre-commit-hooks.yaml | 21 +- biome.jsonc | 7 + hooks/buf-lint-scoped.mjs | 170 +-- hooks/check-commit-message.mjs | 156 +-- hooks/clippy-scoped.mjs | 176 +-- hooks/ensure-tool.mjs | 60 +- hooks/go-vet-scoped.mjs | 139 ++- package-lock.json | 1406 ++++++++++++++++++++++++ package.json | 18 +- tests/fixtures/biome/fail/index.ts | 9 +- tests/fixtures/biome/fail/package.json | 5 +- tests/fixtures/biome/pass/package.json | 5 +- tests/run-hooks.test.mjs | 462 ++++---- 15 files changed, 2145 insertions(+), 507 deletions(-) create mode 100644 biome.jsonc create mode 100644 package-lock.json diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4eb5970..05d9ee4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -3,7 +3,7 @@ name: Release on: push: tags: - - 'v*' + - "v*" permissions: contents: write diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index c0eb0c7..a7bee18 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -3,7 +3,7 @@ # When you contribute to this repo, pre-commit will run the hooks against # your staged changes — the same hooks that external consumers use. fail_fast: false -default_install_hook_types: [pre-commit, commit-msg] +default_install_hook_types: [ pre-commit, commit-msg ] repos: - repo: local @@ -14,7 +14,7 @@ repos: language: system files: \.(ts|tsx|js|jsx|json)$ exclude: "^packages/design-system/" - stages: [pre-commit] + stages: [ pre-commit ] - id: frontal-ruff name: frontal ruff check + format @@ -22,7 +22,7 @@ repos: language: system files: \.py$ exclude: "(^|/)(vendor|gen|generated|node_modules)/" - stages: [pre-commit] + stages: [ pre-commit ] - id: frontal-rustfmt name: frontal rustfmt (staged) @@ -30,7 +30,7 @@ repos: language: system files: \.rs$ pass_filenames: false - stages: [pre-commit] + stages: [ pre-commit ] - id: frontal-clippy name: frontal cargo clippy (scoped) @@ -38,7 +38,7 @@ repos: language: system files: \.rs$ pass_filenames: false - stages: [pre-commit] + stages: [ pre-commit ] - id: frontal-go-vet name: frontal go vet (scoped) @@ -46,7 +46,7 @@ repos: language: system files: \.go$ pass_filenames: false - stages: [pre-commit] + stages: [ pre-commit ] - id: frontal-buf-lint name: frontal buf lint (scoped) @@ -54,7 +54,7 @@ repos: language: system files: \.proto$ pass_filenames: false - stages: [pre-commit] + stages: [ pre-commit ] - id: frontal-commit-msg name: frontal commit-msg (Conventional Commits) @@ -64,4 +64,4 @@ repos: language: system pass_filenames: false always_run: true - stages: [commit-msg] + stages: [ commit-msg ] diff --git a/.pre-commit-hooks.yaml b/.pre-commit-hooks.yaml index 218bffc..144811b 100644 --- a/.pre-commit-hooks.yaml +++ b/.pre-commit-hooks.yaml @@ -12,16 +12,19 @@ # Mirrors lefthook `biome`: # glob: *.{ts,tsx,js,jsx,json} # exclude: ^packages/design-system/ -# run: pnpm exec biome check --no-errors-on-unmatched {staged_files} +# run: biome check --no-errors-on-unmatched {staged_files} # Check-only (no --write); pre-commit passes staged files as arguments. +# The ultracite preset lives in this repo's biome.json (consumers extend it +# the same way: { "extends": ["ultracite/biome/core"] } + the two npm +# devDependencies @biomejs/biome and ultracite). - id: frontal-biome name: frontal biome check description: Biome check (check-only) on staged JS/TS/JSON files - entry: sh -c 'node hooks/ensure-tool.mjs pnpm && pnpm exec biome check --no-errors-on-unmatched "$@"' + entry: sh -c 'node hooks/ensure-tool.mjs biome && biome check --no-errors-on-unmatched "$@"' language: system files: \.(ts|tsx|js|jsx|json)$ exclude: "^packages/design-system/" - stages: [pre-commit] + stages: [ pre-commit ] # ---- Ruff (Python lint + format) ------------------------------------------ # Mirrors lefthook `python-ruff` and `python-format`: @@ -38,7 +41,7 @@ language: system files: \.py$ exclude: "(^|/)(vendor|gen|generated|node_modules)/" - stages: [pre-commit] + stages: [ pre-commit ] # ---- Rustfmt (staged files only) ------------------------------------------ # Mirrors lefthook `rust-fmt`: @@ -55,7 +58,7 @@ language: system files: \.rs$ pass_filenames: false - stages: [pre-commit] + stages: [ pre-commit ] # ---- Clippy (scoped per crate workspace) ----------------------------------- # Mirrors run-checks.mjs `rust:clippy:`: @@ -72,7 +75,7 @@ language: system files: \.rs$ pass_filenames: false - stages: [pre-commit] + stages: [ pre-commit ] # ---- Go vet (scoped per module) -------------------------------------------- # Mirrors run-checks.mjs `go:vet:`: @@ -87,7 +90,7 @@ language: system files: \.go$ pass_filenames: false - stages: [pre-commit] + stages: [ pre-commit ] # ---- Buf lint (scoped per proto module) ------------------------------------ # Mirrors run-checks.mjs `proto:lint:`: @@ -102,7 +105,7 @@ language: system files: \.proto$ pass_filenames: false - stages: [pre-commit] + stages: [ pre-commit ] # ---- Commit message (Conventional Commits) --------------------------------- # Replaces commitlint. Rules are identical to @@ -118,4 +121,4 @@ pass_filenames: false always_run: true language: system - stages: [commit-msg] + stages: [ commit-msg ] diff --git a/biome.jsonc b/biome.jsonc new file mode 100644 index 0000000..6be362c --- /dev/null +++ b/biome.jsonc @@ -0,0 +1,7 @@ +{ + "extends": ["ultracite/biome/core"], + "files": { + // biome-ignore lint/suspicious/noBiomeFirstException: catch-all is required; without it, an `includes` list matches nothing + "includes": ["**", "!tests/fixtures"] + } +} diff --git a/hooks/buf-lint-scoped.mjs b/hooks/buf-lint-scoped.mjs index 0202f22..e7b00d5 100644 --- a/hooks/buf-lint-scoped.mjs +++ b/hooks/buf-lint-scoped.mjs @@ -14,22 +14,29 @@ import { spawnSync } from "node:child_process"; import { existsSync, readFileSync } from "node:fs"; -import { dirname, join, resolve } from "node:path"; +import { dirname, join, resolve, sep } from "node:path"; const EXCLUDED = [ - /(^|\/)gen\//, - /(^|\/)generated\//, - /(^|\/)node_modules\//, - /(^|\/)vendor\//, + /(?^|\/)gen\//u, + /(?^|\/)generated\//u, + /(?^|\/)node_modules\//u, + /(?^|\/)vendor\//u, ]; +const BUF_PATH_RE = /^\s{2}- path:\s*(?\S+)\s*$/u; +const TRAILING_SLASH_RE = /\/+$/u; + function git(args, cwd) { - const result = spawnSync("git", args, { cwd, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 }); - if (result.status !== 0) { - const detail = (result.stderr || "").trim(); - throw new Error(`git ${args.join(" ")} failed: ${detail}`); - } - return result.stdout.split("\n").filter(Boolean); + const result = spawnSync("git", args, { + cwd, + encoding: "utf8", + maxBuffer: 64 * 1024 * 1024, + }); + if (result.status !== 0) { + const detail = (result.stderr || "").trim(); + throw new Error(`git ${args.join(" ")} failed: ${detail}`); + } + return result.stdout.split("\n").filter(Boolean); } /** @@ -37,73 +44,102 @@ function git(args, cwd) { * Parsed the same way as run-checks.mjs readWorkspaceModules(). */ function readWorkspaceModules(root) { - const paths = new Set(); - const manifest = join(root, "buf.yaml"); - if (!existsSync(manifest)) return paths; - for (const line of readFileSync(manifest, "utf8").split("\n")) { - // Stop at the top-level deps:/lint: keys; - path: only appears under modules: - const match = line.match(/^\s{2}- path:\s*(\S+)\s*$/); - if (match) paths.add(match[1].replace(/\/+$/, "")); - } - return paths; + const paths = new Set(); + const manifest = join(root, "buf.yaml"); + if (!existsSync(manifest)) { + return paths; + } + for (const line of readFileSync(manifest, "utf8").split("\n")) { + // Stop at the top-level deps:/lint: keys; - path: only appears under modules: + const match = line.match(BUF_PATH_RE); + if (match) { + paths.add(match.groups.path.replace(TRAILING_SLASH_RE, "")); + } + } + return paths; } +/** + * Walk up from `file` to the nearest ancestor directory containing a + * buf.yaml, stopping at (and including) `root`. + */ function findProtoModule(file, root) { - let dir = dirname(resolve(root, file)); - const stop = resolve(root); - for (;;) { - if (existsSync(join(dir, "buf.yaml"))) { - const rel = dir === stop ? "." : dir.slice(stop.length + 1); - return rel; - } - if (dir === stop) return null; - const parent = dirname(dir); - if (parent === dir) return null; - dir = parent; - } + const rootResolved = resolve(root); + let dir = dirname(resolve(rootResolved, file)); + // Walk up to (and including) the repo root; stop once dir rises above it. + while (dir === rootResolved || dir.startsWith(rootResolved + sep)) { + if (existsSync(join(dir, "buf.yaml"))) { + const rel = + dir === rootResolved ? "." : dir.slice(rootResolved.length + 1); + return rel; + } + const parent = dirname(dir); + if (parent === dir) { + return null; + } + dir = parent; + } + return null; } try { - const root = git(["rev-parse", "--show-toplevel"])[0]; - const staged = git(["diff", "--cached", "--name-only", "--diff-filter=ACMR", "--", "*.proto"], root).filter( - (f) => !EXCLUDED.some((p) => p.test(f)), - ); + const [root] = git(["rev-parse", "--show-toplevel"]); + const staged = git( + ["diff", "--cached", "--name-only", "--diff-filter=ACMR", "--", "*.proto"], + root + ).filter((f) => !EXCLUDED.some((p) => p.test(f))); - if (staged.length === 0) { - process.stderr.write("frontal-buf-lint: no staged proto files — nothing to check\n"); - process.exit(0); - } + if (staged.length === 0) { + process.stderr.write( + "frontal-buf-lint: no staged proto files — nothing to check\n" + ); + process.exit(0); + } - const dirs = [...new Set(staged.map((f) => findProtoModule(f, root)).filter(Boolean))]; - if (dirs.length === 0) { - process.stderr.write("frontal-buf-lint: no proto module owns any staged file — nothing to check\n"); - process.exit(0); - } + const dirs = [ + ...new Set(staged.map((f) => findProtoModule(f, root)).filter(Boolean)), + ]; + if (dirs.length === 0) { + process.stderr.write( + "frontal-buf-lint: no proto module owns any staged file — nothing to check\n" + ); + process.exit(0); + } - const workspaceModules = readWorkspaceModules(root); - const inWorkspace = dirs.filter((dir) => workspaceModules.has(dir)); - const standalone = dirs.filter((dir) => !workspaceModules.has(dir)); + const workspaceModules = readWorkspaceModules(root); + const inWorkspace = dirs.filter((dir) => workspaceModules.has(dir)); + const standalone = dirs.filter((dir) => !workspaceModules.has(dir)); - if (inWorkspace.length > 0) { - process.stderr.write("frontal-buf-lint: buf lint (repo root, workspace modules)\n"); - const result = spawnSync("buf", ["lint"], { cwd: root, shell: false, stdio: "inherit" }); - if (result.status !== 0) { - process.stderr.write("\n ✗ frontal-buf-lint: failed (workspace)\n"); - process.exit(result.status ?? 1); - } - } + if (inWorkspace.length > 0) { + process.stderr.write( + "frontal-buf-lint: buf lint (repo root, workspace modules)\n" + ); + const result = spawnSync("buf", ["lint"], { + cwd: root, + shell: false, + stdio: "inherit", + }); + if (result.status !== 0) { + process.stderr.write("\n ✗ frontal-buf-lint: failed (workspace)\n"); + process.exit(result.status ?? 1); + } + } - for (const dir of standalone) { - process.stderr.write(`frontal-buf-lint: buf lint (in ${dir})\n`); - const result = spawnSync("buf", ["lint"], { cwd: join(root, dir), shell: false, stdio: "inherit" }); - if (result.status !== 0) { - process.stderr.write(`\n ✗ frontal-buf-lint: failed in ${dir}\n`); - process.exit(result.status ?? 1); - } - } + for (const dir of standalone) { + process.stderr.write(`frontal-buf-lint: buf lint (in ${dir})\n`); + const result = spawnSync("buf", ["lint"], { + cwd: join(root, dir), + shell: false, + stdio: "inherit", + }); + if (result.status !== 0) { + process.stderr.write(`\n ✗ frontal-buf-lint: failed in ${dir}\n`); + process.exit(result.status ?? 1); + } + } - process.stderr.write("frontal-buf-lint: ok\n"); + process.stderr.write("frontal-buf-lint: ok\n"); } catch (error) { - process.stderr.write(`frontal-buf-lint: ${error.message}\n`); - process.exit(1); + process.stderr.write(`frontal-buf-lint: ${error.message}\n`); + process.exit(1); } diff --git a/hooks/check-commit-message.mjs b/hooks/check-commit-message.mjs index 7f8dc48..bd0c28e 100644 --- a/hooks/check-commit-message.mjs +++ b/hooks/check-commit-message.mjs @@ -13,65 +13,72 @@ import { resolve } from "node:path"; import { pathToFileURL } from "node:url"; const TYPES = [ - "feat", - "fix", - "docs", - "style", - "refactor", - "perf", - "test", - "build", - "ci", - "chore", - "revert", + "feat", + "fix", + "docs", + "style", + "refactor", + "perf", + "test", + "build", + "ci", + "chore", + "revert", ]; -const HEADER = new RegExp(`^(${TYPES.join("|")})(\\([^)]+\\))?!?: .+`); +const HEADER = new RegExp( + `^(${TYPES.join("|")})(\\((?[^)]+)\\))?!?: .+`, + "u" +); /** Messages git creates itself, which must not be rejected. */ const EXEMPT = [ - /^Merge /, - /^Revert "/, - /^fixup! /, - /^squash! /, - // An in-progress rebase writes these; the final message is validated separately. - /^amend! /, + /^Merge /u, + /^Revert "/u, + /^fixup! /u, + /^squash! /u, + // An in-progress rebase writes these; the final message is validated separately. + /^amend! /u, ]; export function validateMessage(raw) { - // Strip comments and the scissors section git appends in verbose mode. - const body = raw - .split("\n") - .filter((line) => !line.startsWith("#")) - .join("\n"); + // Strip comments and the scissors section git appends in verbose mode. + const body = raw + .split("\n") + .filter((line) => !line.startsWith("#")) + .join("\n"); - const subject = body.split("\n").find((line) => line.trim().length > 0); + const subject = body.split("\n").find((line) => line.trim().length > 0); - if (!subject) return { ok: false, error: "commit message is empty" }; - if (EXEMPT.some((pattern) => pattern.test(subject))) return { ok: true }; + if (!subject) { + return { ok: false, error: "commit message is empty" }; + } + if (EXEMPT.some((pattern) => pattern.test(subject))) { + return { ok: true }; + } - if (!HEADER.test(subject)) { - return { - ok: false, - error: `not a Conventional Commit: "${subject}"`, - hint: [ - "expected (): ", - ` types: ${TYPES.join(", ")}`, - " example: fix(billing): reject subscriptions without a connection row", - ].join("\n"), - }; - } + if (!HEADER.test(subject)) { + return { + ok: false, + error: `not a Conventional Commit: "${subject}"`, + hint: [ + "expected (): ", + ` types: ${TYPES.join(", ")}`, + " example: fix(billing): reject subscriptions without a connection row", + ].join("\n"), + }; + } - // A subject that runs long is truncated in most git UIs. - if (subject.length > 100) { - return { - ok: false, - error: `subject is ${subject.length} characters; keep it under 100`, - hint: "move detail into the commit body", - }; - } + // A subject that runs long is truncated in most git UIs. + if (subject.length > 100) { + return { + ok: false, + error: `subject is ${subject.length} characters; keep it under 100`, + hint: "move detail into the commit body", + }; + } - return { ok: true }; + return { ok: true }; } /** @@ -83,34 +90,41 @@ export function validateMessage(raw) { * shell is invoked bare (e.g. from lefthook or an editor integration), * `argv[2]` may be `sh`/`bash`/empty — in that case fall back to stdin. */ -function resolveMessagePath(argv) { - const candidate = argv[2]; - if (candidate && candidate !== "sh" && candidate !== "bash" && !candidate.endsWith("/sh") && !candidate.endsWith("/bash")) { - return candidate; - } - return null; +function resolveMessagePath([, , candidate]) { + if ( + candidate && + candidate !== "sh" && + candidate !== "bash" && + !candidate.endsWith("/sh") && + !candidate.endsWith("/bash") + ) { + return candidate; + } + return null; } function main() { - const path = resolveMessagePath(process.argv); - const raw = path ? readFileSync(path, "utf8") : readFileSync(0, "utf8"); - const result = validateMessage(raw); - if (!result.ok) { - process.stderr.write(`\n ✗ ${result.error}\n`); - if (result.hint) { - process.stderr.write( - `${result.hint - .split("\n") - .map((l) => ` ${l}`) - .join("\n")}\n`, - ); - } - process.stderr.write("\n"); - process.exit(1); - } + const path = resolveMessagePath(process.argv); + const raw = path ? readFileSync(path, "utf8") : readFileSync(0, "utf8"); + const result = validateMessage(raw); + if (!result.ok) { + process.stderr.write(`\n ✗ ${result.error}\n`); + if (result.hint) { + process.stderr.write( + `${result.hint + .split("\n") + .map((l) => ` ${l}`) + .join("\n")}\n` + ); + } + process.stderr.write("\n"); + process.exit(1); + } } const isMain = - process.argv[1] && - import.meta.url === pathToFileURL(resolve(process.argv[1])).href; -if (isMain) main(); + process.argv[1] && + import.meta.url === pathToFileURL(resolve(process.argv[1])).href; +if (isMain) { + main(); +} diff --git a/hooks/clippy-scoped.mjs b/hooks/clippy-scoped.mjs index cd0d84e..1e58087 100644 --- a/hooks/clippy-scoped.mjs +++ b/hooks/clippy-scoped.mjs @@ -19,89 +19,129 @@ import { spawnSync } from "node:child_process"; import { existsSync, readFileSync } from "node:fs"; import { dirname, join, relative, resolve, sep } from "node:path"; -const EXCLUDED = [/(^|\/)gen\//, /(^|\/)generated\//, /(^|\/)vendor\//, /(^|\/)node_modules\//]; +const EXCLUDED = [ + /(?^|\/)gen\//u, + /(?^|\/)generated\//u, + /(?^|\/)vendor\//u, + /(?^|\/)node_modules\//u, +]; + +const WORKSPACE_SECTION_RE = /^\s*\[workspace\]/mu; +const CRATE_NAME_RE = + /^\s*\[package\][\s\S]*?^\s*name\s*=\s*"(?[^"]+)"/mu; function git(args, cwd) { - const result = spawnSync("git", args, { cwd, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 }); - if (result.status !== 0) { - const detail = (result.stderr || "").trim(); - throw new Error(`git ${args.join(" ")} failed: ${detail}`); - } - return result.stdout.split("\n").filter(Boolean); + const result = spawnSync("git", args, { + cwd, + encoding: "utf8", + maxBuffer: 64 * 1024 * 1024, + }); + if (result.status !== 0) { + const detail = (result.stderr || "").trim(); + throw new Error(`git ${args.join(" ")} failed: ${detail}`); + } + return result.stdout.split("\n").filter(Boolean); } +/** + * Walk up from `file` to the nearest ancestor Cargo.toml that declares a + * [workspace] section, stopping at (and including) `root`. + */ function findRustWorkspace(file, root) { - let dir = dirname(resolve(root, file)); - const stop = resolve(root); - for (;;) { - const manifest = join(dir, "Cargo.toml"); - if (existsSync(manifest)) { - const text = readFileSync(manifest, "utf8"); - if (/^\s*\[workspace\]/m.test(text)) { - const rel = relative(stop, dir); - return rel === "" ? "." : rel.split(sep).join("/"); - } - } - if (dir === stop) return null; - const parent = dirname(dir); - if (parent === dir) return null; - dir = parent; - } + const rootResolved = resolve(root); + let dir = dirname(resolve(rootResolved, file)); + // Walk up to (and including) the repo root; stop once dir rises above it. + while (dir === rootResolved || dir.startsWith(rootResolved + sep)) { + const manifest = join(dir, "Cargo.toml"); + if (existsSync(manifest)) { + const text = readFileSync(manifest, "utf8"); + if (WORKSPACE_SECTION_RE.test(text)) { + const rel = relative(rootResolved, dir); + return rel === "" ? "." : rel.split(sep).join("/"); + } + } + const parent = dirname(dir); + if (parent === dir) { + return null; + } + dir = parent; + } + return null; } function readCrateName(crateDir, root) { - const manifest = join(resolve(root, crateDir), "Cargo.toml"); - if (!existsSync(manifest)) return null; - const match = readFileSync(manifest, "utf8").match(/^\s*\[package\][\s\S]*?^\s*name\s*=\s*"([^"]+)"/m); - return match ? match[1] : null; + const manifest = join(resolve(root, crateDir), "Cargo.toml"); + if (!existsSync(manifest)) { + return null; + } + const match = readFileSync(manifest, "utf8").match(CRATE_NAME_RE); + return match ? match.groups.name : null; } try { - const root = git(["rev-parse", "--show-toplevel"])[0]; - const staged = git(["diff", "--cached", "--name-only", "--diff-filter=ACMR", "--", "*.rs"], root).filter( - (f) => !EXCLUDED.some((p) => p.test(f)), - ); + const [root] = git(["rev-parse", "--show-toplevel"]); + const staged = git( + ["diff", "--cached", "--name-only", "--diff-filter=ACMR", "--", "*.rs"], + root + ).filter((f) => !EXCLUDED.some((p) => p.test(f))); - if (staged.length === 0) { - process.stderr.write("frontal-clippy: no staged Rust files — nothing to check\n"); - process.exit(0); - } + if (staged.length === 0) { + process.stderr.write( + "frontal-clippy: no staged Rust files — nothing to check\n" + ); + process.exit(0); + } - // Map workspace → [crate names] - const clippyCrates = new Map(); - for (const file of staged) { - const workspace = findRustWorkspace(file, root); - if (!workspace) continue; // no workspace manifest; Bazel owns this - // The workspace dir holds the manifest that addresses this crate with - // `-p`. In the self-workspace layout (a crate declaring its own - // [workspace] members = ["."]) that manifest also declares the [package]. - const name = readCrateName(workspace, root); - if (!name) continue; // workspace root with no [package]; not addressable with -p - clippyCrates.set(workspace, [...(clippyCrates.get(workspace) ?? []), name]); - } + // Map workspace → [crate names] + const clippyCrates = new Map(); + for (const file of staged) { + const workspace = findRustWorkspace(file, root); + if (!workspace) { + continue; // no workspace manifest; Bazel owns this + } + // The workspace dir holds the manifest that addresses this crate with + // `-p`. In the self-workspace layout (a crate declaring its own + // [workspace] members = ["."]) that manifest also declares the [package]. + const name = readCrateName(workspace, root); + if (!name) { + continue; // workspace root with no [package]; not addressable with -p + } + clippyCrates.set(workspace, [...(clippyCrates.get(workspace) ?? []), name]); + } - if (clippyCrates.size === 0) { - process.stderr.write("frontal-clippy: no addressable crates in staged files — nothing to check\n"); - process.exit(0); - } + if (clippyCrates.size === 0) { + process.stderr.write( + "frontal-clippy: no addressable crates in staged files — nothing to check\n" + ); + process.exit(0); + } - for (const [workspace, names] of clippyCrates) { - const uniqueNames = [...new Set(names)]; - const args = ["clippy", ...uniqueNames.flatMap((n) => ["-p", n]), "--all-targets", "--", "-D", "warnings"]; - process.stderr.write(`frontal-clippy: cargo ${args.join(" ")} (in ${workspace})\n`); - const result = spawnSync("cargo", args, { - cwd: join(root, workspace), - shell: false, - stdio: "inherit", - }); - if (result.status !== 0) { - process.stderr.write(`\n ✗ frontal-clippy: failed in ${workspace}\n`); - process.exit(result.status ?? 1); - } - } + for (const [workspace, names] of clippyCrates) { + const uniqueNames = [...new Set(names)]; + const args = [ + "clippy", + ...uniqueNames.flatMap((n) => ["-p", n]), + "--all-targets", + "--", + "-D", + "warnings", + ]; + process.stderr.write( + `frontal-clippy: cargo ${args.join(" ")} (in ${workspace})\n` + ); + const result = spawnSync("cargo", args, { + cwd: join(root, workspace), + shell: false, + stdio: "inherit", + }); + if (result.status !== 0) { + process.stderr.write(`\n ✗ frontal-clippy: failed in ${workspace}\n`); + process.exit(result.status ?? 1); + } + } - process.stderr.write("frontal-clippy: ok\n"); + process.stderr.write("frontal-clippy: ok\n"); } catch (error) { - process.stderr.write(`frontal-clippy: ${error.message}\n`); - process.exit(1); + process.stderr.write(`frontal-clippy: ${error.message}\n`); + process.exit(1); } diff --git a/hooks/ensure-tool.mjs b/hooks/ensure-tool.mjs index 5365daf..01c581d 100644 --- a/hooks/ensure-tool.mjs +++ b/hooks/ensure-tool.mjs @@ -16,39 +16,43 @@ import { join } from "node:path"; const tools = process.argv.slice(2); if (tools.length === 0) { - process.stderr.write("ensure-tool: expected at least one tool name\n"); - process.exit(2); + process.stderr.write("ensure-tool: expected at least one tool name\n"); + process.exit(2); } const missing = []; for (const bin of tools) { - if (bin.includes("/")) { - try { - accessSync(bin, fsConstants.X_OK); - } catch { - missing.push(bin); - } - continue; - } - const dirs = (process.env.PATH ?? "").split(":").filter(Boolean); - const found = dirs.some((dir) => { - try { - accessSync(join(dir, bin), fsConstants.X_OK); - return true; - } catch { - return false; - } - }); - if (!found) missing.push(bin); + if (bin.includes("/")) { + try { + accessSync(bin, fsConstants.X_OK); + } catch { + missing.push(bin); + } + continue; + } + const dirs = (process.env.PATH ?? "").split(":").filter(Boolean); + const found = dirs.some((dir) => { + try { + accessSync(join(dir, bin), fsConstants.X_OK); + return true; + } catch { + return false; + } + }); + if (!found) { + missing.push(bin); + } } if (missing.length > 0) { - process.stderr.write(`\n ✗ frontal hook: required tool(s) not found on PATH\n`); - for (const t of missing) { - process.stderr.write(` ${t}\n`); - } - process.stderr.write( - ` Install the missing tool(s) and retry. See README.md for setup.\n\n`, - ); - process.exit(1); + process.stderr.write( + "\n ✗ frontal hook: required tool(s) not found on PATH\n" + ); + for (const t of missing) { + process.stderr.write(` ${t}\n`); + } + process.stderr.write( + " Install the missing tool(s) and retry. See README.md for setup.\n\n" + ); + process.exit(1); } diff --git a/hooks/go-vet-scoped.mjs b/hooks/go-vet-scoped.mjs index 0b09075..1fd86d1 100644 --- a/hooks/go-vet-scoped.mjs +++ b/hooks/go-vet-scoped.mjs @@ -11,81 +11,100 @@ import { spawnSync } from "node:child_process"; import { existsSync } from "node:fs"; -import { dirname, join, resolve } from "node:path"; +import { dirname, join, resolve, sep } from "node:path"; const EXCLUDED = [ - /(^|\/)vendor\//, - /(^|\/)gen\//, - /(^|\/)generated\//, - /(^|\/)node_modules\//, - /(^|\/)docker\//, + /(?^|\/)vendor\//u, + /(?^|\/)gen\//u, + /(?^|\/)generated\//u, + /(?^|\/)node_modules\//u, + /(?^|\/)docker\//u, ]; function git(args, cwd) { - const result = spawnSync("git", args, { cwd, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 }); - if (result.status !== 0) { - const detail = (result.stderr || "").trim(); - throw new Error(`git ${args.join(" ")} failed: ${detail}`); - } - return result.stdout.split("\n").filter(Boolean); + const result = spawnSync("git", args, { + cwd, + encoding: "utf8", + maxBuffer: 64 * 1024 * 1024, + }); + if (result.status !== 0) { + const detail = (result.stderr || "").trim(); + throw new Error(`git ${args.join(" ")} failed: ${detail}`); + } + return result.stdout.split("\n").filter(Boolean); } +/** + * Walk up from `file` to the nearest ancestor directory containing a + * go.mod, stopping at (and including) `root`. + */ function findGoModule(file, root) { - let dir = dirname(resolve(root, file)); - const stop = resolve(root); - for (;;) { - if (existsSync(join(dir, "go.mod"))) { - const rel = dir === stop ? "." : dir.slice(stop.length + 1); - return rel; - } - if (dir === stop) return null; - const parent = dirname(dir); - if (parent === dir) return null; - dir = parent; - } + const rootResolved = resolve(root); + let dir = dirname(resolve(rootResolved, file)); + // Walk up to (and including) the repo root; stop once dir rises above it. + while (dir === rootResolved || dir.startsWith(rootResolved + sep)) { + if (existsSync(join(dir, "go.mod"))) { + const rel = + dir === rootResolved ? "." : dir.slice(rootResolved.length + 1); + return rel; + } + const parent = dirname(dir); + if (parent === dir) { + return null; + } + dir = parent; + } + return null; } try { - const root = git(["rev-parse", "--show-toplevel"])[0]; - const staged = git(["diff", "--cached", "--name-only", "--diff-filter=ACMR", "--", "*.go"], root).filter( - (f) => !EXCLUDED.some((p) => p.test(f)), - ); + const [root] = git(["rev-parse", "--show-toplevel"]); + const staged = git( + ["diff", "--cached", "--name-only", "--diff-filter=ACMR", "--", "*.go"], + root + ).filter((f) => !EXCLUDED.some((p) => p.test(f))); - if (staged.length === 0) { - process.stderr.write("frontal-go-vet: no staged Go files — nothing to check\n"); - process.exit(0); - } + if (staged.length === 0) { + process.stderr.write( + "frontal-go-vet: no staged Go files — nothing to check\n" + ); + process.exit(0); + } - const dirs = [...new Set(staged.map((f) => findGoModule(f, root)).filter(Boolean))]; - if (dirs.length === 0) { - process.stderr.write("frontal-go-vet: no Go module owns any staged file — nothing to check\n"); - process.exit(0); - } + const dirs = [ + ...new Set(staged.map((f) => findGoModule(f, root)).filter(Boolean)), + ]; + if (dirs.length === 0) { + process.stderr.write( + "frontal-go-vet: no Go module owns any staged file — nothing to check\n" + ); + process.exit(0); + } - // Warm the module cache for each affected directory (same as run-checks.mjs). - for (const dir of dirs) { - spawnSync("go", ["list", "-e", "-deps", "-test", "./..."], { - cwd: join(root, dir), - shell: false, - stdio: "ignore", - }); - } + // Warm the module cache for each affected directory (same as run-checks.mjs). + for (const dir of dirs) { + spawnSync("go", ["list", "-e", "-deps", "-test", "./..."], { + cwd: join(root, dir), + shell: false, + stdio: "ignore", + }); + } - for (const dir of dirs) { - process.stderr.write(`frontal-go-vet: go vet ./... (in ${dir})\n`); - const result = spawnSync("go", ["vet", "./..."], { - cwd: join(root, dir), - shell: false, - stdio: "inherit", - }); - if (result.status !== 0) { - process.stderr.write(`\n ✗ frontal-go-vet: failed in ${dir}\n`); - process.exit(result.status ?? 1); - } - } + for (const dir of dirs) { + process.stderr.write(`frontal-go-vet: go vet ./... (in ${dir})\n`); + const result = spawnSync("go", ["vet", "./..."], { + cwd: join(root, dir), + shell: false, + stdio: "inherit", + }); + if (result.status !== 0) { + process.stderr.write(`\n ✗ frontal-go-vet: failed in ${dir}\n`); + process.exit(result.status ?? 1); + } + } - process.stderr.write("frontal-go-vet: ok\n"); + process.stderr.write("frontal-go-vet: ok\n"); } catch (error) { - process.stderr.write(`frontal-go-vet: ${error.message}\n`); - process.exit(1); + process.stderr.write(`frontal-go-vet: ${error.message}\n`); + process.exit(1); } diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..aa642f8 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,1406 @@ +{ + "name": "frontal-pre-commit", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "frontal-pre-commit", + "version": "1.0.0", + "license": "MIT", + "devDependencies": { + "@biomejs/biome": "^2.6.8", + "ultracite": "^8.2.1" + }, + "engines": { + "node": ">=22" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.14.tgz", + "integrity": "sha512-CXvKMFvM80ihI7Vox9jb+kQjnyjESQNPM+vB7U0Zz6TWuZA+Z/FL0QPMH300h33qJtIx+REeBhXqWOPW48TcAQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.14.tgz", + "integrity": "sha512-VL220vXuyO2z3rNIQwY7ftj9UwpqOt+33sH+sBWkOekbsSR2g7EEMnOx24ZlCH0xOA3DM/33SifVFGbnJD8r/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.14" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.14.tgz", + "integrity": "sha512-UjI/dKmwJwT9pOszJitq2G6EObZPnsZUfdCr92z2TlF3EZK9J3EdfOKUrCzHl6wFthbzwhzl1Soc/UIwxRiq6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.14", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@biomejs/biome": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/biome/-/biome-2.6.8.tgz", + "integrity": "sha512-kqZUFvX6/aYQOmzfRN5ANcfNS9wLH4aHLWWP/dQKyhRZVoA6rdWszA7DGugFcxPbMiznUyVYyukVl+ExZN4PQA==", + "dev": true, + "license": "MIT OR Apache-2.0", + "bin": { + "biome": "bin/biome" + }, + "engines": { + "node": ">=14.21.3" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/biome" + }, + "optionalDependencies": { + "@biomejs/cli-android-arm64": "2.6.8", + "@biomejs/cli-android-x64": "2.6.8", + "@biomejs/cli-darwin-arm64": "2.6.8", + "@biomejs/cli-darwin-x64": "2.6.8", + "@biomejs/cli-linux-arm64": "2.6.8", + "@biomejs/cli-linux-arm64-musl": "2.6.8", + "@biomejs/cli-linux-x64": "2.6.8", + "@biomejs/cli-linux-x64-musl": "2.6.8", + "@biomejs/cli-win32-arm64": "2.6.8", + "@biomejs/cli-win32-x64": "2.6.8" + } + }, + "node_modules/@biomejs/cli-android-arm64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-android-arm64/-/cli-android-arm64-2.6.8.tgz", + "integrity": "sha512-X4JKPLK85kfUTwuuaORFplnBfGjKkp62PsFhhcL7F/Tpltc7pyUofjlkkMnlZZLWsifFl7LNB8ngVrwJg1uo1Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-android-x64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-android-x64/-/cli-android-x64-2.6.8.tgz", + "integrity": "sha512-C3Hk485vl+deEj53K08+SYYelPIPkdSZL3qHuD31Xi+qydVa4q2ze+aCYo1k3iJGWtvWtjHaGkDh7S2sX6wk8w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-darwin-arm64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-arm64/-/cli-darwin-arm64-2.6.8.tgz", + "integrity": "sha512-DHyj+JnRHcn4YdvpiqgTFZMYKSPELMCfFpNNlEuu1L8DKTGXhzW7raIwdsbo2Ie9nCljQLAQkVWQk/mwM0ueiA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-darwin-x64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-x64/-/cli-darwin-x64-2.6.8.tgz", + "integrity": "sha512-QWWUPjlA0RnkkgYnFLUHZu+RrDc0FdK0A+wEPA+dENQJwsuSHMH89lspnAw2QUWWc9VHyfluGx1Xmp6Y2GZi8Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-arm64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64/-/cli-linux-arm64-2.6.8.tgz", + "integrity": "sha512-0Bjim8lKwnrvXUHoI4k3Tb51BjoiLEwDnovCI8nSzkk6wj3dShiuAjrx6+X0Hjf4ejR1sRZgTQiSDHlpy9vB7w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-arm64-musl": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.6.8.tgz", + "integrity": "sha512-WB9PhOitX+bRc0G3+GNJGlvbKoWn3JoB9z4E04JQizIC9aPCQyIvwvWG7QZHxw6k20Fi+dHLmZ2fSEmBa9HqiA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-x64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64/-/cli-linux-x64-2.6.8.tgz", + "integrity": "sha512-XIk3pLQT56I6Tti+u0DF8FtSNXjCMTPbxVTzfJ9cS2t1ImVKvrqV5b52GuEaJg6/wuiXvz0sjfb5saB4TPRjzA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-x64-musl": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64-musl/-/cli-linux-x64-musl-2.6.8.tgz", + "integrity": "sha512-64Yzo+J4fEk7Kf9SMnVdVxC+Y2A2e/L86QTP9JjGQ57lsddyELLpbBcNMxSJggre2T1AvISwwSrOApkBAHDqNA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-win32-arm64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-arm64/-/cli-win32-arm64-2.6.8.tgz", + "integrity": "sha512-ezjCEZzHIWE2pdh83a7zLVcAAcDaERcTcvfA7uWlxqz/1CuDxgtfO19pDg9B6YY4wKYIDvYBw2QCMnqIshSwmw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-win32-x64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-x64/-/cli-win32-x64-2.6.8.tgz", + "integrity": "sha512-cD6HvGczZUiAYsY8s2TxxXj2AHFzEdMomvVJfEjzOjBM45nGqIDfBpbtvwGQzDCN8X2yKKk9u1jnDZisT2nxIg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@clack/core": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@clack/core/-/core-1.6.0.tgz", + "integrity": "sha512-4GZynIB2IIe431odxesswvWTCP6orvqd6e2b07b3VFWBQRqUqIHc/EPIZwFoKS692QBp+ooPuXKaJV8g4kXuYA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-string-width": "^3.0.2", + "fast-wrap-ansi": "^0.2.0", + "sisteransi": "^2.0.0" + }, + "engines": { + "node": ">= 20.12.0" + } + }, + "node_modules/@clack/prompts": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@clack/prompts/-/prompts-1.9.0.tgz", + "integrity": "sha512-tEj8X2No2A1c9NDnZECxiiJ8TP3vmFlN9tLlLeSaMqVW4tUmVG2R4qpv/eP4zymWxnymYLkLcIYVV0VcWj3RCQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@clack/core": "1.6.0", + "fast-string-width": "^3.0.2", + "fast-wrap-ansi": "^0.2.0", + "sisteransi": "^2.0.0" + }, + "engines": { + "node": ">= 20.12.0" + } + }, + "node_modules/@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@sec-ant/readable-stream": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@sec-ant/readable-stream/-/readable-stream-0.4.1.tgz", + "integrity": "sha512-831qok9r2t8AlxLko40y2ebgSDhenenCatLVeW/uBtnHPyhHOvG0C7TvfgecV+wHzIm5KUICgzmVpWS+IMEAeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@sindresorhus/merge-streams": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/merge-streams/-/merge-streams-4.0.0.tgz", + "integrity": "sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/acorn": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz", + "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/ansi-escapes": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-7.3.0.tgz", + "integrity": "sha512-BvU8nYgGQBxcmMuEeUEmNTvrMVjJNSH7RgW24vXexN4Ven6qCvy4TntnvlnwnMLTVlcRQQdbRY8NKnaIoeWDNg==", + "dev": true, + "license": "MIT", + "dependencies": { + "environment": "^1.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ansi-regex": { + "version": "6.6.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.6.0.tgz", + "integrity": "sha512-XZ5apbzreCbXSKwPjJstu8R0zOi247w3XYwWxtwBXgpZrCyc1Ka7p9/xY0A9/diMewmHbEKz+FIraWaEWjlN5g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/ansi-styles": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-7.0.0.tgz", + "integrity": "sha512-kKvt3m4uwzqL0wlkPd09CmljPJGOZZ4D0fP65sqFSvPkMRKhNi+74MgIJ5QxE6SxqB4t4KyUFGg8+n5zjo6hew==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=22" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/citty": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/citty/-/citty-0.2.2.tgz", + "integrity": "sha512-+6vJA3L98yv+IdfKGZHBNiGW5KHn22e/JwID0Strsz8h4S/csAu/OuICwxrg44k5MRiZHWIo8XXuJgQTriRP4w==", + "dev": true, + "license": "MIT" + }, + "node_modules/cli-cursor": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-5.0.0.tgz", + "integrity": "sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw==", + "dev": true, + "license": "MIT", + "dependencies": { + "restore-cursor": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-truncate": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-6.2.0.tgz", + "integrity": "sha512-5uyZew3nYoDgyltqSI8OER6DuyecorYOSVDAXl9wQ9Y8Re/HaQ/5qP0HmTUOUQqmvtpB+mlsf1gG/FUS3U1gLQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "slice-ansi": "^10.0.0", + "string-width": "^8.3.0" + }, + "engines": { + "node": ">=22" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/commander": { + "version": "15.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-15.1.0.tgz", + "integrity": "sha512-cgnQ88TRrWcC7pVq46RzJVRMktu3W2RcbnoidnfBsl1bmDCBwJS/udcIZpKoCrbAYYaCqsz1yZCVIgbIaU3ddQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=22.12.0" + } + }, + "node_modules/confbox": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.1.8.tgz", + "integrity": "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/deepmerge": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", + "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/empathic": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/empathic/-/empathic-2.1.0.tgz", + "integrity": "sha512-AnfC1ATldl49/cvZdLPDjBfrRNwbDO05aibiOtzQu3qtlbJtomNLhF30HEtn/7iBz50dlMECqATo3fG0LrdEgw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14" + } + }, + "node_modules/environment": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/environment/-/environment-1.1.0.tgz", + "integrity": "sha512-xUtoPkMggbz0MPyPiIWr1Kp4aeWJjDZ6SMvURhimjdZgsRuDplF5/s9hcgGhyXMhs+6vpnuoiZ2kFiu3FMnS8Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/execa": { + "version": "10.2.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-10.2.1.tgz", + "integrity": "sha512-/Bofl3ZBh2Q4/PG0W63qFzP5vDAypi8Zc90UWTBzaDNIYiX7apPOd0N6L8hG8CojUdq4V51adu8BObP+iVsSTw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@sindresorhus/merge-streams": "^4.0.0", + "figures": "^6.1.0", + "get-stream": "^9.0.1", + "human-signals": "^8.0.1", + "is-plain-obj": "^4.1.0", + "is-stream": "^4.0.1", + "npm-run-path": "^6.0.0", + "pretty-ms": "^9.3.1", + "signal-exit": "^4.1.0", + "strip-final-newline": "^4.0.0", + "which-command": "^0.1.0", + "yoctocolors": "^2.2.0" + }, + "engines": { + "node": ">=22" + }, + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" + } + }, + "node_modules/fast-glob": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", + "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.8" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/fast-string-truncated-width": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/fast-string-truncated-width/-/fast-string-truncated-width-3.0.3.tgz", + "integrity": "sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-string-width": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/fast-string-width/-/fast-string-width-3.0.2.tgz", + "integrity": "sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-string-truncated-width": "^3.0.2" + } + }, + "node_modules/fast-wrap-ansi": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/fast-wrap-ansi/-/fast-wrap-ansi-0.2.2.tgz", + "integrity": "sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-string-width": "^3.0.2" + } + }, + "node_modules/fastq": { + "version": "1.20.3", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.3.tgz", + "integrity": "sha512-XKv5nnLs6nLF71NgiKJLIZFLkPyIEuOselLG7ujZnGrRfQK8HpvY+WqKhAJUAdLomwVHErVS4LfxFlPq0/FTAw==", + "dev": true, + "license": "ISC", + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/figures": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-6.1.0.tgz", + "integrity": "sha512-d+l3qxjSesT4V7v2fh+QnmFnUWv9lSpjarhShNTgBOfA0ttejbQUAlHLitbjkoRiDulW0OPoQPYIGhIC8ohejg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-unicode-supported": "^2.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/find-workspaces": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/find-workspaces/-/find-workspaces-0.3.1.tgz", + "integrity": "sha512-UDkGILGJSA1LN5Aa7McxCid4sqW3/e+UYsVwyxki3dDT0F8+ym0rAfnCkEfkL0rO7M+8/mvkim4t/s3IPHmg+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-glob": "^3.3.2", + "pkg-types": "^1.0.3", + "yaml": "^2.3.4" + } + }, + "node_modules/get-east-asian-width": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz", + "integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/get-stream": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-9.0.1.tgz", + "integrity": "sha512-kVCxPF3vQM/N0B1PmoqVUqgHP+EeVjmZSQn+1oCRPxd2P21P2F19lIgbR3HBosbB1PUhOAoctJnfEn2GbN2eZA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@sec-ant/readable-stream": "^0.4.1", + "is-stream": "^4.0.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/human-signals": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-8.0.1.tgz", + "integrity": "sha512-eKCa6bwnJhvxj14kZk5NCPc6Hb6BdsU9DZcOnmQKSnO1VKrfV0zCvtttPZUsBvjmNDn8rpcJfpwSYnHBjc95MQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-5.1.0.tgz", + "integrity": "sha512-5XHYaSyiqADb4RnZ1Bdad6cPp8Toise4TzEjcOYDHZkTCbKgiUl7WTUCpNWHuxmDt91wnsZBc9xinNzopv3JMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-east-asian-width": "^1.3.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-plain-obj": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz", + "integrity": "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-stream": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-4.0.1.tgz", + "integrity": "sha512-Dnz92NInDqYckGEUJv689RbRiTSEHCQ7wOVeALbkOz999YpqT46yMRIGtSNl2iCL1waAZSx40+h59NV/EwzV/A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-unicode-supported": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-2.1.0.tgz", + "integrity": "sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/jsonc-parser": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.3.1.tgz", + "integrity": "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/log-update": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/log-update/-/log-update-8.0.0.tgz", + "integrity": "sha512-lddSgOt3bPASrylL54ZSpy8nBHns+vBVSoILlVOx+dei300pnLRN958rj/EdlVLKuWlSESU3qdnDZdAI7FXYGg==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-escapes": "^7.3.0", + "cli-cursor": "^5.0.0", + "slice-ansi": "^9.0.0", + "string-width": "^8.2.0", + "strip-ansi": "^7.2.0", + "wrap-ansi": "^10.0.0" + }, + "engines": { + "node": ">=22" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/log-update/node_modules/slice-ansi": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-9.0.1.tgz", + "integrity": "sha512-aBY19bn/XA+hKOKX0qL7Z0UfdBsbQvc9hn993U8ALUjzxCvDcuZqLoRXjGJrUARWAlwMnsRVD9sw2AFNOYvalA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.3", + "is-fullwidth-code-point": "^5.1.0" + }, + "engines": { + "node": ">=22" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" + } + }, + "node_modules/magicast": { + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.5.tgz", + "integrity": "sha512-UicdXN8zQ3JHlxVq+28afMXPr1z7WNY6+7EJnzTdQWkTAlMLF5fNCCKxJHBQwGaNGR11581EiQmQzx73+MvszA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7", + "source-map-js": "^1.2.1" + } + }, + "node_modules/merge2": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/mimic-function": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/mimic-function/-/mimic-function-5.0.1.tgz", + "integrity": "sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mlly": { + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.8.2.tgz", + "integrity": "sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA==", + "dev": true, + "license": "MIT", + "dependencies": { + "acorn": "^8.16.0", + "pathe": "^2.0.3", + "pkg-types": "^1.3.1", + "ufo": "^1.6.3" + } + }, + "node_modules/npm-run-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-6.0.0.tgz", + "integrity": "sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^4.0.0", + "unicorn-magic": "^0.3.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/nypm": { + "version": "0.6.12", + "resolved": "https://registry.npmjs.org/nypm/-/nypm-0.6.12.tgz", + "integrity": "sha512-4AhWntz+ds/P5kz1rN25yGegTPYsO5ffOy+8S0TeuXKZrgjlmgcEBLA1xubzcP/dWX4zYfNybv4TQERlL9Z0LQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "citty": "^0.2.2", + "pathe": "^2.0.3", + "tinyexec": "^1.3.1" + }, + "bin": { + "nypm": "dist/cli.mjs" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/onetime": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-7.0.0.tgz", + "integrity": "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "mimic-function": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parse-ms": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/parse-ms/-/parse-ms-4.0.0.tgz", + "integrity": "sha512-TXfryirbmq34y8QBwgqCVLi+8oA3oWx2eAnSn62ITyEhEYaWRlVZ2DvMM9eZbMs/RfxPu/PK/aBLyGj4IrqMHw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/path-key": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-4.0.0.tgz", + "integrity": "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pkg-types": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.3.1.tgz", + "integrity": "sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "confbox": "^0.1.8", + "mlly": "^1.7.4", + "pathe": "^2.0.1" + } + }, + "node_modules/pretty-ms": { + "version": "9.3.1", + "resolved": "https://registry.npmjs.org/pretty-ms/-/pretty-ms-9.3.1.tgz", + "integrity": "sha512-HzMy3Geq23nVALD/M2LliU+F+M+gVNsvkQWWqeBZ8HDiCgzo6YPJ/Omrmtq24EFrIsk0a3EkQGEd7bDOo+IhGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "parse-ms": "^4.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/queue-microtask": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", + "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/resolve.exports": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/resolve.exports/-/resolve.exports-2.0.4.tgz", + "integrity": "sha512-zepuGL0ulf+nt+XaFrlKeaiTJeyPFPLLY62+ncq1/VTHBdt3HsfXOH60priZ6tnXQozdGcDeIF5JVTanvIcYWQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/restore-cursor": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-5.1.0.tgz", + "integrity": "sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA==", + "dev": true, + "license": "MIT", + "dependencies": { + "onetime": "^7.0.0", + "signal-exit": "^4.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/reusify": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", + "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", + "dev": true, + "license": "MIT", + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/run-parallel": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", + "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "queue-microtask": "^1.2.2" + } + }, + "node_modules/semver": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/sisteransi": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-2.0.0.tgz", + "integrity": "sha512-2WCqLdt12eN6ehLI50S2/ZxoowXU3DD1KVPRyVP0WEsFahrGZZmCdq1K59qjJljMRIDTwx1D9YaRK+hDneBUMg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/slice-ansi": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-10.0.1.tgz", + "integrity": "sha512-CJKEH3zwVX4bOnE+bFbmh+JK/YMT9VAazqBsVBTesnYKXlNtz6oVmrhNp1jHrxHzscuUkWiKZpzNzFraZcrorg==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^7.0.0", + "string-width": "^8.3.0" + }, + "engines": { + "node": ">=22" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/string-width": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.3.0.tgz", + "integrity": "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-east-asian-width": "^1.5.0", + "strip-ansi": "^7.1.2" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/strip-ansi": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", + "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.2.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/strip-final-newline": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-4.0.0.tgz", + "integrity": "sha512-aulFJcD6YK8V1G7iRB5tigAP4TsHBZZrOV8pjV++zdUwmeV8uzbY7yn6h9MswN62adStNZFuCIx4haBnRuMDaw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/tinyexec": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", + "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/ufo": { + "version": "1.6.4", + "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.4.tgz", + "integrity": "sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA==", + "dev": true, + "license": "MIT" + }, + "node_modules/ultracite": { + "version": "8.2.1", + "resolved": "https://registry.npmjs.org/ultracite/-/ultracite-8.2.1.tgz", + "integrity": "sha512-+HAwOkdpdNaf6Fr+JEh0YkikJU4vjRO977kMAvtOsk8YWk+VG3rdy7gyFLgbO1Edv+k5hhL/3CKAiEmUlvt3ow==", + "dev": true, + "license": "MIT", + "dependencies": { + "@clack/prompts": "^1.8.1", + "cli-truncate": "^6.1.1", + "commander": "^15.0.0", + "deepmerge": "^4.3.1", + "empathic": "^2.1.0", + "execa": "^10.0.1", + "fast-glob": "^3.3.3", + "find-workspaces": "^0.3.1", + "jsonc-parser": "^3.3.1", + "log-update": "^8.0.0", + "magicast": "^0.5.5", + "npm-run-path": "^6.0.0", + "nypm": "^0.6.10", + "resolve.exports": "^2.0.3", + "semver": "^7.8.5", + "string-width": "^8.3.0", + "which-command": "^0.1.0", + "yaml": "^2.9.1", + "zod": "^4.6.5" + }, + "bin": { + "ultracite": "dist/index.js" + }, + "engines": { + "node": "^22.22.2 || >=24.15.0" + }, + "peerDependencies": { + "@biomejs/biome": "^2.6.2", + "eslint": "^10.9.0", + "oxfmt": ">=0.71.0 <1", + "oxlint": "^1.90.0", + "prettier": "^3.5.3", + "stylelint": "^17.0.0" + }, + "peerDependenciesMeta": { + "@biomejs/biome": { + "optional": true + }, + "eslint": { + "optional": true + }, + "oxfmt": { + "optional": true + }, + "oxlint": { + "optional": true + }, + "prettier": { + "optional": true + }, + "stylelint": { + "optional": true + } + } + }, + "node_modules/unicorn-magic": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/unicorn-magic/-/unicorn-magic-0.3.0.tgz", + "integrity": "sha512-+QBBXBCvifc56fsbuxZQ6Sic3wqqc3WWaqxs58gvJrcOuN83HGTCwz3oS5phzU9LthRNE9VrJCFCLUgHeeFnfA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/which-command": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/which-command/-/which-command-0.1.0.tgz", + "integrity": "sha512-XZyoF5/5hZtXitIwzrU4NKK+Wtbb9aB9CezUEw2Q0wlYK8NUYQxC1rRXgNueYLtBAJwXIb+/tFVk4dozciNJMA==", + "dev": true, + "license": "MIT", + "bin": { + "which-command": "cli.js" + }, + "engines": { + "node": ">=22" + }, + "funding": { + "url": "https://github.com/sindresorhus/which-command?sponsor=1" + } + }, + "node_modules/wrap-ansi": { + "version": "10.0.2", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-10.0.2.tgz", + "integrity": "sha512-6OLRNZqRntVGBm26ghZ5eZhCuWWyOkRCSn8XsOIuq5stpCE/tjLbdozd93naILZig0lmD8ANfRwnhn0DLeXGlg==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.3", + "string-width": "^8.2.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/yaml": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz", + "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==", + "dev": true, + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + }, + "node_modules/yoctocolors": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/yoctocolors/-/yoctocolors-2.2.0.tgz", + "integrity": "sha512-xYqdZFUK/VYazNl/oCDYN+3WloWQwMfZxBoiNt6qNyk+xfOdi598muWE42rNZFp1kNOiqW936q5RhUdnpqElSg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/zod": { + "version": "4.6.7", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", + "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/package.json b/package.json index 260eb84..8f8ccfd 100644 --- a/package.json +++ b/package.json @@ -1,18 +1,24 @@ { "name": "frontal-pre-commit", "version": "1.0.0", + "private": true, "description": "Frontal's git-hook gates, published as pre-commit hooks and a lefthook remote", - "type": "module", + "repository": { + "type": "git", + "url": "git+https://github.com/frontal-labs/pre-commit.git" + }, "license": "MIT", - "private": true, + "type": "module", "scripts": { + "check": "biome check --no-errors-on-unmatched", + "format": "biome check --write", "test": "node tests/run-hooks.test.mjs" }, + "devDependencies": { + "@biomejs/biome": "^2.6.8", + "ultracite": "^8.2.1" + }, "engines": { "node": ">=22" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/frontal-labs/pre-commit.git" } } diff --git a/tests/fixtures/biome/fail/index.ts b/tests/fixtures/biome/fail/index.ts index a22a000..92bf4ea 100644 --- a/tests/fixtures/biome/fail/index.ts +++ b/tests/fixtures/biome/fail/index.ts @@ -1 +1,8 @@ -export const bad = undefined +function foo() { + if (true) { + return 1; + } + return 2; +} +const unused = 42; +var old = 1; diff --git a/tests/fixtures/biome/fail/package.json b/tests/fixtures/biome/fail/package.json index 883f815..15d769a 100644 --- a/tests/fixtures/biome/fail/package.json +++ b/tests/fixtures/biome/fail/package.json @@ -1 +1,4 @@ -{"name":"biome-fail","version":"1.0.0"} +{ + "name": "biome-fail", + "version": "1.0.0" +} diff --git a/tests/fixtures/biome/pass/package.json b/tests/fixtures/biome/pass/package.json index 1a322c0..e10d328 100644 --- a/tests/fixtures/biome/pass/package.json +++ b/tests/fixtures/biome/pass/package.json @@ -1 +1,4 @@ -{"name":"biome-pass","version":"1.0.0"} +{ + "name": "biome-pass", + "version": "1.0.0" +} diff --git a/tests/run-hooks.test.mjs b/tests/run-hooks.test.mjs index b9e20c1..0aacdb6 100644 --- a/tests/run-hooks.test.mjs +++ b/tests/run-hooks.test.mjs @@ -14,26 +14,41 @@ */ import { execFileSync, spawnSync } from "node:child_process"; -import { cpSync, existsSync, mkdtempSync, readdirSync, rmSync, statSync } from "node:fs"; +import { + cpSync, + existsSync, + mkdtempSync, + readdirSync, + rmSync, + statSync, + symlinkSync, +} from "node:fs"; import { tmpdir } from "node:os"; -import { fileURLToPath } from "node:url"; import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; const TEST_DIR = dirname(fileURLToPath(import.meta.url)); const REPO_ROOT = dirname(TEST_DIR); const FIXTURES = join(TEST_DIR, "fixtures"); +/** Matches the `sh -c ''` wrapper every hook entry uses. */ +const SH_C_RE = /^sh -c '(?.*)'$/su; +const TS_FILE_RE = /(?ts|tsx|js|jsx|json)$/u; +const PY_FILE_RE = /\.py$/u; +const EXCLUDED_PATH_RE = + /(?^|\/)(?vendor|gen|generated|node_modules)\//u; + function listFiles(dir, prefix = "") { - const out = []; - for (const entry of readdirSync(dir).sort()) { - const full = join(dir, entry); - if (statSync(full).isDirectory()) { - out.push(...listFiles(full, prefix ? `${prefix}${entry}/` : `${entry}/`)); - } else { - out.push(prefix ? `${prefix}${entry}` : entry); - } - } - return out; + const out = []; + for (const entry of readdirSync(dir).sort()) { + const full = join(dir, entry); + if (statSync(full).isDirectory()) { + out.push(...listFiles(full, prefix ? `${prefix}${entry}/` : `${entry}/`)); + } else { + out.push(prefix ? `${prefix}${entry}` : entry); + } + } + return out; } /** @@ -42,198 +57,273 @@ function listFiles(dir, prefix = "") { * missing tool, which is indistinguishable from a hook bug without this. */ function toolAvailable(cmd, extraArgs = []) { - const result = spawnSync(cmd, extraArgs, { encoding: "utf8" }); - return result.error === undefined && result.status === 0; + const result = spawnSync(cmd, extraArgs, { encoding: "utf8" }); + return result.error === undefined && result.status === 0; } const HOOK_TOOLS = { - "frontal-biome": () => toolAvailable("pnpm", ["exec", "biome", "--version"]), - "frontal-ruff": () => toolAvailable("ruff", ["--version"]), - "frontal-rustfmt": () => toolAvailable("rustfmt", ["--version"]), - "frontal-clippy": () => toolAvailable("cargo", ["clippy", "--version"]), - "frontal-go-vet": () => toolAvailable("go", ["version"]), - "frontal-buf-lint": () => toolAvailable("buf", ["--version"]), - "frontal-commit-msg": () => toolAvailable("node", ["--version"]), + "frontal-biome": () => + toolAvailable("biome", ["--version"]) || + existsSync(join(REPO_ROOT, "node_modules", ".bin", "biome")), + "frontal-ruff": () => toolAvailable("ruff", ["--version"]), + "frontal-rustfmt": () => toolAvailable("rustfmt", ["--version"]), + "frontal-clippy": () => toolAvailable("cargo", ["clippy", "--version"]), + "frontal-go-vet": () => toolAvailable("go", ["version"]), + "frontal-buf-lint": () => toolAvailable("buf", ["--version"]), + "frontal-commit-msg": () => toolAvailable("node", ["--version"]), }; const HOOKS = { - "frontal-biome": { - entry: "sh -c 'node hooks/ensure-tool.mjs pnpm && pnpm exec biome check --no-errors-on-unmatched \"$@\"'", - staged: (files) => files.filter((f) => /\.(ts|tsx|js|jsx|json)$/.test(f) && !f.startsWith("packages/design-system/")), - pass_filenames: true, - }, - "frontal-ruff": { - entry: "sh -c 'node hooks/ensure-tool.mjs ruff && ruff check \"$@\" && ruff format --check \"$@\"'", - staged: (files) => files.filter((f) => /\.py$/.test(f) && !/(^|\/)(vendor|gen|generated|node_modules)\//.test(f)), - pass_filenames: true, - }, - "frontal-rustfmt": { - entry: 'sh -c \'node hooks/ensure-tool.mjs rustfmt && rust_files=$(git diff --cached --name-only --diff-filter=ACMR -- "*.rs" | grep -vE "(^|/)gen/" || true); if [ -n "$rust_files" ]; then printf "%s\\n" "$rust_files" | xargs rustfmt --edition 2024 --check; fi\'', - staged: () => [], - pass_filenames: false, - }, - "frontal-clippy": { - entry: "sh -c 'node hooks/ensure-tool.mjs cargo && node hooks/clippy-scoped.mjs'", - staged: () => [], - pass_filenames: false, - }, - "frontal-go-vet": { - entry: "sh -c 'node hooks/ensure-tool.mjs go && node hooks/go-vet-scoped.mjs'", - staged: () => [], - pass_filenames: false, - }, - "frontal-buf-lint": { - entry: "sh -c 'node hooks/ensure-tool.mjs buf && node hooks/buf-lint-scoped.mjs'", - staged: () => [], - pass_filenames: false, - }, - "frontal-commit-msg": { - entry: "sh -c 'node hooks/check-commit-message.mjs \"$0\"'", - staged: () => [], - pass_filenames: false, - is_commit_msg: true, - }, + "frontal-biome": { + entry: + "sh -c 'node hooks/ensure-tool.mjs biome && biome check --no-errors-on-unmatched \"$@\"'", + staged: (files) => + files.filter( + (f) => TS_FILE_RE.test(f) && !f.startsWith("packages/design-system/") + ), + pass_filenames: true, + }, + "frontal-ruff": { + entry: + 'sh -c \'node hooks/ensure-tool.mjs ruff && ruff check "$@" && ruff format --check "$@"\'', + staged: (files) => + files.filter((f) => PY_FILE_RE.test(f) && !EXCLUDED_PATH_RE.test(f)), + pass_filenames: true, + }, + "frontal-rustfmt": { + entry: + 'sh -c \'node hooks/ensure-tool.mjs rustfmt && rust_files=$(git diff --cached --name-only --diff-filter=ACMR -- "*.rs" | grep -vE "(^|/)gen/" || true); if [ -n "$rust_files" ]; then printf "%s\\n" "$rust_files" | xargs rustfmt --edition 2024 --check; fi\'', + staged: () => [], + pass_filenames: false, + }, + "frontal-clippy": { + entry: + "sh -c 'node hooks/ensure-tool.mjs cargo && node hooks/clippy-scoped.mjs'", + staged: () => [], + pass_filenames: false, + }, + "frontal-go-vet": { + entry: + "sh -c 'node hooks/ensure-tool.mjs go && node hooks/go-vet-scoped.mjs'", + staged: () => [], + pass_filenames: false, + }, + "frontal-buf-lint": { + entry: + "sh -c 'node hooks/ensure-tool.mjs buf && node hooks/buf-lint-scoped.mjs'", + staged: () => [], + pass_filenames: false, + }, + "frontal-commit-msg": { + entry: "sh -c 'node hooks/check-commit-message.mjs \"$0\"'", + staged: () => [], + pass_filenames: false, + is_commit_msg: true, + }, }; const CASES = [ - // [caseId, fixtureRelPath, hookId, expectedPass] - ["biome-pass", "biome/pass", "frontal-biome", true], - ["biome-fail", "biome/fail", "frontal-biome", false], - ["ruff-pass", "ruff/pass", "frontal-ruff", true], - ["ruff-fail-lint", "ruff/fail-lint", "frontal-ruff", false], - ["ruff-fail-format", "ruff/fail-format", "frontal-ruff", false], - ["rustfmt-pass", "rustfmt/pass", "frontal-rustfmt", true], - ["rustfmt-fail", "rustfmt/fail", "frontal-rustfmt", false], - ["clippy-pass", "clippy/pass", "frontal-clippy", true], - ["clippy-fail", "clippy/fail", "frontal-clippy", false], - ["go-vet-pass", "go-vet/pass", "frontal-go-vet", true], - ["go-vet-fail", "go-vet/fail", "frontal-go-vet", false], - ["buf-lint-pass", "buf-lint/pass", "frontal-buf-lint", true], - ["buf-lint-fail", "buf-lint/fail", "frontal-buf-lint", false], - ["commit-msg-pass", "commit-msg/pass", "frontal-commit-msg", true], - ["commit-msg-fail", "commit-msg/fail", "frontal-commit-msg", false], + // [caseId, fixtureRelPath, hookId, expectedPass] + ["biome-pass", "biome/pass", "frontal-biome", true], + ["biome-fail", "biome/fail", "frontal-biome", false], + ["ruff-pass", "ruff/pass", "frontal-ruff", true], + ["ruff-fail-lint", "ruff/fail-lint", "frontal-ruff", false], + ["ruff-fail-format", "ruff/fail-format", "frontal-ruff", false], + ["rustfmt-pass", "rustfmt/pass", "frontal-rustfmt", true], + ["rustfmt-fail", "rustfmt/fail", "frontal-rustfmt", false], + ["clippy-pass", "clippy/pass", "frontal-clippy", true], + ["clippy-fail", "clippy/fail", "frontal-clippy", false], + ["go-vet-pass", "go-vet/pass", "frontal-go-vet", true], + ["go-vet-fail", "go-vet/fail", "frontal-go-vet", false], + ["buf-lint-pass", "buf-lint/pass", "frontal-buf-lint", true], + ["buf-lint-fail", "buf-lint/fail", "frontal-buf-lint", false], + ["commit-msg-pass", "commit-msg/pass", "frontal-commit-msg", true], + ["commit-msg-fail", "commit-msg/fail", "frontal-commit-msg", false], ]; function setupRepo(fixtureDir, repoDir) { - cpSync(fixtureDir, repoDir, { recursive: true }); - execFileSync("git", ["init", "-q", "--initial-branch=main"], { cwd: repoDir }); - execFileSync("git", ["config", "user.email", "test@test.com"], { cwd: repoDir }); - execFileSync("git", ["config", "user.name", "Test"], { cwd: repoDir }); - execFileSync("git", ["add", "-A"], { cwd: repoDir }); - // Copy hooks/ so relative paths in entry commands work - cpSync(join(REPO_ROOT, "hooks"), join(repoDir, "hooks"), { recursive: true }); + cpSync(fixtureDir, repoDir, { recursive: true }); + execFileSync("git", ["init", "-q", "--initial-branch=main"], { + cwd: repoDir, + }); + execFileSync("git", ["config", "user.email", "test@test.com"], { + cwd: repoDir, + }); + execFileSync("git", ["config", "user.name", "Test"], { cwd: repoDir }); + // Copy hooks/ so relative paths in entry commands work + cpSync(join(REPO_ROOT, "hooks"), join(repoDir, "hooks"), { recursive: true }); + // The biome hook resolves its config (biome.jsonc) and the ultracite preset + // through node_modules, so the throwaway repo needs both: a copy of the + // config and a symlink to this repo's node_modules. + cpSync(join(REPO_ROOT, "biome.jsonc"), join(repoDir, "biome.jsonc")); + symlinkSync(join(REPO_ROOT, "node_modules"), join(repoDir, "node_modules")); + execFileSync("git", ["add", "-A"], { cwd: repoDir }); } function runHook(hook, repoDir, allFiles, extraArgs = []) { - // Every hook entry is of the form `sh -c ''`. pre-commit - // executes it by appending the file list (or the commit-msg file) as - // positional params after the command string. The first positional - // param lands in `$0`, the rest in `$@`. - // - // To avoid a double shell wrapper (which would consume the positional - // param as its own $0 and drop it), parse out the inner command and - // run `sh -c ` directly. - const m = hook.entry.match(/^sh -c '(.*)'$/s); - if (!m) throw new Error(`unexpected entry format: ${hook.entry}`); - const command = m[1]; - - const files = hook.is_commit_msg - ? extraArgs - : hook.pass_filenames - ? [...hook.staged(allFiles), ...extraArgs] - : []; - - const result = spawnSync("sh", ["-c", command, ...files], { - cwd: repoDir, - shell: false, - encoding: "utf8", - timeout: 60_000, - }); - return { status: result.status, stdout: result.stdout ?? "", stderr: result.stderr ?? "" }; + // Every hook entry is of the form `sh -c ''`. pre-commit + // executes it by appending the file list (or the commit-msg file) as + // positional params after the command string. The first positional + // param lands in `$0`, the rest in `$@`. + // + // To avoid a double shell wrapper (which would consume the positional + // param as its own $0 and drop it), parse out the inner command and + // run `sh -c [placeholder-$0] ` directly. + // + // `sh -c 'cmd' a b c` assigns a→$0, b→$1, c→$2. Hooks that reference + // `"$@"` (biome, ruff) expect *all* filenames there, so we pass a dummy + // placeholder for $0 and let the real files start at $1. The commit-msg + // hook is the exception: it reads a single positional param as `$0`, so + // for that hook we pass the message path bare (it becomes $0, matching + // how pre-commit invokes commit-msg hooks). + const m = hook.entry.match(SH_C_RE); + if (!m) { + throw new Error(`unexpected entry format: ${hook.entry}`); + } + const { command } = m.groups; + + let files = []; + if (hook.is_commit_msg) { + files = extraArgs; + } else if (hook.pass_filenames) { + files = [...hook.staged(allFiles), ...extraArgs]; + } + + // Prepend the repo's node_modules/.bin to PATH so locally-installed tools + // (biome) are found even when they are not on the system PATH. + const env = { + ...process.env, + PATH: `${join(repoDir, "node_modules", ".bin")}:${process.env.PATH}`, + }; + + // For commit-msg the single param is the message path and must land in $0. + // For file-based hooks a placeholder occupies $0 so "$@" sees every file. + const positional = hook.is_commit_msg ? files : ["$0-placeholder", ...files]; + + const result = spawnSync("sh", ["-c", command, ...positional], { + cwd: repoDir, + shell: false, + encoding: "utf8", + timeout: 60_000, + env, + }); + return { + status: result.status, + stdout: result.stdout ?? "", + stderr: result.stderr ?? "", + }; } function main() { - const args = process.argv.slice(2); - const filter = args.find((a) => !a.startsWith("--")); - const debug = args.includes("--debug"); - const cases = filter ? CASES.filter(([id]) => id === filter) : CASES; - - let passed = 0; - let failed = 0; - let skipped = 0; - const results = []; - - for (const [caseId, fixturePath, hookId, expectPass] of cases) { - const fixtureDir = join(FIXTURES, fixturePath); - if (!existsSync(fixtureDir)) { - results.push({ caseId, status: "SKIP", reason: `fixture not found: ${fixturePath}` }); - skipped++; - continue; - } - - const hook = HOOKS[hookId]; - - // Skip when the underlying tool is not installed on this machine. - if (!HOOK_TOOLS[hookId]()) { - results.push({ caseId, hookId, status: "SKIP", reason: "tool not installed" }); - skipped++; - continue; - } - - const repoDir = mkdtempSync(join(tmpdir(), `hook-test-${caseId}-`)); - - try { - setupRepo(fixtureDir, repoDir); - const allFiles = listFiles(fixtureDir); - - const extraArgs = hook.is_commit_msg ? [join(repoDir, "message.txt")] : []; - const result = runHook(hook, repoDir, allFiles, extraArgs); - - const actualPass = result.status === 0; - const ok = actualPass === expectPass; - - if (debug) { - process.stderr.write(`\n===== ${caseId} (exit ${result.status}, expected ${expectPass ? "pass" : "fail"}) =====\n`); - process.stderr.write(`--- stdout ---\n${result.stdout}\n--- stderr ---\n${result.stderr}\n`); - } - - results.push({ - caseId, - hookId, - expectPass, - actualPass, - status: ok ? "PASS" : "FAIL", - exitCode: result.status, - output: (result.stderr || result.stdout).trim().slice(0, 300), - }); - - if (ok) passed++; - else failed++; - } catch (error) { - results.push({ caseId, hookId, status: "ERROR", reason: error.message }); - failed++; - } finally { - if (!debug) rmSync(repoDir, { recursive: true, force: true }); - else process.stderr.write(`\n[debug] repo kept at ${repoDir}\n`); - } - } - - // Report - const width = Math.max(...results.map((r) => r.caseId.length), 20); - for (const r of results) { - const mark = r.status === "PASS" ? "ok " : r.status === "SKIP" ? "SKIP" : "FAIL"; - const detail = - r.status === "SKIP" - ? r.reason - : r.status === "ERROR" - ? r.reason - : `${r.hookId} exit=${r.exitCode} expected_pass=${r.expectPass}`; - console.log(` ${mark} ${r.caseId.padEnd(width)} ${detail}`); - } - - const total = results.length; - console.log(`\n${passed}/${total} cases passed, ${failed} failed, ${skipped} skipped\n`); - process.exit(failed > 0 ? 1 : 0); + const args = process.argv.slice(2); + const filter = args.find((a) => !a.startsWith("--")); + const debug = args.includes("--debug"); + const cases = filter ? CASES.filter(([id]) => id === filter) : CASES; + + let passed = 0; + let failed = 0; + let skipped = 0; + const results = []; + + for (const [caseId, fixturePath, hookId, expectPass] of cases) { + const fixtureDir = join(FIXTURES, fixturePath); + if (!existsSync(fixtureDir)) { + results.push({ + caseId, + status: "SKIP", + reason: `fixture not found: ${fixturePath}`, + }); + skipped += 1; + continue; + } + + const hook = HOOKS[hookId]; + + // Skip when the underlying tool is not installed on this machine. + if (!HOOK_TOOLS[hookId]()) { + results.push({ + caseId, + hookId, + status: "SKIP", + reason: "tool not installed", + }); + skipped += 1; + continue; + } + + const repoDir = mkdtempSync(join(tmpdir(), `hook-test-${caseId}-`)); + + try { + setupRepo(fixtureDir, repoDir); + const allFiles = listFiles(fixtureDir); + + const extraArgs = hook.is_commit_msg + ? [join(repoDir, "message.txt")] + : []; + const result = runHook(hook, repoDir, allFiles, extraArgs); + + const actualPass = result.status === 0; + const ok = actualPass === expectPass; + + if (debug) { + process.stderr.write( + `\n===== ${caseId} (exit ${result.status}, expected ${expectPass ? "pass" : "fail"}) =====\n` + ); + process.stderr.write( + `--- stdout ---\n${result.stdout}\n--- stderr ---\n${result.stderr}\n` + ); + } + + results.push({ + caseId, + hookId, + expectPass, + actualPass, + status: ok ? "PASS" : "FAIL", + exitCode: result.status, + output: (result.stderr || result.stdout).trim().slice(0, 300), + }); + + if (ok) { + passed += 1; + } else { + failed += 1; + } + } catch (error) { + results.push({ caseId, hookId, status: "ERROR", reason: error.message }); + failed += 1; + } finally { + if (debug) { + process.stderr.write(`\n[debug] repo kept at ${repoDir}\n`); + } else { + rmSync(repoDir, { recursive: true, force: true }); + } + } + } + + // Report + const width = Math.max(...results.map((r) => r.caseId.length), 20); + for (const r of results) { + let mark = "FAIL"; + if (r.status === "PASS") { + mark = "ok "; + } else if (r.status === "SKIP") { + mark = "SKIP"; + } + let detail; + if (r.status === "PASS") { + detail = `${r.hookId} exit=${r.exitCode} expected_pass=${r.expectPass}`; + } else { + detail = r.reason; + } + console.log(` ${mark} ${r.caseId.padEnd(width)} ${detail}`); + } + + const total = results.length; + console.log( + `\n${passed}/${total} cases passed, ${failed} failed, ${skipped} skipped\n` + ); + process.exit(failed > 0 ? 1 : 0); } main(); From 130194f319e128bcfa0874a2b7339974de038697 Mon Sep 17 00:00:00 2001 From: Gabriel Date: Mon, 16 Nov 2026 17:18:06 +0000 Subject: [PATCH 6/8] docs: align lefthook bridge, CI, and docs with the plain-biome hook - lefthook-remote.yml: frontal-biome now gates on `biome` and runs `biome check --no-errors-on-unmatched {staged_files}`, matching the pre-commit entry (previously `pnpm exec biome`). - CI: npm ci so the devDependency biome is on node_modules/.bin; add an `npm run check` self-lint step; the 2 biome cases now run in CI too. - README: tool table, tool requirements, and Development section updated for the ultracite-preset self-lint and plain-biome entry. - CHANGELOG: note the ultracite self-lint wiring. --- .github/workflows/ci.yml | 11 ++++++++++- CHANGELOG.md | 3 +++ README.md | 19 +++++++++++-------- lefthook-remote.yml | 11 +++++++---- 4 files changed, 31 insertions(+), 13 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 209c486..59334de 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,6 +19,12 @@ jobs: uses: actions/setup-node@v4 with: node-version: 22 + cache: npm + + # Dev dependencies bring @biomejs/biome (on node_modules/.bin, which the + # test runner prepends to PATH) and the ultracite preset used by biome.jsonc. + - name: Install dev dependencies + run: npm ci # Install the tools the hooks need. The hooks fail loudly when a tool # is missing (ensure-tool.mjs), so the test suite only runs the cases @@ -36,7 +42,10 @@ jobs: buf --version # go and cargo ship with the ubuntu-latest runner image. - # biome is not installed: those 2 test cases are SKIPPED, not failed. + # biome comes from the devDependencies installed above (all 15 cases run). + + - name: Run biome self-check + run: npm run check - name: Run hook tests run: npm test diff --git a/CHANGELOG.md b/CHANGELOG.md index 23061db..8a70c12 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,3 +25,6 @@ collection and a lefthook remote config. - Shared excludes: `vendor/`, `gen/`, `generated/`, `node_modules/` - `.pre-commit-hooks.yaml` — hook definitions for pre-commit consumers - GitHub Actions release workflow (tag-triggered) +- Repo self-lints with Biome via the ultracite preset + (`biome.jsonc` extends `ultracite/biome/core`; `@biomejs/biome` + + `ultracite` as devDependencies, `npm run check` / `npm run format`) diff --git a/README.md b/README.md index ab18541..a4fe4ba 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ config. Every hook fails loudly when its tool is missing — no silent passes. | ID | Description | Tool | |---|---|---| -| `frontal-biome` | Biome check (check-only) on staged JS/TS/JSON files | `pnpm exec biome` | +| `frontal-biome` | Biome check (check-only) on staged JS/TS/JSON files | `biome` | | `frontal-ruff` | `ruff check` + `ruff format --check` on staged Python files | `ruff` | | `frontal-rustfmt` | `rustfmt --edition 2024 --check` on staged Rust files only | `rustfmt` | | `frontal-clippy` | `cargo clippy --all-targets -D warnings` scoped to the crate workspaces that own staged Rust files | `cargo clippy` | @@ -81,13 +81,13 @@ steps: ``` Adjust the install steps for whichever tools your enabled hooks require -(`pnpm` + `biome`, `rustfmt`, `cargo clippy`, `go`, `buf`, etc.). +(`biome`, `rustfmt`, `cargo clippy`, `go`, `buf`, etc.). ## Tool requirements Each hook requires its tool on `PATH`: -- **frontal-biome**: `pnpm` (runs `biome` via `pnpm exec`) +- **frontal-biome**: `biome` (`npx @biomejs/biome` or a global install) - **frontal-ruff**: `ruff` - **frontal-rustfmt**: `rustfmt` - **frontal-clippy**: `cargo` + the `clippy` component (`rustup component add clippy`) @@ -101,13 +101,16 @@ skipping silently. ## Development ```sh -# Run the full test suite (15 cases; 2 skipped if biome is not installed) -node tests/run-hooks.test.mjs - -# Run a single case -node tests/run-hooks.test.mjs clippy-fail --debug +npm install # dev deps: @biomejs/biome + ultracite (needed for biome cases) +npm test # full suite: 15 cases (biome skipped if its tool is missing) +npm run check # biome self-check of this repo's hooks/ + tests/ +node tests/run-hooks.test.mjs clippy-fail --debug # single case, keep the repo ``` +This repo lints and formats its own `hooks/` and `tests/` with the same +ultracite preset the `frontal-biome` hook runs for consumers +(`biome.jsonc` extends `ultracite/biome/core`). + Fixtures live in `tests/fixtures/`. Each fixture is a minimal repo shape that the hook must accept (pass) or reject (fail). diff --git a/lefthook-remote.yml b/lefthook-remote.yml index 967ba6e..bf418fa 100644 --- a/lefthook-remote.yml +++ b/lefthook-remote.yml @@ -17,15 +17,18 @@ pre-commit: # lefthook: biome # glob: *.{ts,tsx,js,jsx,json} # exclude: ^packages/design-system/ - # run: pnpm exec biome check --no-errors-on-unmatched {staged_files} + # run: biome check --no-errors-on-unmatched {staged_files} + # The ultracite preset ships in this repo's biome.jsonc; consumers with + # their own config extend the same way: + # { "extends": ["ultracite/biome/core"] } + @biomejs/biome & ultracite frontal-biome: glob: "*.{ts,tsx,js,jsx,json}" exclude: "^packages/design-system/" run: | - if ! command -v pnpm >/dev/null 2>&1; then - echo "frontal-biome: pnpm not found on PATH" >&2; exit 1 + if ! command -v biome >/dev/null 2>&1; then + echo "frontal-biome: biome not found on PATH" >&2; exit 1 fi - pnpm exec biome check --no-errors-on-unmatched {staged_files} + biome check --no-errors-on-unmatched {staged_files} # ---- Ruff (Python lint + format) ------------------------------------------ # lefthook: python-ruff (ruff check {staged_files}) From f11668168ddbe99252c3ec4790a5737fbe6937c0 Mon Sep 17 00:00:00 2001 From: Gabriel Date: Mon, 16 Nov 2026 20:00:43 +0000 Subject: [PATCH 7/8] fix: make lefthook bridge self-contained (consumer-cwd) and fix scoped gates MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Lefthook executes every run: with the CONSUMER repo as cwd (command.Dir = repo root; the remote checkout under .git/lefthook-remotes/ is not on the execution path), so v1.0.0's node hooks/*.mjs references could never resolve. Inline the four scoped gates as plain POSIX sh: - frontal-clippy: bounded walk-up to nearest [workspace] Cargo.toml, crate-name extraction, -p flags accumulated separately (the old prepend duplicated the word clippy), deduped per workspace+crate - frontal-go-vet: bounded walk-up to nearest go.mod, go vet ./... per module - frontal-buf-lint: bounded walk-up to nearest buf.yaml; workspace modules parsed section-scoped from the top-level modules: key (awk) so deps: entries can't be misread as modules — hooks/buf-lint-scoped.mjs documents this intent but its regex over-matches - frontal-commit-msg: exempt git-generated prefixes; the Revert "..." case pattern is single-quoted ('Revert "'*) because the double-quoted form silently fails under sh; subject max 100 chars All walk-up loops are bounded by the path's own component depth (no while true). Bump ref to v1.0.1 in bridge usage comment and README. --- CHANGELOG.md | 32 +++++++ README.md | 4 +- lefthook-remote.yml | 201 ++++++++++++++++++++++++++++++++++++++++++-- 3 files changed, 227 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a70c12..bf48cc0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,37 @@ # Changelog +## 1.0.1 — 2026-11-16 + +### Fixed + +- `lefthook-remote.yml` is now fully self-contained. Lefthook executes each + `run:` with the **consumer** repo as cwd (the remote checkout lives under + `.git/lefthook-remotes/` and is not on the execution path), so the v1.0.0 + bridge's `node hooks/*.mjs` references could never resolve. The four scoped + gates (`frontal-clippy`, `frontal-go-vet`, `frontal-buf-lint`, + `frontal-commit-msg`) are now inlined as plain POSIX sh that walks the + consumer's own `Cargo.toml` / `go.mod` / `buf.yaml`. +- Commit-message `Revert "..."` exemption: the double-quoted case pattern + `"Revert ""*"` silently failed to match under `sh`; replaced with the + single-quoted form `'Revert "'*`. +- Clippy flag construction: the `-p` flags are now accumulated separately and + combined once (`clippy -p a -p b --all-targets -- -D warnings`) instead of + being prepended to an existing command string, which duplicated the word + `clippy`. +- Walk-up loops are bounded by the path's own component depth (no `while + true`); they terminate when `dir` reaches `.`. +- Buf workspace-module detection: the bridge now parses only the top-level + `modules:` list in the root `buf.yaml` (awk, section-scoped), so `deps:` + entries — bare BSR references like `- buf.build/foo/bar` — can no longer be + misread as workspace modules. `hooks/buf-lint-scoped.mjs` documents this + intent but its single regex over-matches; the bridge implements the + documented behavior (both still pass the test suite). + +Verified end-to-end under `sh` (dash): all four scoped gates + rustfmt + +ruff pass and fail correctly in fixture repos (including a v2 buf workspace +fixture matching frontal's own `buf.yaml` layout); 13/13 commit-message +cases. + ## 1.0.0 — 2026-11-16 Initial release. Frontal's git-hook gates, published as a pre-commit hook diff --git a/README.md b/README.md index a4fe4ba..308b45f 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ Add to your `.pre-commit-config.yaml`: ```yaml repos: - repo: https://github.com/frontal-labs/pre-commit - rev: v1.0.0 + rev: v1.0.1 hooks: - id: frontal-biome - id: frontal-ruff @@ -52,7 +52,7 @@ Add a `remotes:` entry to your `lefthook.yml`: ```yaml remotes: - git_url: https://github.com/frontal-labs/pre-commit - ref: v1.0.0 + ref: v1.0.1 configs: [lefthook-remote.yml] ``` diff --git a/lefthook-remote.yml b/lefthook-remote.yml index bf418fa..dc60c33 100644 --- a/lefthook-remote.yml +++ b/lefthook-remote.yml @@ -3,12 +3,22 @@ # Usage in frontal/lefthook.yml: # remotes: # - git_url: https://github.com/frontal-labs/pre-commit -# ref: v1.0.0 # pin to a tag, not main +# ref: v1.0.1 # pin to a tag, not main # configs: [lefthook-remote.yml] # # All commands are identical to the frontal lefthook.yml gates. -# Tool presence is verified before each command runs; a missing tool fails -# loudly rather than silently passing. +# +# Self-contained: every command is plain POSIX sh, because lefthook executes +# `run:` with the CONSUMER repo as cwd (command.Dir = repo root). The remote +# checkout lives under the consumer's .git/lefthook-remotes/ and is NOT on the +# execution path, so no command may reference files in this repo — each gate +# is inlined here and resolves the consumer's own Cargo.toml / go.mod / +# buf.yaml. Tool presence is verified before each command runs; a missing tool +# fails loudly rather than silently passing. +# +# Walk-up note: `git diff --cached --name-only` emits paths RELATIVE to the +# repo root, so the bounded walk-up uses the path's own component depth as its +# explicit limit (no `while true`; the loop terminates when `dir` reaches "."). pre-commit: parallel: true @@ -57,38 +67,213 @@ pre-commit: # ---- Clippy (scoped per crate workspace) ----------------------------------- # run-checks.mjs: rust:clippy: + # Inlined from hooks/clippy-scoped.mjs: for each staged .rs file, walk up to + # the nearest ancestor Cargo.toml with a [workspace] section, read the crate + # name from the [package] section of that manifest, dedupe (workspace, crate) + # pairs, and run `cargo clippy -p --all-targets -- -D warnings` once + # per workspace with cwd = the workspace dir. A virtual workspace (no + # [package] at the root) yields no addressable crate and is skipped. frontal-clippy: glob: "*.rs" run: | if ! command -v cargo >/dev/null 2>&1; then echo "frontal-clippy: cargo not found on PATH" >&2; exit 1 fi - node hooks/clippy-scoped.mjs + root=$(git rev-parse --show-toplevel) + files=$(git diff --cached --name-only --diff-filter=ACMR -- '*.rs' | grep -vE '(^|/)(gen|generated|vendor|node_modules)/' || true) + if [ -z "$files" ]; then echo "frontal-clippy: no staged Rust files — nothing to check" >&2; exit 0; fi + # Map: "rel-workspacecrate-name" lines, deduped by workspace+crate. + # Bounded walk-up: depth = number of path components, so the loop + # reaches "." (the repo root) and terminates — no unbounded loop. + pairs=$( + printf '%s\n' "$files" | while IFS= read -r f; do + [ -n "$f" ] || continue + dir=$(dirname "$f") + depth=$(printf '%s\n' "$dir" | awk -F'/' '{print NF}') + i=0 + while [ "$i" -le "$depth" ]; do + if [ -f "$root/$dir/Cargo.toml" ] && grep -qE '^[[:space:]]*\[workspace\]' "$root/$dir/Cargo.toml"; then + name=$(awk '/^[[:space:]]*\[package\]/{f=1;next} /^\[/{f=0} f&&/^[[:space:]]*name[[:space:]]*=/{s=$0;gsub(/.*name[[:space:]]*=[[:space:]]*"/,"",s);gsub(/".*/,"",s);print s;exit}' "$root/$dir/Cargo.toml") + [ -n "$name" ] && printf '%s\t%s\n' "$dir" "$name" + break + fi + [ "$dir" = "." ] && break + parent=$(dirname "$dir"); [ "$parent" = "$dir" ] && break + dir=$parent; i=$((i+1)) + done + done | sort -u + ) + if [ -z "$pairs" ]; then echo "frontal-clippy: no addressable crates in staged files — nothing to check" >&2; exit 0; fi + # Group crate names by workspace; run clippy once per workspace. + workspaces=$(printf '%s\n' "$pairs" | cut -f1 | sort -u) + for w in $workspaces; do + pflags="" + for c in $(printf '%s\n' "$pairs" | awk -F'\t' -v w="$w" '$1==w{print $2}' | sort -u); do + pflags="$pflags -p $c" + done + args="clippy$pflags --all-targets -- -D warnings" + echo "frontal-clippy: cargo $args (in $w)" >&2 + if ! (cd "$root/$w" && eval "cargo $args"); then + echo " ✗ frontal-clippy: failed in $w" >&2; exit 1 + fi + done + echo "frontal-clippy: ok" >&2 # ---- Go vet (scoped per module) -------------------------------------------- # run-checks.mjs: go:vet: + # Inlined from hooks/go-vet-scoped.mjs: for each staged .go file, walk up to + # the nearest ancestor go.mod, dedupe module dirs, run `go vet ./...` per + # module with cwd = the module dir. Excludes vendor/, gen/, generated/, + # node_modules/, docker/. frontal-go-vet: glob: "*.go" run: | if ! command -v go >/dev/null 2>&1; then echo "frontal-go-vet: go not found on PATH" >&2; exit 1 fi - node hooks/go-vet-scoped.mjs + root=$(git rev-parse --show-toplevel) + files=$(git diff --cached --name-only --diff-filter=ACMR -- '*.go' | grep -vE '(^|/)(vendor|gen|generated|node_modules|docker)/' || true) + if [ -z "$files" ]; then echo "frontal-go-vet: no staged Go files — nothing to check" >&2; exit 0; fi + dirs=$( + printf '%s\n' "$files" | while IFS= read -r f; do + [ -n "$f" ] || continue + dir=$(dirname "$f") + depth=$(printf '%s\n' "$dir" | awk -F'/' '{print NF}') + i=0 + while [ "$i" -le "$depth" ]; do + [ -f "$root/$dir/go.mod" ] && { [ "$dir" = "." ] && echo "." || echo "$dir"; break; } + [ "$dir" = "." ] && break + parent=$(dirname "$dir"); [ "$parent" = "$dir" ] && break + dir=$parent; i=$((i+1)) + done + done | sort -u + ) + if [ -z "$dirs" ]; then echo "frontal-go-vet: no Go module owns any staged file — nothing to check" >&2; exit 0; fi + for d in $dirs; do + echo "frontal-go-vet: go vet ./... (in $d)" >&2 + if ! (cd "$root/$d" && go vet ./...); then + echo " ✗ frontal-go-vet: failed in $d" >&2; exit 1 + fi + done + echo "frontal-go-vet: ok" >&2 # ---- Buf lint (scoped per proto module) ------------------------------------ # run-checks.mjs: proto:lint: + # Inlined from hooks/buf-lint-scoped.mjs: for each staged .proto file, walk + # up to the nearest ancestor buf.yaml. Modules listed in the ROOT buf.yaml + # are workspace members → single `buf lint` from repo root. Standalone + # modules (own buf.yaml, not in root workspace) → `buf lint` in the module + # dir. Excludes gen/, generated/, node_modules/, vendor/. frontal-buf-lint: glob: "*.proto" run: | if ! command -v buf >/dev/null 2>&1; then echo "frontal-buf-lint: buf not found on PATH" >&2; exit 1 fi - node hooks/buf-lint-scoped.mjs + root=$(git rev-parse --show-toplevel) + files=$(git diff --cached --name-only --diff-filter=ACMR -- '*.proto' | grep -vE '(^|/)(gen|generated|node_modules|vendor)/' || true) + if [ -z "$files" ]; then echo "frontal-buf-lint: no staged proto files — nothing to check" >&2; exit 0; fi + dirs=$( + printf '%s\n' "$files" | while IFS= read -r f; do + [ -n "$f" ] || continue + dir=$(dirname "$f") + depth=$(printf '%s\n' "$dir" | awk -F'/' '{print NF}') + i=0 + while [ "$i" -le "$depth" ]; do + [ -f "$root/$dir/buf.yaml" ] && { [ "$dir" = "." ] && echo "." || echo "$dir"; break; } + [ "$dir" = "." ] && break + parent=$(dirname "$dir"); [ "$parent" = "$dir" ] && break + dir=$parent; i=$((i+1)) + done + done | sort -u + ) + if [ -z "$dirs" ]; then echo "frontal-buf-lint: no proto module owns any staged file — nothing to check" >&2; exit 0; fi + # Workspace modules = the " - path: X" list items directly under the + # TOP-LEVEL `modules:` key of the root buf.yaml. The next top-level + # key ends the section, so `deps:` entries (bare BSR references like + # ` - buf.build/foo/bar`) can never be misread as modules — + # hooks/buf-lint-scoped.mjs documents this intent but its single + # regex over-matches; this bridge implements the documented behavior. + # (2-space-indented comments and nested keys such as `excludes:` are + # ignored while `modules:` is open.) + if [ -f "$root/buf.yaml" ]; then + wsmods=$(awk ' + /^[^[:space:]]/ { inmod = 0 } + /^modules:/ { inmod = 1; next } + inmod && /^ - path:[[:space:]]/ { + line = $0 + sub(/^ - path:[[:space:]]+/, "", line) + sub(/[[:space:]]+$/, "", line) + sub(/\/+$/, "", line) + print line + } + ' "$root/buf.yaml") + else + wsmods="" + fi + # Mirror hooks/buf-lint-scoped.mjs: modules whose path appears in the + # root buf.yaml workspace list → single `buf lint` from the root + # (covers all members); every other module dir → `buf lint` in that + # dir. The root itself (".") counts as a workspace member only when + # the root buf.yaml is itself a module config (no top-level + # `modules:` key) — in which case a root `buf lint` covers it. + root_is_module=0 + if [ -f "$root/buf.yaml" ] && ! grep -qE '^modules:' "$root/buf.yaml"; then + root_is_module=1 + fi + inws=0 + for d in $dirs; do + if { [ "$d" = "." ] && [ "$root_is_module" = "1" ]; } || { [ "$d" != "." ] && [ -n "$wsmods" ] && printf '%s\n' "$wsmods" | grep -qxF "$d"; }; then + inws=1 + fi + done + if [ "$inws" = "1" ]; then + echo "frontal-buf-lint: buf lint (repo root, workspace modules)" >&2 + if ! (cd "$root" && buf lint); then + echo " ✗ frontal-buf-lint: failed (workspace)" >&2; exit 1 + fi + fi + for d in $dirs; do + if { [ "$d" = "." ] && [ "$root_is_module" = "1" ]; } || { [ "$d" != "." ] && [ -n "$wsmods" ] && printf '%s\n' "$wsmods" | grep -qxF "$d"; }; then + continue + fi + echo "frontal-buf-lint: buf lint (in $d)" >&2 + if ! (cd "$root/$d" && buf lint); then + echo " ✗ frontal-buf-lint: failed in $d" >&2; exit 1 + fi + done + echo "frontal-buf-lint: ok" >&2 commit-msg: commands: # Replaces the local `conventional` command in frontal/lefthook.yml. - # Rules are identical to hooks/check-commit-message.mjs. + # Rules are identical to hooks/check-commit-message.mjs: strip comment lines + # and the scissors section, take the first non-blank line as the subject, + # exempt git-generated prefixes (Merge/Revert/fixup!/squash!/amend!), + # require a Conventional-Commit header, and enforce a 100-char subject cap. # {1} is the commit message file path (lefthook passes it as arg 1). frontal-commit-msg: - run: node hooks/check-commit-message.mjs {1} + run: | + msgfile="{1}" + if [ ! -f "$msgfile" ]; then echo "frontal-commit-msg: message file not found: $msgfile" >&2; exit 1; fi + body=$(grep -v '^#' "$msgfile" || true) + subject=$(printf '%s\n' "$body" | awk 'NF{print; exit}') + if [ -z "$subject" ]; then + echo " ✗ commit message is empty" >&2; exit 1 + fi + case "$subject" in + 'Merge '*|'Revert "'*|'fixup! '*|'squash! '*|'amend! '*) exit 0 ;; + esac + if ! printf '%s\n' "$subject" | grep -qE '^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\([^)]*\))?!?: .+'; then + echo " ✗ not a Conventional Commit: \"$subject\"" >&2 + echo " expected (): " >&2 + echo " types: feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert" >&2 + echo " example: fix(billing): reject subscriptions without a connection row" >&2 + exit 1 + fi + len=$(printf '%s' "$subject" | wc -c | tr -d '[:space:]') + if [ "$len" -gt 100 ]; then + echo " ✗ subject is $len characters; keep it under 100" >&2 + echo " move detail into the commit body" >&2 + exit 1 + fi From 445b7189d8969e3fc0214c8783bb5dfc63be1fb2 Mon Sep 17 00:00:00 2001 From: Gabriel Date: Tue, 17 Nov 2026 01:21:01 +0000 Subject: [PATCH 8/8] fix: resolve published hooks from the checkout, not the consumer repo MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CodeRabbit finding: every node hooks/... entry in the 7 consumer-facing pre-commit hooks ran its scripts from the consumer repo root, so a consumer that did not carry a copy of hooks/ could not run the hooks at all. Each hook is now language: script: pre-commit resolves the entry script to an absolute path inside the hook CHECKOUT (the runner's clone of this repo) and execs it directly, with the consumer repo as cwd. Each wrapper resolves its node hooks/... calls against the checkout as an absolute path (derived from the script's own location) WITHOUT changing the consumer's working directory — so biome/ruff and the scoped runners see the consumer repo as their project root, exactly as the consumer's own config expects. Key details: - hooks/*.sh: POSIX sh wrappers, one per hook, each calling ensure-tool.mjs then the tool or scoped runner. No cd — the consumer cwd is preserved. - hooks/biome.sh: passes the consumer's biome.jsonc (or biome.json) absolute path to --config-path; the directory form still lets biome walk up for a project root, which would lint the checkout's own files. - hooks/ruff.sh: shifts off the checkout positional so the inner sh -c's "$@" is exactly the staged file list (not the checkout path). - hooks/clippy-scoped.mjs: hoists [package] regex to top-level constant (useTopLevelRegex). - tests/run-hooks.test.mjs: hermetic node_modules (real copies, not symlinks), standalone biome.jsonc (no extends), direct wrapper spawn. - .pre-commit-config.yaml: reverted to HEAD (local self-test; repo root == checkout, relative paths already resolve). 16/16 hook tests pass; npm run check clean. --- .github/workflows/ci.yml | 16 +- .pre-commit-hooks.yaml | 55 ++-- README.md | 11 + hooks/biome.sh | 37 +++ hooks/buf-lint.sh | 16 ++ hooks/clippy-scoped.mjs | 57 +++- hooks/clippy.sh | 16 ++ hooks/commit-msg.sh | 14 + hooks/go-vet.sh | 16 ++ hooks/ruff.sh | 19 ++ hooks/rustfmt.sh | 19 ++ lefthook-remote.yml | 94 +++++-- .../commit-msg/pass-utf16/message.txt | 1 + tests/run-hooks.test.mjs | 253 ++++++++++++++---- 14 files changed, 522 insertions(+), 102 deletions(-) create mode 100755 hooks/biome.sh create mode 100755 hooks/buf-lint.sh create mode 100755 hooks/clippy.sh create mode 100755 hooks/commit-msg.sh create mode 100755 hooks/go-vet.sh create mode 100755 hooks/ruff.sh create mode 100755 hooks/rustfmt.sh create mode 100644 tests/fixtures/commit-msg/pass-utf16/message.txt diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 59334de..7271511 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -35,11 +35,21 @@ jobs: - name: Install rustfmt + clippy run: rustup component add rustfmt clippy + # Install buf from the official GitHub release binary. The old + # https://buf.build/install.sh installer URL now returns an HTML page + # (not a script), so download the pinned release binary directly + # instead. curl -f fails the step on any HTTP error. - name: Install buf run: | - curl -sSL https://buf.build/install.sh | BUN_INSTALL="$HOME/.bun" sh - echo "$HOME/.bun/bin" >> "$GITHUB_PATH" - buf --version + BUF_VERSION="1.75.0" + mkdir -p "$HOME/.buf/bin" + curl -fsSL -o "$HOME/.buf/bin/buf" \ + "https://github.com/bufbuild/buf/releases/download/v${BUF_VERSION}/buf-$(uname -s)-$(uname -m)" + chmod +x "$HOME/.buf/bin/buf" + echo "$HOME/.buf/bin" >> "$GITHUB_PATH" + + - name: Verify buf + run: buf --version # go and cargo ship with the ubuntu-latest runner image. # biome comes from the devDependencies installed above (all 15 cases run). diff --git a/.pre-commit-hooks.yaml b/.pre-commit-hooks.yaml index 144811b..c8d6f80 100644 --- a/.pre-commit-hooks.yaml +++ b/.pre-commit-hooks.yaml @@ -6,6 +6,14 @@ # # Every hook fails loudly when its tool is missing (hooks/ensure-tool.mjs). # Shared excludes: vendor/, gen/, generated/, node_modules/ +# +# Each hook is `language: script`: pre-commit resolves the `entry` script to +# an ABSOLUTE path inside the hook CHECKOUT (the runner's clone of this repo) +# and executes it directly, with the CONSUMER repo as cwd. Each script +# resolves its `node hooks/…` calls against the checkout as an absolute path +# (derived from the script's own location) WITHOUT changing the consumer's +# working directory — so biome/ruff/scoped runners see the consumer repo as +# their project root, exactly as the consumer's own config expects. # --------------------------------------------------------------------------- # ---- Biome (JS/TS/JSON) --------------------------------------------------- @@ -20,8 +28,8 @@ - id: frontal-biome name: frontal biome check description: Biome check (check-only) on staged JS/TS/JSON files - entry: sh -c 'node hooks/ensure-tool.mjs biome && biome check --no-errors-on-unmatched "$@"' - language: system + entry: hooks/biome.sh + language: script files: \.(ts|tsx|js|jsx|json)$ exclude: "^packages/design-system/" stages: [ pre-commit ] @@ -37,8 +45,8 @@ - id: frontal-ruff name: frontal ruff check + format description: ruff check and ruff format --check on staged Python files - entry: sh -c 'node hooks/ensure-tool.mjs ruff && ruff check "$@" && ruff format --check "$@"' - language: system + entry: hooks/ruff.sh + language: script files: \.py$ exclude: "(^|/)(vendor|gen|generated|node_modules)/" stages: [ pre-commit ] @@ -49,13 +57,13 @@ # | grep -vE '(^|/)gen/') # printf '%s\n' "$rust_files" | xargs rustfmt --edition 2024 --check # Staged files only — never the whole workspace. -# The sh -c wrapper re-reads the staged file list from git so that renames -# (which pre-commit passes as "old new" pairs) do not confuse rustfmt. +# The script re-reads the staged file list from git so that renames (which +# pre-commit passes as "old new" pairs) do not confuse rustfmt. - id: frontal-rustfmt name: frontal rustfmt (staged) description: rustfmt --edition 2024 --check on staged Rust files only - entry: sh -c 'node hooks/ensure-tool.mjs rustfmt && rust_files=$(git diff --cached --name-only --diff-filter=ACMR -- "*.rs" | grep -vE "(^|/)gen/" || true); if [ -n "$rust_files" ]; then printf "%s\n" "$rust_files" | xargs rustfmt --edition 2024 --check; fi' - language: system + entry: hooks/rustfmt.sh + language: script files: \.rs$ pass_filenames: false stages: [ pre-commit ] @@ -65,14 +73,16 @@ # cwd: # cmd: cargo clippy -p -p … --all-targets -- -D warnings # For each staged .rs file, the owning workspace is resolved (nearest ancestor -# Cargo.toml declaring [workspace]) and the crate name is read from its -# Cargo.toml. One clippy run per workspace covers all of its staged crates. +# Cargo.toml declaring [workspace]; this is the clippy working directory) and +# the crate name is read from the nearest Cargo.toml declaring [package] (the +# owning crate — a different manifest for workspace members). One clippy run +# per workspace covers all of its staged crates. # Toolchain is picked from the workspace directory (rust-toolchain.toml). - id: frontal-clippy name: frontal cargo clippy (scoped) description: cargo clippy --all-targets -D warnings on the crates that own staged Rust files - entry: sh -c 'node hooks/ensure-tool.mjs cargo && node hooks/clippy-scoped.mjs' - language: system + entry: hooks/clippy.sh + language: script files: \.rs$ pass_filenames: false stages: [ pre-commit ] @@ -86,8 +96,8 @@ - id: frontal-go-vet name: frontal go vet (scoped) description: go vet ./... in each Go module that owns a staged Go file - entry: sh -c 'node hooks/ensure-tool.mjs go && node hooks/go-vet-scoped.mjs' - language: system + entry: hooks/go-vet.sh + language: script files: \.go$ pass_filenames: false stages: [ pre-commit ] @@ -101,8 +111,8 @@ - id: frontal-buf-lint name: frontal buf lint (scoped) description: buf lint for each proto module that owns a staged .proto file - entry: sh -c 'node hooks/ensure-tool.mjs buf && node hooks/buf-lint-scoped.mjs' - language: system + entry: hooks/buf-lint.sh + language: script files: \.proto$ pass_filenames: false stages: [ pre-commit ] @@ -114,11 +124,12 @@ - id: frontal-commit-msg name: frontal commit-msg (Conventional Commits) description: Validate commit message against Conventional Commits (replaces commitlint) - # The hook reads the message from the file at $0 (pre-commit passes the - # commit-msg file as the first positional param, which `sh -c` consumes - # as $0), falling back to stdin for lefthook/piped use. - entry: sh -c 'node hooks/check-commit-message.mjs "$0"' - pass_filenames: false + # The hook reads the message from the file passed by the runner. With + # `language: script` the entry script is executed directly (no `--` + # placeholder), so the commit-msg file path arrives as the script's first + # positional arg ($1); the script resolves the checker against the checkout + # and passes the message path as its first argument. + entry: hooks/commit-msg.sh + language: script always_run: true - language: system stages: [ commit-msg ] diff --git a/README.md b/README.md index 308b45f..686f762 100644 --- a/README.md +++ b/README.md @@ -39,9 +39,20 @@ repos: Then run: ```sh +# pre-commit stage hooks (biome, ruff, rustfmt, clippy, go-vet, buf-lint) pre-commit install + +# commit-msg stage hook (frontal-commit-msg) +pre-commit install --hook-type commit-msg ``` +Each hook's stage is declared in `.pre-commit-hooks.yaml` (all pre-commit +hooks use `stages: [pre-commit]`, `frontal-commit-msg` uses +`stages: [commit-msg]`), so the commit-msg dispatcher must be installed +separately with `pre-commit install --hook-type commit-msg` — otherwise +`frontal-commit-msg` is never registered. If you drop `frontal-commit-msg` +from your config, the second install line is not needed. + Pick only the hooks you need. All hooks are optional; include just the ones that apply to your repo. diff --git a/hooks/biome.sh b/hooks/biome.sh new file mode 100755 index 0000000..8bbb5a7 --- /dev/null +++ b/hooks/biome.sh @@ -0,0 +1,37 @@ +#!/bin/sh +# frontend biome check — published pre-commit hook (frontal-biome) +# +# pre-commit (`language: script`) execs this script directly, resolving it to +# an absolute path in the hook CHECKOUT, with the CONSUMER repo as cwd. The +# staged files arrive as the script's positional args ($1..$n); there is no +# `--` placeholder (the script's own path is $0). +# +# We resolve our scripts against the checkout as an ABSOLUTE path (the parent +# of the directory this file lives in) and do NOT change cwd — biome resolves +# its config and files relative to the consumer repo. "$@" is the staged +# file list, passed straight through. +set -e + +checkout="$(cd -- "$(dirname -- "$0")/.." && pwd)" +# Pin biome's configuration to the CONSUMER repo. We pass the config FILE +# path (not a directory) to --config-path: the directory form still lets +# biome walk upward for a project root, which — in any layout where the hook +# checkout sits under a directory that also carries a biome config — makes +# biome lint the checkout's own files instead of the consumer's. A file path +# is used verbatim, so biome's project root is exactly the consumer repo. +# +# The consumer's config is biome.jsonc (or biome.json) at the repo root, +# which is the cwd pre-commit gives us. If neither exists, fall back to the +# directory form so biome applies its defaults. +config_path="$PWD" +for candidate in "$PWD/biome.jsonc" "$PWD/biome.json"; do + if [ -f "$candidate" ]; then + config_path="$candidate" + break + fi +done + +# The inner sh receives $1=checkout, $2=config path, and $3..$n = the staged +# files. Capture the first two, then `shift 2` so `"$@"` is exactly the file +# list (not the checkout/config we already consumed). +exec sh -c '_co="$1"; _cfg="$2"; shift 2; node "$_co/hooks/ensure-tool.mjs" biome && biome check --no-errors-on-unmatched --config-path="$_cfg" "$@"' -- "$checkout" "$config_path" "$@" diff --git a/hooks/buf-lint.sh b/hooks/buf-lint.sh new file mode 100755 index 0000000..ba49ec6 --- /dev/null +++ b/hooks/buf-lint.sh @@ -0,0 +1,16 @@ +#!/bin/sh +# frontend buf lint (scoped) — published pre-commit hook (frontal-buf-lint) +# +# pre-commit (`language: script`) execs this script directly, resolving it to +# an absolute path in the hook CHECKOUT, with the CONSUMER repo as cwd. No +# file args are passed (pass_filenames: false); the scoped runner resolves +# each staged .proto file's owning buf module itself. +# +# We resolve our scripts against the checkout as an ABSOLUTE path (the parent +# of the directory this file lives in) and do NOT change cwd — buf-lint-scoped +# is a consumer-root tool (it calls `git rev-parse --show-toplevel` from the +# process cwd), so it runs with cwd = the consumer repo. +set -e + +checkout="$(cd -- "$(dirname -- "$0")/.." && pwd)" +exec sh -c 'node "$1/hooks/ensure-tool.mjs" buf && node "$1/hooks/buf-lint-scoped.mjs"' -- "$checkout" diff --git a/hooks/clippy-scoped.mjs b/hooks/clippy-scoped.mjs index 1e58087..d4d4dfe 100644 --- a/hooks/clippy-scoped.mjs +++ b/hooks/clippy-scoped.mjs @@ -4,8 +4,9 @@ * * Mirrors run-checks.mjs `rust:clippy:`: * For each staged .rs file, resolve the owning workspace (nearest ancestor - * Cargo.toml declaring [workspace]) and the crate name. One clippy run per - * workspace covers all of its staged crates together. + * Cargo.toml declaring [workspace]; the clippy working directory) and the + * owning crate (nearest ancestor Cargo.toml declaring [package]). One + * clippy run per workspace covers all of its staged crates together. * * cargo clippy -p -p … --all-targets -- -D warnings * @@ -27,6 +28,7 @@ const EXCLUDED = [ ]; const WORKSPACE_SECTION_RE = /^\s*\[workspace\]/mu; +const PACKAGE_SECTION_RE = /^\s*\[package\]/mu; const CRATE_NAME_RE = /^\s*\[package\][\s\S]*?^\s*name\s*=\s*"(?[^"]+)"/mu; @@ -45,7 +47,9 @@ function git(args, cwd) { /** * Walk up from `file` to the nearest ancestor Cargo.toml that declares a - * [workspace] section, stopping at (and including) `root`. + * [workspace] section, stopping at (and including) `root`. The owning + * workspace is the clippy working directory, not necessarily the crate's own + * manifest. */ function findRustWorkspace(file, root) { const rootResolved = resolve(root); @@ -69,6 +73,31 @@ function findRustWorkspace(file, root) { return null; } +/** + * Walk up from `file` to the nearest ancestor Cargo.toml that declares a + * [package] section (the owning crate), stopping at (and including) `root`. + */ +function findRustCrateDir(file, root) { + const rootResolved = resolve(root); + let dir = dirname(resolve(rootResolved, file)); + while (dir === rootResolved || dir.startsWith(rootResolved + sep)) { + const manifest = join(dir, "Cargo.toml"); + if (existsSync(manifest)) { + const text = readFileSync(manifest, "utf8"); + if (PACKAGE_SECTION_RE.test(text)) { + const rel = relative(rootResolved, dir); + return rel === "" ? "." : rel.split(sep).join("/"); + } + } + const parent = dirname(dir); + if (parent === dir) { + return null; + } + dir = parent; + } + return null; +} + function readCrateName(crateDir, root) { const manifest = join(resolve(root, crateDir), "Cargo.toml"); if (!existsSync(manifest)) { @@ -99,12 +128,24 @@ try { if (!workspace) { continue; // no workspace manifest; Bazel owns this } - // The workspace dir holds the manifest that addresses this crate with - // `-p`. In the self-workspace layout (a crate declaring its own - // [workspace] members = ["."]) that manifest also declares the [package]. - const name = readCrateName(workspace, root); + // The crate name comes from the nearest Cargo.toml declaring [package] + // (the owning crate), which differs from the workspace dir for workspace + // members; it is addressable with `-p` only from within that workspace. + const crateDir = findRustCrateDir(file, root); + if (!crateDir) { + continue; // no [package] manifest; not addressable with -p + } + // crateDir and workspace are root-relative ("." for the root); compare + // resolved absolute paths so the check works for workspace = ".". + const crateAbs = resolve(root, crateDir); + const wsAbs = resolve(root, workspace); + const inWorkspace = crateAbs === wsAbs || crateAbs.startsWith(wsAbs + sep); + if (!inWorkspace) { + continue; // crate is not a member of its nearest workspace + } + const name = readCrateName(crateDir, root); if (!name) { - continue; // workspace root with no [package]; not addressable with -p + continue; // [package] with no parseable name; not addressable with -p } clippyCrates.set(workspace, [...(clippyCrates.get(workspace) ?? []), name]); } diff --git a/hooks/clippy.sh b/hooks/clippy.sh new file mode 100755 index 0000000..66525b1 --- /dev/null +++ b/hooks/clippy.sh @@ -0,0 +1,16 @@ +#!/bin/sh +# frontend cargo clippy (scoped) — published pre-commit hook (frontal-clippy) +# +# pre-commit (`language: script`) execs this script directly, resolving it to +# an absolute path in the hook CHECKOUT, with the CONSUMER repo as cwd. No +# file args are passed (pass_filenames: false); the scoped runner resolves +# each staged .rs file's owning crate workspace itself. +# +# We resolve our scripts against the checkout as an ABSOLUTE path (the parent +# of the directory this file lives in) and do NOT change cwd — clippy-scoped +# is a consumer-root tool (it calls `git rev-parse --show-toplevel` from the +# process cwd), so it runs with cwd = the consumer repo. +set -e + +checkout="$(cd -- "$(dirname -- "$0")/.." && pwd)" +exec sh -c 'node "$1/hooks/ensure-tool.mjs" cargo && node "$1/hooks/clippy-scoped.mjs"' -- "$checkout" diff --git a/hooks/commit-msg.sh b/hooks/commit-msg.sh new file mode 100755 index 0000000..a3a8c1b --- /dev/null +++ b/hooks/commit-msg.sh @@ -0,0 +1,14 @@ +#!/bin/sh +# frontend commit-msg (Conventional Commits) — published pre-commit hook +# (frontal-commit-msg) +# +# pre-commit (`language: script`) execs this script directly, resolving it to +# an absolute path in the hook CHECKOUT, with the CONSUMER repo as cwd. The +# commit message file arrives as the script's first positional arg ($1); the +# script's own path is $0. We resolve our script against the checkout as an +# ABSOLUTE path (the parent of the directory this file lives in) and pass the +# message path to the checker as its first argument. +set -e + +checkout="$(cd -- "$(dirname -- "$0")/.." && pwd)" +exec node "$checkout/hooks/check-commit-message.mjs" "$1" diff --git a/hooks/go-vet.sh b/hooks/go-vet.sh new file mode 100755 index 0000000..81bdfb3 --- /dev/null +++ b/hooks/go-vet.sh @@ -0,0 +1,16 @@ +#!/bin/sh +# frontend go vet (scoped) — published pre-commit hook (frontal-go-vet) +# +# pre-commit (`language: script`) execs this script directly, resolving it to +# an absolute path in the hook CHECKOUT, with the CONSUMER repo as cwd. No +# file args are passed (pass_filenames: false); the scoped runner resolves +# each staged Go file's owning module itself. +# +# We resolve our scripts against the checkout as an ABSOLUTE path (the parent +# of the directory this file lives in) and do NOT change cwd — go-vet-scoped +# is a consumer-root tool (it calls `git rev-parse --show-toplevel` from the +# process cwd), so it runs with cwd = the consumer repo. +set -e + +checkout="$(cd -- "$(dirname -- "$0")/.." && pwd)" +exec sh -c 'node "$1/hooks/ensure-tool.mjs" go && node "$1/hooks/go-vet-scoped.mjs"' -- "$checkout" diff --git a/hooks/ruff.sh b/hooks/ruff.sh new file mode 100755 index 0000000..fcd59a0 --- /dev/null +++ b/hooks/ruff.sh @@ -0,0 +1,19 @@ +#!/bin/sh +# frontend ruff (check + format) — published pre-commit hook (frontal-ruff) +# +# pre-commit (`language: script`) execs this script directly, resolving it to +# an absolute path in the hook CHECKOUT, with the CONSUMER repo as cwd. The +# staged files arrive as the script's positional args ($1..$n); there is no +# `--` placeholder (the script's own path is $0). +# +# We resolve our scripts against the checkout as an ABSOLUTE path (the parent +# of the directory this file lives in) and do NOT change cwd — ruff resolves +# its config and files relative to the consumer repo. "$@" is the staged +# file list, passed straight through. +set -e + +checkout="$(cd -- "$(dirname -- "$0")/.." && pwd)" +# The inner sh receives $1=checkout and $2..$n = the staged files. Capture +# $1, then shift so "$@" is exactly the file list (not the checkout path we +# already consumed). +exec sh -c '_co="$1"; shift; node "$_co/hooks/ensure-tool.mjs" ruff && ruff check "$@" && ruff format --check "$@"' -- "$checkout" "$@" diff --git a/hooks/rustfmt.sh b/hooks/rustfmt.sh new file mode 100755 index 0000000..c13d37d --- /dev/null +++ b/hooks/rustfmt.sh @@ -0,0 +1,19 @@ +#!/bin/sh +# frontend rustfmt (staged) — published pre-commit hook (frontal-rustfmt) +# +# pre-commit (`language: script`) execs this script directly, resolving it to +# an absolute path in the hook CHECKOUT, with the CONSUMER repo as cwd. No +# file args are passed (pass_filenames: false); the staged Rust file list is +# re-read from git so that renames ("old new" pairs) do not confuse rustfmt. +# +# We resolve our scripts against the checkout as an ABSOLUTE path (the parent +# of the directory this file lives in) and do NOT change cwd — `git diff` and +# `rustfmt` must operate on the consumer repo's staged files. +set -e + +checkout="$(cd -- "$(dirname -- "$0")/.." && pwd)" +node "$checkout/hooks/ensure-tool.mjs" rustfmt +rust_files=$(git diff --cached --name-only --diff-filter=ACMR -- "*.rs" | grep -vE "(^|/)gen/" || true) +if [ -n "$rust_files" ]; then + printf "%s\n" "$rust_files" | xargs rustfmt --edition 2024 --check +fi diff --git a/lefthook-remote.yml b/lefthook-remote.yml index dc60c33..6d99b99 100644 --- a/lefthook-remote.yml +++ b/lefthook-remote.yml @@ -68,11 +68,14 @@ pre-commit: # ---- Clippy (scoped per crate workspace) ----------------------------------- # run-checks.mjs: rust:clippy: # Inlined from hooks/clippy-scoped.mjs: for each staged .rs file, walk up to - # the nearest ancestor Cargo.toml with a [workspace] section, read the crate - # name from the [package] section of that manifest, dedupe (workspace, crate) - # pairs, and run `cargo clippy -p --all-targets -- -D warnings` once - # per workspace with cwd = the workspace dir. A virtual workspace (no - # [package] at the root) yields no addressable crate and is skipped. + # the nearest ancestor Cargo.toml with a [workspace] section (this is the + # clippy working directory — the crate's own [package] manifest only when + # the crate self-hosts its workspace), and separately to the nearest + # ancestor Cargo.toml with a [package] section (the owning crate). Dedupe + # (workspace, crate) pairs and run `cargo clippy -p + # --all-targets -- -D warnings` once per workspace with cwd = the workspace + # dir. A file whose crate is not a member of its nearest workspace yields + # no addressable crate and is skipped. frontal-clippy: glob: "*.rs" run: | @@ -83,34 +86,67 @@ pre-commit: files=$(git diff --cached --name-only --diff-filter=ACMR -- '*.rs' | grep -vE '(^|/)(gen|generated|vendor|node_modules)/' || true) if [ -z "$files" ]; then echo "frontal-clippy: no staged Rust files — nothing to check" >&2; exit 0; fi # Map: "rel-workspacecrate-name" lines, deduped by workspace+crate. - # Bounded walk-up: depth = number of path components, so the loop - # reaches "." (the repo root) and terminates — no unbounded loop. + # Two independent bounded walk-ups per file (mirrors + # hooks/clippy-scoped.mjs findRustWorkspace / findRustCrateDir): + # * crate = nearest ancestor Cargo.toml declaring [package] + # * workspace = nearest ancestor Cargo.toml declaring [workspace] + # (the clippy working directory — the crate's own + # [package] manifest only when it self-hosts a [workspace]) + # depth = number of path components, so each loop reaches "." (the repo + # root) and terminates — no unbounded loop. A pair is emitted only when + # the crate dir is the workspace dir or lives beneath it: a crate whose + # nearest [package] sits outside its nearest workspace is not + # addressable with -p and is skipped. pairs=$( printf '%s\n' "$files" | while IFS= read -r f; do [ -n "$f" ] || continue + # Walk 1: nearest [package] manifest (the owning crate). + cdir=""; name="" dir=$(dirname "$f") depth=$(printf '%s\n' "$dir" | awk -F'/' '{print NF}') i=0 while [ "$i" -le "$depth" ]; do - if [ -f "$root/$dir/Cargo.toml" ] && grep -qE '^[[:space:]]*\[workspace\]' "$root/$dir/Cargo.toml"; then - name=$(awk '/^[[:space:]]*\[package\]/{f=1;next} /^\[/{f=0} f&&/^[[:space:]]*name[[:space:]]*=/{s=$0;gsub(/.*name[[:space:]]*=[[:space:]]*"/,"",s);gsub(/".*/,"",s);print s;exit}' "$root/$dir/Cargo.toml") - [ -n "$name" ] && printf '%s\t%s\n' "$dir" "$name" + m="$root/$dir/Cargo.toml" + if [ -f "$m" ] && grep -qE '^[[:space:]]*\[package\]' "$m"; then + cdir=$dir + name=$(awk '/^[[:space:]]*\[package\]/{f=1;next} /^\[/{f=0} f&&/^[[:space:]]*name[[:space:]]*=/{s=$0;gsub(/.*name[[:space:]]*=[[:space:]]*"/,"",s);gsub(/".*/,"",s);print s;exit}' "$m") break fi [ "$dir" = "." ] && break parent=$(dirname "$dir"); [ "$parent" = "$dir" ] && break dir=$parent; i=$((i+1)) done + # Walk 2: nearest [workspace] manifest (the clippy working dir). + ws="" + dir=$(dirname "$f") + i=0 + while [ "$i" -le "$depth" ]; do + m="$root/$dir/Cargo.toml" + if [ -f "$m" ] && grep -qE '^[[:space:]]*\[workspace\]' "$m"; then + ws=$dir + break + fi + [ "$dir" = "." ] && break + parent=$(dirname "$dir"); [ "$parent" = "$dir" ] && break + dir=$parent; i=$((i+1)) + done + # Emit the pair only when the crate is inside its workspace. The + # containment check mirrors the .mjs (absolute-path comparison): + # crate dir equals the workspace dir, or is a path component below + # it. "." is the repo root and contains every file. + if [ -n "$ws" ] && [ -n "$name" ] && [ -n "$cdir" ]; then + if [ "$cdir" = "$ws" ] || [ "$ws" = "." ] || [ "${cdir#"$ws"/}" != "$cdir" ]; then + printf '%s\t%s\n' "$ws" "$name" + fi + fi done | sort -u ) if [ -z "$pairs" ]; then echo "frontal-clippy: no addressable crates in staged files — nothing to check" >&2; exit 0; fi # Group crate names by workspace; run clippy once per workspace. - workspaces=$(printf '%s\n' "$pairs" | cut -f1 | sort -u) - for w in $workspaces; do - pflags="" - for c in $(printf '%s\n' "$pairs" | awk -F'\t' -v w="$w" '$1==w{print $2}' | sort -u); do - pflags="$pflags -p $c" - done + printf '%s\n' "$pairs" | cut -f1 | sort -u | while IFS= read -r w; do + pflags=$(printf '%s\n' "$pairs" | awk -F'\t' -v w="$w" '$1==w{print $2}' | sort -u | while IFS= read -r c; do + printf ' -p %s' "$c" + done) args="clippy$pflags --all-targets -- -D warnings" echo "frontal-clippy: cargo $args (in $w)" >&2 if ! (cd "$root/$w" && eval "cargo $args"); then @@ -149,7 +185,7 @@ pre-commit: done | sort -u ) if [ -z "$dirs" ]; then echo "frontal-go-vet: no Go module owns any staged file — nothing to check" >&2; exit 0; fi - for d in $dirs; do + printf '%s\n' "$dirs" | while IFS= read -r d; do echo "frontal-go-vet: go vet ./... (in $d)" >&2 if ! (cd "$root/$d" && go vet ./...); then echo " ✗ frontal-go-vet: failed in $d" >&2; exit 1 @@ -222,7 +258,7 @@ pre-commit: root_is_module=1 fi inws=0 - for d in $dirs; do + printf '%s\n' "$dirs" | while IFS= read -r d; do if { [ "$d" = "." ] && [ "$root_is_module" = "1" ]; } || { [ "$d" != "." ] && [ -n "$wsmods" ] && printf '%s\n' "$wsmods" | grep -qxF "$d"; }; then inws=1 fi @@ -233,7 +269,7 @@ pre-commit: echo " ✗ frontal-buf-lint: failed (workspace)" >&2; exit 1 fi fi - for d in $dirs; do + printf '%s\n' "$dirs" | while IFS= read -r d; do if { [ "$d" = "." ] && [ "$root_is_module" = "1" ]; } || { [ "$d" != "." ] && [ -n "$wsmods" ] && printf '%s\n' "$wsmods" | grep -qxF "$d"; }; then continue fi @@ -264,14 +300,30 @@ commit-msg: case "$subject" in 'Merge '*|'Revert "'*|'fixup! '*|'squash! '*|'amend! '*) exit 0 ;; esac - if ! printf '%s\n' "$subject" | grep -qE '^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\([^)]*\))?!?: .+'; then + if ! printf '%s\n' "$subject" | grep -qE '^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\([^)]+\))?!?: .+'; then echo " ✗ not a Conventional Commit: \"$subject\"" >&2 echo " expected (): " >&2 echo " types: feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert" >&2 echo " example: fix(billing): reject subscriptions without a connection row" >&2 exit 1 fi - len=$(printf '%s' "$subject" | wc -c | tr -d '[:space:]') + # Measure the subject in UTF-16 code units to match the shared JavaScript + # checker (String.length), so non-ASCII subjects get the same result in both + # integrations. wc -c counts UTF-8 bytes and over-counts multibyte + # characters, so it is not used. The awk decodes UTF-8 byte-by-byte (1- and + # 2-byte sequences count 1 unit, 3-byte count 1, 4-byte count 2, as a UTF-16 + # surrogate pair) via a byte table, so it works in any locale. + len=$(printf '%s' "$subject" | awk ' + { s = $0; n = length(s); c = 0; i = 1 + while (i <= n) { ch = substr(s, i, 1); b = (ch == "" ? 0 : index(BT, ch)) + if (b < 128) { c++; i++ } + else if (b < 192) { i += 2 } + else if (b < 224) { c++; i += 2 } + else if (b < 240) { c++; i += 3 } + else { c += 2; i += 4 } } + print c } + BEGIN { BT = ""; for (v = 1; v < 256; v++) BT = BT sprintf("%c", v) } + ') if [ "$len" -gt 100 ]; then echo " ✗ subject is $len characters; keep it under 100" >&2 echo " move detail into the commit body" >&2 diff --git a/tests/fixtures/commit-msg/pass-utf16/message.txt b/tests/fixtures/commit-msg/pass-utf16/message.txt new file mode 100644 index 0000000..384288a --- /dev/null +++ b/tests/fixtures/commit-msg/pass-utf16/message.txt @@ -0,0 +1 @@ +fix: 这是一个用于验证 UTF-16 长度测量的中文提交主题示例,确保非 ASCII 字符在 JS 与 shell 两种实现中得到相同的长度结果 diff --git a/tests/run-hooks.test.mjs b/tests/run-hooks.test.mjs index 0aacdb6..0714c62 100644 --- a/tests/run-hooks.test.mjs +++ b/tests/run-hooks.test.mjs @@ -17,11 +17,14 @@ import { execFileSync, spawnSync } from "node:child_process"; import { cpSync, existsSync, + mkdirSync, mkdtempSync, readdirSync, + readFileSync, rmSync, statSync, symlinkSync, + writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; @@ -31,8 +34,6 @@ const TEST_DIR = dirname(fileURLToPath(import.meta.url)); const REPO_ROOT = dirname(TEST_DIR); const FIXTURES = join(TEST_DIR, "fixtures"); -/** Matches the `sh -c ''` wrapper every hook entry uses. */ -const SH_C_RE = /^sh -c '(?.*)'$/su; const TS_FILE_RE = /(?ts|tsx|js|jsx|json)$/u; const PY_FILE_RE = /\.py$/u; const EXCLUDED_PATH_RE = @@ -58,7 +59,20 @@ function listFiles(dir, prefix = "") { */ function toolAvailable(cmd, extraArgs = []) { const result = spawnSync(cmd, extraArgs, { encoding: "utf8" }); - return result.error === undefined && result.status === 0; + if (result.error !== undefined) { + // Only a missing executable (ENOENT) means the tool is genuinely absent + // and the case should be skipped. Other startup errors (EACCES = + // permission denied, ELOOP = too many symlinks, ...) mean the executable + // exists but cannot be launched; surface them as test errors instead of + // silently skipping. + if (result.error.code === "ENOENT") { + return false; + } + throw new Error( + `failed to launch ${cmd}: ${result.error.code ?? result.error.message}` + ); + } + return result.status === 0; } const HOOK_TOOLS = { @@ -73,10 +87,16 @@ const HOOK_TOOLS = { "frontal-commit-msg": () => toolAvailable("node", ["--version"]), }; +// Every published hook is `language: script`: pre-commit resolves `entry` to +// an absolute path in the hook CHECKOUT and executes it directly (not via +// `sh -c`), with the CONSUMER repo as cwd. The wrapper resolves its node +// scripts against the checkout as an absolute path (derived from its own +// location) without changing the consumer's working directory. The test +// repo's `hooks/` copy IS the simulated checkout, so `REPO_ROOT` (the source +// of that copy) is the checkout the wrapper resolves its scripts against. const HOOKS = { "frontal-biome": { - entry: - "sh -c 'node hooks/ensure-tool.mjs biome && biome check --no-errors-on-unmatched \"$@\"'", + script: "hooks/biome.sh", staged: (files) => files.filter( (f) => TS_FILE_RE.test(f) && !f.startsWith("packages/design-system/") @@ -84,38 +104,33 @@ const HOOKS = { pass_filenames: true, }, "frontal-ruff": { - entry: - 'sh -c \'node hooks/ensure-tool.mjs ruff && ruff check "$@" && ruff format --check "$@"\'', + script: "hooks/ruff.sh", staged: (files) => files.filter((f) => PY_FILE_RE.test(f) && !EXCLUDED_PATH_RE.test(f)), pass_filenames: true, }, "frontal-rustfmt": { - entry: - 'sh -c \'node hooks/ensure-tool.mjs rustfmt && rust_files=$(git diff --cached --name-only --diff-filter=ACMR -- "*.rs" | grep -vE "(^|/)gen/" || true); if [ -n "$rust_files" ]; then printf "%s\\n" "$rust_files" | xargs rustfmt --edition 2024 --check; fi\'', + script: "hooks/rustfmt.sh", staged: () => [], pass_filenames: false, }, "frontal-clippy": { - entry: - "sh -c 'node hooks/ensure-tool.mjs cargo && node hooks/clippy-scoped.mjs'", + script: "hooks/clippy.sh", staged: () => [], pass_filenames: false, }, "frontal-go-vet": { - entry: - "sh -c 'node hooks/ensure-tool.mjs go && node hooks/go-vet-scoped.mjs'", + script: "hooks/go-vet.sh", staged: () => [], pass_filenames: false, }, "frontal-buf-lint": { - entry: - "sh -c 'node hooks/ensure-tool.mjs buf && node hooks/buf-lint-scoped.mjs'", + script: "hooks/buf-lint.sh", staged: () => [], pass_filenames: false, }, "frontal-commit-msg": { - entry: "sh -c 'node hooks/check-commit-message.mjs \"$0\"'", + script: "hooks/commit-msg.sh", staged: () => [], pass_filenames: false, is_commit_msg: true, @@ -139,6 +154,16 @@ const CASES = [ ["buf-lint-fail", "buf-lint/fail", "frontal-buf-lint", false], ["commit-msg-pass", "commit-msg/pass", "frontal-commit-msg", true], ["commit-msg-fail", "commit-msg/fail", "frontal-commit-msg", false], + // A CJK subject that is 74 UTF-16 units (passes the 100-unit cap) but 160 + // UTF-8 bytes. Guards the shared checker's String.length measurement: a + // regression to counting bytes (like `wc -c` did in the lefthook bridge) + // would wrongly reject this subject, and the bridge is kept in sync with it. + [ + "commit-msg-pass-utf16", + "commit-msg/pass-utf16", + "frontal-commit-msg", + true, + ], ]; function setupRepo(fixtureDir, repoDir) { @@ -150,37 +175,126 @@ function setupRepo(fixtureDir, repoDir) { cwd: repoDir, }); execFileSync("git", ["config", "user.name", "Test"], { cwd: repoDir }); - // Copy hooks/ so relative paths in entry commands work + // Copy hooks/ — the simulated hook CHECKOUT the wrappers resolve against. cpSync(join(REPO_ROOT, "hooks"), join(repoDir, "hooks"), { recursive: true }); + // A consumer-root marker. The wrappers resolve their scripts against the + // CHECKOUT (their own directory's parent), so a consumer-root `hooks/` file + // is invisible to them. If a wrapper resolved scripts against the consumer + // cwd instead, it would find this file and the test would fail — proving + // checkout-resolution. + mkdirSync(join(repoDir, "hooks"), { recursive: true }); + writeFileSync( + join(repoDir, "hooks", "__consumer_marker__.sh"), + "not-a-hook\n" + ); // The biome hook resolves its config (biome.jsonc) and the ultracite preset - // through node_modules, so the throwaway repo needs both: a copy of the - // config and a symlink to this repo's node_modules. - cpSync(join(REPO_ROOT, "biome.jsonc"), join(repoDir, "biome.jsonc")); - symlinkSync(join(REPO_ROOT, "node_modules"), join(repoDir, "node_modules")); + // through node_modules. We build a SELF-CONTAINED node_modules (a real + // directory tree, not a symlink) containing only the packages biome needs: + // a symlink to REPO_ROOT's node_modules would let biome's `includes: ["**"]` + // walk back to REPO_ROOT and lint its own files (including uncommitted + // working-tree edits), which is not hermetic. Real copies cannot be walked + // out of. + const nmDir = join(repoDir, "node_modules"); + mkdirSync(nmDir, { recursive: true }); + // Copy the ultracite preset and its dependencies. + const ultracitePkg = JSON.parse( + readFileSync( + join(REPO_ROOT, "node_modules", "ultracite", "package.json"), + "utf8" + ) + ); + const ultraciteDeps = { + ...(ultracitePkg.dependencies ?? {}), + ...(ultracitePkg.peerDependencies ?? {}), + }; + cpSync( + join(REPO_ROOT, "node_modules", "ultracite"), + join(nmDir, "ultracite"), + { recursive: true } + ); + for (const dep of Object.keys(ultraciteDeps)) { + const src = join(REPO_ROOT, "node_modules", dep); + if (existsSync(src)) { + cpSync(src, join(nmDir, dep), { recursive: true }); + } + } + // Provide node_modules/.bin/biome so the test's PATH (which prepends + // repoDir/node_modules/.bin) can find the biome executable. Copy the real + // biome CLI package + its platform binary instead of symlinking: a symlink + // into REPO_ROOT would let biome resolve its location to the source repo, + // which is not hermetic. + const binDir = join(nmDir, ".bin"); + mkdirSync(binDir, { recursive: true }); + const biomePkgDir = join(REPO_ROOT, "node_modules", "@biomejs", "biome"); + if (existsSync(biomePkgDir)) { + cpSync(biomePkgDir, join(nmDir, "@biomejs", "biome"), { + recursive: true, + }); + const platformDir = join( + REPO_ROOT, + "node_modules", + `@biomejs/cli-${process.platform}-${process.arch}` + ); + if (existsSync(platformDir)) { + cpSync( + platformDir, + join(nmDir, `@biomejs/cli-${process.platform}-${process.arch}`), + { + recursive: true, + } + ); + } + symlinkSync( + join(nmDir, "@biomejs", "biome", "bin", "biome"), + join(binDir, "biome") + ); + } + // Write a minimal, STANDALONE biome.jsonc for the consumer. Intentionally + // no `extends`: ultracite's core preset uses `files.includes: ["**"]` plus + // `vcs.useIgnoreFile: true`, and when merged a consumer config's own + // `includes` the preset's `**` still applies — which would make biome + // lint the consumer's copied hooks/ (carrying REPO_ROOT's working-tree + // lint state) and drag in gitignore machinery. A standalone config with + // an explicit file list keeps the consumer fully hermetic: biome only + // ever sees the staged fixture files. + writeFileSync( + join(repoDir, "biome.jsonc"), + `${JSON.stringify( + { + linter: { enabled: true }, + formatter: { enabled: true, indentStyle: "space", indentWidth: 2 }, + files: { + includes: ["**", "!**/node_modules", "!**/hooks"], + }, + }, + null, + 2 + )}\n` + ); execFileSync("git", ["add", "-A"], { cwd: repoDir }); } function runHook(hook, repoDir, allFiles, extraArgs = []) { - // Every hook entry is of the form `sh -c ''`. pre-commit - // executes it by appending the file list (or the commit-msg file) as - // positional params after the command string. The first positional - // param lands in `$0`, the rest in `$@`. + // `language: script`: pre-commit execs the entry script directly (not via + // `sh -c`), resolving it to an absolute path in the checkout, with the + // CONSUMER repo as cwd. `$0` is the script's own path; the staged files / + // the commit-msg path arrive as positional args $1…$n — there is no `--` + // placeholder. The wrapper resolves its node scripts against the checkout + // (its own directory's parent) WITHOUT changing cwd, so the scoped tools + // see the consumer repo as their project root. // - // To avoid a double shell wrapper (which would consume the positional - // param as its own $0 and drop it), parse out the inner command and - // run `sh -c [placeholder-$0] ` directly. + // - File-based hooks (biome, ruff): the staged files are the positional + // args ($1…$n); the wrapper's `"$@"` is exactly that list. + // - pass_filenames: false hooks (rustfmt, clippy, go-vet, buf-lint): no + // file args — they read staged state from git themselves. + // - commit-msg: the message path is the single positional arg ($1). // - // `sh -c 'cmd' a b c` assigns a→$0, b→$1, c→$2. Hooks that reference - // `"$@"` (biome, ruff) expect *all* filenames there, so we pass a dummy - // placeholder for $0 and let the real files start at $1. The commit-msg - // hook is the exception: it reads a single positional param as `$0`, so - // for that hook we pass the message path bare (it becomes $0, matching - // how pre-commit invokes commit-msg hooks). - const m = hook.entry.match(SH_C_RE); - if (!m) { - throw new Error(`unexpected entry format: ${hook.entry}`); + // We mirror this by invoking the wrapper (an absolute path in the + // REPO_ROOT checkout) directly, with cwd = consumer repo (repoDir). + const scriptPath = join(REPO_ROOT, hook.script); + if (!existsSync(scriptPath)) { + throw new Error(`wrapper script not found: ${scriptPath}`); } - const { command } = m.groups; let files = []; if (hook.is_commit_msg) { @@ -196,11 +310,11 @@ function runHook(hook, repoDir, allFiles, extraArgs = []) { PATH: `${join(repoDir, "node_modules", ".bin")}:${process.env.PATH}`, }; - // For commit-msg the single param is the message path and must land in $0. - // For file-based hooks a placeholder occupies $0 so "$@" sees every file. - const positional = hook.is_commit_msg ? files : ["$0-placeholder", ...files]; - - const result = spawnSync("sh", ["-c", command, ...positional], { + // No `--` placeholder: the staged files (or the commit-msg path) are the + // script's positional args $1..$n, exactly as `language: script` delivers + // them (the script's own path is $0). + const args = [...files]; + const result = spawnSync(scriptPath, args, { cwd: repoDir, shell: false, encoding: "utf8", @@ -209,6 +323,8 @@ function runHook(hook, repoDir, allFiles, extraArgs = []) { }); return { status: result.status, + error: result.error, + signal: result.signal, stdout: result.stdout ?? "", stderr: result.stderr ?? "", }; @@ -240,7 +356,22 @@ function main() { const hook = HOOKS[hookId]; // Skip when the underlying tool is not installed on this machine. - if (!HOOK_TOOLS[hookId]()) { + // A genuinely missing executable (ENOENT) is skipped; any other startup + // error (e.g. EACCES) is a test error, not a skip. + let toolMissing; + try { + toolMissing = !HOOK_TOOLS[hookId](); + } catch (error) { + results.push({ + caseId, + hookId, + status: "ERROR", + reason: error.message, + }); + failed += 1; + continue; + } + if (toolMissing) { results.push({ caseId, hookId, @@ -262,18 +393,44 @@ function main() { : []; const result = runHook(hook, repoDir, allFiles, extraArgs); - const actualPass = result.status === 0; - const ok = actualPass === expectPass; - if (debug) { process.stderr.write( - `\n===== ${caseId} (exit ${result.status}, expected ${expectPass ? "pass" : "fail"}) =====\n` + `\n===== ${caseId} (exit ${result.status ?? "n/a"}, signal ${result.signal ?? "none"}, expected ${expectPass ? "pass" : "fail"}) =====\n` ); process.stderr.write( `--- stdout ---\n${result.stdout}\n--- stderr ---\n${result.stderr}\n` ); } + // Only classify PASS/FAIL when the process completed with an exit + // status. A spawn error or signal termination (e.g. timeout kill) + // is an execution problem, not a hook result, so report it as ERROR. + if (result.error !== undefined) { + results.push({ + caseId, + hookId, + status: "ERROR", + reason: `execution error: ${result.error.message}`, + output: (result.stderr || result.stdout).trim().slice(0, 300), + }); + failed += 1; + continue; + } + if (result.status === null && result.signal !== null) { + results.push({ + caseId, + hookId, + status: "ERROR", + reason: `terminated by signal: ${result.signal}`, + output: (result.stderr || result.stdout).trim().slice(0, 300), + }); + failed += 1; + continue; + } + + const actualPass = result.status === 0; + const ok = actualPass === expectPass; + results.push({ caseId, hookId,