From 08668811d22fd100aebb6bcacb6cd138031c0bbe Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 16:14:18 +1300 Subject: [PATCH 1/3] Add the node module: Node, npm/pnpm/Yarn, a frozen install and its cache `modules: [node]` installs the Node the project pins and its package manager, runs a frozen install and caches the package manager's downloads, on GitHub Actions and CircleCI. - Node's version: .nvmrc or .node-version in `path`, else at the root, else package.json's engines.node, else `version:` (or `preinstalled`). On CircleCI the job's image must be a node/cimg/node image matching the pinned version. - Package manager: package.json's packageManager, else the one lockfile present. pnpm and Yarn go through pnpm/action-setup or Corepack. - Install: npm ci, pnpm install --frozen-lockfile, yarn install --immutable (Berry) or --frozen-lockfile (Classic). - Cache: setup-node's cache keyed on the lockfile on GitHub; restore_cache/save_cache keyed on the lockfile's checksum on CircleCI. - Inputs: package.json files, lockfiles, pnpm-workspace.yaml, .npmrc, Yarn config and patches, and the version file. Tests: unit tests for detection, expansion and every mistake; a golden fixture for both providers; mockci scenarios that a skipped job installs nothing and that each contributed input and the parameters rerun it. --- README.md | 3 +- docs/src/content/docs/modules.md | 56 +++- docs/src/pages/index.astro | 6 +- .../module_node/.circleci/config.yml | 248 ++++++++++++++++ .../module_node/.circleci/main.yml | 269 +++++++++++++++++ .../module_node/.github/workflows/ci.yml | 215 ++++++++++++++ integration_tests/module_node/.nvmrc | 1 + integration_tests/module_node/cigen.yml | 21 ++ .../module_node/docs/package-lock.json | 5 + .../module_node/docs/package.json | 7 + integration_tests/module_node/package.json | 8 + integration_tests/module_node/pnpm-lock.yaml | 1 + internal_docs/STATUS.md | 18 +- schemas/v1/cigen.schema.json | 26 ++ schemas/v1/job.schema.json | 26 ++ schemas/v1/workflow.schema.json | 26 ++ src/modules/README.md | 1 + src/modules/expand.rs | 11 +- src/modules/mod.rs | 41 ++- src/modules/node/README.md | 76 +++++ src/modules/node/SKILL.md | 30 ++ src/modules/node/expand.rs | 191 ++++++++++++ src/modules/node/manager.rs | 132 +++++++++ src/modules/node/mod.rs | 265 +++++++++++++++++ src/modules/node/tests.rs | 280 ++++++++++++++++++ src/modules/rust/mod.rs | 7 +- src/modules/rust/tests.rs | 2 +- src/modules/steps.rs | 53 ++++ tests/golden_fixtures.rs | 1 + tests/module_catalogue.rs | 39 ++- tests/module_node.rs | 140 +++++++++ tests/support/doc_examples.rs | 10 +- 32 files changed, 2177 insertions(+), 38 deletions(-) create mode 100644 integration_tests/module_node/.circleci/config.yml create mode 100644 integration_tests/module_node/.circleci/main.yml create mode 100644 integration_tests/module_node/.github/workflows/ci.yml create mode 100644 integration_tests/module_node/.nvmrc create mode 100644 integration_tests/module_node/cigen.yml create mode 100644 integration_tests/module_node/docs/package-lock.json create mode 100644 integration_tests/module_node/docs/package.json create mode 100644 integration_tests/module_node/package.json create mode 100644 integration_tests/module_node/pnpm-lock.yaml create mode 100644 src/modules/node/README.md create mode 100644 src/modules/node/SKILL.md create mode 100644 src/modules/node/expand.rs create mode 100644 src/modules/node/manager.rs create mode 100644 src/modules/node/mod.rs create mode 100644 src/modules/node/tests.rs create mode 100644 src/modules/steps.rs create mode 100644 tests/module_node.rs diff --git a/README.md b/README.md index e9e8b42..3b7678b 100644 --- a/README.md +++ b/README.md @@ -121,7 +121,8 @@ workflows: ``` The `rust` module installs the toolchain your project pins, caches cargo's downloads and build output, and adds -`Cargo.toml`, `Cargo.lock` and the toolchain file to the job's hash. `node`, Playwright and services are next. +`Cargo.toml`, `Cargo.lock` and the toolchain file to the job's hash. The `node` module does the same for +Node with npm, pnpm or Yarn. Playwright and services are next. ## Install diff --git a/docs/src/content/docs/modules.md b/docs/src/content/docs/modules.md index 137a060..870c844 100644 --- a/docs/src/content/docs/modules.md +++ b/docs/src/content/docs/modules.md @@ -7,7 +7,7 @@ A module is setup you'd otherwise paste into every job: installing a toolchain, that setup depends on. A job lists its modules under `modules:`, and cigen expands each into ordinary steps before a provider sees the job. -The project in this page's examples is a Rust crate: +The project in this page's examples is a Rust crate with a Node frontend: ```toml title="Cargo.toml" [package] @@ -98,8 +98,58 @@ It installs with `rustup`, which GitHub's runners and the Rust images ship. On G architecture, the toolchain and `Cargo.lock`. Its full reference is [`src/modules/rust/README.md`](https://github.com/DocSpring/cigen/blob/main/src/modules/rust/README.md). +## The `node` module + +Installs Node and the package manager your project pins (npm, pnpm or Yarn), runs a frozen install, and caches the +package manager's downloads. Node's version comes from `.nvmrc` or `.node-version`, else `engines.node` in +`package.json`, and pnpm's or Yarn's from `packageManager` in `package.json`: + +```json title="package.json" +{ + "private": true, + "packageManager": "pnpm@9.15.0", + "scripts": { "lint": "eslint ." } +} +``` + +```yaml title="pnpm-lock.yaml" +lockfileVersion: '9.0' +``` + +```text title=".nvmrc" +22 +``` + +```yaml +# cigen.yml +provider: github + +workflows: + ci: + jobs: + lint: + modules: [node] + inputs: ['src/**'] + steps: + - run: pnpm lint +``` + +| Parameter | Default | Meaning | +| ----------------- | ---------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | +| `version` | what `.nvmrc` or `.node-version` in `path` or the root says, else `package.json`'s `engines.node`, else an error | a Node version, or `preinstalled` for the Node the image or runner already has | +| `package_manager` | `package.json`'s `packageManager`, else the one lockfile present, else an error | `npm`, `pnpm` or `yarn` | +| `install` | `true` | run a frozen install (`npm ci`, `pnpm install --frozen-lockfile`, `yarn install --immutable`) | +| `cache` | `true` | cache the package manager's downloads | +| `path` | `.` | the directory holding `package.json` and the lockfile | + +On GitHub Actions it uses `pnpm/action-setup` for pnpm, Corepack for Yarn, and `actions/setup-node` (pinned to commits) +with its cache. On CircleCI, Node comes from the job's image: a `cimg/node` or `node` image whose tag starts with the +pinned version, or any image with `version: preinstalled`; pnpm and Yarn come through Corepack, and the cache through +`restore_cache` and `save_cache`. It adds `package.json`, every tracked `**/package.json`, the lockfiles, workspace and +package manager config, patches and the version file to the job's inputs. Its full reference is +[`src/modules/node/README.md`](https://github.com/DocSpring/cigen/blob/main/src/modules/node/README.md). + ## More modules -`rust` is the first. Node with npm, pnpm or Yarn comes next, then Playwright, services (Postgres, an S3-compatible -store), a shared compile cache and Ruby with Bundler. The +Playwright, services (Postgres, an S3-compatible store), a shared compile cache and Ruby with Bundler come next. The [module catalogue](https://github.com/DocSpring/cigen/blob/main/src/modules/README.md) lists the ones that exist. diff --git a/docs/src/pages/index.astro b/docs/src/pages/index.astro index e52b2dc..aa5cc6c 100644 --- a/docs/src/pages/index.astro +++ b/docs/src/pages/index.astro @@ -164,7 +164,7 @@ const skipped = run.jobs.filter((job) => job.status === 'skipped').length;
-

Started · rust is built; node, Playwright and services are coming

+

Started · rust and node are built; Playwright and services are coming

Modules replace the setup you paste into every job

Toolchains, dependency caches, services and upload steps, pinned and tested once. Each module also adds the @@ -197,7 +197,7 @@ const skipped = run.jobs.filter((job) => job.status === 'skipped').length;

  • Skipping on GitHub Actions, with markers in its cache
  • Generated workflows install a checksum-checked cigen release
  • Byte-for-byte deterministic output
  • -
  • Modules, starting with rust
  • +
  • Modules for Rust and Node
  • @@ -205,7 +205,7 @@ const skipped = run.jobs.filter((job) => job.status === 'skipped').length;
    • The v0.2.0 release, the first those workflows can install
    • A planner job, so skipped jobs never start a runner
    • -
    • More modules: Node, Playwright, services and caches
    • +
    • More modules: Playwright, services and caches
    • cigen plan: which jobs will run or skip, and why
    • Free hosted pass records on VisualCI, shared across branches
    • Skipping on CircleCI
    • diff --git a/integration_tests/module_node/.circleci/config.yml b/integration_tests/module_node/.circleci/config.yml new file mode 100644 index 0000000..91db463 --- /dev/null +++ b/integration_tests/module_node/.circleci/config.yml @@ -0,0 +1,248 @@ +version: '2.1' +setup: true +parameters: + skip_cache: + type: boolean + default: false + description: Disable job-status cache and rerun all jobs +orbs: + continuation: circleci/continuation@1.0.0 +commands: + cigen_shallow_checkout: + description: | + Fast shallow git checkout using configurable clone depth and options. 99% faster than full checkout for most CI jobs that don't need git history. + parameters: + clone_options: + type: string + default: --depth 1 + description: | + git clone options such as '--depth 1 --verbose' or '--depth 1 --shallow-since "5 days ago"' + fetch_options: + type: string + default: --depth 10 + description: | + git fetch options such as '--depth 1 --verbose' or '--depth 1 --shallow-since "5 days ago"' Note: '--force' is already set by default. For tags, use tag_fetch_options instead. + tag_fetch_options: + type: string + default: --tags + description: | + Git fetch options specifically for tag operations. Use fetch_options for PR and other operations. To exclude tags, use '--no-tags' in both this option and tag_fetch_options. + keyscan_github: + type: boolean + default: false + description: | + Enable SSH keyscan for github.com + keyscan_gitlab: + type: boolean + default: false + description: | + Enable SSH keyscan for gitlab.com + keyscan_bitbucket: + type: boolean + default: false + description: | + Enable SSH keyscan for bitbucket.org + path: + type: string + default: . + description: | + Checkout directory (default: job working_directory) + steps: + - run: + name: Shallow Git Checkout + command: | + # Shallow checkout implementation + # Based on git-shallow-clone-orb (MIT license) + + set -e + + # Set parameters + CLONE_OPTIONS="<< parameters.clone_options >>" + FETCH_OPTIONS="<< parameters.fetch_options >>" + TAG_FETCH_OPTIONS="<< parameters.tag_fetch_options >>" + KEYSCAN_GITHUB="<< parameters.keyscan_github >>" + KEYSCAN_GITLAB="<< parameters.keyscan_gitlab >>" + KEYSCAN_BITBUCKET="<< parameters.keyscan_bitbucket >>" + CHECKOUT_PATH="<< parameters.path >>" + + # Verify ssh is available (required for git ssh operations and keyscan) + if ! command -v ssh >/dev/null 2>&1; then + echo "ERROR: ssh command not found" >&2 + echo "" >&2 + echo "You must run this command from a Docker image that has openssh-client installed." >&2 + echo "" >&2 + echo "Use a CircleCI convenience image (cimg/*) or install openssh-client in your Dockerfile:" >&2 + echo " - Debian/Ubuntu: RUN apt-get update && apt-get install -y openssh-client" >&2 + echo " - Alpine: RUN apk add --no-cache openssh-client" >&2 + echo " - RHEL/CentOS: RUN yum install -y openssh-clients" >&2 + exit 1 + fi + + # Create SSH directory if not exists + if [ ! -d ~/.ssh ]; then + mkdir -p ~/.ssh + chmod 700 ~/.ssh + fi + + # Add SSH host keys based on keyscan parameters + if [ "$KEYSCAN_GITHUB" = "true" ]; then + echo "Adding GitHub SSH host key..." + ssh-keyscan -H github.com >> ~/.ssh/known_hosts 2>/dev/null || true + fi + + if [ "$KEYSCAN_GITLAB" = "true" ]; then + echo "Adding GitLab SSH host key..." + ssh-keyscan -H gitlab.com >> ~/.ssh/known_hosts 2>/dev/null || true + fi + + if [ "$KEYSCAN_BITBUCKET" = "true" ]; then + echo "Adding Bitbucket SSH host key..." + ssh-keyscan -H bitbucket.org >> ~/.ssh/known_hosts 2>/dev/null || true + fi + + # Set up repository URL and branch info + if [ -n "$CIRCLE_REPOSITORY_URL" ]; then + REPO_URL="$CIRCLE_REPOSITORY_URL" + else + echo "Error: CIRCLE_REPOSITORY_URL not set" + exit 1 + fi + + # Determine checkout target + if [ -n "$CIRCLE_TAG" ]; then + CHECKOUT_TARGET="$CIRCLE_TAG" + FETCH_OPTIONS="$TAG_FETCH_OPTIONS" + elif [ -n "$CIRCLE_BRANCH" ]; then + CHECKOUT_TARGET="$CIRCLE_BRANCH" + else + CHECKOUT_TARGET="HEAD" + fi + + echo "Repository: $REPO_URL" + echo "Target: $CHECKOUT_TARGET" + echo "Path: $CHECKOUT_PATH" + echo "Clone options: $CLONE_OPTIONS" + echo "Fetch options: $FETCH_OPTIONS" + + # Create checkout directory + mkdir -p "$CHECKOUT_PATH" + cd "$CHECKOUT_PATH" + + # Initialize or update repository + if [ ! -d ".git" ]; then + echo "Initializing new repository..." + git init + git remote add origin "$REPO_URL" + else + echo "Updating existing repository..." + # Ensure origin is set correctly + if git remote get-url origin >/dev/null 2>&1; then + git remote set-url origin "$REPO_URL" + else + git remote add origin "$REPO_URL" + fi + fi + + # Configure Git for CircleCI + git config gc.auto 0 + + # Perform shallow fetch + echo "Fetching with options: $FETCH_OPTIONS" + + if [ -n "$CIRCLE_TAG" ]; then + # For tags, fetch the specific tag + git fetch $FETCH_OPTIONS origin "refs/tags/$CIRCLE_TAG:refs/tags/$CIRCLE_TAG" || \ + git fetch $FETCH_OPTIONS origin "$CIRCLE_TAG" + git checkout "refs/tags/$CIRCLE_TAG" + elif [ -n "$CIRCLE_SHA1" ]; then + # For specific commit + git fetch $FETCH_OPTIONS origin "$CIRCLE_SHA1" || \ + git fetch $FETCH_OPTIONS origin "$CHECKOUT_TARGET" + git checkout "$CIRCLE_SHA1" 2>/dev/null || git checkout "$CHECKOUT_TARGET" + else + # For branch + git fetch $FETCH_OPTIONS origin "$CHECKOUT_TARGET:$CHECKOUT_TARGET" || \ + git fetch $FETCH_OPTIONS origin "$CHECKOUT_TARGET" + git checkout "$CHECKOUT_TARGET" + fi + + # Show final state + echo "Checked out to: $(git rev-parse HEAD)" + echo "Current branch/tag: $(git describe --always --tags 2>/dev/null || git rev-parse --abbrev-ref HEAD)" + + # Set CircleCI environment variables for consistency + echo "export GIT_COMMIT_SHA=\"$(git rev-parse HEAD)\"" >> $BASH_ENV + echo "export GIT_BRANCH=\"$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo 'HEAD')\"" >> $BASH_ENV +jobs: + setup: + docker: + - image: cimg/rust:1.76 + steps: + - checkout + - run: + name: Handle skip_cache parameter + command: | + set -euo pipefail + if [ "<< pipeline.parameters.skip_cache >>" = "true" ]; then + cigen generate main + circleci step halt + fi + - run: + name: Prepare skip list + command: | + rm -rf /tmp/skip && mkdir -p /tmp/skip /tmp/cigen /tmp/cigen_job_exists + - run: + name: Hash sources for docs + command: | + set -euo pipefail + mkdir -p /tmp/cigen + JOB_HASH=$(cigen hash --job docs --modules-digest da34e492687eef00 | tr -d '\r') + printf '%s' "$JOB_HASH" > /tmp/cigen/job_hash + echo "export JOB_HASH=$JOB_HASH" >> $BASH_ENV + echo 'Computed hash for docs: '$JOB_HASH + - restore_cache: + name: 'Restore job status: docs' + keys: + - linux-{{ checksum "/etc/os-release" }}-job_status-exists-v1-docs-{{ checksum "/tmp/cigen/job_hash" }} + - linux-{{ checksum "/etc/os-release" }}-job_status-exists-v1- + - run: + name: 'Probe exists: docs' + command: | + set -euo pipefail + if [ -f '/tmp/cigen_job_exists/done_${JOB_HASH}' ]; then echo 'docs' >> /tmp/skip/main.txt; fi + rm -rf /tmp/cigen_job_exists + - run: + name: Hash sources for lint + command: | + set -euo pipefail + mkdir -p /tmp/cigen + JOB_HASH=$(cigen hash --job lint --modules-digest 2b37c6170286a7c7 | tr -d '\r') + printf '%s' "$JOB_HASH" > /tmp/cigen/job_hash + echo "export JOB_HASH=$JOB_HASH" >> $BASH_ENV + echo 'Computed hash for lint: '$JOB_HASH + - restore_cache: + name: 'Restore job status: lint' + keys: + - linux-{{ checksum "/etc/os-release" }}-job_status-exists-v1-lint-{{ checksum "/tmp/cigen/job_hash" }} + - linux-{{ checksum "/etc/os-release" }}-job_status-exists-v1- + - run: + name: 'Probe exists: lint' + command: | + set -euo pipefail + if [ -f '/tmp/cigen_job_exists/done_${JOB_HASH}' ]; then echo 'lint' >> /tmp/skip/main.txt; fi + rm -rf /tmp/cigen_job_exists + - run: + name: Generate filtered main + command: | + set -euo pipefail + if [ -s "/tmp/skip/main.txt" ]; then + CIGEN_SKIP_JOBS_FILE="/tmp/skip/main.txt" cigen generate main + else + cigen generate main + fi + - continuation/continue: + configuration_path: .circleci/main.yml +workflows: + main: + jobs: + - setup diff --git a/integration_tests/module_node/.circleci/main.yml b/integration_tests/module_node/.circleci/main.yml new file mode 100644 index 0000000..86a17a4 --- /dev/null +++ b/integration_tests/module_node/.circleci/main.yml @@ -0,0 +1,269 @@ +version: '2.1' +orbs: + continuation: circleci/continuation@1.0.0 +commands: + cigen_shallow_checkout: + description: | + Fast shallow git checkout using configurable clone depth and options. 99% faster than full checkout for most CI jobs that don't need git history. + parameters: + clone_options: + type: string + default: --depth 1 + description: | + git clone options such as '--depth 1 --verbose' or '--depth 1 --shallow-since "5 days ago"' + fetch_options: + type: string + default: --depth 10 + description: | + git fetch options such as '--depth 1 --verbose' or '--depth 1 --shallow-since "5 days ago"' Note: '--force' is already set by default. For tags, use tag_fetch_options instead. + tag_fetch_options: + type: string + default: --tags + description: | + Git fetch options specifically for tag operations. Use fetch_options for PR and other operations. To exclude tags, use '--no-tags' in both this option and tag_fetch_options. + keyscan_github: + type: boolean + default: false + description: | + Enable SSH keyscan for github.com + keyscan_gitlab: + type: boolean + default: false + description: | + Enable SSH keyscan for gitlab.com + keyscan_bitbucket: + type: boolean + default: false + description: | + Enable SSH keyscan for bitbucket.org + path: + type: string + default: . + description: | + Checkout directory (default: job working_directory) + steps: + - run: + name: Shallow Git Checkout + command: | + # Shallow checkout implementation + # Based on git-shallow-clone-orb (MIT license) + + set -e + + # Set parameters + CLONE_OPTIONS="<< parameters.clone_options >>" + FETCH_OPTIONS="<< parameters.fetch_options >>" + TAG_FETCH_OPTIONS="<< parameters.tag_fetch_options >>" + KEYSCAN_GITHUB="<< parameters.keyscan_github >>" + KEYSCAN_GITLAB="<< parameters.keyscan_gitlab >>" + KEYSCAN_BITBUCKET="<< parameters.keyscan_bitbucket >>" + CHECKOUT_PATH="<< parameters.path >>" + + # Verify ssh is available (required for git ssh operations and keyscan) + if ! command -v ssh >/dev/null 2>&1; then + echo "ERROR: ssh command not found" >&2 + echo "" >&2 + echo "You must run this command from a Docker image that has openssh-client installed." >&2 + echo "" >&2 + echo "Use a CircleCI convenience image (cimg/*) or install openssh-client in your Dockerfile:" >&2 + echo " - Debian/Ubuntu: RUN apt-get update && apt-get install -y openssh-client" >&2 + echo " - Alpine: RUN apk add --no-cache openssh-client" >&2 + echo " - RHEL/CentOS: RUN yum install -y openssh-clients" >&2 + exit 1 + fi + + # Create SSH directory if not exists + if [ ! -d ~/.ssh ]; then + mkdir -p ~/.ssh + chmod 700 ~/.ssh + fi + + # Add SSH host keys based on keyscan parameters + if [ "$KEYSCAN_GITHUB" = "true" ]; then + echo "Adding GitHub SSH host key..." + ssh-keyscan -H github.com >> ~/.ssh/known_hosts 2>/dev/null || true + fi + + if [ "$KEYSCAN_GITLAB" = "true" ]; then + echo "Adding GitLab SSH host key..." + ssh-keyscan -H gitlab.com >> ~/.ssh/known_hosts 2>/dev/null || true + fi + + if [ "$KEYSCAN_BITBUCKET" = "true" ]; then + echo "Adding Bitbucket SSH host key..." + ssh-keyscan -H bitbucket.org >> ~/.ssh/known_hosts 2>/dev/null || true + fi + + # Set up repository URL and branch info + if [ -n "$CIRCLE_REPOSITORY_URL" ]; then + REPO_URL="$CIRCLE_REPOSITORY_URL" + else + echo "Error: CIRCLE_REPOSITORY_URL not set" + exit 1 + fi + + # Determine checkout target + if [ -n "$CIRCLE_TAG" ]; then + CHECKOUT_TARGET="$CIRCLE_TAG" + FETCH_OPTIONS="$TAG_FETCH_OPTIONS" + elif [ -n "$CIRCLE_BRANCH" ]; then + CHECKOUT_TARGET="$CIRCLE_BRANCH" + else + CHECKOUT_TARGET="HEAD" + fi + + echo "Repository: $REPO_URL" + echo "Target: $CHECKOUT_TARGET" + echo "Path: $CHECKOUT_PATH" + echo "Clone options: $CLONE_OPTIONS" + echo "Fetch options: $FETCH_OPTIONS" + + # Create checkout directory + mkdir -p "$CHECKOUT_PATH" + cd "$CHECKOUT_PATH" + + # Initialize or update repository + if [ ! -d ".git" ]; then + echo "Initializing new repository..." + git init + git remote add origin "$REPO_URL" + else + echo "Updating existing repository..." + # Ensure origin is set correctly + if git remote get-url origin >/dev/null 2>&1; then + git remote set-url origin "$REPO_URL" + else + git remote add origin "$REPO_URL" + fi + fi + + # Configure Git for CircleCI + git config gc.auto 0 + + # Perform shallow fetch + echo "Fetching with options: $FETCH_OPTIONS" + + if [ -n "$CIRCLE_TAG" ]; then + # For tags, fetch the specific tag + git fetch $FETCH_OPTIONS origin "refs/tags/$CIRCLE_TAG:refs/tags/$CIRCLE_TAG" || \ + git fetch $FETCH_OPTIONS origin "$CIRCLE_TAG" + git checkout "refs/tags/$CIRCLE_TAG" + elif [ -n "$CIRCLE_SHA1" ]; then + # For specific commit + git fetch $FETCH_OPTIONS origin "$CIRCLE_SHA1" || \ + git fetch $FETCH_OPTIONS origin "$CHECKOUT_TARGET" + git checkout "$CIRCLE_SHA1" 2>/dev/null || git checkout "$CHECKOUT_TARGET" + else + # For branch + git fetch $FETCH_OPTIONS origin "$CHECKOUT_TARGET:$CHECKOUT_TARGET" || \ + git fetch $FETCH_OPTIONS origin "$CHECKOUT_TARGET" + git checkout "$CHECKOUT_TARGET" + fi + + # Show final state + echo "Checked out to: $(git rev-parse HEAD)" + echo "Current branch/tag: $(git describe --always --tags 2>/dev/null || git rev-parse --abbrev-ref HEAD)" + + # Set CircleCI environment variables for consistency + echo "export GIT_COMMIT_SHA=\"$(git rev-parse HEAD)\"" >> $BASH_ENV + echo "export GIT_BRANCH=\"$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo 'HEAD')\"" >> $BASH_ENV +jobs: + docs: + docker: + - image: cimg/node:22.11.0 + steps: + - checkout + - run: + name: Compute job hash + command: | + set -euo pipefail + mkdir -p /tmp/cigen /tmp/cigen_job_exists + JOB_HASH=$(cigen hash --job docs --modules-digest da34e492687eef00 | tr -d '\r') + printf '%s' "$JOB_HASH" > /tmp/cigen/job_hash + echo "export JOB_HASH=$JOB_HASH" >> $BASH_ENV + echo "Computed job hash: $JOB_HASH" + - run: + name: Install dependencies + command: cd docs && npm ci + - run: + command: cd docs && npm run build + - run: + name: Record job completion + command: | + set -euo pipefail + mkdir -p /tmp/cigen_job_exists + if [ -z "${JOB_HASH:-}" ]; then + JOB_HASH=$(cigen hash --job docs --modules-digest da34e492687eef00 | tr -d '\r') + fi + printf '%s' "$JOB_HASH" > /tmp/cigen/job_hash + touch "/tmp/cigen_job_exists/done_${JOB_HASH}" + echo "Recorded job completion for $JOB_HASH" + when: on_success + - save_cache: + name: Persist job status + key: linux-{{ checksum "/etc/os-release" }}-job_status-exists-v1-docs-{{ checksum "/tmp/cigen/job_hash" }} + paths: + - /tmp/cigen_job_exists + when: on_success + lint: + docker: + - image: cimg/node:22.11.0 + steps: + - checkout + - run: + name: Compute job hash + command: | + set -euo pipefail + mkdir -p /tmp/cigen /tmp/cigen_job_exists + JOB_HASH=$(cigen hash --job lint --modules-digest 2b37c6170286a7c7 | tr -d '\r') + printf '%s' "$JOB_HASH" > /tmp/cigen/job_hash + echo "export JOB_HASH=$JOB_HASH" >> $BASH_ENV + echo "Computed job hash: $JOB_HASH" + - run: + name: Enable Corepack + command: | + export PATH="$HOME/.corepack"/bin:$PATH + mkdir -p "$HOME/.corepack"/bin + command -v corepack >/dev/null || npm install --global --prefix "$HOME/.corepack" corepack@0.36.0 + corepack enable --install-directory "$HOME/.corepack"/bin + echo 'export PATH="$HOME/.corepack/bin:$PATH"' >> "$BASH_ENV" + echo 'export COREPACK_ENABLE_DOWNLOAD_PROMPT=0' >> "$BASH_ENV" + echo 'export npm_config_store_dir="$HOME/.pnpm-store"' >> "$BASH_ENV" + - restore_cache: + name: Restore pnpm cache + keys: + - node-v1-{{ arch }}-pnpm-{{ checksum "pnpm-lock.yaml" }} + - node-v1-{{ arch }}-pnpm- + - run: + name: Install dependencies + command: pnpm install --frozen-lockfile + - run: + command: pnpm lint + - save_cache: + name: Save pnpm cache + key: node-v1-{{ arch }}-pnpm-{{ checksum "pnpm-lock.yaml" }} + paths: + - ~/.pnpm-store + - run: + name: Record job completion + command: | + set -euo pipefail + mkdir -p /tmp/cigen_job_exists + if [ -z "${JOB_HASH:-}" ]; then + JOB_HASH=$(cigen hash --job lint --modules-digest 2b37c6170286a7c7 | tr -d '\r') + fi + printf '%s' "$JOB_HASH" > /tmp/cigen/job_hash + touch "/tmp/cigen_job_exists/done_${JOB_HASH}" + echo "Recorded job completion for $JOB_HASH" + when: on_success + - save_cache: + name: Persist job status + key: linux-{{ checksum "/etc/os-release" }}-job_status-exists-v1-lint-{{ checksum "/tmp/cigen/job_hash" }} + paths: + - /tmp/cigen_job_exists + when: on_success +workflows: + ci: + jobs: + - docs + - lint diff --git a/integration_tests/module_node/.github/workflows/ci.yml b/integration_tests/module_node/.github/workflows/ci.yml new file mode 100644 index 0000000..596e6fb --- /dev/null +++ b/integration_tests/module_node/.github/workflows/ci.yml @@ -0,0 +1,215 @@ +# DO NOT EDIT - This file is generated by cigen +# Source: cigen.yml +# Regenerate with: cigen generate +# +on: + push: + branches: + - main +name: CI +jobs: + docs: + runs-on: ubuntu-latest + container: + image: cimg/node:22.11.0 + steps: + - name: Checkout repository + uses: actions/checkout@v4 + - name: Install cigen 0.1.0 + run: | + set -eu + version=0.1.0 + base="${CIGEN_RELEASE_URL:-https://github.com/DocSpring/cigen/releases/download}" + case "$(uname -s)" in + Linux) os=unknown-linux-musl ;; + Darwin) os=apple-darwin ;; + *) echo "cigen has no release for $(uname -s)" >&2; exit 1 ;; + esac + case "$(uname -m)" in + x86_64 | amd64) arch=x86_64 ;; + aarch64 | arm64) arch=aarch64 ;; + *) echo "cigen has no release for $(uname -m)" >&2; exit 1 ;; + esac + asset="cigen-$arch-$os.tar.gz" + dir="${RUNNER_TEMP:-/tmp}/cigen" + mkdir -p "$dir/bin" + fetch() { + if command -v curl >/dev/null 2>&1; then + curl -fsSL --retry 3 "$1" -o "$2" + else + wget -q "$1" -O "$2" + fi + } + fetch "$base/v$version/$asset" "$dir/$asset" + fetch "$base/v$version/$asset.sha256" "$dir/$asset.sha256" + expected=$(cut -d ' ' -f 1 "$dir/$asset.sha256") + if command -v sha256sum >/dev/null 2>&1; then + actual=$(sha256sum "$dir/$asset" | cut -d ' ' -f 1) + else + actual=$(shasum -a 256 "$dir/$asset" | cut -d ' ' -f 1) + fi + if [ "$actual" != "$expected" ]; then + echo "cigen $version: $asset doesn't match its checksum (expected $expected, got $actual)" >&2 + exit 1 + fi + tar -xzf "$dir/$asset" -C "$dir/bin" + echo "$dir/bin" >> "$GITHUB_PATH" + - name: Compute source hash + id: compute_hash + run: | + set -euo pipefail + mkdir -p .cigen/skip-cache + mkdir -p .cigen/cache + cigen hash \ + --job docs \ + --base-dir . \ + --modules-digest da34e492687eef00 \ + --output job_hash \ + --cache .cigen/cache/file-hashes.json + - name: Restore skip cache + id: job_skip_cache + uses: actions/cache@v4 + with: + path: .cigen/skip-cache/docs + key: job-skip-${{ runner.os }}-docs-${{ steps.compute_hash.outputs.job_hash }} + if: ${{ env.ACT != 'true' }} + - name: Skip job (cached) + if: steps.job_skip_cache.outputs.cache-hit == 'true' + run: echo 'Job cache hit; skipping remaining steps.' && exit 0 + - name: Prepare Node runtime for actions + if: (env.ACT == 'true') && (steps.job_skip_cache.outputs.cache-hit != 'true') + run: | + set -e + if ! command -v node >/dev/null 2>&1 || ! command -v protoc >/dev/null 2>&1; then + apt-get update + apt-get install -y nodejs npm protobuf-compiler + fi + - name: Set up Node + uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce + with: + package-manager-cache: false + if: steps.job_skip_cache.outputs.cache-hit != 'true' + - name: Install dependencies + run: cd docs && npm ci + if: steps.job_skip_cache.outputs.cache-hit != 'true' + - run: cd docs && npm run build + if: steps.job_skip_cache.outputs.cache-hit != 'true' + - name: Record job completion + if: success() && steps.job_skip_cache.outputs.cache-hit != 'true' + run: | + set -e + HASH="${JOB_HASH}" + if [ -z "$HASH" ]; then + echo 'JOB_HASH missing' >&2 + exit 1 + fi + MARKER=.cigen/skip-cache/docs/$HASH + mkdir -p "$(dirname "$MARKER")" + date > "$MARKER" + env: + JOB_HASH: ${{ steps.compute_hash.outputs.job_hash }} + lint: + runs-on: ubuntu-latest + container: + image: cimg/node:22.11.0 + steps: + - name: Checkout repository + uses: actions/checkout@v4 + - name: Install cigen 0.1.0 + run: | + set -eu + version=0.1.0 + base="${CIGEN_RELEASE_URL:-https://github.com/DocSpring/cigen/releases/download}" + case "$(uname -s)" in + Linux) os=unknown-linux-musl ;; + Darwin) os=apple-darwin ;; + *) echo "cigen has no release for $(uname -s)" >&2; exit 1 ;; + esac + case "$(uname -m)" in + x86_64 | amd64) arch=x86_64 ;; + aarch64 | arm64) arch=aarch64 ;; + *) echo "cigen has no release for $(uname -m)" >&2; exit 1 ;; + esac + asset="cigen-$arch-$os.tar.gz" + dir="${RUNNER_TEMP:-/tmp}/cigen" + mkdir -p "$dir/bin" + fetch() { + if command -v curl >/dev/null 2>&1; then + curl -fsSL --retry 3 "$1" -o "$2" + else + wget -q "$1" -O "$2" + fi + } + fetch "$base/v$version/$asset" "$dir/$asset" + fetch "$base/v$version/$asset.sha256" "$dir/$asset.sha256" + expected=$(cut -d ' ' -f 1 "$dir/$asset.sha256") + if command -v sha256sum >/dev/null 2>&1; then + actual=$(sha256sum "$dir/$asset" | cut -d ' ' -f 1) + else + actual=$(shasum -a 256 "$dir/$asset" | cut -d ' ' -f 1) + fi + if [ "$actual" != "$expected" ]; then + echo "cigen $version: $asset doesn't match its checksum (expected $expected, got $actual)" >&2 + exit 1 + fi + tar -xzf "$dir/$asset" -C "$dir/bin" + echo "$dir/bin" >> "$GITHUB_PATH" + - name: Compute source hash + id: compute_hash + run: | + set -euo pipefail + mkdir -p .cigen/skip-cache + mkdir -p .cigen/cache + cigen hash \ + --job lint \ + --base-dir . \ + --modules-digest 2b37c6170286a7c7 \ + --output job_hash \ + --cache .cigen/cache/file-hashes.json + - name: Restore skip cache + id: job_skip_cache + uses: actions/cache@v4 + with: + path: .cigen/skip-cache/lint + key: job-skip-${{ runner.os }}-lint-${{ steps.compute_hash.outputs.job_hash }} + if: ${{ env.ACT != 'true' }} + - name: Skip job (cached) + if: steps.job_skip_cache.outputs.cache-hit == 'true' + run: echo 'Job cache hit; skipping remaining steps.' && exit 0 + - name: Prepare Node runtime for actions + if: (env.ACT == 'true') && (steps.job_skip_cache.outputs.cache-hit != 'true') + run: | + set -e + if ! command -v node >/dev/null 2>&1 || ! command -v protoc >/dev/null 2>&1; then + apt-get update + apt-get install -y nodejs npm protobuf-compiler + fi + - name: Install pnpm + uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 + if: steps.job_skip_cache.outputs.cache-hit != 'true' + - name: Set up Node + uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce + with: + cache: pnpm + cache-dependency-path: pnpm-lock.yaml + node-version-file: .nvmrc + if: steps.job_skip_cache.outputs.cache-hit != 'true' + - name: Install dependencies + run: pnpm install --frozen-lockfile + if: steps.job_skip_cache.outputs.cache-hit != 'true' + - run: pnpm lint + if: steps.job_skip_cache.outputs.cache-hit != 'true' + - name: Record job completion + if: success() && steps.job_skip_cache.outputs.cache-hit != 'true' + run: | + set -e + HASH="${JOB_HASH}" + if [ -z "$HASH" ]; then + echo 'JOB_HASH missing' >&2 + exit 1 + fi + MARKER=.cigen/skip-cache/lint/$HASH + mkdir -p "$(dirname "$MARKER")" + date > "$MARKER" + env: + JOB_HASH: ${{ steps.compute_hash.outputs.job_hash }} diff --git a/integration_tests/module_node/.nvmrc b/integration_tests/module_node/.nvmrc new file mode 100644 index 0000000..2bd5a0a --- /dev/null +++ b/integration_tests/module_node/.nvmrc @@ -0,0 +1 @@ +22 diff --git a/integration_tests/module_node/cigen.yml b/integration_tests/module_node/cigen.yml new file mode 100644 index 0000000..f61dc9a --- /dev/null +++ b/integration_tests/module_node/cigen.yml @@ -0,0 +1,21 @@ +provider: [github, circleci] +workflows: + ci: + github: + on: + push: + branches: [main] + jobs: + lint: + image: cimg/node:22.11.0 + modules: [node] + inputs: ["src/**"] + steps: + - run: pnpm lint + docs: + image: cimg/node:22.11.0 + modules: + - node: { path: docs, version: preinstalled, cache: false } + inputs: ["docs/src/**"] + steps: + - run: cd docs && npm run build diff --git a/integration_tests/module_node/docs/package-lock.json b/integration_tests/module_node/docs/package-lock.json new file mode 100644 index 0000000..54b338a --- /dev/null +++ b/integration_tests/module_node/docs/package-lock.json @@ -0,0 +1,5 @@ +{ + "name": "docs", + "lockfileVersion": 3, + "packages": {} +} diff --git a/integration_tests/module_node/docs/package.json b/integration_tests/module_node/docs/package.json new file mode 100644 index 0000000..32ffd14 --- /dev/null +++ b/integration_tests/module_node/docs/package.json @@ -0,0 +1,7 @@ +{ + "name": "docs", + "private": true, + "scripts": { + "build": "echo build" + } +} diff --git a/integration_tests/module_node/package.json b/integration_tests/module_node/package.json new file mode 100644 index 0000000..63887c3 --- /dev/null +++ b/integration_tests/module_node/package.json @@ -0,0 +1,8 @@ +{ + "name": "fixture", + "private": true, + "packageManager": "pnpm@9.15.0", + "scripts": { + "lint": "echo lint" + } +} diff --git a/integration_tests/module_node/pnpm-lock.yaml b/integration_tests/module_node/pnpm-lock.yaml new file mode 100644 index 0000000..c1a4322 --- /dev/null +++ b/integration_tests/module_node/pnpm-lock.yaml @@ -0,0 +1 @@ +lockfileVersion: "9.0" diff --git a/internal_docs/STATUS.md b/internal_docs/STATUS.md index 98fd6b6..38a9b27 100644 --- a/internal_docs/STATUS.md +++ b/internal_docs/STATUS.md @@ -79,6 +79,12 @@ What the code does today, checked against the code in December 2026. Where cigen `README.md` and `SKILL.md`, and `src/modules/README.md` is the generated index. The generated hash step passes `--modules-digest`, the digest of the job's module expansions at generation, and `cigen hash` mixes it into the hash and warns when its own expansion differs, so a config generated by another cigen never reuses a pass. Modules: + - `node`: installs Node from `.nvmrc` or `.node-version` (or `version:`, or the image's with `preinstalled`) and the + package manager `packageManager` pins (npm, pnpm through `pnpm/action-setup`, Yarn through Corepack), runs a frozen + install and caches downloads (`actions/setup-node`'s cache on GitHub, `restore_cache`/`save_cache` on CircleCI). + On CircleCI, Node comes from the job's image, and a `node` or `cimg/node` image whose tag doesn't match the pinned + version fails generation. It adds `package.json`, every tracked `**/package.json`, the lockfiles, workspace and + package manager config, patches and the version file to the job's inputs. - `rust`: installs the toolchain `rust-toolchain.toml` names (or a channel) with `rustup`, adds components and targets, and caches with `Swatinem/rust-cache` (GitHub) or `restore_cache`/`save_cache` (CircleCI). It adds `Cargo.toml`, `**/Cargo.toml`, `Cargo.lock`, the toolchain files and `.cargo/config.toml` to the job's inputs. @@ -158,12 +164,15 @@ What the code does today, checked against the code in December 2026. Where cigen `packageManager` pin changes the job's hash; an unused command or service doesn't. - `tests/docs_examples.rs`: every YAML example in the docs (`docs/src/content/docs/`), the case studies (`docs/src/content/case-studies/`, drafts included), the compare pages (`docs/src/content/compare/`) and the - README, and the homepage's config, is run through - `cigen generate`; examples of errors must fail with the error they show. Every file it reads must be an input of - cigen's own `test` job. + README, and the homepage's config, is run through `cigen generate`; examples of errors must fail with the error they + show. A block titled with a path (` ```toml title="Cargo.toml" `) is a project file written into every example on + its page. Every file it reads must be an input of cigen's own `test` job. - `tests/module_scenarios.rs`: a job using the `rust` module installs nothing when it skips, and reruns in mockci when a file the module contributes or its parameters change; the generated `--modules-digest` changes the hash, and a local `hash --job` without it gives the CI step's hash; unknown modules and parameters fail generation with a fix. +- `tests/module_node.rs`: a job using the `node` module installs nothing when it skips, and reruns in mockci when its + lockfile, `.npmrc`, `pnpm-workspace.yaml`, a workspace package's `package.json`, the Node version file or its + parameters change. - `tests/module_catalogue.rs`: every registered module has a skill with frontmatter, a README documenting exactly its parameters, a golden fixture (`integration_tests/module_/`) for each provider it supports that mockci's parser loads, and actions pinned to commit SHAs; the index is generated from the registry @@ -238,4 +247,5 @@ What the code does today, checked against the code in December 2026. Where cigen ## Next -More modules: the `narrow_inputs` opt-in, then `node` and `ruby`. See "Modules" in DIRECTION.md. +More modules: Playwright, the Postgres and S3-compatible services and kache, then `ruby`; the `narrow_inputs` +opt-in is in review (PR #26). See "Modules" in DIRECTION.md. diff --git a/schemas/v1/cigen.schema.json b/schemas/v1/cigen.schema.json index 8fe0ed3..a32e3d4 100644 --- a/schemas/v1/cigen.schema.json +++ b/schemas/v1/cigen.schema.json @@ -322,12 +322,38 @@ { "type": "string", "enum": [ + "node", "rust" ] }, { "type": "object", "properties": { + "node": { + "description": "Installs Node and a package manager (npm, pnpm or Yarn), runs a frozen install and caches the package manager's downloads.", + "type": [ + "object", + "null" + ], + "properties": { + "cache": { + "description": "cache the package manager's downloads (default: `true`)" + }, + "install": { + "description": "run a frozen install (`npm ci`, `pnpm install --frozen-lockfile`, `yarn install --immutable`) (default: `true`)" + }, + "package_manager": { + "description": "`npm`, `pnpm` or `yarn` (default: `package.json`'s `packageManager`, else the one lockfile present, else an error)" + }, + "path": { + "description": "the directory holding `package.json` and the lockfile (default: `.`)" + }, + "version": { + "description": "a Node version, or `preinstalled` for the Node the image or runner already has (default: what `.nvmrc` or `.node-version` in `path` or the root says, else `package.json`'s `engines.node`, else an error)" + } + }, + "additionalProperties": false + }, "rust": { "description": "Installs the Rust toolchain, its components and targets, and caches cargo's downloads and `target/`.", "type": [ diff --git a/schemas/v1/job.schema.json b/schemas/v1/job.schema.json index d2f2503..2763505 100644 --- a/schemas/v1/job.schema.json +++ b/schemas/v1/job.schema.json @@ -150,12 +150,38 @@ { "type": "string", "enum": [ + "node", "rust" ] }, { "type": "object", "properties": { + "node": { + "description": "Installs Node and a package manager (npm, pnpm or Yarn), runs a frozen install and caches the package manager's downloads.", + "type": [ + "object", + "null" + ], + "properties": { + "cache": { + "description": "cache the package manager's downloads (default: `true`)" + }, + "install": { + "description": "run a frozen install (`npm ci`, `pnpm install --frozen-lockfile`, `yarn install --immutable`) (default: `true`)" + }, + "package_manager": { + "description": "`npm`, `pnpm` or `yarn` (default: `package.json`'s `packageManager`, else the one lockfile present, else an error)" + }, + "path": { + "description": "the directory holding `package.json` and the lockfile (default: `.`)" + }, + "version": { + "description": "a Node version, or `preinstalled` for the Node the image or runner already has (default: what `.nvmrc` or `.node-version` in `path` or the root says, else `package.json`'s `engines.node`, else an error)" + } + }, + "additionalProperties": false + }, "rust": { "description": "Installs the Rust toolchain, its components and targets, and caches cargo's downloads and `target/`.", "type": [ diff --git a/schemas/v1/workflow.schema.json b/schemas/v1/workflow.schema.json index fd6cddb..fe7ce44 100644 --- a/schemas/v1/workflow.schema.json +++ b/schemas/v1/workflow.schema.json @@ -208,12 +208,38 @@ { "type": "string", "enum": [ + "node", "rust" ] }, { "type": "object", "properties": { + "node": { + "description": "Installs Node and a package manager (npm, pnpm or Yarn), runs a frozen install and caches the package manager's downloads.", + "type": [ + "object", + "null" + ], + "properties": { + "cache": { + "description": "cache the package manager's downloads (default: `true`)" + }, + "install": { + "description": "run a frozen install (`npm ci`, `pnpm install --frozen-lockfile`, `yarn install --immutable`) (default: `true`)" + }, + "package_manager": { + "description": "`npm`, `pnpm` or `yarn` (default: `package.json`'s `packageManager`, else the one lockfile present, else an error)" + }, + "path": { + "description": "the directory holding `package.json` and the lockfile (default: `.`)" + }, + "version": { + "description": "a Node version, or `preinstalled` for the Node the image or runner already has (default: what `.nvmrc` or `.node-version` in `path` or the root says, else `package.json`'s `engines.node`, else an error)" + } + }, + "additionalProperties": false + }, "rust": { "description": "Installs the Rust toolchain, its components and targets, and caches cargo's downloads and `target/`.", "type": [ diff --git a/src/modules/README.md b/src/modules/README.md index c337fb9..23403d9 100644 --- a/src/modules/README.md +++ b/src/modules/README.md @@ -8,4 +8,5 @@ A job lists modules under `modules:`. Each module's directory holds its docs (`R | Module | Summary | Family | Providers | Parameters | | ------ | ------- | ------ | --------- | ---------- | +| [`node`](node/README.md) | Installs Node and a package manager (npm, pnpm or Yarn), runs a frozen install and caches the package manager's downloads. | node | circleci, github | `version`, `package_manager`, `install`, `cache`, `path` | | [`rust`](rust/README.md) | Installs the Rust toolchain, its components and targets, and caches cargo's downloads and `target/`. | rust | circleci, github | `toolchain`, `components`, `targets`, `cache`, `path` | diff --git a/src/modules/expand.rs b/src/modules/expand.rs index 05013d9..2f01f36 100644 --- a/src/modules/expand.rs +++ b/src/modules/expand.rs @@ -1,9 +1,9 @@ //! Modules applied to jobs: the steps they add when generating, and what they add to a job's //! hash. -use super::{Expansion, Module, load}; +use super::{Context, Expansion, Module, load}; use crate::inputs::canonical_json; use crate::schema::{CigenConfig, Job}; -use anyhow::{Context, Result, bail}; +use anyhow::{Context as _, Result, bail}; use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, BTreeSet}; use std::path::Path; @@ -89,7 +89,12 @@ fn load_all(job_id: &str, job: &Job, root: &Path) -> Result)> = Vec::new(); let mut seen = BTreeSet::new(); for module in &job.modules { - let configured = load(module, root).with_context(|| context(job_id, &module.name))?; + let job_context = Context { + root, + image: &job.image, + }; + let configured = + load(module, &job_context).with_context(|| context(job_id, &module.name))?; let path = configured.resolved()["path"].to_string(); if !seen.insert((module.name.clone(), path.clone())) { bail!( diff --git a/src/modules/mod.rs b/src/modules/mod.rs index 1c32d81..086af01 100644 --- a/src/modules/mod.rs +++ b/src/modules/mod.rs @@ -8,20 +8,22 @@ pub mod catalogue; mod expand; +pub mod node; pub mod rust; mod shell; +mod steps; pub use expand::{JobModules, expand_jobs, for_job}; use crate::schema::{ModuleUse, Step}; -use anyhow::{Context, Result, bail}; +use anyhow::{Context as _, Result, bail}; use serde::Serialize; use serde::de::DeserializeOwned; use serde_yaml::{Mapping, Value}; use std::path::Path; /// Every module, in the order the catalogue lists them. -pub const REGISTRY: &[ModuleSpec] = &[rust::SPEC]; +pub const REGISTRY: &[ModuleSpec] = &[node::SPEC, rust::SPEC]; /// What the catalogue knows about a module. pub struct ModuleSpec { @@ -33,8 +35,22 @@ pub struct ModuleSpec { pub parameters: &'static [Parameter], pub readme: &'static str, pub skill: &'static str, - /// Validates the parameters against the project and returns the configured module. - pub load: fn(&Mapping, &Path) -> Result>, + /// Validates the parameters against the project and job and returns the configured module. + pub load: fn(&Mapping, &Context) -> Result>, +} + +/// What a module can see when it's configured: the project and the job that lists it. +pub struct Context<'a> { + pub root: &'a Path, + /// The job's `image`: a container image or a runner label. + pub image: &'a str, +} + +impl<'a> Context<'a> { + /// A context for a job with no image of its own (tests). + pub fn project(root: &'a Path) -> Self { + Self { root, image: "" } + } } /// One parameter, as documented in the module's README and named in its errors. @@ -77,7 +93,7 @@ pub fn spec(name: &str) -> Result<&'static ModuleSpec> { } /// Configures the module a job lists, checking its parameters first. -pub fn load(module: &ModuleUse, project_root: &Path) -> Result> { +pub fn load(module: &ModuleUse, context: &Context) -> Result> { let spec = spec(&module.name)?; let names: Vec<&str> = spec.parameters.iter().map(|p| p.name).collect(); for key in module.params.keys() { @@ -96,7 +112,7 @@ pub fn load(module: &ModuleUse, project_root: &Path) -> Result> } } } - (spec.load)(&module.params, project_root) + (spec.load)(&module.params, context) } /// Parses a module's parameters into its own type, with serde's error explained. @@ -168,16 +184,19 @@ mod tests { let error = spec("rsut").err().unwrap().to_string(); assert!(error.contains("did you mean `rust`?"), "{error}"); let error = spec("elixir").err().unwrap().to_string(); - assert!(error.contains("modules: `rust`"), "{error}"); + assert!(error.contains("modules: `node`, `rust`"), "{error}"); } #[test] fn an_unknown_parameter_names_the_closest() { let dir = tempfile::tempdir().unwrap(); - let error = load(&module("rust: { component: [clippy] }"), dir.path()) - .err() - .unwrap() - .to_string(); + let error = load( + &module("rust: { component: [clippy] }"), + &Context::project(dir.path()), + ) + .err() + .unwrap() + .to_string(); assert!(error.contains("did you mean `components`?"), "{error}"); } diff --git a/src/modules/node/README.md b/src/modules/node/README.md new file mode 100644 index 0000000..8b4b8ff --- /dev/null +++ b/src/modules/node/README.md @@ -0,0 +1,76 @@ +# `node` module + +Installs Node and the package manager your project pins (npm, pnpm or Yarn), runs a frozen install, and caches the +package manager's downloads. + +```yaml +jobs: + lint: + modules: [node] + inputs: ['src/**'] + steps: + - run: pnpm lint +``` + +## Parameters + +| Parameter | Default | Meaning | +| ----------------- | ---------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | +| `version` | what `.nvmrc` or `.node-version` in `path` or the root says, else `package.json`'s `engines.node`, else an error | a Node version, or `preinstalled` for the Node the image or runner already has | +| `package_manager` | `package.json`'s `packageManager`, else the one lockfile present, else an error | `npm`, `pnpm` or `yarn` | +| `install` | `true` | run a frozen install (`npm ci`, `pnpm install --frozen-lockfile`, `yarn install --immutable`) | +| `cache` | `true` | cache the package manager's downloads | +| `path` | `.` | the directory holding `package.json` and the lockfile | + +- The version file is `.nvmrc` or `.node-version` in `path`, else at the root. Two in one directory, or a file and + `version:`, are an error. `version: preinstalled` ignores them. +- Without a version file, `engines.node` in `path`'s `package.json` pins Node: GitHub's `setup-node` takes the range + (`>=20 <23`) and installs the newest Node in it. On CircleCI the image must match, so `engines.node` must be a version + number there (`22`), not a range. A version file wins over `engines`: it's the exact version, and `engines` the range + the package accepts. +- pnpm and Yarn need a version in `packageManager` (Corepack's convention, such as `"packageManager": "pnpm@9.15.0"`). + Without `packageManager`, the module uses npm, pnpm or Yarn by the one lockfile in `path`; two lockfiles are an + error that names both. Bun isn't supported yet. +- A frozen install and the cache need the lockfile; without one, set `install: false` and `cache: false`. + +## What it adds to a job + +The install is `npm ci`, `pnpm install --frozen-lockfile`, `yarn install --immutable` (Yarn 2 and later) or +`yarn install --frozen-lockfile` (Yarn 1), after `cd &&` when `path` isn't `.`. + +**GitHub Actions**: + +1. pnpm: `pnpm/action-setup`, which installs the version `packageManager` names (with `package_json_file` when `path` + isn't `.`). Yarn: a step that enables Corepack, installing it first when the Node in use doesn't bundle it (Node 25 + and later). +2. `actions/setup-node`, with `node-version-file` or `node-version` (neither for `preinstalled`), and with `cache` set + to the package manager and `cache-dependency-path` to the lockfile, or `package-manager-cache: false` without the + cache. +3. The install. + +**CircleCI**: Node comes from the job's image. With a pinned version, the image must be `node` or `cimg/node` with a +tag that starts with that version (`cimg/node:22.11.0` for `22`), or generation fails and says what to change; any +other image needs `version: preinstalled`. Then: + +1. pnpm and Yarn: a step that enables Corepack in `~/.corepack/bin` and puts it on `PATH`. For pnpm it also sets the + store to `~/.pnpm-store`. +2. With `install` and `cache`, `restore_cache` keyed by the architecture, the package manager and the lockfile, with a + fallback to the newest cache for the same package manager. +3. The install. +4. After the job's steps, `save_cache` of `~/.npm`, `~/.pnpm-store`, `~/.cache/yarn` (Yarn 1) or + `~/.yarn/berry/cache` (Yarn 2 and later). + +## Inputs + +The module adds these files, inside `path`, to the hash of every job that uses it: `package.json`, every tracked +`**/package.json`, the lockfiles (`package-lock.json`, `npm-shrinkwrap.json`, `pnpm-lock.yaml`, `yarn.lock`), +`pnpm-workspace.yaml`, `.npmrc`, `.yarnrc`, `.yarnrc.yml`, `.yarn/patches/**`, `.yarn/releases/**`, `patches/**`, +`.nvmrc` and `.node-version`, plus the version file it found (`engines.node` lives in `package.json`, already among them). Its parameters and the steps it adds go into the hash +too, so a job reruns when either changes. + +## Pinned actions + +| Action | Release | Commit | +| -------------------- | ------- | ------------------------------------------ | +| `actions/setup-node` | v7.2.0 | `8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce` | +| `pnpm/action-setup` | v6.1.1 | `73e46992e05b19abd31f2f3c20e0e7370d762115` | diff --git a/src/modules/node/SKILL.md b/src/modules/node/SKILL.md new file mode 100644 index 0000000..9d9a3fb --- /dev/null +++ b/src/modules/node/SKILL.md @@ -0,0 +1,30 @@ +--- +name: node +description: Set up Node, a package manager (npm, pnpm or Yarn) and a frozen install in a cigen job with `modules: [node]`. Use when a cigen job runs node, npm, pnpm, yarn or npx, instead of writing setup-node, Corepack, install and cache steps by hand. +--- + +# The `node` module + +Add `node` to the job's `modules:` instead of writing setup and install steps: + +```yaml +jobs: + lint: + modules: [node] + inputs: ['src/**'] + steps: + - run: pnpm lint +``` + +- Pin Node in `.nvmrc` or `.node-version` (or `engines.node` in `package.json`) rather than with `version:`; setting both is an error. On CircleCI, Node + comes from the job's image: use a `cimg/node:` image that matches, or `version: preinstalled`. +- Pin pnpm or Yarn with `packageManager` in `package.json` (`"packageManager": "pnpm@9.15.0"`). The module needs it, + and it reads the package manager from it. +- The module runs the frozen install (`npm ci`, `pnpm install --frozen-lockfile`, `yarn install --immutable`). Don't + add an install step; set `install: false` for a job that doesn't need `node_modules`. +- For a project that isn't at the repository root, set `path:` to the directory with its `package.json`. +- Don't add `package.json`, the lockfile or `.nvmrc` to `inputs`: the module adds them. Declare the job's sources. +- Don't write `uses: actions/setup-node` or `pnpm/action-setup` beside the module. + +Parameters: `version`, `package_manager`, `install`, `cache`, `path`. An unknown parameter is an error that names the +closest one. diff --git a/src/modules/node/expand.rs b/src/modules/node/expand.rs new file mode 100644 index 0000000..393d18e --- /dev/null +++ b/src/modules/node/expand.rs @@ -0,0 +1,191 @@ +//! The steps the node module adds on each provider. +use super::{Manager, Node, Version}; +use crate::modules::Expansion; +use crate::modules::in_path; +use crate::modules::steps::{restore_cache, run, save_cache, uses}; +use anyhow::{Result, bail}; +use serde_yaml::Value; +use std::collections::BTreeMap; + +/// `actions/setup-node` v7.2.0. +pub const SETUP_NODE: &str = "actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce"; +/// `pnpm/action-setup` v6.1.1. +pub const PNPM_SETUP: &str = "pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115"; +/// Corepack, installed with npm when the Node in use doesn't bundle it (Node 25 and later). +pub const COREPACK: &str = "corepack@0.36.0"; + +impl Node { + pub(super) fn github(&self) -> Expansion { + let mut before = Vec::new(); + match self.manager.manager { + Manager::Npm => {} + Manager::Pnpm => { + let mut with = BTreeMap::new(); + if self.path != "." { + with.insert( + "package_json_file".to_string(), + Value::from(in_path(&self.path, "package.json")), + ); + } + before.push(uses("Install pnpm", PNPM_SETUP, with)); + } + // Before setup-node, whose Yarn cache asks `yarn` where its cache is. + Manager::Yarn => before.push(run( + "Enable Corepack", + corepack( + "\"$RUNNER_TEMP/corepack\"", + "echo \"$RUNNER_TEMP/corepack/bin\" >> \"$GITHUB_PATH\"\necho COREPACK_ENABLE_DOWNLOAD_PROMPT=0 >> \"$GITHUB_ENV\"", + ), + )), + } + let mut with = BTreeMap::new(); + match &self.version { + Version::File { file, .. } => { + with.insert("node-version-file".to_string(), Value::from(file.clone())); + } + Version::Given(version) | Version::Engines { range: version, .. } => { + with.insert("node-version".to_string(), Value::from(version.clone())); + } + Version::Preinstalled => {} + } + if self.cache { + with.insert( + "cache".to_string(), + Value::from(self.manager.manager.name()), + ); + with.insert( + "cache-dependency-path".to_string(), + Value::from(self.lockfile.clone()), + ); + } else { + with.insert("package-manager-cache".to_string(), Value::from(false)); + } + before.push(uses("Set up Node", SETUP_NODE, with)); + if self.install { + before.push(run("Install dependencies", self.install_command())); + } + Expansion { + before, + after: Vec::new(), + } + } + + pub(super) fn circleci(&self) -> Result { + if let Some(error) = &self.circleci_image_error { + bail!("{error}"); + } + let mut before = Vec::new(); + let mut env = + vec!["echo 'export COREPACK_ENABLE_DOWNLOAD_PROMPT=0' >> \"$BASH_ENV\"".to_string()]; + if self.manager.manager == Manager::Pnpm { + // A fixed store, so `save_cache` knows where it is. + env.push( + "echo 'export npm_config_store_dir=\"$HOME/.pnpm-store\"' >> \"$BASH_ENV\"" + .to_string(), + ); + } + if self.manager.manager != Manager::Npm { + env.insert( + 0, + "echo 'export PATH=\"$HOME/.corepack/bin:$PATH\"' >> \"$BASH_ENV\"".to_string(), + ); + before.push(run( + "Enable Corepack", + corepack("\"$HOME/.corepack\"", &env.join("\n")), + )); + } + let mut after = Vec::new(); + if self.install { + let paths = self.circleci_cache_paths(); + let name = self.manager.manager.name(); + let prefix = format!("node-v1-{{{{ arch }}}}-{name}-"); + let key = format!("{prefix}{{{{ checksum \"{}\" }}}}", self.lockfile); + if self.cache { + before.push(restore_cache( + &format!("Restore {name} cache"), + vec![key.clone(), prefix], + )); + } + before.push(run("Install dependencies", self.install_command())); + if self.cache { + after.push(save_cache(&format!("Save {name} cache"), key, paths)); + } + } + Ok(Expansion { before, after }) + } + + fn install_command(&self) -> String { + let install = match self.manager.manager { + Manager::Npm => "npm ci", + Manager::Pnpm => "pnpm install --frozen-lockfile", + Manager::Yarn if self.manager.is_yarn_classic() => "yarn install --frozen-lockfile", + Manager::Yarn => "yarn install --immutable", + }; + if self.path == "." { + install.to_string() + } else { + format!("cd {} && {install}", self.path) + } + } + + fn circleci_cache_paths(&self) -> Vec { + let paths: &[&str] = match self.manager.manager { + Manager::Npm => &["~/.npm"], + Manager::Pnpm => &["~/.pnpm-store"], + Manager::Yarn if self.manager.is_yarn_classic() => &["~/.cache/yarn"], + Manager::Yarn => &["~/.yarn/berry/cache"], + }; + paths.iter().map(|path| path.to_string()).collect() + } +} + +/// Enables Corepack's shims in `/bin`, installing Corepack there first when the Node in +/// use doesn't bundle it, then runs `persist` so later steps find them. +fn corepack(prefix: &str, persist: &str) -> String { + format!( + "export PATH={prefix}/bin:$PATH\n\ + mkdir -p {prefix}/bin\n\ + command -v corepack >/dev/null || npm install --global --prefix {prefix} {COREPACK}\n\ + corepack enable --install-directory {prefix}/bin\n\ + {persist}\n" + ) +} + +/// On CircleCI, Node comes from the job's image: a `node` or `cimg/node` image whose tag +/// starts with the pinned version, or any image with `version: preinstalled`. +pub fn circleci_image_error(image: &str, version: &Version) -> Option { + let pinned = match version { + Version::Preinstalled => return None, + Version::File { version, .. } + | Version::Given(version) + | Version::Engines { range: version, .. } => version.trim_start_matches('v').to_string(), + }; + let image = image.split('@').next().unwrap_or(image); + let (name, tag) = match image.rsplit_once(':') { + Some((name, tag)) if !tag.contains('/') => (name, tag), + _ => (image, "latest"), + }; + let node_image = matches!( + name.trim_start_matches("docker.io/"), + "node" | "library/node" | "cimg/node" | "circleci/node" + ); + if !node_image { + return Some(format!( + "on CircleCI, Node comes from the job's image, and `{image}` isn't a `node` or `cimg/node` image; use one (such as `cimg/node:{pinned}`), or set `version: preinstalled` to use the Node it has" + )); + } + let numeric = !pinned.is_empty() && pinned.chars().all(|c| c.is_ascii_digit() || c == '.'); + if !numeric { + return Some(format!( + "on CircleCI, Node comes from the job's image, and cigen can't check `{image}` against Node `{pinned}`; pin a version number, or set `version: preinstalled`" + )); + } + let matches = tag == pinned + || tag.starts_with(&format!("{pinned}.")) + || tag.starts_with(&format!("{pinned}-")); + (!matches).then(|| { + format!( + "the job's image `{image}` doesn't have Node `{pinned}`; change the image's tag to `{pinned}`, or the pinned version to the image's" + ) + }) +} diff --git a/src/modules/node/manager.rs b/src/modules/node/manager.rs new file mode 100644 index 0000000..045c116 --- /dev/null +++ b/src/modules/node/manager.rs @@ -0,0 +1,132 @@ +//! Which package manager a Node project uses, and its version. +use crate::modules::in_path; +use anyhow::{Context as _, Result, bail}; +use std::path::Path; + +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Manager { + Npm, + Pnpm, + Yarn, +} + +impl Manager { + pub fn name(self) -> &'static str { + match self { + Manager::Npm => "npm", + Manager::Pnpm => "pnpm", + Manager::Yarn => "yarn", + } + } + + pub fn lockfile(self) -> &'static str { + match self { + Manager::Npm => "package-lock.json", + Manager::Pnpm => "pnpm-lock.yaml", + Manager::Yarn => "yarn.lock", + } + } + + fn parse(name: &str) -> Result { + match name { + "npm" => Ok(Manager::Npm), + "pnpm" => Ok(Manager::Pnpm), + "yarn" => Ok(Manager::Yarn), + "bun" => bail!("the node module doesn't support Bun yet"), + other => bail!("unknown package manager `{other}`; use `npm`, `pnpm` or `yarn`"), + } + } +} + +/// A package manager and the version `packageManager` pins (pnpm and Yarn always have one). +#[derive(Debug, Clone, PartialEq)] +pub struct PackageManager { + pub manager: Manager, + pub version: Option, +} + +impl PackageManager { + /// Yarn 1, which installs with `--frozen-lockfile` rather than `--immutable`. + pub fn is_yarn_classic(&self) -> bool { + self.manager == Manager::Yarn + && self + .version + .as_deref() + .is_some_and(|version| version.starts_with("1.")) + } +} + +/// The package manager for the project in `path`: `packageManager` in its `package.json`, the +/// `package_manager` parameter, or the one lockfile present. +pub fn detect(root: &Path, path: &str, given: Option<&str>) -> Result { + let package_json = in_path(path, "package.json"); + let text = std::fs::read_to_string(root.join(&package_json))?; + let json: serde_json::Value = serde_json::from_str(&text) + .with_context(|| format!("`{package_json}` isn't valid JSON"))?; + let pinned = match json.get("packageManager") { + None => None, + Some(serde_json::Value::String(spec)) => Some(parse_spec(spec, &package_json)?), + Some(_) => { + bail!("`packageManager` in `{package_json}` must be a string such as `pnpm@9.15.0`") + } + }; + let given = given.map(Manager::parse).transpose()?; + let found = match (pinned, given) { + (Some(pinned), Some(given)) if pinned.manager != given => bail!( + "`package_manager: {}` but `packageManager` in `{package_json}` says `{}`; remove the parameter", + given.name(), + pinned.manager.name() + ), + (Some(pinned), _) => pinned, + (None, Some(manager)) => PackageManager { + manager, + version: None, + }, + (None, None) => PackageManager { + manager: from_lockfiles(root, path)?, + version: None, + }, + }; + if found.manager != Manager::Npm && found.version.is_none() { + bail!( + "{} needs a version in `packageManager` in `{package_json}`, such as `\"packageManager\": \"{}@\"` (Corepack's convention)", + found.manager.name(), + found.manager.name() + ); + } + Ok(found) +} + +/// `pnpm@9.15.0+sha512.…` → pnpm, `9.15.0`. +fn parse_spec(spec: &str, package_json: &str) -> Result { + let Some((name, version)) = spec.split_once('@') else { + bail!( + "`packageManager` in `{package_json}` is `{spec}`; write `@`, such as `pnpm@9.15.0`" + ); + }; + let version = version.split('+').next().unwrap_or(version); + super::super::shell::check_token("packageManager version", version, "")?; + Ok(PackageManager { + manager: Manager::parse(name)?, + version: Some(version.to_string()), + }) +} + +fn from_lockfiles(root: &Path, path: &str) -> Result { + let found: Vec = [Manager::Npm, Manager::Pnpm, Manager::Yarn] + .into_iter() + .filter(|manager| root.join(in_path(path, manager.lockfile())).is_file()) + .collect(); + match found.as_slice() { + [manager] => Ok(*manager), + [] => bail!( + "can't tell the package manager: `{}` has no `packageManager` and `{path}` has no lockfile; set `packageManager` (such as `pnpm@9.15.0`) or `package_manager:`", + in_path(path, "package.json") + ), + _ => bail!( + "`{}` and `{}` are both in `{path}`; delete the one you don't use, or set `packageManager` in `package.json`", + found[0].lockfile(), + found[1].lockfile() + ), + } +} diff --git a/src/modules/node/mod.rs b/src/modules/node/mod.rs new file mode 100644 index 0000000..b57bb8e --- /dev/null +++ b/src/modules/node/mod.rs @@ -0,0 +1,265 @@ +//! The `node` module: Node, a package manager (npm, pnpm or Yarn), a frozen install and the +//! package manager's download cache. +use super::{ + Context, Expansion, Module, ModuleSpec, Parameter, in_path, module_path, parse_params, +}; +use anyhow::{Result, bail}; +use serde::Deserialize; +use serde_yaml::Mapping; +use std::path::Path; + +mod expand; +mod manager; + +use manager::{Manager, PackageManager}; + +/// The files that pin Node, in the order the module looks for them. +const VERSION_FILES: &[&str] = &[".nvmrc", ".node-version"]; + +pub const SPEC: ModuleSpec = ModuleSpec { + name: "node", + summary: "Installs Node and a package manager (npm, pnpm or Yarn), runs a frozen install and caches the package manager's downloads.", + family: "node", + providers: &["circleci", "github"], + parameters: &[ + Parameter { + name: "version", + default: "what `.nvmrc` or `.node-version` in `path` or the root says, else `package.json`'s `engines.node`, else an error", + meaning: "a Node version, or `preinstalled` for the Node the image or runner already has", + }, + Parameter { + name: "package_manager", + default: "`package.json`'s `packageManager`, else the one lockfile present, else an error", + meaning: "`npm`, `pnpm` or `yarn`", + }, + Parameter { + name: "install", + default: "`true`", + meaning: "run a frozen install (`npm ci`, `pnpm install --frozen-lockfile`, `yarn install --immutable`)", + }, + Parameter { + name: "cache", + default: "`true`", + meaning: "cache the package manager's downloads", + }, + Parameter { + name: "path", + default: "`.`", + meaning: "the directory holding `package.json` and the lockfile", + }, + ], + readme: include_str!("README.md"), + skill: include_str!("SKILL.md"), + load, +}; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Params { + #[serde(default)] + version: Option, + #[serde(default)] + package_manager: Option, + #[serde(default = "yes")] + install: bool, + #[serde(default = "yes")] + cache: bool, + #[serde(default = "dot")] + path: String, +} + +fn yes() -> bool { + true +} + +fn dot() -> String { + ".".to_string() +} + +/// Where Node's version comes from. +#[derive(Debug, Clone, PartialEq)] +enum Version { + /// A version file, relative to the project root, and the version it holds. + File { + file: String, + version: String, + }, + Given(String), + /// `engines.node` in a `package.json` (relative to the project root): a range. + Engines { + file: String, + range: String, + }, + /// The Node the image or runner already has. + Preinstalled, +} + +struct Node { + path: String, + version: Version, + manager: PackageManager, + install: bool, + cache: bool, + /// The lockfile, relative to the project root. + lockfile: String, + /// The CircleCI image's problem with the version, found when loading and reported only + /// when expanding for CircleCI, so a GitHub-only config never sees it. + circleci_image_error: Option, +} + +fn load(params: &Mapping, context: &Context) -> Result> { + let root = context.root; + let params: Params = parse_params(params)?; + let path = module_path(¶ms.path, root)?; + let package_json = in_path(&path, "package.json"); + if !root.join(&package_json).is_file() { + bail!("there's no `package.json` in `{path}`; set `path:` to the directory that has it"); + } + let version = match params.version.as_deref() { + Some("preinstalled") => Version::Preinstalled, + Some(version) => { + if let Some(file) = version_file(&path, root)? { + bail!("`version: {version}` and `{file}` both pin Node; remove one"); + } + Version::Given(version.to_string()) + } + None => match version_file(&path, root)? { + Some(file) => { + let version = std::fs::read_to_string(root.join(&file))? + .trim() + .to_string(); + if version.is_empty() { + bail!("`{file}` is empty; write a Node version in it"); + } + Version::File { file, version } + } + None => match engines(root, &package_json)? { + Some(range) => Version::Engines { + file: package_json.clone(), + range, + }, + None => bail!( + "nothing pins Node's version: add `.nvmrc` (such as `22`), set `engines.node` in `{package_json}`, or set `version:` (a version, or `preinstalled` for the image's Node)" + ), + }, + }, + }; + let manager = manager::detect(root, &path, params.package_manager.as_deref())?; + let lockfile = in_path(&path, manager.manager.lockfile()); + if (params.install || params.cache) && !root.join(&lockfile).is_file() { + bail!( + "there's no `{lockfile}`, which a frozen install and the cache need; commit it, or set `install: false` and `cache: false`" + ); + } + let circleci_image_error = expand::circleci_image_error(context.image, &version); + Ok(Box::new(Node { + path, + version, + manager, + install: params.install, + cache: params.cache, + lockfile, + circleci_image_error, + })) +} + +/// `engines.node` in `package_json`, if it's set. +fn engines(root: &Path, package_json: &str) -> Result> { + let text = std::fs::read_to_string(root.join(package_json))?; + let json: serde_json::Value = serde_json::from_str(&text) + .map_err(|error| anyhow::anyhow!("`{package_json}` isn't valid JSON: {error}"))?; + match json.pointer("/engines/node") { + None => Ok(None), + Some(serde_json::Value::String(range)) if !range.trim().is_empty() => { + Ok(Some(range.trim().to_string())) + } + Some(other) => { + bail!("`engines.node` in `{package_json}` is `{other}`; make it a version string") + } + } +} + +/// The version file in `path`, else at the root. Two in one directory are an error. +fn version_file(path: &str, root: &Path) -> Result> { + let mut dirs = vec![path.to_string()]; + if path != "." { + dirs.push(".".to_string()); + } + for dir in dirs { + let found: Vec = VERSION_FILES + .iter() + .map(|file| in_path(&dir, file)) + .filter(|file| root.join(file).is_file()) + .collect(); + match found.as_slice() { + [] => continue, + [file] => return Ok(Some(file.clone())), + _ => bail!("`{}` and `{}` both pin Node; keep one", found[0], found[1]), + } + } + Ok(None) +} + +impl Module for Node { + fn resolved(&self) -> serde_json::Value { + let version = match &self.version { + Version::File { file, version } => { + serde_json::json!({ "file": file, "version": version }) + } + Version::Given(version) => serde_json::json!({ "given": version }), + Version::Engines { file, range } => { + serde_json::json!({ "engines": range, "file": file }) + } + Version::Preinstalled => serde_json::json!("preinstalled"), + }; + serde_json::json!({ + "path": self.path, + "version": version, + "package_manager": self.manager.manager.name(), + "package_manager_version": self.manager.version, + "install": self.install, + "cache": self.cache, + "lockfile": self.lockfile, + }) + } + + fn inputs(&self) -> Vec { + let mut inputs: Vec = [ + "package.json", + "**/package.json", + "package-lock.json", + "npm-shrinkwrap.json", + "pnpm-lock.yaml", + "pnpm-workspace.yaml", + "yarn.lock", + ".npmrc", + ".yarnrc", + ".yarnrc.yml", + ".yarn/patches/**", + ".yarn/releases/**", + "patches/**", + ".nvmrc", + ".node-version", + ] + .iter() + .map(|file| in_path(&self.path, file)) + .collect(); + if let Version::File { file, .. } = &self.version { + inputs.push(file.clone()); + } + inputs.sort(); + inputs.dedup(); + inputs + } + + fn expand(&self, provider: &str) -> Result { + match provider { + "github" => Ok(self.github()), + "circleci" => self.circleci(), + other => bail!("the node module doesn't support provider `{other}`"), + } + } +} + +#[cfg(test)] +mod tests; diff --git a/src/modules/node/tests.rs b/src/modules/node/tests.rs new file mode 100644 index 0000000..590258f --- /dev/null +++ b/src/modules/node/tests.rs @@ -0,0 +1,280 @@ +use super::expand::{PNPM_SETUP, SETUP_NODE}; +use super::*; +use crate::modules::Context; +use crate::schema::Step; +use std::fs; +use tempfile::TempDir; + +fn project(files: &[(&str, &str)]) -> TempDir { + let dir = tempfile::tempdir().unwrap(); + for (path, contents) in files { + let path = dir.path().join(path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, contents).unwrap(); + } + dir +} + +fn node(params: &str, dir: &TempDir) -> Result> { + node_on(params, dir, "") +} + +fn node_on(params: &str, dir: &TempDir, image: &str) -> Result> { + let params: Mapping = serde_yaml::from_str(params).unwrap(); + load( + ¶ms, + &Context { + root: dir.path(), + image, + }, + ) +} + +fn error(result: Result>) -> String { + format!("{:#}", result.err().expect("an error")) +} + +/// Each step as `name: what it runs or uses`. +fn summary(steps: &[Step]) -> Vec { + steps + .iter() + .map(|step| match step { + Step::Run(run) => format!( + "{}: {}", + run.name.as_deref().unwrap(), + run.run.command().trim() + ), + Step::Uses(uses) => { + let with = serde_json::to_string(&uses.with).unwrap(); + format!("{}: {} {with}", uses.name.as_deref().unwrap(), uses.uses) + } + Step::RestoreCache { restore_cache } => { + format!("restore: {}", restore_cache.keys.join(" | ")) + } + Step::SaveCache { save_cache } => format!( + "save: {} {}", + save_cache.key.as_deref().unwrap(), + save_cache.paths.join(",") + ), + Step::Custom(_) => "custom".to_string(), + }) + .collect() +} + +const PNPM: &[(&str, &str)] = &[ + ( + "package.json", + r#"{"packageManager": "pnpm@9.15.0+sha512.abc"}"#, + ), + ("pnpm-lock.yaml", "lockfileVersion: '9.0'\n"), + (".nvmrc", "22\n"), +]; + +#[test] +fn pnpm_on_github() { + let dir = project(PNPM); + let expansion = node("{}", &dir).unwrap().expand("github").unwrap(); + assert_eq!( + summary(&expansion.before), + [ + format!("Install pnpm: {PNPM_SETUP} {{}}"), + format!( + "Set up Node: {SETUP_NODE} {{\"cache\":\"pnpm\",\"cache-dependency-path\":\"pnpm-lock.yaml\",\"node-version-file\":\".nvmrc\"}}" + ), + "Install dependencies: pnpm install --frozen-lockfile".to_string(), + ] + ); + assert!(expansion.after.is_empty()); +} + +#[test] +fn pnpm_on_circleci_uses_corepack_and_a_fixed_store() { + let dir = project(PNPM); + let expansion = node_on("{}", &dir, "cimg/node:22.11.0") + .unwrap() + .expand("circleci") + .unwrap(); + let before = summary(&expansion.before); + assert!(before[0].starts_with("Enable Corepack:"), "{before:?}"); + assert!( + before[0].contains("corepack enable --install-directory"), + "{before:?}" + ); + assert!(before[0].contains("npm_config_store_dir"), "{before:?}"); + assert_eq!( + before[1..], + [ + "restore: node-v1-{{ arch }}-pnpm-{{ checksum \"pnpm-lock.yaml\" }} | node-v1-{{ arch }}-pnpm-", + "Install dependencies: pnpm install --frozen-lockfile", + ] + ); + assert_eq!( + summary(&expansion.after), + ["save: node-v1-{{ arch }}-pnpm-{{ checksum \"pnpm-lock.yaml\" }} ~/.pnpm-store"] + ); +} + +#[test] +fn npm_needs_no_corepack_and_yarn_installs_by_major_version() { + let dir = project(&[ + ("web/package.json", "{}"), + ("web/package-lock.json", "{}"), + ("web/.node-version", "v20.18.0\n"), + ]); + let module = node("{ path: web, cache: false }", &dir).unwrap(); + assert_eq!( + summary(&module.expand("github").unwrap().before), + [ + format!( + "Set up Node: {SETUP_NODE} {{\"node-version-file\":\"web/.node-version\",\"package-manager-cache\":false}}" + ), + "Install dependencies: cd web && npm ci".to_string(), + ] + ); + for (version, install) in [("1.22.22", "--frozen-lockfile"), ("4.5.0", "--immutable")] { + let dir = project(&[ + ( + "package.json", + &format!(r#"{{"packageManager": "yarn@{version}"}}"#), + ), + ("yarn.lock", ""), + ]); + let module = node("{ version: preinstalled }", &dir).unwrap(); + let before = summary(&module.expand("github").unwrap().before); + assert!(before[0].starts_with("Enable Corepack:"), "{before:?}"); + assert_eq!( + before[2], + format!("Install dependencies: yarn install {install}") + ); + } +} + +#[test] +fn circleci_checks_the_image_has_the_pinned_node() { + let dir = project(PNPM); + for image in [ + "cimg/node:22.11.0", + "node:22-bookworm", + "cimg/node:22.11.0-browsers", + ] { + assert!( + node_on("{}", &dir, image) + .unwrap() + .expand("circleci") + .is_ok(), + "{image}" + ); + } + let wrong = node_on("{}", &dir, "cimg/node:20.18.0").unwrap(); + let message = format!("{:#}", wrong.expand("circleci").unwrap_err()); + assert!(message.contains("doesn't have Node `22`"), "{message}"); + // GitHub doesn't care about the image. + assert!(wrong.expand("github").is_ok()); + let other = node_on("{}", &dir, "ruby:3.4").unwrap(); + let message = format!("{:#}", other.expand("circleci").unwrap_err()); + assert!(message.contains("version: preinstalled"), "{message}"); + // `preinstalled` uses whatever Node the image has, whatever `.nvmrc` says. + let preinstalled = node_on("{ version: preinstalled }", &dir, "ruby:3.4").unwrap(); + assert!(preinstalled.expand("circleci").is_ok()); +} + +#[test] +fn mistakes_fail_with_a_fix() { + let dir = project(&[("package.json", "{}")]); + assert!(error(node("{}", &dir)).contains("add `.nvmrc`")); + let dir = project(&[ + ("package.json", "{}"), + (".nvmrc", "22"), + ("pnpm-lock.yaml", ""), + ("yarn.lock", ""), + ]); + assert!(error(node("{}", &dir)).contains("`pnpm-lock.yaml` and `yarn.lock` are both in `.`")); + let dir = project(&[ + ("package.json", "{}"), + (".nvmrc", "22"), + ("pnpm-lock.yaml", ""), + ]); + assert!(error(node("{}", &dir)).contains("pnpm needs a version in `packageManager`")); + let dir = project(&[ + ("package.json", "{}"), + (".nvmrc", "22"), + (".node-version", "22"), + ]); + assert!(error(node("{}", &dir)).contains("both pin Node; keep one")); + let dir = project(&[ + ("package.json", r#"{"packageManager": "npm@10.9.0"}"#), + (".nvmrc", "22"), + ]); + assert!(error(node("{}", &dir)).contains("there's no `package-lock.json`")); + assert!(node("{ install: false, cache: false }", &dir).is_ok()); + assert!(error(node("{ package_manager: pnpm }", &dir)).contains("remove the parameter")); + let dir = project(&[ + ("package.json", r#"{"packageManager": "bun@1.1.0"}"#), + (".nvmrc", "22"), + ]); + assert!(error(node("{}", &dir)).contains("doesn't support Bun yet")); + let dir = project(&[(".nvmrc", "22")]); + assert!(error(node("{}", &dir)).contains("there's no `package.json` in `.`")); +} + +#[test] +fn inputs_cover_the_project_in_its_path() { + let dir = project(&[ + ("docs/package.json", r#"{"packageManager": "pnpm@9.15.0"}"#), + ("docs/pnpm-lock.yaml", ""), + (".nvmrc", "22"), + ]); + let inputs = node("{ path: docs }", &dir).unwrap().inputs(); + for input in [ + ".nvmrc", + "docs/package.json", + "docs/**/package.json", + "docs/pnpm-lock.yaml", + "docs/.npmrc", + ] { + assert!(inputs.contains(&input.to_string()), "{input}: {inputs:?}"); + } +} + +#[test] +fn without_a_version_file_engines_pins_node() { + let engines = r#"{"packageManager": "pnpm@9.15.0", "engines": {"node": ">=20 <23"}}"#; + let dir = project(&[("package.json", engines), ("pnpm-lock.yaml", "")]); + let module = node("{}", &dir).unwrap(); + assert_eq!( + module.resolved()["version"], + serde_json::json!({ "engines": ">=20 <23", "file": "package.json" }) + ); + let steps = summary(&module.expand("github").unwrap().before); + assert!( + steps + .iter() + .any(|step| step.starts_with("Set up Node") + && step.contains(r#""node-version":">=20 <23""#)), + "{steps:?}" + ); + // A range can't be checked against a CircleCI image. + let circleci = node_on("{}", &dir, "cimg/node:22.11") + .unwrap() + .expand("circleci"); + let message = format!("{:#}", circleci.expect_err("an error")); + assert!(message.contains("pin a version number"), "{message}"); + let dir = project(&[ + ( + "package.json", + r#"{"packageManager": "pnpm@9.15.0", "engines": {"node": "22"}}"#, + ), + ("pnpm-lock.yaml", ""), + ]); + let module = node_on("{}", &dir, "cimg/node:22.11").unwrap(); + assert!(module.expand("circleci").is_ok()); + + // A version file wins: it's the exact version, engines the range the package accepts. + let dir = project(&[ + ("package.json", engines), + ("pnpm-lock.yaml", ""), + (".nvmrc", "22\n"), + ]); + let module = node("{}", &dir).unwrap(); + assert_eq!(module.resolved()["version"]["file"], ".nvmrc"); +} diff --git a/src/modules/rust/mod.rs b/src/modules/rust/mod.rs index 73d9fc8..d0a5c60 100644 --- a/src/modules/rust/mod.rs +++ b/src/modules/rust/mod.rs @@ -1,7 +1,9 @@ //! The `rust` module: installs the toolchain `rust-toolchain.toml` names (or a channel), adds //! components and targets, and caches cargo's downloads and `target/`. use super::shell::check_token; -use super::{Expansion, Module, ModuleSpec, Parameter, in_path, module_path, parse_params}; +use super::{ + Context, Expansion, Module, ModuleSpec, Parameter, in_path, module_path, parse_params, +}; use crate::schema::{ RestoreCacheDefinition, RunCommand, RunStep, SaveCacheDefinition, Step, UsesStep, }; @@ -95,7 +97,8 @@ struct Rust { lockfile: String, } -fn load(params: &Mapping, root: &Path) -> Result> { +fn load(params: &Mapping, context: &Context) -> Result> { + let root = context.root; let params: Params = parse_params(params)?; let path = module_path(¶ms.path, root)?; if !root.join(in_path(&path, "Cargo.toml")).is_file() { diff --git a/src/modules/rust/tests.rs b/src/modules/rust/tests.rs index 746b78f..53712ef 100644 --- a/src/modules/rust/tests.rs +++ b/src/modules/rust/tests.rs @@ -14,7 +14,7 @@ fn project(files: &[&str]) -> TempDir { fn rust(params: &str, dir: &TempDir) -> Result> { let params: Mapping = serde_yaml::from_str(params).unwrap(); - load(¶ms, dir.path()) + load(¶ms, &super::super::Context::project(dir.path())) } fn run_command(step: &Step) -> &str { diff --git a/src/modules/steps.rs b/src/modules/steps.rs new file mode 100644 index 0000000..c844240 --- /dev/null +++ b/src/modules/steps.rs @@ -0,0 +1,53 @@ +//! Building the plain steps a module expands into. +use crate::schema::{ + RestoreCacheDefinition, RunCommand, RunStep, SaveCacheDefinition, Step, UsesStep, +}; +use serde_yaml::Value; +use std::collections::BTreeMap; + +/// A run step named `name`. +pub fn run(name: &str, command: impl Into) -> Step { + Step::Run(RunStep { + run: RunCommand::Command(command.into()), + name: Some(name.to_string()), + env: BTreeMap::new(), + condition: None, + extra: BTreeMap::new(), + }) +} + +/// A GitHub action step: `action` is pinned to a commit, `with` holds its inputs. +pub fn uses(name: &str, action: &str, with: BTreeMap) -> Step { + Step::Uses(UsesStep { + name: Some(name.to_string()), + uses: action.to_string(), + with, + condition: None, + extra: BTreeMap::new(), + }) +} + +/// A CircleCI `restore_cache` that tries each key in turn. +pub fn restore_cache(name: &str, keys: Vec) -> Step { + Step::RestoreCache { + restore_cache: RestoreCacheDefinition { + name: Some(name.to_string()), + key: None, + keys, + restore_keys: Vec::new(), + extra: BTreeMap::new(), + }, + } +} + +/// A CircleCI `save_cache` of `paths` under `key`. +pub fn save_cache(name: &str, key: String, paths: Vec) -> Step { + Step::SaveCache { + save_cache: SaveCacheDefinition { + name: Some(name.to_string()), + key: Some(key), + paths, + extra: BTreeMap::new(), + }, + } +} diff --git a/tests/golden_fixtures.rs b/tests/golden_fixtures.rs index d17c92a..fae1935 100644 --- a/tests/golden_fixtures.rs +++ b/tests/golden_fixtures.rs @@ -22,6 +22,7 @@ const FIXTURES: &[(&str, &[&str])] = &[ ("circleci_node_simple_inline", &[".circleci"]), ("circleci_node_simple_split", &[".circleci"]), ("circleci_rails", &[".circleci"]), + ("module_node", &[".circleci", ".github"]), ("module_rust", &[".circleci", ".github"]), ]; diff --git a/tests/module_catalogue.rs b/tests/module_catalogue.rs index b459aff..a0a6cd0 100644 --- a/tests/module_catalogue.rs +++ b/tests/module_catalogue.rs @@ -7,8 +7,9 @@ mod support; -use cigen::modules::{ModuleSpec, REGISTRY, catalogue, load}; +use cigen::modules::{Context, ModuleSpec, REGISTRY, catalogue, load}; use cigen::schema::{ModuleUse, Step}; +use serde_yaml::Value; use std::path::PathBuf; fn fixture(spec: &ModuleSpec) -> PathBuf { @@ -17,6 +18,32 @@ fn fixture(spec: &ModuleSpec) -> PathBuf { .join(format!("module_{}", spec.name)) } +/// The first job in the module's fixture that uses it: the module as it lists it, and its image. +fn first_use(spec: &ModuleSpec) -> (ModuleUse, String) { + let text = std::fs::read_to_string(fixture(spec).join("cigen.yml")).unwrap(); + let config: Value = serde_yaml::from_str(&text).unwrap(); + let jobs = config["workflows"] + .as_mapping() + .into_iter() + .flat_map(|workflows| workflows.values()) + .flat_map(|workflow| { + workflow["jobs"] + .as_mapping() + .into_iter() + .flat_map(|jobs| jobs.values()) + }); + for job in jobs { + for module in job["modules"].as_sequence().into_iter().flatten() { + let module: ModuleUse = serde_yaml::from_value(module.clone()).unwrap(); + if module.name == spec.name { + let image = job["image"].as_str().unwrap_or_default().to_string(); + return (module, image); + } + } + } + panic!("no job in {}'s fixture uses it", spec.name); +} + #[test] fn the_index_is_generated_from_the_registry() { let path = support::repo_root().join("src/modules/README.md"); @@ -118,12 +145,14 @@ fn every_module_has_a_golden_fixture_per_provider() { #[test] fn modules_pin_actions_to_commits() { for spec in REGISTRY { + let (module, image) = first_use(spec); + let root = fixture(spec); let module = load( - &ModuleUse { - name: spec.name.to_string(), - ..Default::default() + &module, + &Context { + root: &root, + image: &image, }, - &fixture(spec), ) .unwrap_or_else(|error| panic!("{}: {error:#}", spec.name)); for provider in spec.providers { diff --git a/tests/module_node.rs b/tests/module_node.rs new file mode 100644 index 0000000..29c10e0 --- /dev/null +++ b/tests/module_node.rs @@ -0,0 +1,140 @@ +//! The `node` module end to end: a job that uses it skips with nothing installed, and reruns +//! in mockci when a file the module contributes or its parameters change. + +mod support; + +use cigen_mockci::{RunReport, Simulator}; +use support::fixture_repo::FixtureRepo; +use support::skip::{WORKFLOW, push, simulator, tests_ran}; + +const INSTALL_STEP: &str = "Install dependencies"; + +/// A pnpm project in `web/`, with Node pinned at the root. +fn node_fixture(params: &str) -> FixtureRepo { + let repo = FixtureRepo::new(); + repo.write(".cigen/config.yml", "provider: github\n") + .write( + ".cigen/workflows/ci/jobs/test.yml", + &format!( + "modules:\n - node: {{ path: web{params} }}\ninputs: \"web/src/**\"\nsteps:\n - run:\n name: Run tests\n command: cd web && pnpm test\n" + ), + ) + .write(".nvmrc", "22\n") + .write( + "web/package.json", + "{\"packageManager\": \"pnpm@9.15.0\", \"scripts\": {\"test\": \"echo ok\"}}\n", + ) + .write("web/pnpm-lock.yaml", "lockfileVersion: '9.0'\n") + .write("web/src/index.js", "export const one = 1;\n") + .generate(); + repo +} + +/// mockci runs steps on the host, so the actions are stubs and `pnpm` is a fake. +fn node_simulator(repo: &FixtureRepo) -> Simulator { + let mut sim = simulator(repo); + sim.stub_action("pnpm/action-setup", []) + .stub_action("actions/setup-node", []) + .provide_command("pnpm", "echo \"pnpm $*\"\n") + .unwrap(); + sim +} + +fn installed(run: &RunReport) -> bool { + run.job("test").ran(INSTALL_STEP) +} + +#[test] +fn the_module_installs_only_when_the_job_runs() { + let repo = node_fixture(""); + let mut sim = node_simulator(&repo); + let sha = repo.commit("initial"); + + let first = sim.run(WORKFLOW, &push(&sha)).unwrap(); + assert!(tests_ran(&first)); + let log = &first.job("test").step(INSTALL_STEP).log; + assert!(log.contains("pnpm install --frozen-lockfile"), "{first}"); + + let second = sim.run(WORKFLOW, &push(&sha)).unwrap(); + assert!(!tests_ran(&second)); + assert!( + !installed(&second), + "a skipped job installs nothing\n{second}" + ); +} + +#[test] +fn changing_a_file_the_module_contributes_reruns_the_job() { + // None of these is in the job's `inputs`; the node module adds them. + for (path, contents) in [ + ("web/pnpm-lock.yaml", "lockfileVersion: '9.0'\n# changed\n"), + ("web/.npmrc", "auto-install-peers=true\n"), + ("web/pnpm-workspace.yaml", "packages: ['packages/*']\n"), + ("web/packages/ui/package.json", "{\"name\": \"ui\"}\n"), + (".nvmrc", "22.11.0\n"), + // A version file beside the package wins over the root's. + ("web/.node-version", "22.12.0\n"), + ("web/patches/left-pad.patch", "--- a\n+++ b\n"), + ] { + let repo = node_fixture(""); + let mut sim = node_simulator(&repo); + let first = repo.commit("initial"); + assert!(tests_ran(&sim.run(WORKFLOW, &push(&first)).unwrap())); + assert!(!tests_ran(&sim.run(WORKFLOW, &push(&first)).unwrap())); + + repo.write(path, contents); + let changed = repo.commit(&format!("change {path}")); + let run = sim.run(WORKFLOW, &push(&changed)).unwrap(); + assert!(tests_ran(&run), "changing {path} must rerun the job\n{run}"); + assert!(installed(&run), "{run}"); + } +} + +#[test] +fn changing_the_modules_parameters_reruns_the_job() { + let repo = node_fixture(""); + let mut sim = node_simulator(&repo); + let first = repo.commit("initial"); + assert!(tests_ran(&sim.run(WORKFLOW, &push(&first)).unwrap())); + assert!(!tests_ran(&sim.run(WORKFLOW, &push(&first)).unwrap())); + + repo.write( + ".cigen/workflows/ci/jobs/test.yml", + "modules:\n - node: { path: web, cache: false }\ninputs: \"web/src/**\"\nsteps:\n - run:\n name: Run tests\n command: cd web && pnpm test\n", + ) + .generate(); + let changed = repo.commit("no cache"); + assert!(tests_ran(&sim.run(WORKFLOW, &push(&changed)).unwrap())); +} + +#[test] +fn a_node_version_from_engines_reruns_the_job_when_it_changes() { + let repo = FixtureRepo::new(); + let package = |range: &str| { + format!( + "{{\"packageManager\": \"pnpm@9.15.0\", \"engines\": {{\"node\": \"{range}\"}}, \"scripts\": {{\"test\": \"echo ok\"}}}}\n" + ) + }; + repo.write(".cigen/config.yml", "provider: github\n") + .write( + ".cigen/workflows/ci/jobs/test.yml", + "modules:\n - node\ninputs: \"src/**\"\nsteps:\n - run:\n name: Run tests\n command: pnpm test\n", + ) + .write("package.json", &package(">=20")) + .write("pnpm-lock.yaml", "lockfileVersion: '9.0'\n") + .write("src/index.js", "export const one = 1;\n") + .generate(); + let mut sim = node_simulator(&repo); + let first = repo.commit("initial"); + let run = sim.run(WORKFLOW, &push(&first)).unwrap(); + assert!(tests_ran(&run), "{run}"); + assert!(!tests_ran(&sim.run(WORKFLOW, &push(&first)).unwrap())); + + repo.write("package.json", &package(">=22")); + let changed = repo.commit("require Node 22"); + let run = sim.run(WORKFLOW, &push(&changed)).unwrap(); + assert!( + tests_ran(&run), + "changing engines.node must rerun the job\n{run}" + ); +} diff --git a/tests/support/doc_examples.rs b/tests/support/doc_examples.rs index ce2da1e..8f5a080 100644 --- a/tests/support/doc_examples.rs +++ b/tests/support/doc_examples.rs @@ -11,9 +11,9 @@ //! A second line `# error: ` says the config must fail to generate, with `` in the //! error. //! -//! A block in another language with a title, such as ```` ```toml title="Cargo.toml" ````, is a -//! project file: it's written into every example on its page (a module needs its project's -//! `Cargo.toml` or `package.json`). +//! A block with a title, such as ```` ```toml title="Cargo.toml" ```` or +//! ```` ```yaml title="pnpm-lock.yaml" ````, is a project file: it's written into every example +//! on its page (a module needs its project's `Cargo.toml` or `package.json`). use std::path::{Path, PathBuf}; @@ -41,7 +41,7 @@ pub struct PageExamples { struct Block { line: usize, text: String, - /// A non-YAML block's `title=""`: a project file. + /// A block's `title=""`: a project file. file: Option, } @@ -68,7 +68,7 @@ fn yaml_blocks(markdown: &str) -> Vec { if let Some(info) = trimmed.strip_prefix("```") { let lang = info.split_whitespace().next().unwrap_or(""); let yaml = lang == "yaml" || lang == "yml"; - let file = if yaml { None } else { fence_title(info) }; + let file = fence_title(info); // Other untitled fences are tracked only so their contents are skipped. current = Some(Block { line: if yaml || file.is_some() { index + 1 } else { 0 }, From e71d40b2f8acc4b78a7a3e5c467a26fb2a740318 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 16:52:01 +1300 Subject: [PATCH 2/3] node: hash the pnpmfile, Yarn plugins and cache, and config above path; always install the pinned Corepack; set pnpm 11's store dir --- docs/src/content/docs/modules.md | 6 +- .../module_node/.circleci/config.yml | 4 +- .../module_node/.circleci/main.yml | 14 +- .../module_node/.github/workflows/ci.yml | 4 +- internal_docs/STATUS.md | 15 +- src/modules/node/README.md | 41 +++-- src/modules/node/expand.rs | 27 +-- src/modules/node/inputs.rs | 163 ++++++++++++++++++ src/modules/node/mod.rs | 27 +-- src/modules/node/tests.rs | 31 ++++ tests/module_node.rs | 46 +++++ 11 files changed, 317 insertions(+), 61 deletions(-) create mode 100644 src/modules/node/inputs.rs diff --git a/docs/src/content/docs/modules.md b/docs/src/content/docs/modules.md index 870c844..8fc0f4e 100644 --- a/docs/src/content/docs/modules.md +++ b/docs/src/content/docs/modules.md @@ -145,8 +145,10 @@ workflows: On GitHub Actions it uses `pnpm/action-setup` for pnpm, Corepack for Yarn, and `actions/setup-node` (pinned to commits) with its cache. On CircleCI, Node comes from the job's image: a `cimg/node` or `node` image whose tag starts with the pinned version, or any image with `version: preinstalled`; pnpm and Yarn come through Corepack, and the cache through -`restore_cache` and `save_cache`. It adds `package.json`, every tracked `**/package.json`, the lockfiles, workspace and -package manager config, patches and the version file to the job's inputs. Its full reference is +`restore_cache` and `save_cache`. It adds every tracked `package.json` under `path`, and in `path` and each folder above +it the lockfiles, workspace and package manager config, the pnpmfile, Yarn's plugins, releases and cache, patches and +the version files, to the job's inputs. A loose version (`22`, `lts/*`, an `engines.node` range) resolves when the job +runs, and only the spec is hashed, so a new Node release doesn't rerun a job that passed. Its full reference is [`src/modules/node/README.md`](https://github.com/DocSpring/cigen/blob/main/src/modules/node/README.md). ## More modules diff --git a/integration_tests/module_node/.circleci/config.yml b/integration_tests/module_node/.circleci/config.yml index 91db463..416004d 100644 --- a/integration_tests/module_node/.circleci/config.yml +++ b/integration_tests/module_node/.circleci/config.yml @@ -196,7 +196,7 @@ jobs: command: | set -euo pipefail mkdir -p /tmp/cigen - JOB_HASH=$(cigen hash --job docs --modules-digest da34e492687eef00 | tr -d '\r') + JOB_HASH=$(cigen hash --job docs --modules-digest dc362dbabbf9bd14 | tr -d '\r') printf '%s' "$JOB_HASH" > /tmp/cigen/job_hash echo "export JOB_HASH=$JOB_HASH" >> $BASH_ENV echo 'Computed hash for docs: '$JOB_HASH @@ -216,7 +216,7 @@ jobs: command: | set -euo pipefail mkdir -p /tmp/cigen - JOB_HASH=$(cigen hash --job lint --modules-digest 2b37c6170286a7c7 | tr -d '\r') + JOB_HASH=$(cigen hash --job lint --modules-digest 988c9386cf4ef8b6 | tr -d '\r') printf '%s' "$JOB_HASH" > /tmp/cigen/job_hash echo "export JOB_HASH=$JOB_HASH" >> $BASH_ENV echo 'Computed hash for lint: '$JOB_HASH diff --git a/integration_tests/module_node/.circleci/main.yml b/integration_tests/module_node/.circleci/main.yml index 86a17a4..009dc21 100644 --- a/integration_tests/module_node/.circleci/main.yml +++ b/integration_tests/module_node/.circleci/main.yml @@ -178,7 +178,7 @@ jobs: command: | set -euo pipefail mkdir -p /tmp/cigen /tmp/cigen_job_exists - JOB_HASH=$(cigen hash --job docs --modules-digest da34e492687eef00 | tr -d '\r') + JOB_HASH=$(cigen hash --job docs --modules-digest dc362dbabbf9bd14 | tr -d '\r') printf '%s' "$JOB_HASH" > /tmp/cigen/job_hash echo "export JOB_HASH=$JOB_HASH" >> $BASH_ENV echo "Computed job hash: $JOB_HASH" @@ -193,7 +193,7 @@ jobs: set -euo pipefail mkdir -p /tmp/cigen_job_exists if [ -z "${JOB_HASH:-}" ]; then - JOB_HASH=$(cigen hash --job docs --modules-digest da34e492687eef00 | tr -d '\r') + JOB_HASH=$(cigen hash --job docs --modules-digest dc362dbabbf9bd14 | tr -d '\r') fi printf '%s' "$JOB_HASH" > /tmp/cigen/job_hash touch "/tmp/cigen_job_exists/done_${JOB_HASH}" @@ -215,7 +215,7 @@ jobs: command: | set -euo pipefail mkdir -p /tmp/cigen /tmp/cigen_job_exists - JOB_HASH=$(cigen hash --job lint --modules-digest 2b37c6170286a7c7 | tr -d '\r') + JOB_HASH=$(cigen hash --job lint --modules-digest 988c9386cf4ef8b6 | tr -d '\r') printf '%s' "$JOB_HASH" > /tmp/cigen/job_hash echo "export JOB_HASH=$JOB_HASH" >> $BASH_ENV echo "Computed job hash: $JOB_HASH" @@ -223,12 +223,12 @@ jobs: name: Enable Corepack command: | export PATH="$HOME/.corepack"/bin:$PATH - mkdir -p "$HOME/.corepack"/bin - command -v corepack >/dev/null || npm install --global --prefix "$HOME/.corepack" corepack@0.36.0 - corepack enable --install-directory "$HOME/.corepack"/bin + npm install --global --prefix "$HOME/.corepack" corepack@0.36.0 + "$HOME/.corepack"/bin/corepack enable --install-directory "$HOME/.corepack"/bin echo 'export PATH="$HOME/.corepack/bin:$PATH"' >> "$BASH_ENV" echo 'export COREPACK_ENABLE_DOWNLOAD_PROMPT=0' >> "$BASH_ENV" echo 'export npm_config_store_dir="$HOME/.pnpm-store"' >> "$BASH_ENV" + echo 'export pnpm_config_store_dir="$HOME/.pnpm-store"' >> "$BASH_ENV" - restore_cache: name: Restore pnpm cache keys: @@ -250,7 +250,7 @@ jobs: set -euo pipefail mkdir -p /tmp/cigen_job_exists if [ -z "${JOB_HASH:-}" ]; then - JOB_HASH=$(cigen hash --job lint --modules-digest 2b37c6170286a7c7 | tr -d '\r') + JOB_HASH=$(cigen hash --job lint --modules-digest 988c9386cf4ef8b6 | tr -d '\r') fi printf '%s' "$JOB_HASH" > /tmp/cigen/job_hash touch "/tmp/cigen_job_exists/done_${JOB_HASH}" diff --git a/integration_tests/module_node/.github/workflows/ci.yml b/integration_tests/module_node/.github/workflows/ci.yml index 596e6fb..db34110 100644 --- a/integration_tests/module_node/.github/workflows/ci.yml +++ b/integration_tests/module_node/.github/workflows/ci.yml @@ -63,7 +63,7 @@ jobs: cigen hash \ --job docs \ --base-dir . \ - --modules-digest da34e492687eef00 \ + --modules-digest dc362dbabbf9bd14 \ --output job_hash \ --cache .cigen/cache/file-hashes.json - name: Restore skip cache @@ -163,7 +163,7 @@ jobs: cigen hash \ --job lint \ --base-dir . \ - --modules-digest 2b37c6170286a7c7 \ + --modules-digest 988c9386cf4ef8b6 \ --output job_hash \ --cache .cigen/cache/file-hashes.json - name: Restore skip cache diff --git a/internal_docs/STATUS.md b/internal_docs/STATUS.md index 38a9b27..f2dd8f4 100644 --- a/internal_docs/STATUS.md +++ b/internal_docs/STATUS.md @@ -83,8 +83,10 @@ What the code does today, checked against the code in December 2026. Where cigen package manager `packageManager` pins (npm, pnpm through `pnpm/action-setup`, Yarn through Corepack), runs a frozen install and caches downloads (`actions/setup-node`'s cache on GitHub, `restore_cache`/`save_cache` on CircleCI). On CircleCI, Node comes from the job's image, and a `node` or `cimg/node` image whose tag doesn't match the pinned - version fails generation. It adds `package.json`, every tracked `**/package.json`, the lockfiles, workspace and - package manager config, patches and the version file to the job's inputs. + version fails generation. It installs the pinned Corepack rather than an image's own. It adds every tracked + `package.json` under `path`, and in `path` and each folder above it the lockfiles, workspace and package manager + config, the pnpmfile (and one `pnpmfile` names), Yarn's plugins, releases and cache, patches and the version files, + to the job's inputs. - `rust`: installs the toolchain `rust-toolchain.toml` names (or a channel) with `rustup`, adds components and targets, and caches with `Swatinem/rust-cache` (GitHub) or `restore_cache`/`save_cache` (CircleCI). It adds `Cargo.toml`, `**/Cargo.toml`, `Cargo.lock`, the toolchain files and `.cargo/config.toml` to the job's inputs. @@ -171,8 +173,9 @@ What the code does today, checked against the code in December 2026. Where cigen a file the module contributes or its parameters change; the generated `--modules-digest` changes the hash, and a local `hash --job` without it gives the CI step's hash; unknown modules and parameters fail generation with a fix. - `tests/module_node.rs`: a job using the `node` module installs nothing when it skips, and reruns in mockci when its - lockfile, `.npmrc`, `pnpm-workspace.yaml`, a workspace package's `package.json`, the Node version file or its - parameters change. + lockfile, `.npmrc`, `pnpm-workspace.yaml`, a workspace package's `package.json`, `patches/`, a pnpmfile (default or + named in `pnpm-workspace.yaml` or `.npmrc`), Yarn's plugins or cache, the root's package manager config, the root + `.nvmrc`, a package-level `.node-version`, `engines.node` or its parameters change. - `tests/module_catalogue.rs`: every registered module has a skill with frontmatter, a README documenting exactly its parameters, a golden fixture (`integration_tests/module_/`) for each provider it supports that mockci's parser loads, and actions pinned to commit SHAs; the index is generated from the registry @@ -185,7 +188,9 @@ What the code does today, checked against the code in December 2026. Where cigen 1. **Derived inputs err towards running but have gaps.** Files that a named script mentions aren't followed. Paths in steps are looked up from the project root, so a step with a different `working-directory` can miss its script. A - moving image tag (`rust:latest`) isn't resolved to a digest. Toolchain pins and lockfiles go into every job, so a + moving image tag (`rust:latest`) isn't resolved to a digest, and neither is a loose Node version in the `node` + module (`22`, `lts/*`, an `engines.node` range): only the spec is hashed. Patches in a folder of the project's own + (outside `patches/` and `.yarn/patches/`) aren't added. Toolchain pins and lockfiles go into every job, so a `yarn.lock` change reruns Rust jobs. 2. GitHub Actions skipping happens per step inside a started job, so a skipped job still gets a runner and a checkout. The planner job in DIRECTION.md replaces it. diff --git a/src/modules/node/README.md b/src/modules/node/README.md index 8b4b8ff..07e6538 100644 --- a/src/modules/node/README.md +++ b/src/modules/node/README.md @@ -1,7 +1,7 @@ # `node` module -Installs Node and the package manager your project pins (npm, pnpm or Yarn), runs a frozen install, and caches the -package manager's downloads. +Installs Node, and pnpm or Yarn at the version your project pins (npm is the one that comes with Node), runs a frozen +install, and caches the package manager's downloads. ```yaml jobs: @@ -31,6 +31,11 @@ jobs: - pnpm and Yarn need a version in `packageManager` (Corepack's convention, such as `"packageManager": "pnpm@9.15.0"`). Without `packageManager`, the module uses npm, pnpm or Yarn by the one lockfile in `path`; two lockfiles are an error that names both. Bun isn't supported yet. +- npm is the one bundled with the Node installed: a version in `"packageManager": "npm@"` picks npm but isn't + installed. +- A loose version (`22`, `lts/*`, an `engines.node` range, `preinstalled`) is resolved when the job runs, and only the + version as written goes into the hash. A new Node release that the spec allows doesn't rerun a job that passed; pin + an exact version (`22.11.0`) where that matters. - A frozen install and the cache need the lockfile; without one, set `install: false` and `cache: false`. ## What it adds to a job @@ -41,8 +46,7 @@ The install is `npm ci`, `pnpm install --frozen-lockfile`, `yarn install --immut **GitHub Actions**: 1. pnpm: `pnpm/action-setup`, which installs the version `packageManager` names (with `package_json_file` when `path` - isn't `.`). Yarn: a step that enables Corepack, installing it first when the Node in use doesn't bundle it (Node 25 - and later). + isn't `.`). Yarn: a step that installs the pinned Corepack (below) and enables it. 2. `actions/setup-node`, with `node-version-file` or `node-version` (neither for `preinstalled`), and with `cache` set to the package manager and `cache-dependency-path` to the lockfile, or `package-manager-cache: false` without the cache. @@ -52,21 +56,32 @@ The install is `npm ci`, `pnpm install --frozen-lockfile`, `yarn install --immut tag that starts with that version (`cimg/node:22.11.0` for `22`), or generation fails and says what to change; any other image needs `version: preinstalled`. Then: -1. pnpm and Yarn: a step that enables Corepack in `~/.corepack/bin` and puts it on `PATH`. For pnpm it also sets the - store to `~/.pnpm-store`. +1. pnpm and Yarn: a step that installs the pinned Corepack in `~/.corepack`, enables it in `~/.corepack/bin` and puts + that on `PATH`. For pnpm it also sets the store to `~/.pnpm-store` (`npm_config_store_dir`, and + `pnpm_config_store_dir` for pnpm 11). 2. With `install` and `cache`, `restore_cache` keyed by the architecture, the package manager and the lockfile, with a fallback to the newest cache for the same package manager. 3. The install. -4. After the job's steps, `save_cache` of `~/.npm`, `~/.pnpm-store`, `~/.cache/yarn` (Yarn 1) or - `~/.yarn/berry/cache` (Yarn 2 and later). +4. After the job's steps, `save_cache` of `~/.npm`, `~/.pnpm-store`, `~/.cache/yarn` (Yarn 1), or for Yarn 2 and + later both `~/.yarn/berry/cache` and `/.yarn/cache` (Yarn 2 and 3 keep the cache in the project unless + `enableGlobalCache` is on). + +The module always installs Corepack 0.36.0 with npm rather than using the one bundled with Node: older bundled +releases (such as Node 22.11's) can't verify the signatures of current pnpm and Yarn releases. ## Inputs -The module adds these files, inside `path`, to the hash of every job that uses it: `package.json`, every tracked -`**/package.json`, the lockfiles (`package-lock.json`, `npm-shrinkwrap.json`, `pnpm-lock.yaml`, `yarn.lock`), -`pnpm-workspace.yaml`, `.npmrc`, `.yarnrc`, `.yarnrc.yml`, `.yarn/patches/**`, `.yarn/releases/**`, `patches/**`, -`.nvmrc` and `.node-version`, plus the version file it found (`engines.node` lives in `package.json`, already among them). Its parameters and the steps it adds go into the hash -too, so a job reruns when either changes. +npm, pnpm and Yarn walk up from the package for their config and workspace files, so the module adds these files in +`path` and in every folder above it, up to the project root, to the hash of every job that uses it: `package.json`, +the lockfiles (`package-lock.json`, `npm-shrinkwrap.json`, `pnpm-lock.yaml`, `yarn.lock`), `pnpm-workspace.yaml`, +`.npmrc`, `.yarnrc`, `.yarnrc.yml`, the pnpmfile (`.pnpmfile.cjs`, `.pnpmfile.mjs`), `.yarn/cache/**`, +`.yarn/patches/**`, `.yarn/plugins/**`, `.yarn/releases/**`, `patches/**`, `.nvmrc` and `.node-version`. It also adds +every tracked `package.json` under `path`, the version file it found (`engines.node` lives in `package.json`, already +among them), and a pnpmfile that `pnpmfile` names in `pnpm-workspace.yaml` or `.npmrc` (one outside the project is an +error). Its parameters and the steps it adds go into the hash too, so a job reruns when either changes. + +Patches in a folder of your own (pnpm's `patchedDependencies` or Yarn's `patch:` protocol pointing outside `patches/` +and `.yarn/patches/`) aren't added: add that folder to the job's `inputs`. ## Pinned actions diff --git a/src/modules/node/expand.rs b/src/modules/node/expand.rs index 393d18e..3e6f208 100644 --- a/src/modules/node/expand.rs +++ b/src/modules/node/expand.rs @@ -79,10 +79,12 @@ impl Node { vec!["echo 'export COREPACK_ENABLE_DOWNLOAD_PROMPT=0' >> \"$BASH_ENV\"".to_string()]; if self.manager.manager == Manager::Pnpm { // A fixed store, so `save_cache` knows where it is. - env.push( - "echo 'export npm_config_store_dir=\"$HOME/.pnpm-store\"' >> \"$BASH_ENV\"" - .to_string(), - ); + // pnpm 11 reads only `pnpm_config_*`; earlier versions read `npm_config_*`. + for prefix in ["npm", "pnpm"] { + env.push(format!( + "echo 'export {prefix}_config_store_dir=\"$HOME/.pnpm-store\"' >> \"$BASH_ENV\"" + )); + } } if self.manager.manager != Manager::Npm { env.insert( @@ -135,18 +137,23 @@ impl Node { Manager::Yarn if self.manager.is_yarn_classic() => &["~/.cache/yarn"], Manager::Yarn => &["~/.yarn/berry/cache"], }; - paths.iter().map(|path| path.to_string()).collect() + let mut paths: Vec = paths.iter().map(|path| path.to_string()).collect(); + // Yarn 2 and 3 keep the cache in the project unless `enableGlobalCache` is on. + if self.manager.manager == Manager::Yarn && !self.manager.is_yarn_classic() { + paths.push(in_path(&self.path, ".yarn/cache")); + } + paths } } -/// Enables Corepack's shims in `/bin`, installing Corepack there first when the Node in -/// use doesn't bundle it, then runs `persist` so later steps find them. +/// Installs the pinned Corepack in `` and enables its shims in `/bin`, then runs +/// `persist` so later steps find them. Always the pinned one: an image's bundled Corepack can be +/// too old to verify the signatures of current pnpm and Yarn releases. fn corepack(prefix: &str, persist: &str) -> String { format!( "export PATH={prefix}/bin:$PATH\n\ - mkdir -p {prefix}/bin\n\ - command -v corepack >/dev/null || npm install --global --prefix {prefix} {COREPACK}\n\ - corepack enable --install-directory {prefix}/bin\n\ + npm install --global --prefix {prefix} {COREPACK}\n\ + {prefix}/bin/corepack enable --install-directory {prefix}/bin\n\ {persist}\n" ) } diff --git a/src/modules/node/inputs.rs b/src/modules/node/inputs.rs new file mode 100644 index 0000000..89fc34c --- /dev/null +++ b/src/modules/node/inputs.rs @@ -0,0 +1,163 @@ +//! The files a Node job's install depends on. npm, pnpm and Yarn walk up from the package for +//! their config and workspace files, so the module hashes them in `path` and in every folder +//! above it, up to the project root. +use crate::modules::in_path; +use anyhow::{Result, bail}; +use std::path::Path; + +/// Files in `path` and each folder above it. +const CONFIG_FILES: &[&str] = &[ + "package.json", + "package-lock.json", + "npm-shrinkwrap.json", + "pnpm-lock.yaml", + "pnpm-workspace.yaml", + "yarn.lock", + ".npmrc", + ".yarnrc", + ".yarnrc.yml", + // pnpm checksums its pnpmfile into the lockfile. + ".pnpmfile.cjs", + ".pnpmfile.mjs", + ".yarn/cache/**", + ".yarn/patches/**", + ".yarn/plugins/**", + ".yarn/releases/**", + "patches/**", + ".nvmrc", + ".node-version", +]; + +/// `path` and every folder above it, ending with the root (`.`). +pub fn dirs_up(path: &str) -> Vec { + let mut dirs = vec![path.to_string()]; + let mut current = path; + while current != "." { + current = match current.rsplit_once('/') { + Some((parent, _)) => parent, + None => ".", + }; + dirs.push(current.to_string()); + } + dirs +} + +/// The patterns for `path`: its config files and every `package.json` under it, the same +/// config files in each folder above it, and `extra` (a custom pnpmfile). +pub fn patterns(path: &str, extra: &[String]) -> Vec { + let mut patterns = vec![in_path(path, "**/package.json")]; + for dir in dirs_up(path) { + for file in CONFIG_FILES { + patterns.push(anchored(&dir, file)); + } + } + patterns.extend(extra.iter().cloned()); + patterns.sort(); + patterns.dedup(); + patterns +} + +/// `file` in `dir`. A bare name would match at any depth, so a file at the root gets a leading +/// `/`. Packages nested under `path` are covered by `**/package.json`. +fn anchored(dir: &str, file: &str) -> String { + if dir == "." && file.contains('/') { + file.to_string() + } else if dir == "." { + format!("/{file}") + } else { + in_path(dir, file) + } +} + +/// The pnpmfiles named by `pnpmfile` in `pnpm-workspace.yaml` or `.npmrc`, in `path` or a folder +/// above it, relative to the project root. +pub fn custom_pnpmfiles(root: &Path, path: &str) -> Result> { + let mut found = Vec::new(); + for dir in dirs_up(path) { + let workspace = in_path(&dir, "pnpm-workspace.yaml"); + if let Ok(text) = std::fs::read_to_string(root.join(&workspace)) { + let yaml: serde_yaml::Value = serde_yaml::from_str(&text) + .map_err(|error| anyhow::anyhow!("`{workspace}` isn't valid YAML: {error}"))?; + match yaml.get("pnpmfile") { + None => {} + Some(serde_yaml::Value::String(file)) => { + found.push(resolve(&dir, file, &workspace)?); + } + Some(serde_yaml::Value::Sequence(files)) => { + for file in files { + let Some(file) = file.as_str() else { + bail!("`pnpmfile` in `{workspace}` must list paths"); + }; + found.push(resolve(&dir, file, &workspace)?); + } + } + Some(_) => bail!("`pnpmfile` in `{workspace}` must be a path"), + } + } + let npmrc = in_path(&dir, ".npmrc"); + if let Ok(text) = std::fs::read_to_string(root.join(&npmrc)) { + for line in text.lines() { + let Some((key, value)) = line.split_once('=') else { + continue; + }; + if key.trim() == "pnpmfile" { + let value = value.trim().trim_matches('"').trim_matches('\''); + found.push(resolve(&dir, value, &npmrc)?); + } + } + } + } + Ok(found) +} + +fn resolve(dir: &str, file: &str, config: &str) -> Result { + let joined = in_path(dir, file); + match crate::inputs::project_path(&joined) { + Some(relative) if !file.contains('$') => Ok(relative), + _ => bail!( + "`pnpmfile: {file}` in `{config}` isn't a plain path inside the project, so cigen can't hash it; move the pnpmfile into the project and name it by a relative path" + ), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dirs_go_up_to_the_root() { + assert_eq!(dirs_up("."), ["."]); + assert_eq!(dirs_up("web"), ["web", "."]); + assert_eq!(dirs_up("apps/web"), ["apps/web", "apps", "."]); + } + + #[test] + fn root_files_are_anchored_above_a_nested_path() { + let patterns = patterns("apps/web", &[]); + for expected in [ + "apps/web/**/package.json", + "apps/web/.npmrc", + "apps/.npmrc", + "/.npmrc", + "/package.json", + ".yarn/plugins/**", + "apps/.yarn/releases/**", + ] { + assert!( + patterns.contains(&expected.to_string()), + "{expected}: {patterns:?}" + ); + } + } + + #[test] + fn a_pnpmfile_outside_the_project_is_an_error() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join(".npmrc"), "pnpmfile=../hooks.cjs\n").unwrap(); + let error = custom_pnpmfiles(dir.path(), ".").unwrap_err().to_string(); + assert!( + error.contains("isn't a plain path inside the project"), + "{error}" + ); + } +} diff --git a/src/modules/node/mod.rs b/src/modules/node/mod.rs index b57bb8e..e4fdbbb 100644 --- a/src/modules/node/mod.rs +++ b/src/modules/node/mod.rs @@ -9,6 +9,7 @@ use serde_yaml::Mapping; use std::path::Path; mod expand; +mod inputs; mod manager; use manager::{Manager, PackageManager}; @@ -102,6 +103,8 @@ struct Node { cache: bool, /// The lockfile, relative to the project root. lockfile: String, + /// Pnpmfiles that `pnpm-workspace.yaml` or `.npmrc` name, relative to the project root. + pnpmfiles: Vec, /// The CircleCI image's problem with the version, found when loading and reported only /// when expanding for CircleCI, so a GitHub-only config never sees it. circleci_image_error: Option, @@ -152,7 +155,9 @@ fn load(params: &Mapping, context: &Context) -> Result> { ); } let circleci_image_error = expand::circleci_image_error(context.image, &version); + let pnpmfiles = inputs::custom_pnpmfiles(root, &path)?; Ok(Box::new(Node { + pnpmfiles, path, version, manager, @@ -220,30 +225,12 @@ impl Module for Node { "install": self.install, "cache": self.cache, "lockfile": self.lockfile, + "pnpmfiles": self.pnpmfiles, }) } fn inputs(&self) -> Vec { - let mut inputs: Vec = [ - "package.json", - "**/package.json", - "package-lock.json", - "npm-shrinkwrap.json", - "pnpm-lock.yaml", - "pnpm-workspace.yaml", - "yarn.lock", - ".npmrc", - ".yarnrc", - ".yarnrc.yml", - ".yarn/patches/**", - ".yarn/releases/**", - "patches/**", - ".nvmrc", - ".node-version", - ] - .iter() - .map(|file| in_path(&self.path, file)) - .collect(); + let mut inputs = inputs::patterns(&self.path, &self.pnpmfiles); if let Version::File { file, .. } = &self.version { inputs.push(file.clone()); } diff --git a/src/modules/node/tests.rs b/src/modules/node/tests.rs index 590258f..f94e80e 100644 --- a/src/modules/node/tests.rs +++ b/src/modules/node/tests.rs @@ -101,6 +101,14 @@ fn pnpm_on_circleci_uses_corepack_and_a_fixed_store() { "{before:?}" ); assert!(before[0].contains("npm_config_store_dir"), "{before:?}"); + // pnpm 11 reads only its own prefix. + assert!(before[0].contains("pnpm_config_store_dir"), "{before:?}"); + // The image's own Corepack may be too old to verify current pnpm and Yarn releases. + assert!( + before[0].contains("npm install --global --prefix \"$HOME/.corepack\" corepack@0.36.0"), + "{before:?}" + ); + assert!(!before[0].contains("command -v corepack"), "{before:?}"); assert_eq!( before[1..], [ @@ -278,3 +286,26 @@ fn without_a_version_file_engines_pins_node() { let module = node("{}", &dir).unwrap(); assert_eq!(module.resolved()["version"]["file"], ".nvmrc"); } + +#[test] +fn yarn_berry_on_circleci_caches_the_global_and_the_project_cache() { + let dir = project(&[ + ("web/package.json", r#"{"packageManager": "yarn@3.8.0"}"#), + ("web/yarn.lock", ""), + ]); + let expansion = node_on( + "{ path: web, version: preinstalled }", + &dir, + "cimg/base:current", + ) + .unwrap() + .expand("circleci") + .unwrap(); + // Yarn 2 and 3 keep the cache in the project unless `enableGlobalCache` is on. + assert_eq!( + summary(&expansion.after), + [ + "save: node-v1-{{ arch }}-yarn-{{ checksum \"web/yarn.lock\" }} ~/.yarn/berry/cache,web/.yarn/cache" + ] + ); +} diff --git a/tests/module_node.rs b/tests/module_node.rs index 29c10e0..07b454a 100644 --- a/tests/module_node.rs +++ b/tests/module_node.rs @@ -75,6 +75,20 @@ fn changing_a_file_the_module_contributes_reruns_the_job() { // A version file beside the package wins over the root's. ("web/.node-version", "22.12.0\n"), ("web/patches/left-pad.patch", "--- a\n+++ b\n"), + // pnpm checksums its pnpmfile into the lockfile; Yarn Berry loads plugins to install. + ("web/.pnpmfile.cjs", "module.exports = { hooks: {} };\n"), + ("web/.pnpmfile.mjs", "export const hooks = {};\n"), + ("web/.yarn/plugins/plugin.cjs", "module.exports = {};\n"), + ("web/.yarn/cache/left-pad.zip", "zip\n"), + // The package manager walks up from `path` for its config and workspace files. + (".npmrc", "auto-install-peers=true\n"), + (".yarnrc", "registry \"https://registry.example.com\"\n"), + (".yarnrc.yml", "nodeLinker: node-modules\n"), + ("pnpm-workspace.yaml", "packages: ['web']\n"), + (".pnpmfile.cjs", "module.exports = { hooks: {} };\n"), + (".yarn/releases/yarn-4.5.0.cjs", "// yarn\n"), + (".yarn/plugins/plugin.cjs", "module.exports = {};\n"), + ("patches/left-pad.patch", "--- a\n+++ b\n"), ] { let repo = node_fixture(""); let mut sim = node_simulator(&repo); @@ -90,6 +104,38 @@ fn changing_a_file_the_module_contributes_reruns_the_job() { } } +#[test] +fn a_pnpmfile_named_in_the_workspace_file_or_npmrc_reruns_the_job() { + for (config, contents) in [ + ("web/pnpm-workspace.yaml", "pnpmfile: hooks/pnpmfile.cjs\n"), + ("web/.npmrc", "pnpmfile=hooks/pnpmfile.cjs\n"), + // At the root, the path is relative to the root. + ( + "pnpm-workspace.yaml", + "packages: ['web']\npnpmfile: web/hooks/pnpmfile.cjs\n", + ), + ] { + let repo = node_fixture(""); + repo.write(config, contents) + .write("web/hooks/pnpmfile.cjs", "module.exports = {};\n"); + let mut sim = node_simulator(&repo); + let first = repo.commit("initial"); + assert!(tests_ran(&sim.run(WORKFLOW, &push(&first)).unwrap())); + assert!(!tests_ran(&sim.run(WORKFLOW, &push(&first)).unwrap())); + + repo.write( + "web/hooks/pnpmfile.cjs", + "module.exports = { hooks: {} };\n", + ); + let changed = repo.commit("change the pnpmfile"); + let run = sim.run(WORKFLOW, &push(&changed)).unwrap(); + assert!( + tests_ran(&run), + "{config}: changing the pnpmfile must rerun the job\n{run}" + ); + } +} + #[test] fn changing_the_modules_parameters_reruns_the_job() { let repo = node_fixture(""); From 5e29f8a554166085a670d26929efd2d2857910bb Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 17:24:56 +1300 Subject: [PATCH 3/3] node: hash Yarn's yarnPath, plugins, cacheFolder and patchFolder, and nested package manager config under path --- docs/src/content/docs/modules.md | 3 +- .../module_node/.circleci/config.yml | 4 +- .../module_node/.circleci/main.yml | 8 +- .../module_node/.github/workflows/ci.yml | 4 +- internal_docs/STATUS.md | 8 +- src/modules/node/README.md | 8 +- src/modules/node/custom.rs | 185 ++++++++++++++++++ src/modules/node/inputs.rs | 95 +++------ src/modules/node/mod.rs | 14 +- src/modules/node/tests/circleci.rs | 89 +++++++++ src/modules/node/{tests.rs => tests/mod.rs} | 89 +-------- tests/module_node.rs | 52 +++++ 12 files changed, 388 insertions(+), 171 deletions(-) create mode 100644 src/modules/node/custom.rs create mode 100644 src/modules/node/tests/circleci.rs rename src/modules/node/{tests.rs => tests/mod.rs} (70%) diff --git a/docs/src/content/docs/modules.md b/docs/src/content/docs/modules.md index 8fc0f4e..103a463 100644 --- a/docs/src/content/docs/modules.md +++ b/docs/src/content/docs/modules.md @@ -147,7 +147,8 @@ with its cache. On CircleCI, Node comes from the job's image: a `cimg/node` or ` pinned version, or any image with `version: preinstalled`; pnpm and Yarn come through Corepack, and the cache through `restore_cache` and `save_cache`. It adds every tracked `package.json` under `path`, and in `path` and each folder above it the lockfiles, workspace and package manager config, the pnpmfile, Yarn's plugins, releases and cache, patches and -the version files, to the job's inputs. A loose version (`22`, `lts/*`, an `engines.node` range) resolves when the job +the version files, to the job's inputs, along with files the config names elsewhere (a `pnpmfile`, Yarn's `yarnPath`, +plugins, `cacheFolder` and `patchFolder`). A loose version (`22`, `lts/*`, an `engines.node` range) resolves when the job runs, and only the spec is hashed, so a new Node release doesn't rerun a job that passed. Its full reference is [`src/modules/node/README.md`](https://github.com/DocSpring/cigen/blob/main/src/modules/node/README.md). diff --git a/integration_tests/module_node/.circleci/config.yml b/integration_tests/module_node/.circleci/config.yml index 416004d..a859554 100644 --- a/integration_tests/module_node/.circleci/config.yml +++ b/integration_tests/module_node/.circleci/config.yml @@ -196,7 +196,7 @@ jobs: command: | set -euo pipefail mkdir -p /tmp/cigen - JOB_HASH=$(cigen hash --job docs --modules-digest dc362dbabbf9bd14 | tr -d '\r') + JOB_HASH=$(cigen hash --job docs --modules-digest 6309559df8466e00 | tr -d '\r') printf '%s' "$JOB_HASH" > /tmp/cigen/job_hash echo "export JOB_HASH=$JOB_HASH" >> $BASH_ENV echo 'Computed hash for docs: '$JOB_HASH @@ -216,7 +216,7 @@ jobs: command: | set -euo pipefail mkdir -p /tmp/cigen - JOB_HASH=$(cigen hash --job lint --modules-digest 988c9386cf4ef8b6 | tr -d '\r') + JOB_HASH=$(cigen hash --job lint --modules-digest fe1690dbdc5677cc | tr -d '\r') printf '%s' "$JOB_HASH" > /tmp/cigen/job_hash echo "export JOB_HASH=$JOB_HASH" >> $BASH_ENV echo 'Computed hash for lint: '$JOB_HASH diff --git a/integration_tests/module_node/.circleci/main.yml b/integration_tests/module_node/.circleci/main.yml index 009dc21..c192a24 100644 --- a/integration_tests/module_node/.circleci/main.yml +++ b/integration_tests/module_node/.circleci/main.yml @@ -178,7 +178,7 @@ jobs: command: | set -euo pipefail mkdir -p /tmp/cigen /tmp/cigen_job_exists - JOB_HASH=$(cigen hash --job docs --modules-digest dc362dbabbf9bd14 | tr -d '\r') + JOB_HASH=$(cigen hash --job docs --modules-digest 6309559df8466e00 | tr -d '\r') printf '%s' "$JOB_HASH" > /tmp/cigen/job_hash echo "export JOB_HASH=$JOB_HASH" >> $BASH_ENV echo "Computed job hash: $JOB_HASH" @@ -193,7 +193,7 @@ jobs: set -euo pipefail mkdir -p /tmp/cigen_job_exists if [ -z "${JOB_HASH:-}" ]; then - JOB_HASH=$(cigen hash --job docs --modules-digest dc362dbabbf9bd14 | tr -d '\r') + JOB_HASH=$(cigen hash --job docs --modules-digest 6309559df8466e00 | tr -d '\r') fi printf '%s' "$JOB_HASH" > /tmp/cigen/job_hash touch "/tmp/cigen_job_exists/done_${JOB_HASH}" @@ -215,7 +215,7 @@ jobs: command: | set -euo pipefail mkdir -p /tmp/cigen /tmp/cigen_job_exists - JOB_HASH=$(cigen hash --job lint --modules-digest 988c9386cf4ef8b6 | tr -d '\r') + JOB_HASH=$(cigen hash --job lint --modules-digest fe1690dbdc5677cc | tr -d '\r') printf '%s' "$JOB_HASH" > /tmp/cigen/job_hash echo "export JOB_HASH=$JOB_HASH" >> $BASH_ENV echo "Computed job hash: $JOB_HASH" @@ -250,7 +250,7 @@ jobs: set -euo pipefail mkdir -p /tmp/cigen_job_exists if [ -z "${JOB_HASH:-}" ]; then - JOB_HASH=$(cigen hash --job lint --modules-digest 988c9386cf4ef8b6 | tr -d '\r') + JOB_HASH=$(cigen hash --job lint --modules-digest fe1690dbdc5677cc | tr -d '\r') fi printf '%s' "$JOB_HASH" > /tmp/cigen/job_hash touch "/tmp/cigen_job_exists/done_${JOB_HASH}" diff --git a/integration_tests/module_node/.github/workflows/ci.yml b/integration_tests/module_node/.github/workflows/ci.yml index db34110..924109b 100644 --- a/integration_tests/module_node/.github/workflows/ci.yml +++ b/integration_tests/module_node/.github/workflows/ci.yml @@ -63,7 +63,7 @@ jobs: cigen hash \ --job docs \ --base-dir . \ - --modules-digest dc362dbabbf9bd14 \ + --modules-digest 6309559df8466e00 \ --output job_hash \ --cache .cigen/cache/file-hashes.json - name: Restore skip cache @@ -163,7 +163,7 @@ jobs: cigen hash \ --job lint \ --base-dir . \ - --modules-digest 988c9386cf4ef8b6 \ + --modules-digest fe1690dbdc5677cc \ --output job_hash \ --cache .cigen/cache/file-hashes.json - name: Restore skip cache diff --git a/internal_docs/STATUS.md b/internal_docs/STATUS.md index f2dd8f4..ba983a0 100644 --- a/internal_docs/STATUS.md +++ b/internal_docs/STATUS.md @@ -85,8 +85,9 @@ What the code does today, checked against the code in December 2026. Where cigen On CircleCI, Node comes from the job's image, and a `node` or `cimg/node` image whose tag doesn't match the pinned version fails generation. It installs the pinned Corepack rather than an image's own. It adds every tracked `package.json` under `path`, and in `path` and each folder above it the lockfiles, workspace and package manager - config, the pnpmfile (and one `pnpmfile` names), Yarn's plugins, releases and cache, patches and the version files, - to the job's inputs. + config, the pnpmfile, Yarn's plugins, releases and cache, patches and the version files, nested package manager + config under `path`, and files the config names elsewhere (a `pnpmfile`; Yarn's `yarnPath`, plugin paths, + `cacheFolder`, `patchFolder`), to the job's inputs. - `rust`: installs the toolchain `rust-toolchain.toml` names (or a channel) with `rustup`, adds components and targets, and caches with `Swatinem/rust-cache` (GitHub) or `restore_cache`/`save_cache` (CircleCI). It adds `Cargo.toml`, `**/Cargo.toml`, `Cargo.lock`, the toolchain files and `.cargo/config.toml` to the job's inputs. @@ -174,7 +175,8 @@ What the code does today, checked against the code in December 2026. Where cigen local `hash --job` without it gives the CI step's hash; unknown modules and parameters fail generation with a fix. - `tests/module_node.rs`: a job using the `node` module installs nothing when it skips, and reruns in mockci when its lockfile, `.npmrc`, `pnpm-workspace.yaml`, a workspace package's `package.json`, `patches/`, a pnpmfile (default or - named in `pnpm-workspace.yaml` or `.npmrc`), Yarn's plugins or cache, the root's package manager config, the root + named in `pnpm-workspace.yaml` or `.npmrc`), Yarn's plugins or cache, a file `.yarnrc.yml` names (`yarnPath`, + a plugin, `cacheFolder`, `patchFolder`), the root's package manager config, the root `.nvmrc`, a package-level `.node-version`, `engines.node` or its parameters change. - `tests/module_catalogue.rs`: every registered module has a skill with frontmatter, a README documenting exactly its parameters, a golden fixture (`integration_tests/module_/`) for each provider it supports that mockci's parser diff --git a/src/modules/node/README.md b/src/modules/node/README.md index 07e6538..df4a093 100644 --- a/src/modules/node/README.md +++ b/src/modules/node/README.md @@ -76,9 +76,11 @@ npm, pnpm and Yarn walk up from the package for their config and workspace files the lockfiles (`package-lock.json`, `npm-shrinkwrap.json`, `pnpm-lock.yaml`, `yarn.lock`), `pnpm-workspace.yaml`, `.npmrc`, `.yarnrc`, `.yarnrc.yml`, the pnpmfile (`.pnpmfile.cjs`, `.pnpmfile.mjs`), `.yarn/cache/**`, `.yarn/patches/**`, `.yarn/plugins/**`, `.yarn/releases/**`, `patches/**`, `.nvmrc` and `.node-version`. It also adds -every tracked `package.json` under `path`, the version file it found (`engines.node` lives in `package.json`, already -among them), and a pnpmfile that `pnpmfile` names in `pnpm-workspace.yaml` or `.npmrc` (one outside the project is an -error). Its parameters and the steps it adds go into the hash too, so a job reruns when either changes. +every tracked `package.json`, `.npmrc`, `.yarnrc`, `.yarnrc.yml` and `patches/**` under `path` (a step can run the +package manager inside a nested package), the version file it found (`engines.node` lives in `package.json`, already +among them), and the files the config names at paths of its own: a pnpmfile that `pnpmfile` names in +`pnpm-workspace.yaml` or `.npmrc`, and Yarn's `yarnPath`, `plugins` paths, `cacheFolder` and `patchFolder` in +`.yarnrc.yml`, each relative to the config's folder. One of those outside the project is an error. Its parameters and the steps it adds go into the hash too, so a job reruns when either changes. Patches in a folder of your own (pnpm's `patchedDependencies` or Yarn's `patch:` protocol pointing outside `patches/` and `.yarn/patches/`) aren't added: add that folder to the job's `inputs`. diff --git a/src/modules/node/custom.rs b/src/modules/node/custom.rs new file mode 100644 index 0000000..ebb1402 --- /dev/null +++ b/src/modules/node/custom.rs @@ -0,0 +1,185 @@ +//! Files the package manager's config names at paths of the project's choosing: a pnpmfile +//! named in `pnpm-workspace.yaml` or `.npmrc`, and Yarn's `yarnPath`, plugins, cache and patch +//! folders in `.yarnrc.yml`. They're read in `path` and every folder above it, and each path is +//! relative to the folder of the config that names it. +use super::inputs::dirs_up; +use crate::modules::in_path; +use anyhow::{Result, bail}; +use serde_yaml::Value; +use std::path::Path; + +/// Input patterns for every such file, relative to the project root. +pub fn custom_inputs(root: &Path, path: &str) -> Result> { + let mut found = Vec::new(); + for dir in dirs_up(path) { + pnpm_workspace(root, &dir, &mut found)?; + npmrc(root, &dir, &mut found)?; + yarnrc(root, &dir, &mut found)?; + } + Ok(found) +} + +fn read_yaml(root: &Path, file: &str) -> Result> { + let Ok(text) = std::fs::read_to_string(root.join(file)) else { + return Ok(None); + }; + let yaml = serde_yaml::from_str(&text) + .map_err(|error| anyhow::anyhow!("`{file}` isn't valid YAML: {error}"))?; + Ok(Some(yaml)) +} + +fn pnpm_workspace(root: &Path, dir: &str, found: &mut Vec) -> Result<()> { + let config = in_path(dir, "pnpm-workspace.yaml"); + let Some(yaml) = read_yaml(root, &config)? else { + return Ok(()); + }; + match yaml.get("pnpmfile") { + None => {} + Some(Value::String(file)) => found.push(resolve(dir, file, "pnpmfile", &config)?), + Some(Value::Sequence(files)) => { + for file in files { + let Some(file) = file.as_str() else { + bail!("`pnpmfile` in `{config}` must list paths"); + }; + found.push(resolve(dir, file, "pnpmfile", &config)?); + } + } + Some(_) => bail!("`pnpmfile` in `{config}` must be a path"), + } + Ok(()) +} + +fn npmrc(root: &Path, dir: &str, found: &mut Vec) -> Result<()> { + let config = in_path(dir, ".npmrc"); + let Ok(text) = std::fs::read_to_string(root.join(&config)) else { + return Ok(()); + }; + for line in text.lines() { + let Some((key, value)) = line.split_once('=') else { + continue; + }; + if key.trim() == "pnpmfile" { + let value = value.trim().trim_matches('"').trim_matches('\''); + found.push(resolve(dir, value, "pnpmfile", &config)?); + } + } + Ok(()) +} + +fn yarnrc(root: &Path, dir: &str, found: &mut Vec) -> Result<()> { + let config = in_path(dir, ".yarnrc.yml"); + let Some(yaml) = read_yaml(root, &config)? else { + return Ok(()); + }; + let string = |key: &str| -> Result> { + match yaml.get(key) { + None => Ok(None), + Some(Value::String(value)) => Ok(Some(value.clone())), + Some(_) => bail!("`{key}` in `{config}` must be a path"), + } + }; + // The Yarn binary that runs the install. + if let Some(file) = string("yarnPath")? { + found.push(resolve(dir, &file, "yarnPath", &config)?); + } + for key in ["cacheFolder", "patchFolder"] { + if let Some(folder) = string(key)? { + found.push(format!("{}/**", resolve(dir, &folder, key, &config)?)); + } + } + match yaml.get("plugins") { + None => {} + Some(Value::Sequence(plugins)) => { + for plugin in plugins { + let file = match plugin { + Value::String(file) => file.as_str(), + Value::Mapping(_) => match plugin.get("path") { + Some(Value::String(file)) => file.as_str(), + _ => bail!("each plugin in `{config}` needs a `path`"), + }, + _ => bail!("`plugins` in `{config}` must list paths or `{{ path, spec }}`"), + }; + found.push(resolve(dir, file, "plugins", &config)?); + } + } + Some(_) => bail!("`plugins` in `{config}` must be a list"), + } + Ok(()) +} + +fn resolve(dir: &str, file: &str, key: &str, config: &str) -> Result { + let outside = || { + anyhow::anyhow!( + "`{key}: {file}` in `{config}` isn't a plain path inside the project, so cigen can't hash it; move it into the project and name it by a relative path" + ) + }; + if file.is_empty() || file.starts_with(['/', '~']) || file.contains(['$', '\\']) { + return Err(outside()); + } + // `..` may climb out of the config's folder, but not out of the project. + let joined = in_path(dir, file); + let mut parts: Vec<&str> = Vec::new(); + for part in joined.split('/') { + match part { + "" | "." => {} + ".." => { + parts.pop().ok_or_else(outside)?; + } + part => parts.push(part), + } + } + if parts.is_empty() { + return Err(outside()); + } + Ok(parts.join("/")) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn project(files: &[(&str, &str)]) -> tempfile::TempDir { + let dir = tempfile::tempdir().unwrap(); + for (path, contents) in files { + let path = dir.path().join(path); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, contents).unwrap(); + } + dir + } + + #[test] + fn yarnrc_paths_are_relative_to_its_folder() { + let dir = project(&[( + "web/.yarnrc.yml", + "yarnPath: .yarn/releases/yarn.cjs\ncacheFolder: ./cache\npatchFolder: ../patches\nplugins:\n - path: plugins/a.cjs\n - b.cjs\n", + )]); + assert_eq!( + custom_inputs(dir.path(), "web").unwrap(), + [ + "web/.yarn/releases/yarn.cjs", + "web/cache/**", + "patches/**", + "web/plugins/a.cjs", + "web/b.cjs", + ] + ); + } + + #[test] + fn a_path_outside_the_project_is_an_error() { + for (file, contents) in [ + (".npmrc", "pnpmfile=../hooks.cjs\n"), + (".yarnrc.yml", "yarnPath: /usr/local/yarn.cjs\n"), + (".yarnrc.yml", "cacheFolder: ~/.yarn/cache\n"), + (".yarnrc.yml", "cacheFolder: ${YARN_CACHE}\n"), + ] { + let dir = project(&[(file, contents)]); + let error = custom_inputs(dir.path(), ".").unwrap_err().to_string(); + assert!( + error.contains("isn't a plain path inside the project"), + "{contents}: {error}" + ); + } + } +} diff --git a/src/modules/node/inputs.rs b/src/modules/node/inputs.rs index 89fc34c..34381fc 100644 --- a/src/modules/node/inputs.rs +++ b/src/modules/node/inputs.rs @@ -2,8 +2,6 @@ //! their config and workspace files, so the module hashes them in `path` and in every folder //! above it, up to the project root. use crate::modules::in_path; -use anyhow::{Result, bail}; -use std::path::Path; /// Files in `path` and each folder above it. const CONFIG_FILES: &[&str] = &[ @@ -28,6 +26,15 @@ const CONFIG_FILES: &[&str] = &[ ".node-version", ]; +/// Files anywhere under `path`. +const NESTED_FILES: &[&str] = &[ + "**/package.json", + "**/.npmrc", + "**/.yarnrc", + "**/.yarnrc.yml", + "**/patches/**", +]; + /// `path` and every folder above it, ending with the root (`.`). pub fn dirs_up(path: &str) -> Vec { let mut dirs = vec![path.to_string()]; @@ -43,9 +50,13 @@ pub fn dirs_up(path: &str) -> Vec { } /// The patterns for `path`: its config files and every `package.json` under it, the same -/// config files in each folder above it, and `extra` (a custom pnpmfile). +/// config files in each folder above it, and `extra` (files at paths the config names). pub fn patterns(path: &str, extra: &[String]) -> Vec { - let mut patterns = vec![in_path(path, "**/package.json")]; + // A step can run the package manager inside a nested package, which reads its own config. + let mut patterns: Vec = NESTED_FILES + .iter() + .map(|file| in_path(path, file)) + .collect(); for dir in dirs_up(path) { for file in CONFIG_FILES { patterns.push(anchored(&dir, file)); @@ -69,57 +80,6 @@ fn anchored(dir: &str, file: &str) -> String { } } -/// The pnpmfiles named by `pnpmfile` in `pnpm-workspace.yaml` or `.npmrc`, in `path` or a folder -/// above it, relative to the project root. -pub fn custom_pnpmfiles(root: &Path, path: &str) -> Result> { - let mut found = Vec::new(); - for dir in dirs_up(path) { - let workspace = in_path(&dir, "pnpm-workspace.yaml"); - if let Ok(text) = std::fs::read_to_string(root.join(&workspace)) { - let yaml: serde_yaml::Value = serde_yaml::from_str(&text) - .map_err(|error| anyhow::anyhow!("`{workspace}` isn't valid YAML: {error}"))?; - match yaml.get("pnpmfile") { - None => {} - Some(serde_yaml::Value::String(file)) => { - found.push(resolve(&dir, file, &workspace)?); - } - Some(serde_yaml::Value::Sequence(files)) => { - for file in files { - let Some(file) = file.as_str() else { - bail!("`pnpmfile` in `{workspace}` must list paths"); - }; - found.push(resolve(&dir, file, &workspace)?); - } - } - Some(_) => bail!("`pnpmfile` in `{workspace}` must be a path"), - } - } - let npmrc = in_path(&dir, ".npmrc"); - if let Ok(text) = std::fs::read_to_string(root.join(&npmrc)) { - for line in text.lines() { - let Some((key, value)) = line.split_once('=') else { - continue; - }; - if key.trim() == "pnpmfile" { - let value = value.trim().trim_matches('"').trim_matches('\''); - found.push(resolve(&dir, value, &npmrc)?); - } - } - } - } - Ok(found) -} - -fn resolve(dir: &str, file: &str, config: &str) -> Result { - let joined = in_path(dir, file); - match crate::inputs::project_path(&joined) { - Some(relative) if !file.contains('$') => Ok(relative), - _ => bail!( - "`pnpmfile: {file}` in `{config}` isn't a plain path inside the project, so cigen can't hash it; move the pnpmfile into the project and name it by a relative path" - ), - } -} - #[cfg(test)] mod tests { use super::*; @@ -136,6 +96,9 @@ mod tests { let patterns = patterns("apps/web", &[]); for expected in [ "apps/web/**/package.json", + "apps/web/**/.npmrc", + "apps/web/**/.yarnrc.yml", + "apps/web/**/patches/**", "apps/web/.npmrc", "apps/.npmrc", "/.npmrc", @@ -151,13 +114,19 @@ mod tests { } #[test] - fn a_pnpmfile_outside_the_project_is_an_error() { - let dir = tempfile::tempdir().unwrap(); - std::fs::write(dir.path().join(".npmrc"), "pnpmfile=../hooks.cjs\n").unwrap(); - let error = custom_pnpmfiles(dir.path(), ".").unwrap_err().to_string(); - assert!( - error.contains("isn't a plain path inside the project"), - "{error}" - ); + fn at_the_root_nested_config_is_an_input() { + let patterns = patterns(".", &[]); + for expected in [ + "**/.npmrc", + "**/.yarnrc", + "**/.yarnrc.yml", + "**/patches/**", + "/.npmrc", + ] { + assert!( + patterns.contains(&expected.to_string()), + "{expected}: {patterns:?}" + ); + } } } diff --git a/src/modules/node/mod.rs b/src/modules/node/mod.rs index e4fdbbb..59eff92 100644 --- a/src/modules/node/mod.rs +++ b/src/modules/node/mod.rs @@ -8,6 +8,7 @@ use serde::Deserialize; use serde_yaml::Mapping; use std::path::Path; +mod custom; mod expand; mod inputs; mod manager; @@ -103,8 +104,9 @@ struct Node { cache: bool, /// The lockfile, relative to the project root. lockfile: String, - /// Pnpmfiles that `pnpm-workspace.yaml` or `.npmrc` name, relative to the project root. - pnpmfiles: Vec, + /// Files at paths the package manager's config names (a pnpmfile, Yarn's `yarnPath`, + /// plugins, cache and patch folders), relative to the project root. + custom_inputs: Vec, /// The CircleCI image's problem with the version, found when loading and reported only /// when expanding for CircleCI, so a GitHub-only config never sees it. circleci_image_error: Option, @@ -155,9 +157,9 @@ fn load(params: &Mapping, context: &Context) -> Result> { ); } let circleci_image_error = expand::circleci_image_error(context.image, &version); - let pnpmfiles = inputs::custom_pnpmfiles(root, &path)?; + let custom_inputs = custom::custom_inputs(root, &path)?; Ok(Box::new(Node { - pnpmfiles, + custom_inputs, path, version, manager, @@ -225,12 +227,12 @@ impl Module for Node { "install": self.install, "cache": self.cache, "lockfile": self.lockfile, - "pnpmfiles": self.pnpmfiles, + "custom_inputs": self.custom_inputs, }) } fn inputs(&self) -> Vec { - let mut inputs = inputs::patterns(&self.path, &self.pnpmfiles); + let mut inputs = inputs::patterns(&self.path, &self.custom_inputs); if let Version::File { file, .. } = &self.version { inputs.push(file.clone()); } diff --git a/src/modules/node/tests/circleci.rs b/src/modules/node/tests/circleci.rs new file mode 100644 index 0000000..c34abda --- /dev/null +++ b/src/modules/node/tests/circleci.rs @@ -0,0 +1,89 @@ +//! The node module's CircleCI steps: Node from the image, Corepack and the cache. +use super::*; + +#[test] +fn pnpm_on_circleci_uses_corepack_and_a_fixed_store() { + let dir = project(PNPM); + let expansion = node_on("{}", &dir, "cimg/node:22.11.0") + .unwrap() + .expand("circleci") + .unwrap(); + let before = summary(&expansion.before); + assert!(before[0].starts_with("Enable Corepack:"), "{before:?}"); + assert!( + before[0].contains("corepack enable --install-directory"), + "{before:?}" + ); + assert!(before[0].contains("npm_config_store_dir"), "{before:?}"); + // pnpm 11 reads only its own prefix. + assert!(before[0].contains("pnpm_config_store_dir"), "{before:?}"); + // The image's own Corepack may be too old to verify current pnpm and Yarn releases. + assert!( + before[0].contains("npm install --global --prefix \"$HOME/.corepack\" corepack@0.36.0"), + "{before:?}" + ); + assert!(!before[0].contains("command -v corepack"), "{before:?}"); + assert_eq!( + before[1..], + [ + "restore: node-v1-{{ arch }}-pnpm-{{ checksum \"pnpm-lock.yaml\" }} | node-v1-{{ arch }}-pnpm-", + "Install dependencies: pnpm install --frozen-lockfile", + ] + ); + assert_eq!( + summary(&expansion.after), + ["save: node-v1-{{ arch }}-pnpm-{{ checksum \"pnpm-lock.yaml\" }} ~/.pnpm-store"] + ); +} + +#[test] +fn circleci_checks_the_image_has_the_pinned_node() { + let dir = project(PNPM); + for image in [ + "cimg/node:22.11.0", + "node:22-bookworm", + "cimg/node:22.11.0-browsers", + ] { + assert!( + node_on("{}", &dir, image) + .unwrap() + .expand("circleci") + .is_ok(), + "{image}" + ); + } + let wrong = node_on("{}", &dir, "cimg/node:20.18.0").unwrap(); + let message = format!("{:#}", wrong.expand("circleci").unwrap_err()); + assert!(message.contains("doesn't have Node `22`"), "{message}"); + // GitHub doesn't care about the image. + assert!(wrong.expand("github").is_ok()); + let other = node_on("{}", &dir, "ruby:3.4").unwrap(); + let message = format!("{:#}", other.expand("circleci").unwrap_err()); + assert!(message.contains("version: preinstalled"), "{message}"); + // `preinstalled` uses whatever Node the image has, whatever `.nvmrc` says. + let preinstalled = node_on("{ version: preinstalled }", &dir, "ruby:3.4").unwrap(); + assert!(preinstalled.expand("circleci").is_ok()); +} + +#[test] +fn yarn_berry_on_circleci_caches_the_global_and_the_project_cache() { + let dir = project(&[ + ("web/package.json", r#"{"packageManager": "yarn@3.8.0"}"#), + ("web/yarn.lock", ""), + ]); + let expansion = node_on( + "{ path: web, version: preinstalled }", + &dir, + "cimg/base:current", + ) + .unwrap() + .expand("circleci") + .unwrap(); + // Yarn 2 and 3 keep the cache in the project unless `enableGlobalCache` is on. + assert_eq!( + summary(&expansion.after), + [ + "save: node-v1-{{ arch }}-yarn-{{ checksum \"web/yarn.lock\" }} ~/.yarn/berry/cache,web/.yarn/cache" + ] + ); +} diff --git a/src/modules/node/tests.rs b/src/modules/node/tests/mod.rs similarity index 70% rename from src/modules/node/tests.rs rename to src/modules/node/tests/mod.rs index f94e80e..9bf1632 100644 --- a/src/modules/node/tests.rs +++ b/src/modules/node/tests/mod.rs @@ -70,6 +70,8 @@ const PNPM: &[(&str, &str)] = &[ (".nvmrc", "22\n"), ]; +mod circleci; + #[test] fn pnpm_on_github() { let dir = project(PNPM); @@ -87,41 +89,6 @@ fn pnpm_on_github() { assert!(expansion.after.is_empty()); } -#[test] -fn pnpm_on_circleci_uses_corepack_and_a_fixed_store() { - let dir = project(PNPM); - let expansion = node_on("{}", &dir, "cimg/node:22.11.0") - .unwrap() - .expand("circleci") - .unwrap(); - let before = summary(&expansion.before); - assert!(before[0].starts_with("Enable Corepack:"), "{before:?}"); - assert!( - before[0].contains("corepack enable --install-directory"), - "{before:?}" - ); - assert!(before[0].contains("npm_config_store_dir"), "{before:?}"); - // pnpm 11 reads only its own prefix. - assert!(before[0].contains("pnpm_config_store_dir"), "{before:?}"); - // The image's own Corepack may be too old to verify current pnpm and Yarn releases. - assert!( - before[0].contains("npm install --global --prefix \"$HOME/.corepack\" corepack@0.36.0"), - "{before:?}" - ); - assert!(!before[0].contains("command -v corepack"), "{before:?}"); - assert_eq!( - before[1..], - [ - "restore: node-v1-{{ arch }}-pnpm-{{ checksum \"pnpm-lock.yaml\" }} | node-v1-{{ arch }}-pnpm-", - "Install dependencies: pnpm install --frozen-lockfile", - ] - ); - assert_eq!( - summary(&expansion.after), - ["save: node-v1-{{ arch }}-pnpm-{{ checksum \"pnpm-lock.yaml\" }} ~/.pnpm-store"] - ); -} - #[test] fn npm_needs_no_corepack_and_yarn_installs_by_major_version() { let dir = project(&[ @@ -157,35 +124,6 @@ fn npm_needs_no_corepack_and_yarn_installs_by_major_version() { } } -#[test] -fn circleci_checks_the_image_has_the_pinned_node() { - let dir = project(PNPM); - for image in [ - "cimg/node:22.11.0", - "node:22-bookworm", - "cimg/node:22.11.0-browsers", - ] { - assert!( - node_on("{}", &dir, image) - .unwrap() - .expand("circleci") - .is_ok(), - "{image}" - ); - } - let wrong = node_on("{}", &dir, "cimg/node:20.18.0").unwrap(); - let message = format!("{:#}", wrong.expand("circleci").unwrap_err()); - assert!(message.contains("doesn't have Node `22`"), "{message}"); - // GitHub doesn't care about the image. - assert!(wrong.expand("github").is_ok()); - let other = node_on("{}", &dir, "ruby:3.4").unwrap(); - let message = format!("{:#}", other.expand("circleci").unwrap_err()); - assert!(message.contains("version: preinstalled"), "{message}"); - // `preinstalled` uses whatever Node the image has, whatever `.nvmrc` says. - let preinstalled = node_on("{ version: preinstalled }", &dir, "ruby:3.4").unwrap(); - assert!(preinstalled.expand("circleci").is_ok()); -} - #[test] fn mistakes_fail_with_a_fix() { let dir = project(&[("package.json", "{}")]); @@ -286,26 +224,3 @@ fn without_a_version_file_engines_pins_node() { let module = node("{}", &dir).unwrap(); assert_eq!(module.resolved()["version"]["file"], ".nvmrc"); } - -#[test] -fn yarn_berry_on_circleci_caches_the_global_and_the_project_cache() { - let dir = project(&[ - ("web/package.json", r#"{"packageManager": "yarn@3.8.0"}"#), - ("web/yarn.lock", ""), - ]); - let expansion = node_on( - "{ path: web, version: preinstalled }", - &dir, - "cimg/base:current", - ) - .unwrap() - .expand("circleci") - .unwrap(); - // Yarn 2 and 3 keep the cache in the project unless `enableGlobalCache` is on. - assert_eq!( - summary(&expansion.after), - [ - "save: node-v1-{{ arch }}-yarn-{{ checksum \"web/yarn.lock\" }} ~/.yarn/berry/cache,web/.yarn/cache" - ] - ); -} diff --git a/tests/module_node.rs b/tests/module_node.rs index 07b454a..40467ee 100644 --- a/tests/module_node.rs +++ b/tests/module_node.rs @@ -136,6 +136,58 @@ fn a_pnpmfile_named_in_the_workspace_file_or_npmrc_reruns_the_job() { } } +#[test] +fn yarn_files_at_paths_yarnrc_names_rerun_the_job() { + // Paths in a `.yarnrc.yml` are relative to its folder. + for (config, contents, file) in [ + ( + "web/.yarnrc.yml", + "yarnPath: tools/yarn.cjs\n", + "web/tools/yarn.cjs", + ), + ( + "web/.yarnrc.yml", + "plugins:\n - path: tools/plugin.cjs\n spec: plugin\n", + "web/tools/plugin.cjs", + ), + ( + "web/.yarnrc.yml", + "plugins:\n - tools/plugin.cjs\n", + "web/tools/plugin.cjs", + ), + ( + "web/.yarnrc.yml", + "cacheFolder: tools/cache\n", + "web/tools/cache/left-pad.zip", + ), + ( + "web/.yarnrc.yml", + "patchFolder: tools/patches\n", + "web/tools/patches/left-pad.patch", + ), + ( + ".yarnrc.yml", + "yarnPath: web/tools/yarn.cjs\n", + "web/tools/yarn.cjs", + ), + ] { + let repo = node_fixture(""); + repo.write(config, contents).write(file, "one\n"); + let mut sim = node_simulator(&repo); + let first = repo.commit("initial"); + assert!(tests_ran(&sim.run(WORKFLOW, &push(&first)).unwrap())); + assert!(!tests_ran(&sim.run(WORKFLOW, &push(&first)).unwrap())); + + repo.write(file, "two\n"); + let changed = repo.commit(&format!("change {file}")); + let run = sim.run(WORKFLOW, &push(&changed)).unwrap(); + assert!( + tests_ran(&run), + "{config} {contents}: changing {file} must rerun the job\n{run}" + ); + } +} + #[test] fn changing_the_modules_parameters_reruns_the_job() { let repo = node_fixture("");