diff --git a/README.md b/README.md index 053c418..f0d834b 100644 --- a/README.md +++ b/README.md @@ -121,7 +121,9 @@ 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, and the `playwright` module installs Playwright's browsers and system packages with +both cached. Services are next. ## Install diff --git a/crates/mockci/src/actions.rs b/crates/mockci/src/actions.rs index 644f783..4844c03 100644 --- a/crates/mockci/src/actions.rs +++ b/crates/mockci/src/actions.rs @@ -87,12 +87,8 @@ pub fn run(uses: &str, with: &BTreeMap, ctx: &JobContext) -> Res "actions/cache/save" => { check_inputs(name, with, CACHE_INPUTS)?; let paths = cache::parse_paths(required(with, "path")?)?; - ctx.cache().save( - &ctx.workspace, - required(with, "key")?, - &paths, - &ctx.save_scope(), - )?; + ctx.cache() + .save(required(with, "key")?, &paths, &ctx.save_scope())?; Ok(ActionResult::ok("cache saved")) } "actions/upload-artifact" => { @@ -155,7 +151,6 @@ fn restore(name: &str, with: &BTreeMap, ctx: &JobContext) -> Res }) .unwrap_or_default(); let restored = ctx.cache().restore( - &ctx.workspace, key, &restore_keys, &paths, @@ -275,6 +270,8 @@ impl JobContext<'_> { blobs: &self.sim.cache_dir, job_row: self.job_row, now: self.sim.now, + workspace: &self.workspace, + home: &self.home, } } } diff --git a/crates/mockci/src/cache.rs b/crates/mockci/src/cache.rs index 4a3fbd8..c80435f 100644 --- a/crates/mockci/src/cache.rs +++ b/crates/mockci/src/cache.rs @@ -10,6 +10,8 @@ //! - Entries not used for 7 days are evicted. //! - The version is derived from the cached paths, so a save and a restore of different //! paths never see each other. +//! - A path is relative to the workspace, or to the job's home directory when it starts +//! with `~/`. use crate::db::{CacheEntry, CacheEvent, Db}; use anyhow::{Context, Result, bail}; @@ -23,6 +25,8 @@ pub struct Cache<'a> { pub blobs: &'a Path, pub job_row: i64, pub now: i64, + pub workspace: &'a Path, + pub home: &'a Path, } /// The result of a restore, as the action reports it. @@ -44,8 +48,10 @@ pub fn parse_paths(input: &str) -> Result> { bail!("actions/cache needs a `path`"); } for path in &paths { - if path.starts_with('/') || path.starts_with('~') || path.contains("..") { - bail!("mockci only caches paths inside the workspace, got `{path}`"); + let home_relative = path.strip_prefix("~/").is_some_and(|rest| !rest.is_empty()); + if path.starts_with('/') || (path.starts_with('~') && !home_relative) || path.contains("..") + { + bail!("mockci only caches paths inside the workspace or under `~/`, got `{path}`"); } if path.contains(['*', '?', '[', '!']) { bail!("mockci doesn't support glob patterns in cache paths yet, got `{path}`"); @@ -61,7 +67,6 @@ pub fn version(paths: &[String]) -> String { impl Cache<'_> { pub fn restore( &self, - workspace: &Path, key: &str, restore_keys: &[String], paths: &[String], @@ -82,7 +87,7 @@ impl Cache<'_> { for (index, path) in paths.iter().enumerate() { let stored = self.blob_path(entry.id, index); if stored.exists() { - copy_tree(&stored, &workspace.join(path))?; + copy_tree(&stored, &self.resolve(path))?; } } let exact = entry.key == key; @@ -115,7 +120,7 @@ impl Cache<'_> { } /// Saves `paths` under `key` in `scope`, unless the key already exists there. - pub fn save(&self, workspace: &Path, key: &str, paths: &[String], scope: &str) -> Result<()> { + pub fn save(&self, key: &str, paths: &[String], scope: &str) -> Result<()> { let version = version(paths); if self .db @@ -124,12 +129,12 @@ impl Cache<'_> { { return self.record("save", key, None, Some(scope), "exists"); } - if !paths.iter().any(|path| workspace.join(path).exists()) { + if !paths.iter().any(|path| self.resolve(path).exists()) { return self.record("save", key, None, Some(scope), "no-files"); } let id = self.db.insert_cache_entry(key, &version, scope, self.now)?; for (index, path) in paths.iter().enumerate() { - let source = workspace.join(path); + let source = self.resolve(path); if source.exists() { copy_tree(&source, &self.blob_path(id, index))?; } @@ -137,6 +142,14 @@ impl Cache<'_> { self.record("save", key, None, Some(scope), "saved") } + /// Where a cached path is on the runner. + fn resolve(&self, path: &str) -> PathBuf { + match path.strip_prefix("~/") { + Some(rest) => self.home.join(rest), + None => self.workspace.join(path), + } + } + fn blob_path(&self, id: i64, index: usize) -> PathBuf { self.blobs.join(id.to_string()).join(index.to_string()) } diff --git a/crates/mockci/src/job.rs b/crates/mockci/src/job.rs index 296c9d6..03a03b9 100644 --- a/crates/mockci/src/job.rs +++ b/crates/mockci/src/job.rs @@ -19,6 +19,8 @@ pub struct JobContext<'a> { pub job_row: i64, pub workspace: PathBuf, pub temp: PathBuf, + /// The job's `HOME`, empty at the start of every job like a fresh hosted runner's. + pub home: PathBuf, } impl JobContext<'_> { @@ -49,6 +51,7 @@ struct State { pub fn run(ctx: &JobContext, workflow: &Workflow, job: &Job, needs: &Value) -> Result { std::fs::create_dir_all(&ctx.workspace)?; std::fs::create_dir_all(&ctx.temp)?; + std::fs::create_dir_all(&ctx.home)?; let github = ctx .event .github_context(&ctx.workspace.to_string_lossy(), ctx.run_id); @@ -82,8 +85,7 @@ pub fn run(ctx: &JobContext, workflow: &Workflow, job: &Job, needs: &Value) -> R } else { match post { PostStep::CacheSave { key, paths } => { - ctx.cache() - .save(&ctx.workspace, &key, &paths, &ctx.save_scope())?; + ctx.cache().save(&key, &paths, &ctx.save_scope())?; Outcome::Success } } @@ -290,6 +292,7 @@ fn default_env(ctx: &JobContext, job: &Job) -> BTreeMap { ("GITHUB_RUN_ID".into(), ctx.run_id.to_string()), ("GITHUB_SHA".into(), ctx.event.sha().into()), ("GITHUB_WORKSPACE".into(), workspace), + ("HOME".into(), ctx.home.to_string_lossy().into_owned()), ("RUNNER_OS".into(), "Linux".into()), ( "RUNNER_TEMP".into(), diff --git a/crates/mockci/src/shell.rs b/crates/mockci/src/shell.rs index e33ea4a..91fa001 100644 --- a/crates/mockci/src/shell.rs +++ b/crates/mockci/src/shell.rs @@ -64,6 +64,14 @@ pub fn run( command.env(name, value); } } + // The job gets its own `HOME`, so point the host's Rust toolchain at where it lives, as a + // runner image sets `CARGO_HOME` and `RUSTUP_HOME` for the tools it ships. + if let Ok(home) = std::env::var("HOME") { + for (name, dir) in [("CARGO_HOME", ".cargo"), ("RUSTUP_HOME", ".rustup")] { + let value = std::env::var(name).unwrap_or_else(|_| format!("{home}/{dir}")); + command.env(name, value); + } + } command .envs(env) .env("PATH", path) diff --git a/crates/mockci/src/sim.rs b/crates/mockci/src/sim.rs index f33da6d..399a328 100644 --- a/crates/mockci/src/sim.rs +++ b/crates/mockci/src/sim.rs @@ -153,6 +153,11 @@ impl Simulator { .join(run_id.to_string()) .join(&id) .join("temp"), + home: self + .runs_dir + .join(run_id.to_string()) + .join(&id) + .join("home"), }; job::run(&ctx, &workflow, job, &needs)? } else { diff --git a/docs/src/content/case-studies/bootstrap.md b/docs/src/content/case-studies/bootstrap.md index da540f9..b8c7554 100644 --- a/docs/src/content/case-studies/bootstrap.md +++ b/docs/src/content/case-studies/bootstrap.md @@ -378,4 +378,4 @@ And gaps, filed as issues: A `node` module would replace the `setup_node` command and the npm cache, and a `playwright` module the browser installs in the CSS and JS jobs, with the browsers cached by Playwright's version. Each job would come down to its -inputs and two or three `npm run` steps. Both modules are in progress. +inputs and two or three `npm run` steps. Both modules are built; this case study's config doesn't use them yet. diff --git a/docs/src/content/docs/modules.md b/docs/src/content/docs/modules.md index 137a060..d70df26 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,109 @@ 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 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). + +## The `playwright` module + +Installs Playwright's browsers and, on Linux, the system packages they need. It comes after `node` in the job's +`modules:`, because Playwright runs from the `node_modules` that `node` installs; listed without `node` before it, +generation fails and says so. Here the end-to-end tests are a package of their own: + +```json title="e2e/package.json" +{ + "private": true, + "devDependencies": { "@playwright/test": "1.49.0" } +} +``` + +```json title="e2e/package-lock.json" +{ "lockfileVersion": 3 } +``` + +```yaml +# cigen.yml +provider: github + +workflows: + ci: + jobs: + e2e: + image: ubuntu-24.04 + modules: + - node: { path: e2e } + - playwright: { path: e2e, browsers: [chromium, firefox] } + inputs: ['src/**', 'e2e/tests/**'] + steps: + - run: cd e2e && npx playwright test +``` + +| Parameter | Default | Meaning | +| ------------- | ------------ | --------------------------------------------------------------------------------------------------------- | +| `browsers` | `[chromium]` | the browsers to install: `chromium`, `chromium-headless-shell`, `firefox`, `webkit`, `chrome` or `msedge` | +| `system_deps` | `true` | install the system packages the browsers need (`--with-deps`) | +| `deb_cache` | `true` | keep those packages' `.deb` files in the cache (with `system_deps`) | +| `save_branch` | `main` | the only branch that saves the `.deb` cache; other branches read it | +| `path` | `.` | the directory whose `package.json` depends on Playwright | + +It reads the installed Playwright's version and caches `~/.cache/ms-playwright` under it. On Linux, it tells apt to +keep the `.deb` files it downloads for `playwright install-deps` in a cached directory, prunes that directory to the +packages installed, and saves it only from `save_branch`, so pull requests and other branches read `main`'s packages +and never write a cache of their own. It adds `package.json`, the lockfile and `playwright.config.*` to the job's +inputs. GitHub Actions only, so far. Its full reference is +[`src/modules/playwright/README.md`](https://github.com/DocSpring/cigen/blob/main/src/modules/playwright/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 +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 3c2b7ed..4fb3252 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, node and Playwright are built; 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: services and caches
    • cigen plan and expand for agents
    • 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..416004d --- /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 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 + - 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 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 + - 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..009dc21 --- /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 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" + - 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 dc362dbabbf9bd14 | 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 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" + - run: + name: Enable Corepack + command: | + export PATH="$HOME/.corepack"/bin:$PATH + 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: + - 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 988c9386cf4ef8b6 | 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..db34110 --- /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 dc362dbabbf9bd14 \ + --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 988c9386cf4ef8b6 \ + --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/integration_tests/module_playwright/.github/workflows/ci.yml b/integration_tests/module_playwright/.github/workflows/ci.yml new file mode 100644 index 0000000..9c8305c --- /dev/null +++ b/integration_tests/module_playwright/.github/workflows/ci.yml @@ -0,0 +1,299 @@ +# DO NOT EDIT - This file is generated by cigen +# Source: cigen.yml +# Regenerate with: cigen generate +# +on: + push: + branches: + - main + pull_request: null +name: CI +jobs: + cross_browser: + runs-on: ubuntu-24.04 + 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 cross_browser \ + --base-dir . \ + --modules-digest 334692ba954f20f3 \ + --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/cross_browser + key: job-skip-${{ runner.os }}-cross_browser-${{ 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' + - name: Find Playwright's version + run: | + version=$(pnpm exec playwright --version | sed -n 's/^Version //p') + if [ -z "$version" ]; then + echo "Playwright isn't installed in the project; install the project's dependencies first (the node module does)" >&2 + exit 1 + fi + echo "version=$version" >> "$GITHUB_OUTPUT" + echo "os=$(cat /etc/os-release 2>/dev/null | cksum | cut -d ' ' -f 1)" >> "$GITHUB_OUTPUT" + id: playwright_version + if: steps.job_skip_cache.outputs.cache-hit != 'true' + - name: Cache Playwright's browsers + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 + with: + key: playwright-browsers-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.playwright_version.outputs.version }}-firefox-webkit + path: ~/.cache/ms-playwright + if: steps.job_skip_cache.outputs.cache-hit != 'true' + - name: Install Playwright's browsers + run: pnpm exec playwright install --with-deps firefox webkit + if: steps.job_skip_cache.outputs.cache-hit != 'true' + - run: pnpm exec playwright test --project firefox --project webkit + 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/cross_browser/$HASH + mkdir -p "$(dirname "$MARKER")" + date > "$MARKER" + env: + JOB_HASH: ${{ steps.compute_hash.outputs.job_hash }} + e2e: + runs-on: ubuntu-24.04 + 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 e2e \ + --base-dir . \ + --modules-digest 49a7679262ccc499 \ + --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/e2e + key: job-skip-${{ runner.os }}-e2e-${{ 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' + - name: Find Playwright's version + run: | + version=$(pnpm exec playwright --version | sed -n 's/^Version //p') + if [ -z "$version" ]; then + echo "Playwright isn't installed in the project; install the project's dependencies first (the node module does)" >&2 + exit 1 + fi + echo "version=$version" >> "$GITHUB_OUTPUT" + echo "os=$(cat /etc/os-release 2>/dev/null | cksum | cut -d ' ' -f 1)" >> "$GITHUB_OUTPUT" + id: playwright_version + if: steps.job_skip_cache.outputs.cache-hit != 'true' + - name: Cache Playwright's browsers + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 + with: + key: playwright-browsers-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.playwright_version.outputs.version }}-chromium + path: ~/.cache/ms-playwright + if: steps.job_skip_cache.outputs.cache-hit != 'true' + - name: Restore Playwright's system packages + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 + with: + key: playwright-debs-v1-${{ runner.arch }}-${{ steps.playwright_version.outputs.os }}-${{ steps.playwright_version.outputs.version }}-chromium + path: ~/.cache/playwright-debs + restore-keys: playwright-debs-v1-${{ runner.arch }}-${{ steps.playwright_version.outputs.os }}- + if: (runner.os == 'Linux') && (steps.job_skip_cache.outputs.cache-hit != 'true') + id: playwright_debs + - name: Install Playwright's system packages + run: | + debs="$HOME/.cache/playwright-debs" + mkdir -p "$debs/partial" + echo "Dir::Cache::Archives \"$debs/\"; APT::Keep-Downloaded-Packages \"true\";" | sudo tee /etc/apt/apt.conf.d/90cigen-playwright-debs >/dev/null + pnpm exec playwright install-deps chromium + if: (runner.os == 'Linux') && (steps.job_skip_cache.outputs.cache-hit != 'true') + - name: Prune Playwright's system packages + run: | + sudo rm -f /etc/apt/apt.conf.d/90cigen-playwright-debs + debs="$HOME/.cache/playwright-debs" + mkdir -p "$debs" + sudo chown -R "$(id -u):$(id -g)" "$debs" + rm -rf "$debs/partial" "$debs/lock" + count=0 + for deb in "$debs"/*.deb; do + [ -e "$deb" ] || continue + package=$(dpkg-deb -f "$deb" Package) + version=$(dpkg-deb -f "$deb" Version) + if dpkg-query -W -f='${Version}\n' "$package" 2>/dev/null | grep -qxF "$version"; then + count=$((count + 1)) + else + rm -f "$deb" + fi + done + echo "count=$count" >> "$GITHUB_OUTPUT" + if: (always() && runner.os == 'Linux') && (steps.job_skip_cache.outputs.cache-hit != 'true') + id: playwright_debs_prune + - name: Save Playwright's system packages + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 + with: + key: playwright-debs-v1-${{ runner.arch }}-${{ steps.playwright_version.outputs.os }}-${{ steps.playwright_version.outputs.version }}-chromium + path: ~/.cache/playwright-debs + if: (runner.os == 'Linux' && github.ref == 'refs/heads/main' && steps.playwright_debs.outputs.cache-hit != 'true' && steps.playwright_debs_prune.outputs.count != '0') && (steps.job_skip_cache.outputs.cache-hit != 'true') + - name: Install Playwright's browsers + run: pnpm exec playwright install chromium + if: steps.job_skip_cache.outputs.cache-hit != 'true' + - run: pnpm exec playwright test + 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/e2e/$HASH + mkdir -p "$(dirname "$MARKER")" + date > "$MARKER" + env: + JOB_HASH: ${{ steps.compute_hash.outputs.job_hash }} diff --git a/integration_tests/module_playwright/.nvmrc b/integration_tests/module_playwright/.nvmrc new file mode 100644 index 0000000..2bd5a0a --- /dev/null +++ b/integration_tests/module_playwright/.nvmrc @@ -0,0 +1 @@ +22 diff --git a/integration_tests/module_playwright/cigen.yml b/integration_tests/module_playwright/cigen.yml new file mode 100644 index 0000000..4d7d34a --- /dev/null +++ b/integration_tests/module_playwright/cigen.yml @@ -0,0 +1,23 @@ +provider: github +workflows: + ci: + github: + on: + push: + branches: [main] + pull_request: + jobs: + e2e: + image: ubuntu-24.04 + modules: [node, playwright] + inputs: ["src/**", "e2e/**"] + steps: + - run: pnpm exec playwright test + cross_browser: + image: ubuntu-24.04 + modules: + - node + - playwright: { browsers: [firefox, webkit], deb_cache: false } + inputs: ["src/**", "e2e/**"] + steps: + - run: pnpm exec playwright test --project firefox --project webkit diff --git a/integration_tests/module_playwright/package.json b/integration_tests/module_playwright/package.json new file mode 100644 index 0000000..61691c0 --- /dev/null +++ b/integration_tests/module_playwright/package.json @@ -0,0 +1,8 @@ +{ + "name": "fixture", + "private": true, + "packageManager": "pnpm@9.15.0", + "devDependencies": { + "@playwright/test": "1.49.0" + } +} diff --git a/integration_tests/module_playwright/pnpm-lock.yaml b/integration_tests/module_playwright/pnpm-lock.yaml new file mode 100644 index 0000000..c1a4322 --- /dev/null +++ b/integration_tests/module_playwright/pnpm-lock.yaml @@ -0,0 +1 @@ +lockfileVersion: "9.0" diff --git a/internal_docs/MOCK_CI.md b/internal_docs/MOCK_CI.md index 8d89c89..b2bef37 100644 --- a/internal_docs/MOCK_CI.md +++ b/internal_docs/MOCK_CI.md @@ -10,7 +10,8 @@ what GitHub would do with it. - **Real work:** each run clones the repository at the event's commit, runs `run:` steps with the shell GitHub would use (`bash -e {0}` by default, `bash --noprofile --norc -eo pipefail {0}` for `shell: bash`, `sh -e {0}`), and reads `GITHUB_OUTPUT`, `GITHUB_ENV` and `GITHUB_PATH`, heredoc values included. Steps run on the host; `container:` - is recorded but not used. + is recorded but not used. Each job gets its own empty `HOME`, like a fresh hosted runner, with `CARGO_HOME` and + `RUSTUP_HOME` still pointing at the host's Rust toolchain. - **Expressions:** `${{ }}` in `run`, `with`, `env`, step names and job outputs; `if:` with or without the wrapper, the implicit `success()`, and the status functions; GitHub's loose equality and truthiness; `contains`, `startsWith`, `endsWith`, `format`, `join`, `toJSON`, `fromJSON`, `hashFiles`. @@ -20,8 +21,8 @@ what GitHub would do with it. - **The cache service** (`src/cache.rs`), as `actions/cache` sees it: lookups search the run's ref, then a pull request's base branch, then the default branch, each by exact key, then prefix; `cache-hit` is `'true'` only for an exact match; entries are immutable; saves happen in a post step only when the job succeeded and the key wasn't an - exact hit, and go to the run's own ref; entries unused for 7 days are evicted. `actions/cache/restore` and - `actions/cache/save` work too. + exact hit, and go to the run's own ref; entries unused for 7 days are evicted. Paths are relative to the workspace, + or to the job's `HOME` when they start with `~/`. `actions/cache/restore` and `actions/cache/save` work too. - **Artifacts:** `actions/upload-artifact` (a file as itself, a directory's contents, hidden files under a directory left out unless `include-hidden-files: true`) and `actions/download-artifact` by name, within a run. - **Tools in the image:** `Simulator::provide_file` places a file in the workspace after every checkout, the way a diff --git a/internal_docs/STATUS.md b/internal_docs/STATUS.md index 8943639..c54d484 100644 --- a/internal_docs/STATUS.md +++ b/internal_docs/STATUS.md @@ -76,7 +76,22 @@ What the code does today, checked against the code in December 2026. Where cigen that name the closest one. The registry in `src/modules/mod.rs` is the catalogue; each module's directory holds its `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: + hash and warns when its own expansion differs, so a config generated by another cigen never reuses a pass. A + module's spec names the modules the job must list before it (`playwright` needs `node`); generation fails otherwise. + 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 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. + - `playwright` (GitHub only): reads the installed Playwright's + version, caches `~/.cache/ms-playwright` under it, and installs the browsers. On Linux it installs their system + packages with apt keeping the `.deb` files in a cached directory, which an always-run step prunes to the packages + installed and only `save_branch` saves. It adds `package.json`, the lockfile and `playwright.config.*` 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. @@ -151,12 +166,22 @@ 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`, `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_playwright.rs`: a job using the `playwright` module installs nothing when it skips, and reruns in + mockci when `playwright.config.*`, the lockfile, `package.json` or its parameters change; a pull request before + `main` has a `.deb` cache downloads and saves nothing, `main` saves, later pull requests restore `main`'s and save + nothing, an exact hit saves nothing, a new Playwright restores the older cache and saves under its own key, and a + `.deb` for a package not installed is pruned before saving. +- `tests/mockci_home.rs`: each mockci job has its own empty `HOME`, and `actions/cache` caches paths under `~/`. - `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 @@ -169,7 +194,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. @@ -231,4 +258,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: 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..889eec9 100644 --- a/schemas/v1/cigen.schema.json +++ b/schemas/v1/cigen.schema.json @@ -322,12 +322,64 @@ { "type": "string", "enum": [ + "node", + "playwright", "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 + }, + "playwright": { + "description": "Installs Playwright's browsers and the system packages they need, with the packages' .deb files cached so a slow apt mirror doesn't stall the job.", + "type": [ + "object", + "null" + ], + "properties": { + "browsers": { + "description": "the browsers to install: `chromium`, `chromium-headless-shell`, `firefox`, `webkit`, `chrome` or `msedge` (default: `[chromium]`)" + }, + "deb_cache": { + "description": "keep those packages' `.deb` files in the cache (with `system_deps`) (default: `true`)" + }, + "path": { + "description": "the directory whose `package.json` depends on Playwright (default: `.`)" + }, + "save_branch": { + "description": "the only branch that saves the `.deb` cache; other branches read it (default: `main`)" + }, + "system_deps": { + "description": "install the system packages the browsers need (`--with-deps`) (default: `true`)" + } + }, + "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..86496cc 100644 --- a/schemas/v1/job.schema.json +++ b/schemas/v1/job.schema.json @@ -150,12 +150,64 @@ { "type": "string", "enum": [ + "node", + "playwright", "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 + }, + "playwright": { + "description": "Installs Playwright's browsers and the system packages they need, with the packages' .deb files cached so a slow apt mirror doesn't stall the job.", + "type": [ + "object", + "null" + ], + "properties": { + "browsers": { + "description": "the browsers to install: `chromium`, `chromium-headless-shell`, `firefox`, `webkit`, `chrome` or `msedge` (default: `[chromium]`)" + }, + "deb_cache": { + "description": "keep those packages' `.deb` files in the cache (with `system_deps`) (default: `true`)" + }, + "path": { + "description": "the directory whose `package.json` depends on Playwright (default: `.`)" + }, + "save_branch": { + "description": "the only branch that saves the `.deb` cache; other branches read it (default: `main`)" + }, + "system_deps": { + "description": "install the system packages the browsers need (`--with-deps`) (default: `true`)" + } + }, + "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..55719a3 100644 --- a/schemas/v1/workflow.schema.json +++ b/schemas/v1/workflow.schema.json @@ -208,12 +208,64 @@ { "type": "string", "enum": [ + "node", + "playwright", "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 + }, + "playwright": { + "description": "Installs Playwright's browsers and the system packages they need, with the packages' .deb files cached so a slow apt mirror doesn't stall the job.", + "type": [ + "object", + "null" + ], + "properties": { + "browsers": { + "description": "the browsers to install: `chromium`, `chromium-headless-shell`, `firefox`, `webkit`, `chrome` or `msedge` (default: `[chromium]`)" + }, + "deb_cache": { + "description": "keep those packages' `.deb` files in the cache (with `system_deps`) (default: `true`)" + }, + "path": { + "description": "the directory whose `package.json` depends on Playwright (default: `.`)" + }, + "save_branch": { + "description": "the only branch that saves the `.deb` cache; other branches read it (default: `main`)" + }, + "system_deps": { + "description": "install the system packages the browsers need (`--with-deps`) (default: `true`)" + } + }, + "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..2f012cd 100644 --- a/src/modules/README.md +++ b/src/modules/README.md @@ -8,4 +8,6 @@ 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` | +| [`playwright`](playwright/README.md) | Installs Playwright's browsers and the system packages they need, with the packages' .deb files cached so a slow apt mirror doesn't stall the job. | node | github | `browsers`, `system_deps`, `deb_cache`, `save_branch`, `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..7acbe74 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,21 @@ 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 spec = super::spec(&module.name).with_context(|| context(job_id, &module.name))?; + for required in spec.requires { + if !loaded.iter().any(|(name, _)| name == required) { + bail!( + "{}: it needs the `{required}` module; list `{required}` before it in the job's `modules:`", + 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!( @@ -205,4 +219,39 @@ mod tests { let modules = for_job(&config, "plain", Path::new(".")).unwrap(); assert_eq!(modules, JobModules::default()); } + + #[test] + fn a_module_that_needs_another_must_come_after_it() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write( + dir.path().join("package.json"), + "{\"devDependencies\": {\"@playwright/test\": \"1.49.0\"}}", + ) + .unwrap(); + std::fs::write(dir.path().join("package-lock.json"), "{}").unwrap(); + std::fs::write(dir.path().join(".nvmrc"), "22\n").unwrap(); + for (modules, ok) in [ + ("[playwright]", false), + ("[playwright, node]", false), + ("[node, playwright]", true), + ] { + let job: Job = + serde_yaml::from_str(&format!("modules: {modules}\nsteps: []\n")).unwrap(); + let config = CigenConfig { + providers: vec!["github".to_string()], + jobs: BTreeMap::from([("e2e".to_string(), job)]), + ..Default::default() + }; + let result = for_job(&config, "e2e", dir.path()); + if ok { + result.unwrap(); + } else { + let error = format!("{:#}", result.unwrap_err()); + assert!( + error.contains("list `node` before it in the job's `modules:`"), + "{modules}: {error}" + ); + } + } + } } diff --git a/src/modules/mod.rs b/src/modules/mod.rs index 1c32d81..749ee3e 100644 --- a/src/modules/mod.rs +++ b/src/modules/mod.rs @@ -8,20 +8,23 @@ pub mod catalogue; mod expand; +pub mod node; +pub mod playwright; 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, playwright::SPEC, rust::SPEC]; /// What the catalogue knows about a module. pub struct ModuleSpec { @@ -30,11 +33,27 @@ pub struct ModuleSpec { /// The toolchain family whose pins and lockfiles the module contributes. pub family: &'static str, pub providers: &'static [&'static str], + /// Modules the job must list before this one, because its steps use what they set up. + pub requires: &'static [&'static str], 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 +96,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 +115,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 +187,22 @@ 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`, `playwright`, `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..07e6538 --- /dev/null +++ b/src/modules/node/README.md @@ -0,0 +1,91 @@ +# `node` module + +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: + 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. +- 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 + +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 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. +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 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 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 + +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 + +| 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..3e6f208 --- /dev/null +++ b/src/modules/node/expand.rs @@ -0,0 +1,198 @@ +//! 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. + // 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( + 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"], + }; + 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 + } +} + +/// 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\ + npm install --global --prefix {prefix} {COREPACK}\n\ + {prefix}/bin/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/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/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..834628d --- /dev/null +++ b/src/modules/node/mod.rs @@ -0,0 +1,253 @@ +//! 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 inputs; +pub(in crate::modules) 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"], + requires: &[], + 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, + /// 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, +} + +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); + let pnpmfiles = inputs::custom_pnpmfiles(root, &path)?; + Ok(Box::new(Node { + pnpmfiles, + 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, + "pnpmfiles": self.pnpmfiles, + }) + } + + fn inputs(&self) -> Vec { + let mut inputs = inputs::patterns(&self.path, &self.pnpmfiles); + 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..f94e80e --- /dev/null +++ b/src/modules/node/tests.rs @@ -0,0 +1,311 @@ +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:?}"); + // 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(&[ + ("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"); +} + +#[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/playwright/README.md b/src/modules/playwright/README.md new file mode 100644 index 0000000..23e9408 --- /dev/null +++ b/src/modules/playwright/README.md @@ -0,0 +1,70 @@ +# `playwright` module + +Installs Playwright's browsers and, on Linux, the system packages they need. The browsers are cached by Playwright's +version. The packages' `.deb` files are cached too, so a job whose packages are cached doesn't wait on a slow apt +mirror, and only one branch writes that cache. + +```yaml +jobs: + e2e: + image: ubuntu-24.04 + modules: [node, playwright] + inputs: ['src/**', 'e2e/**'] + steps: + - run: pnpm exec playwright test +``` + +List `node` before `playwright`: Playwright runs from the project's `node_modules`, which the `node` module installs. +Without it, generation fails and says so. + +## Parameters + +| Parameter | Default | Meaning | +| ------------- | ------------ | --------------------------------------------------------------------------------------------------------- | +| `browsers` | `[chromium]` | the browsers to install: `chromium`, `chromium-headless-shell`, `firefox`, `webkit`, `chrome` or `msedge` | +| `system_deps` | `true` | install the system packages the browsers need (`--with-deps`) | +| `deb_cache` | `true` | keep those packages' `.deb` files in the cache (with `system_deps`) | +| `save_branch` | `main` | the only branch that saves the `.deb` cache; other branches read it | +| `path` | `.` | the directory whose `package.json` depends on Playwright | + +- `path`'s `package.json` must depend on `@playwright/test` or `playwright`, and the package manager comes from it the + way the `node` module finds it: `packageManager`, else the one lockfile. Playwright runs with `npx`, `pnpm exec` or + `yarn`. +- `deb_cache: true` with `system_deps: false` is an error; `system_deps: false` alone turns the `.deb` cache off. +- GitHub Actions only, so far. The caches work on Linux runners: the `.deb` steps run only on Linux, and the browser + cache holds `~/.cache/ms-playwright`, Playwright's directory on Linux. + +## What it adds to a job + +**GitHub Actions**, after the `node` module's steps: + +1. A step that reads the installed Playwright's version (`playwright --version`) and a checksum of + `/etc/os-release`. It fails if Playwright isn't installed, rather than letting `npx` download the latest. +2. `actions/cache` of `~/.cache/ms-playwright`, keyed by the runner's OS and architecture, Playwright's version and + the browsers. +3. With `deb_cache` (on Linux): + 1. `actions/cache/restore` of `~/.cache/playwright-debs`, keyed by the architecture, the OS release, Playwright's + version and the browsers, falling back to the newest cache for the same OS release. + 2. A step that points apt's download directory at `~/.cache/playwright-debs` and tells it to keep what it + downloads (in `/etc/apt/apt.conf.d/90cigen-playwright-debs`), then runs `playwright install-deps `. + 3. A step that always runs: it removes that apt configuration, gives the directory back to the runner's user, and + deletes every `.deb` that isn't an installed package at its installed version, so the cache holds only what + this job used. + 4. `actions/cache/save` of the directory, only on `save_branch`, only when the restore wasn't an exact hit, and + only when there's a `.deb` left to save. Pull requests and other branches read `save_branch`'s cache and never + write one of their own. +4. `playwright install `, with `--with-deps` when `system_deps` is on and `deb_cache` is off. + +Commands run after `cd &&` when `path` isn't `.`. + +## Inputs + +The module adds these files, inside `path`, to the hash of every job that uses it: `package.json`, the package +manager's lockfile (which pins Playwright, and so the browsers and packages it installs) and `playwright.config.*`. +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/cache`, `actions/cache/restore`, `actions/cache/save` | v6.1.0 | `55cc8345863c7cc4c66a329aec7e433d2d1c52a9` | diff --git a/src/modules/playwright/SKILL.md b/src/modules/playwright/SKILL.md new file mode 100644 index 0000000..f6484e7 --- /dev/null +++ b/src/modules/playwright/SKILL.md @@ -0,0 +1,31 @@ +--- +name: playwright +description: Install Playwright's browsers and their system packages in a cigen job with `modules: [node, playwright]`, with both cached. Use when a cigen job runs Playwright tests, instead of writing `playwright install --with-deps` and its caches by hand. +--- + +# The `playwright` module + +List `playwright` after `node` in the job's `modules:`: + +```yaml +jobs: + e2e: + image: ubuntu-24.04 + modules: [node, playwright] + inputs: ['src/**', 'e2e/**'] + steps: + - run: pnpm exec playwright test +``` + +- `node` must come first: it installs `node_modules`, where Playwright runs from. +- Set `browsers:` to the browsers the tests use (`[chromium]` by default); each one costs install time and cache space. +- Don't add a `playwright install` step, `--with-deps`, or a cache of `~/.cache/ms-playwright`: the module does all + three. +- The `.deb` cache is saved only from `save_branch` (`main` by default). Set it to the branch your pushes merge into. +- For Playwright in a package that isn't at the root, set `path:` to that package's directory. +- Don't add `package.json`, the lockfile or `playwright.config.*` to `inputs`: the module adds them. Declare the tests + and the sources they cover. +- GitHub Actions only, so far. + +Parameters: `browsers`, `system_deps`, `deb_cache`, `save_branch`, `path`. An unknown parameter is an error that names +the closest one. diff --git a/src/modules/playwright/expand.rs b/src/modules/playwright/expand.rs new file mode 100644 index 0000000..a278554 --- /dev/null +++ b/src/modules/playwright/expand.rs @@ -0,0 +1,201 @@ +//! The steps the playwright module adds on GitHub Actions. +//! +//! The browsers are cached by Playwright's version. On Linux, the system packages they need are +//! installed with apt told to keep the `.deb` files it downloads in a directory the cache +//! restores, so a run whose packages are cached doesn't wait on a slow mirror. Only +//! `save_branch` saves that cache: other branches read it and never write it. +use super::Playwright; +use crate::modules::Expansion; +use crate::modules::steps::{run, uses}; +use crate::schema::Step; +use serde_yaml::Value; +use std::collections::BTreeMap; + +/// `actions/cache` v6.1.0, and its `restore` and `save` halves. +const CACHE: &str = "actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9"; +const CACHE_RESTORE: &str = "actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9"; +const CACHE_SAVE: &str = "actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9"; + +/// Where Playwright keeps its browsers on Linux, and where apt keeps the `.deb` files. +const BROWSERS_DIR: &str = "~/.cache/ms-playwright"; +const DEBS_DIR: &str = "~/.cache/playwright-debs"; +/// The apt configuration the module writes while it installs, and removes after. +const APT_CONF: &str = "/etc/apt/apt.conf.d/90cigen-playwright-debs"; + +const VERSION_ID: &str = "playwright_version"; +const DEBS_ID: &str = "playwright_debs"; +const PRUNE_ID: &str = "playwright_debs_prune"; + +impl Playwright { + pub(super) fn github(&self) -> Expansion { + let browsers = self.browsers.join(" "); + let mut before = vec![ + with_id( + run("Find Playwright's version", self.version_script()), + VERSION_ID, + ), + uses( + "Cache Playwright's browsers", + CACHE, + cache_with( + BROWSERS_DIR, + format!( + "playwright-browsers-v1-${{{{ runner.os }}}}-${{{{ runner.arch }}}}-${{{{ steps.{VERSION_ID}.outputs.version }}}}-{}", + self.browsers.join("-") + ), + None, + ), + ), + ]; + if self.deb_cache { + before.extend(self.deb_steps(&browsers)); + } + let with_deps = if self.system_deps && !self.deb_cache { + " --with-deps" + } else { + "" + }; + before.push(run( + "Install Playwright's browsers", + self.in_path(&format!( + "{} playwright install{with_deps} {browsers}", + self.exec + )), + )); + Expansion { + before, + after: Vec::new(), + } + } + + /// Writes the installed Playwright's version, and a checksum of the runner's OS release, + /// to the step's outputs. Fails when Playwright isn't installed, rather than letting `npx` + /// download whatever version is latest. + fn version_script(&self) -> String { + let find = self.in_path(&format!("{} playwright --version", self.exec)); + format!( + "version=$({find} | sed -n 's/^Version //p')\n\ + if [ -z \"$version\" ]; then\n \ + echo \"Playwright isn't installed in {place}; install the project's dependencies first (the node module does)\" >&2\n \ + exit 1\n\ + fi\n\ + echo \"version=$version\" >> \"$GITHUB_OUTPUT\"\n\ + echo \"os=$(cat /etc/os-release 2>/dev/null | cksum | cut -d ' ' -f 1)\" >> \"$GITHUB_OUTPUT\"\n", + place = if self.path == "." { + "the project".to_string() + } else { + format!("`{}`", self.path) + }, + ) + } + + /// Restore the `.deb` cache, install the system packages through it, prune it to the + /// packages installed, and save it from `save_branch` when it changed. + fn deb_steps(&self, browsers: &str) -> Vec { + let linux = "runner.os == 'Linux'"; + let prefix = format!( + "playwright-debs-v1-${{{{ runner.arch }}}}-${{{{ steps.{VERSION_ID}.outputs.os }}}}-" + ); + let key = format!( + "{prefix}${{{{ steps.{VERSION_ID}.outputs.version }}}}-{}", + self.browsers.join("-") + ); + let install = format!( + "debs=\"$HOME/.cache/playwright-debs\"\n\ + mkdir -p \"$debs/partial\"\n\ + echo \"Dir::Cache::Archives \\\"$debs/\\\"; APT::Keep-Downloaded-Packages \\\"true\\\";\" | sudo tee {APT_CONF} >/dev/null\n\ + {}\n", + self.in_path(&format!("{} playwright install-deps {browsers}", self.exec)) + ); + vec![ + with_condition( + with_id( + uses( + "Restore Playwright's system packages", + CACHE_RESTORE, + cache_with(DEBS_DIR, key.clone(), Some(prefix)), + ), + DEBS_ID, + ), + linux, + ), + with_condition(run("Install Playwright's system packages", install), linux), + with_condition( + with_id( + run("Prune Playwright's system packages", PRUNE_SCRIPT), + PRUNE_ID, + ), + &format!("always() && {linux}"), + ), + with_condition( + uses( + "Save Playwright's system packages", + CACHE_SAVE, + cache_with(DEBS_DIR, key, None), + ), + &format!( + "{linux} && github.ref == 'refs/heads/{}' && steps.{DEBS_ID}.outputs.cache-hit != 'true' && steps.{PRUNE_ID}.outputs.count != '0'", + self.save_branch + ), + ), + ] + } + + fn in_path(&self, command: &str) -> String { + if self.path == "." { + command.to_string() + } else { + format!("cd {} && {command}", self.path) + } + } +} + +/// Removes the apt configuration (always, so a self-hosted runner isn't left with it), then +/// keeps only the `.deb` files of packages installed at exactly that version, and counts them. +const PRUNE_SCRIPT: &str = r#"sudo rm -f /etc/apt/apt.conf.d/90cigen-playwright-debs +debs="$HOME/.cache/playwright-debs" +mkdir -p "$debs" +sudo chown -R "$(id -u):$(id -g)" "$debs" +rm -rf "$debs/partial" "$debs/lock" +count=0 +for deb in "$debs"/*.deb; do + [ -e "$deb" ] || continue + package=$(dpkg-deb -f "$deb" Package) + version=$(dpkg-deb -f "$deb" Version) + if dpkg-query -W -f='${Version}\n' "$package" 2>/dev/null | grep -qxF "$version"; then + count=$((count + 1)) + else + rm -f "$deb" + fi +done +echo "count=$count" >> "$GITHUB_OUTPUT" +"#; + +fn cache_with(path: &str, key: String, restore_prefix: Option) -> BTreeMap { + let mut with = BTreeMap::new(); + with.insert("path".to_string(), Value::from(path)); + with.insert("key".to_string(), Value::from(key)); + if let Some(prefix) = restore_prefix { + with.insert("restore-keys".to_string(), Value::from(prefix)); + } + with +} + +fn with_id(mut step: Step, id: &str) -> Step { + let extra = match &mut step { + Step::Run(run) => &mut run.extra, + Step::Uses(uses) => &mut uses.extra, + _ => unreachable!("the module only builds run and uses steps"), + }; + extra.insert("id".to_string(), id.into()); + step +} + +fn with_condition(mut step: Step, condition: &str) -> Step { + match &mut step { + Step::Run(run) => run.condition = Some(condition.to_string()), + Step::Uses(uses) => uses.condition = Some(condition.to_string()), + _ => unreachable!("the module only builds run and uses steps"), + } + step +} diff --git a/src/modules/playwright/mod.rs b/src/modules/playwright/mod.rs new file mode 100644 index 0000000..d7b2616 --- /dev/null +++ b/src/modules/playwright/mod.rs @@ -0,0 +1,192 @@ +//! The `playwright` module: Playwright's browsers, and on Linux the system packages they need, +//! with those packages' `.deb` files kept in a cache that only one branch writes. +use super::node::manager::{self, Manager}; +use super::shell::check_token; +use super::{ + Context, Expansion, Module, ModuleSpec, Parameter, in_path, module_path, parse_params, +}; +use anyhow::{Result, bail}; +use serde::Deserialize; +use serde_yaml::Mapping; + +mod expand; + +/// The browsers `playwright install` accepts. +const BROWSERS: &[&str] = &[ + "chrome", + "chromium", + "chromium-headless-shell", + "firefox", + "msedge", + "webkit", +]; + +pub const SPEC: ModuleSpec = ModuleSpec { + name: "playwright", + summary: "Installs Playwright's browsers and the system packages they need, with the packages' .deb files cached so a slow apt mirror doesn't stall the job.", + family: "node", + providers: &["github"], + requires: &["node"], + parameters: &[ + Parameter { + name: "browsers", + default: "`[chromium]`", + meaning: "the browsers to install: `chromium`, `chromium-headless-shell`, `firefox`, `webkit`, `chrome` or `msedge`", + }, + Parameter { + name: "system_deps", + default: "`true`", + meaning: "install the system packages the browsers need (`--with-deps`)", + }, + Parameter { + name: "deb_cache", + default: "`true`", + meaning: "keep those packages' `.deb` files in the cache (with `system_deps`)", + }, + Parameter { + name: "save_branch", + default: "`main`", + meaning: "the only branch that saves the `.deb` cache; other branches read it", + }, + Parameter { + name: "path", + default: "`.`", + meaning: "the directory whose `package.json` depends on Playwright", + }, + ], + readme: include_str!("README.md"), + skill: include_str!("SKILL.md"), + load, +}; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Params { + #[serde(default = "chromium")] + browsers: Vec, + #[serde(default = "yes")] + system_deps: bool, + #[serde(default)] + deb_cache: Option, + #[serde(default = "main")] + save_branch: String, + #[serde(default = "dot")] + path: String, +} + +fn chromium() -> Vec { + vec!["chromium".to_string()] +} + +fn yes() -> bool { + true +} + +fn main() -> String { + "main".to_string() +} + +fn dot() -> String { + ".".to_string() +} + +struct Playwright { + path: String, + browsers: Vec, + system_deps: bool, + deb_cache: bool, + save_branch: String, + /// How the project runs a package's binary: `npx`, `pnpm exec` or `yarn`. + exec: &'static str, + /// The package manager's lockfile name, which pins Playwright. + lockfile: &'static str, +} + +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"); + let Ok(text) = std::fs::read_to_string(root.join(&package_json)) else { + bail!( + "there's no `package.json` in `{path}`; set `path:` to the directory whose `package.json` depends on Playwright" + ); + }; + if !text.contains("\"@playwright/test\"") && !text.contains("\"playwright\"") { + bail!( + "`{package_json}` doesn't depend on `@playwright/test` or `playwright`; add it, or set `path:` to the package that does" + ); + } + if params.browsers.is_empty() { + bail!("`browsers` is empty; list at least one, such as `[chromium]`"); + } + for browser in ¶ms.browsers { + if !BROWSERS.contains(&browser.as_str()) { + bail!( + "unknown browser `{browser}`; use {}", + BROWSERS + .iter() + .map(|b| format!("`{b}`")) + .collect::>() + .join(", ") + ); + } + } + if params.deb_cache == Some(true) && !params.system_deps { + bail!( + "`deb_cache: true` needs `system_deps: true`; there are no system packages to cache without it" + ); + } + check_token("save_branch", ¶ms.save_branch, "/")?; + let manager = manager::detect(root, &path, None)?.manager; + let exec = match manager { + Manager::Npm => "npx", + Manager::Pnpm => "pnpm exec", + Manager::Yarn => "yarn", + }; + Ok(Box::new(Playwright { + path, + browsers: params.browsers, + system_deps: params.system_deps, + deb_cache: params.deb_cache.unwrap_or(true) && params.system_deps, + save_branch: params.save_branch, + exec, + lockfile: manager.lockfile(), + })) +} + +impl Module for Playwright { + fn resolved(&self) -> serde_json::Value { + serde_json::json!({ + "path": self.path, + "browsers": self.browsers, + "system_deps": self.system_deps, + "deb_cache": self.deb_cache, + "save_branch": self.save_branch, + "exec": self.exec, + }) + } + + fn inputs(&self) -> Vec { + // The lockfile pins Playwright, and so the browsers and system packages it installs; + // Playwright reads its config when the tests run. + let mut inputs: Vec = ["package.json", self.lockfile, "playwright.config.*"] + .iter() + .map(|file| in_path(&self.path, file)) + .collect(); + inputs.sort(); + inputs + } + + fn expand(&self, provider: &str) -> Result { + match provider { + "github" => Ok(self.github()), + other => bail!( + "the playwright module supports GitHub Actions only so far, not `{other}`; install the browsers with a run step there" + ), + } + } +} + +#[cfg(test)] +mod tests; diff --git a/src/modules/playwright/tests.rs b/src/modules/playwright/tests.rs new file mode 100644 index 0000000..2806bf3 --- /dev/null +++ b/src/modules/playwright/tests.rs @@ -0,0 +1,224 @@ +use super::*; +use crate::modules::Context; +use crate::schema::Step; +use serde_yaml::Value; +use std::fs; +use tempfile::TempDir; + +const PNPM_PROJECT: &[(&str, &str)] = &[ + ( + "package.json", + "{\"packageManager\": \"pnpm@9.15.0\", \"devDependencies\": {\"@playwright/test\": \"1.49.0\"}}", + ), + ("pnpm-lock.yaml", "lockfileVersion: '9.0'\n"), +]; + +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 playwright(params: &str, dir: &TempDir) -> Result> { + let params: Mapping = serde_yaml::from_str(params).unwrap(); + load(¶ms, &Context::project(dir.path())) +} + +fn error(result: Result>) -> String { + format!("{:#}", result.err().expect("an error")) +} + +fn names(steps: &[Step]) -> Vec { + steps + .iter() + .map(|step| match step { + Step::Run(run) => run.name.clone().unwrap(), + Step::Uses(uses) => uses.name.clone().unwrap(), + other => panic!("unexpected step {other:?}"), + }) + .collect() +} + +fn find<'a>(steps: &'a [Step], name: &str) -> &'a Step { + steps + .iter() + .find(|step| match step { + Step::Run(run) => run.name.as_deref() == Some(name), + Step::Uses(uses) => uses.name.as_deref() == Some(name), + _ => false, + }) + .unwrap_or_else(|| panic!("no step `{name}`")) +} + +fn command(step: &Step) -> String { + let Step::Run(run) = step else { + panic!("expected a run step") + }; + run.run.command().to_string() +} + +fn condition(step: &Step) -> Option { + match step { + Step::Run(run) => run.condition.clone(), + Step::Uses(uses) => uses.condition.clone(), + _ => None, + } +} + +#[test] +fn by_default_it_caches_the_browsers_and_the_system_packages() { + let dir = project(PNPM_PROJECT); + let module = playwright("{}", &dir).unwrap(); + let steps = module.expand("github").unwrap().before; + assert_eq!( + names(&steps), + [ + "Find Playwright's version", + "Cache Playwright's browsers", + "Restore Playwright's system packages", + "Install Playwright's system packages", + "Prune Playwright's system packages", + "Save Playwright's system packages", + "Install Playwright's browsers", + ] + ); + assert!( + command(find(&steps, "Find Playwright's version")) + .contains("pnpm exec playwright --version") + ); + let Step::Uses(browsers) = find(&steps, "Cache Playwright's browsers") else { + panic!() + }; + assert_eq!( + browsers.with["key"], + Value::from( + "playwright-browsers-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.playwright_version.outputs.version }}-chromium" + ) + ); + assert_eq!(browsers.with["path"], Value::from("~/.cache/ms-playwright")); + let Step::Uses(restore) = find(&steps, "Restore Playwright's system packages") else { + panic!() + }; + assert_eq!( + restore.with["key"], + Value::from( + "playwright-debs-v1-${{ runner.arch }}-${{ steps.playwright_version.outputs.os }}-${{ steps.playwright_version.outputs.version }}-chromium" + ) + ); + assert_eq!( + restore.with["restore-keys"], + Value::from( + "playwright-debs-v1-${{ runner.arch }}-${{ steps.playwright_version.outputs.os }}-" + ) + ); + let install = command(find(&steps, "Install Playwright's system packages")); + assert!(install.contains("Dir::Cache::Archives"), "{install}"); + assert!( + install.contains("pnpm exec playwright install-deps chromium"), + "{install}" + ); + assert_eq!( + condition(find(&steps, "Prune Playwright's system packages")).as_deref(), + Some("always() && runner.os == 'Linux'") + ); + assert_eq!( + condition(find(&steps, "Save Playwright's system packages")).as_deref(), + Some( + "runner.os == 'Linux' && github.ref == 'refs/heads/main' && steps.playwright_debs.outputs.cache-hit != 'true' && steps.playwright_debs_prune.outputs.count != '0'" + ) + ); + // The system packages are already installed, so no `--with-deps`. + assert_eq!( + command(find(&steps, "Install Playwright's browsers")), + "pnpm exec playwright install chromium" + ); +} + +#[test] +fn without_the_deb_cache_it_installs_with_deps_and_without_system_deps_it_installs_none() { + let dir = project(PNPM_PROJECT); + let module = playwright("{deb_cache: false, browsers: [chromium, firefox]}", &dir).unwrap(); + let steps = module.expand("github").unwrap().before; + assert_eq!(steps.len(), 3); + assert_eq!( + command(find(&steps, "Install Playwright's browsers")), + "pnpm exec playwright install --with-deps chromium firefox" + ); + + let module = playwright("{system_deps: false}", &dir).unwrap(); + let steps = module.expand("github").unwrap().before; + assert_eq!(steps.len(), 3); + assert_eq!( + command(find(&steps, "Install Playwright's browsers")), + "pnpm exec playwright install chromium" + ); +} + +#[test] +fn the_package_manager_decides_how_playwright_runs_and_path_where() { + let dir = project(&[ + ( + "e2e/package.json", + "{\"devDependencies\": {\"playwright\": \"1.49.0\"}}", + ), + ("e2e/package-lock.json", "{}"), + ]); + let module = playwright("{path: e2e, save_branch: release/stable}", &dir).unwrap(); + let steps = module.expand("github").unwrap().before; + assert_eq!( + command(find(&steps, "Install Playwright's browsers")), + "cd e2e && npx playwright install chromium" + ); + assert!( + condition(find(&steps, "Save Playwright's system packages")) + .unwrap() + .contains("github.ref == 'refs/heads/release/stable'") + ); + assert_eq!( + module.inputs(), + [ + "e2e/package-lock.json", + "e2e/package.json", + "e2e/playwright.config.*" + ] + ); +} + +#[test] +fn mistakes_fail_with_a_fix() { + let dir = project(PNPM_PROJECT); + for (params, expected) in [ + ("{browsers: [safari]}", "unknown browser `safari`"), + ("{browsers: []}", "`browsers` is empty"), + ( + "{system_deps: false, deb_cache: true}", + "`deb_cache: true` needs `system_deps: true`", + ), + ( + "{save_branch: 'main; rm -rf /'}", + "`save_branch: main; rm -rf /` can only contain", + ), + ("{path: missing}", "isn't a directory"), + ] { + let message = error(playwright(params, &dir)); + assert!(message.contains(expected), "{params}: {message}"); + } + let message = error( + playwright("{}", &dir) + .unwrap() + .expand("circleci") + .map(|_| -> Box { unreachable!() }), + ); + assert!(message.contains("GitHub Actions only"), "{message}"); + + let without = project(&[("package.json", "{}"), ("package-lock.json", "{}")]); + let message = error(playwright("{}", &without)); + assert!( + message.contains("doesn't depend on `@playwright/test`"), + "{message}" + ); +} diff --git a/src/modules/rust/mod.rs b/src/modules/rust/mod.rs index 73d9fc8..fc16bd5 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, }; @@ -22,6 +24,7 @@ pub const SPEC: ModuleSpec = ModuleSpec { summary: "Installs the Rust toolchain, its components and targets, and caches cargo's downloads and `target/`.", family: "rust", providers: &["circleci", "github"], + requires: &[], parameters: &[ Parameter { name: "toolchain", @@ -95,7 +98,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..4ab6183 100644 --- a/tests/golden_fixtures.rs +++ b/tests/golden_fixtures.rs @@ -22,6 +22,8 @@ const FIXTURES: &[(&str, &[&str])] = &[ ("circleci_node_simple_inline", &[".circleci"]), ("circleci_node_simple_split", &[".circleci"]), ("circleci_rails", &[".circleci"]), + ("module_node", &[".circleci", ".github"]), + ("module_playwright", &[".github"]), ("module_rust", &[".circleci", ".github"]), ]; diff --git a/tests/mockci_home.rs b/tests/mockci_home.rs new file mode 100644 index 0000000..0b6379a --- /dev/null +++ b/tests/mockci_home.rs @@ -0,0 +1,40 @@ +//! mockci gives each job its own empty `HOME`, as a hosted runner does, and caches paths +//! under `~/` there. + +mod support; + +use cigen_mockci::{Event, Simulator}; +use support::fixture_repo::FixtureRepo; + +const WORKFLOW: &str = ".github/workflows/ci.yml"; + +const CACHE: &str = "actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9"; + +fn push(sha: &str) -> Event { + Event::Push { + branch: "main".into(), + sha: sha.into(), + } +} + +#[test] +fn each_job_has_its_own_home_and_caches_paths_under_it() { + let repo = FixtureRepo::new(); + repo.write( + WORKFLOW, + &format!( + "on: push\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: {CACHE}\n with:\n path: ~/.cache/tool\n key: tool-v1\n - name: Use the cache\n run: |\n test \"$HOME\" != \"$HOST_HOME\"\n if [ -f ~/.cache/tool/built ]; then echo restored; else echo empty; fi\n mkdir -p ~/.cache/tool\n echo yes > ~/.cache/tool/built\n" + ), + ); + let sha = repo.commit("initial"); + let mut sim = Simulator::new(repo.path()).unwrap(); + sim.runner_env("HOST_HOME", &std::env::var("HOME").unwrap()); + + let first = sim.run(WORKFLOW, &push(&sha)).unwrap(); + let log = &first.job("test").step("Use the cache").log; + assert!(log.contains("empty"), "{first}"); + + let second = sim.run(WORKFLOW, &push(&sha)).unwrap(); + let log = &second.job("test").step("Use the cache").log; + assert!(log.contains("restored"), "{second}"); +} 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..07b454a --- /dev/null +++ b/tests/module_node.rs @@ -0,0 +1,186 @@ +//! 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"), + // 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); + 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 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(""); + 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/module_playwright.rs b/tests/module_playwright.rs new file mode 100644 index 0000000..57c3795 --- /dev/null +++ b/tests/module_playwright.rs @@ -0,0 +1,286 @@ +//! The `playwright` module end to end: a job that uses it installs nothing when it skips, +//! reruns when a file the module contributes or its parameters change, and keeps the system +//! packages' `.deb` files in a cache that only `main` writes. + +mod support; + +use cigen_mockci::{Event, RunReport, Simulator}; +use support::fixture_repo::FixtureRepo; +use support::skip::{WORKFLOW, push, simulator, tests_ran}; + +const DEPS_STEP: &str = "Install Playwright's system packages"; +const BROWSERS_STEP: &str = "Install Playwright's browsers"; +const SAVE_STEP: &str = "Save Playwright's system packages"; + +/// A pnpm project at the root that depends on Playwright, tested with `modules: [node, +/// playwright]`. The lockfile says which Playwright is installed. +fn playwright_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\n - playwright: {{ {params} }}\ninputs: \"src/**\"\nsteps:\n - run:\n name: Run tests\n command: pnpm exec playwright test\n" + ), + ) + .write(".nvmrc", "22\n") + .write( + "package.json", + "{\"packageManager\": \"pnpm@9.15.0\", \"devDependencies\": {\"@playwright/test\": \"1.49.0\"}}\n", + ) + .write( + "pnpm-lock.yaml", + "lockfileVersion: '9.0'\n# @playwright/test@1.49.0\n", + ) + .write("playwright.config.ts", "export default {};\n") + .write("src/index.js", "export const one = 1;\n") + .generate(); + repo +} + +/// mockci runs steps on the host, so pnpm, sudo and dpkg are fakes. The fake `install-deps` +/// "downloads" `libnss3` into apt's archive directory, as the module's apt configuration names +/// it, unless the `.deb` is already there, and records the package as installed. +fn playwright_simulator(repo: &FixtureRepo) -> Simulator { + let mut sim = simulator(repo); + sim.stub_action("pnpm/action-setup", []) + .stub_action("actions/setup-node", []) + .provide_command( + "pnpm", + r#"case "$*" in + "exec playwright --version") + echo "Version $(sed -n 's/.*@playwright\/test@//p' pnpm-lock.yaml)" ;; + "exec playwright install-deps "*) + debs=$(sed -n 's/^Dir::Cache::Archives "\([^"]*\)".*/\1/p' "$HOME/etc/90cigen-playwright-debs") + if [ -f "$debs/libnss3.deb" ]; then + echo "reused libnss3" + else + printf 'Package: libnss3\nVersion: 3.98\n' > "$debs/libnss3.deb" + echo "downloaded libnss3" + fi + echo "libnss3 3.98" >> "$HOME/installed" ;; + *) echo "pnpm $*" ;; +esac +"#, + ) + .unwrap() + .provide_command( + "sudo", + r#"case "$1" in + tee) mkdir -p "$HOME/etc"; cat > "$HOME/etc/$(basename "$2")" ;; + rm) shift 2; for file in "$@"; do rm -f "$HOME/etc/$(basename "$file")"; done ;; + chown) ;; + *) echo "unexpected: sudo $*" >&2; exit 1 ;; +esac +"#, + ) + .unwrap() + .provide_command("dpkg-deb", "sed -n \"s/^$3: //p\" \"$2\"\n") + .unwrap() + .provide_command( + "dpkg-query", + "package=$(eval echo \"\\${$#}\")\nsed -n \"s/^$package //p\" \"$HOME/installed\" 2>/dev/null\n", + ) + .unwrap(); + sim +} + +fn pr(sha: &str) -> Event { + Event::PullRequest { + number: 1, + head: "feature".into(), + base: "main".into(), + sha: sha.into(), + } +} + +fn deps_log(run: &RunReport) -> String { + run.job("test").step(DEPS_STEP).log.clone() +} + +/// The cache events for the `.deb` cache, as `action:result`. +fn deb_cache_events(run: &RunReport) -> Vec { + run.job("test") + .cache_events + .iter() + .filter(|event| event.key.starts_with("playwright-debs-")) + .map(|event| format!("{}:{}", event.action, event.result)) + .collect() +} + +#[test] +fn the_module_installs_only_when_the_job_runs() { + let repo = playwright_fixture(""); + let mut sim = playwright_simulator(&repo); + let sha = repo.commit("initial"); + + let first = sim.run(WORKFLOW, &push(&sha)).unwrap(); + assert!(tests_ran(&first)); + assert!(deps_log(&first).contains("downloaded libnss3"), "{first}"); + let browsers = &first.job("test").step(BROWSERS_STEP).log; + assert!( + browsers.contains("pnpm exec playwright install chromium"), + "{first}" + ); + + let second = sim.run(WORKFLOW, &push(&sha)).unwrap(); + assert!(!tests_ran(&second)); + let job = second.job("test"); + assert!( + !job.ran(DEPS_STEP) && !job.ran(BROWSERS_STEP), + "a skipped job installs nothing\n{second}" + ); +} + +#[test] +fn only_main_saves_the_deb_cache_and_other_branches_read_it() { + let repo = playwright_fixture(""); + let mut sim = playwright_simulator(&repo); + let base = repo.commit("initial"); + + // A pull request before main has a cache downloads, and doesn't save. + repo.switch("feature", true); + repo.write("src/index.js", "export const one = 2;\n"); + let early = repo.commit("feature change"); + let run = sim.run(WORKFLOW, &pr(&early)).unwrap(); + assert!(tests_ran(&run)); + assert!(deps_log(&run).contains("downloaded libnss3"), "{run}"); + assert!(!run.job("test").ran(SAVE_STEP), "{run}"); + assert_eq!(deb_cache_events(&run), ["restore:miss"], "{run}"); + + // Main downloads and saves, with the apt configuration removed afterwards. + repo.switch("main", false); + let run = sim.run(WORKFLOW, &push(&base)).unwrap(); + assert!(deps_log(&run).contains("downloaded libnss3"), "{run}"); + assert_eq!( + deb_cache_events(&run), + ["restore:miss", "save:saved"], + "{run}" + ); + + // A pull request now reads main's packages and still saves nothing. + repo.switch("feature", false); + repo.write("src/index.js", "export const one = 3;\n"); + let later = repo.commit("another feature change"); + let run = sim.run(WORKFLOW, &pr(&later)).unwrap(); + assert!(deps_log(&run).contains("reused libnss3"), "{run}"); + assert!(!run.job("test").ran(SAVE_STEP), "{run}"); + assert_eq!(deb_cache_events(&run), ["restore:hit"], "{run}"); + + // Main with the same Playwright hits its own cache exactly and doesn't save it again. + repo.switch("main", false); + repo.write("src/index.js", "export const one = 4;\n"); + let next = repo.commit("main change"); + let run = sim.run(WORKFLOW, &push(&next)).unwrap(); + assert!(deps_log(&run).contains("reused libnss3"), "{run}"); + assert_eq!(deb_cache_events(&run), ["restore:hit"], "{run}"); + + // A new Playwright on main falls back to the older cache, then saves under its own key. + repo.write( + "pnpm-lock.yaml", + "lockfileVersion: '9.0'\n# @playwright/test@1.50.0\n", + ); + let bumped = repo.commit("bump Playwright"); + let run = sim.run(WORKFLOW, &push(&bumped)).unwrap(); + assert!(deps_log(&run).contains("reused libnss3"), "{run}"); + assert_eq!( + deb_cache_events(&run), + ["restore:partial", "save:saved"], + "{run}" + ); +} + +#[test] +fn a_deb_for_a_package_not_installed_is_pruned_before_saving() { + let repo = playwright_fixture(""); + let mut sim = playwright_simulator(&repo); + let sha = repo.commit("initial"); + // An old version left in the cache by an earlier Playwright, which apt didn't install. + sim.provide_command( + "pnpm", + r#"case "$*" in + "exec playwright --version") echo "Version 1.49.0" ;; + "exec playwright install-deps "*) + debs=$(sed -n 's/^Dir::Cache::Archives "\([^"]*\)".*/\1/p' "$HOME/etc/90cigen-playwright-debs") + printf 'Package: libnss3\nVersion: 3.98\n' > "$debs/libnss3.deb" + printf 'Package: libold\nVersion: 1.0\n' > "$debs/libold.deb" + echo "libnss3 3.98" >> "$HOME/installed" ;; + "exec playwright test") ls "$HOME/.cache/playwright-debs" ;; + *) echo "pnpm $*" ;; +esac +"#, + ) + .unwrap(); + let run = sim.run(WORKFLOW, &push(&sha)).unwrap(); + let listed = &run.job("test").step("Run tests").log; + assert!(listed.contains("libnss3.deb"), "{run}"); + assert!(!listed.contains("libold.deb"), "{run}"); + assert!(!listed.contains("partial"), "{run}"); + assert_eq!( + deb_cache_events(&run), + ["restore:miss", "save:saved"], + "{run}" + ); +} + +#[test] +fn changing_a_file_the_module_contributes_reruns_the_job() { + // None of these is in the job's `inputs`. + for (path, contents) in [ + ("playwright.config.ts", "export default { retries: 2 };\n"), + ( + "pnpm-lock.yaml", + "lockfileVersion: '9.0'\n# @playwright/test@1.50.0\n", + ), + ( + "package.json", + "{\"packageManager\": \"pnpm@9.15.0\", \"devDependencies\": {\"@playwright/test\": \"1.50.0\"}}\n", + ), + ] { + let repo = playwright_fixture(""); + let mut sim = playwright_simulator(&repo); + let sha = repo.commit("initial"); + assert!(tests_ran(&sim.run(WORKFLOW, &push(&sha)).unwrap())); + assert!(!tests_ran(&sim.run(WORKFLOW, &push(&sha)).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} should rerun the job\n{run}" + ); + } +} + +#[test] +fn changing_the_modules_parameters_reruns_the_job() { + let repo = playwright_fixture(""); + let mut sim = playwright_simulator(&repo); + let sha = repo.commit("initial"); + assert!(tests_ran(&sim.run(WORKFLOW, &push(&sha)).unwrap())); + + for params in ["browsers: [chromium, firefox]", "deb_cache: false"] { + let repo_params = playwright_fixture(params); + let mut sim = playwright_simulator(&repo_params); + let base = repo_params.commit("initial"); + let first = sim.run(WORKFLOW, &push(&base)).unwrap(); + assert!(tests_ran(&first), "{params}\n{first}"); + assert!(!tests_ran(&sim.run(WORKFLOW, &push(&base)).unwrap())); + } + + // The same repository, with only the parameters changed, reruns. + repo.write( + ".cigen/workflows/ci/jobs/test.yml", + "modules:\n - node\n - playwright: { browsers: [firefox] }\ninputs: \"src/**\"\nsteps:\n - run:\n name: Run tests\n command: pnpm exec playwright test\n", + ) + .generate(); + let changed = repo.commit("install firefox instead"); + let run = sim.run(WORKFLOW, &push(&changed)).unwrap(); + assert!(tests_ran(&run), "{run}"); + let browsers = &run.job("test").step(BROWSERS_STEP).log; + assert!( + browsers.contains("pnpm exec playwright install firefox"), + "{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 },