Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
11 changes: 4 additions & 7 deletions crates/mockci/src/actions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,12 +87,8 @@ pub fn run(uses: &str, with: &BTreeMap<String, String>, 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" => {
Expand Down Expand Up @@ -155,7 +151,6 @@ fn restore(name: &str, with: &BTreeMap<String, String>, ctx: &JobContext) -> Res
})
.unwrap_or_default();
let restored = ctx.cache().restore(
&ctx.workspace,
key,
&restore_keys,
&paths,
Expand Down Expand Up @@ -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,
}
}
}
27 changes: 20 additions & 7 deletions crates/mockci/src/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -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.
Expand All @@ -44,8 +48,10 @@ pub fn parse_paths(input: &str) -> Result<Vec<String>> {
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}`");
Expand All @@ -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],
Expand All @@ -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;
Expand Down Expand Up @@ -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
Expand All @@ -124,19 +129,27 @@ 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))?;
}
}
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())
}
Expand Down
7 changes: 5 additions & 2 deletions crates/mockci/src/job.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<'_> {
Expand Down Expand Up @@ -49,6 +51,7 @@ struct State {
pub fn run(ctx: &JobContext, workflow: &Workflow, job: &Job, needs: &Value) -> Result<JobReport> {
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);
Expand Down Expand Up @@ -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
}
}
Expand Down Expand Up @@ -290,6 +292,7 @@ fn default_env(ctx: &JobContext, job: &Job) -> BTreeMap<String, String> {
("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(),
Expand Down
8 changes: 8 additions & 0 deletions crates/mockci/src/shell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
5 changes: 5 additions & 0 deletions crates/mockci/src/sim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion docs/src/content/case-studies/bootstrap.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
107 changes: 104 additions & 3 deletions docs/src/content/docs/modules.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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.
6 changes: 3 additions & 3 deletions docs/src/pages/index.astro
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ const skipped = run.jobs.filter((job) => job.status === 'skipped').length;

<section class="modules wrap" aria-labelledby="modules-title">
<div class="modules__head">
<p class="chip chip--soon"><span class="chip__dot" aria-hidden="true"></span>Started · rust is built; node, Playwright and services are coming</p>
<p class="chip chip--soon"><span class="chip__dot" aria-hidden="true"></span>Started · rust, node and Playwright are built; services are coming</p>
<h2 id="modules-title">Modules replace the setup you paste into every job</h2>
<p>
Toolchains, dependency caches, services and upload steps, pinned and tested once. Each module also adds the
Expand Down Expand Up @@ -197,15 +197,15 @@ const skipped = run.jobs.filter((job) => job.status === 'skipped').length;
<li>Skipping on GitHub Actions, with markers in its cache</li>
<li>Generated workflows install a checksum-checked cigen release</li>
<li>Byte-for-byte deterministic output</li>
<li>Modules, starting with <code>rust</code></li>
<li>Modules for Rust and Node</li>
</ul>
</div>
<div>
<p class="label">Coming</p>
<ul class="ticks ticks--soon">
<li>The v0.2.0 release, the first those workflows can install</li>
<li>A planner job, so skipped jobs never start a runner</li>
<li>More modules: Node, Playwright, services and caches</li>
<li>More modules: services and caches</li>
<li><code>cigen plan</code> and <code>expand</code> for agents</li>
<li>Free hosted pass records on VisualCI, shared across branches</li>
<li>Skipping on CircleCI</li>
Expand Down
Loading
Loading