CI recipes
Use trellis in GitHub Actions to select packages for tests, check changelog coverage, and prepare releases. Its CI commands emit matrices and output records that workflows can consume.
Installing trellis
Section titled “Installing trellis”Pin the installer to a released version so CI upgrades only when you change the pin. For other methods, including mise, see installation.
- name: Install trellisrun: | curl --proto '=https' --tlsv1.2 -LsSf \ https://github.com/tylerbutler/trellis/releases/download/v1.7.0/trellis-gleam-installer.sh | sh # the installer adds its install dir to $GITHUB_PATH automaticallyAn affected-only test matrix
Section titled “An affected-only test matrix”trellis ci matrix emits a strategy matrix
({"include":[{"name","path","version"},…]}). With --since it covers only
the packages a PR touched, dependents included.
Set the repository variable TRELLIS_VERSION to a released version that
supports your workflow. Each job installs its own tools; the test job also
needs Gleam and Erlang/OTP. Adjust their versions for your packages:
on: pull_requestpermissions: contents: readenv: TRELLIS_VERSION: ${{ vars.TRELLIS_VERSION }}jobs: plan: runs-on: ubuntu-latest outputs: matrix: ${{ steps.plan.outputs.matrix }} steps: - uses: actions/checkout@v4 with: fetch-depth: 0 # --since needs history - name: Install trellis run: | curl --proto '=https' --tlsv1.2 -LsSf \ "https://github.com/tylerbutler/trellis/releases/download/v${TRELLIS_VERSION}/trellis-gleam-installer.sh" | sh - id: plan run: | matrix=$(trellis ci matrix --since "origin/${{ github.base_ref }}") echo "matrix=$matrix" >> "$GITHUB_OUTPUT"
test: needs: plan if: needs.plan.outputs.matrix != '{"include":[]}' runs-on: ubuntu-latest strategy: matrix: ${{ fromJSON(needs.plan.outputs.matrix) }} steps: - uses: actions/checkout@v4 - name: Install trellis run: | curl --proto '=https' --tlsv1.2 -LsSf \ "https://github.com/tylerbutler/trellis/releases/download/v${TRELLIS_VERSION}/trellis-gleam-installer.sh" | sh - uses: erlef/setup-beam@v1.24.1 with: otp-version: "28.1" gleam-version: "1.13.0" - run: trellis run test ${{ matrix.name }} --target allWithout --since, the matrix includes all packages. Affected-only selection
uses files and path dependencies; it cannot detect other coupling, such as a
shared repository-level configuration file. Run the full matrix when those
changes can affect packages.
Workspace facts as outputs
Section titled “Workspace facts as outputs”trellis ci outputs emits workspace facts as key=value lines, ready for
$GITHUB_OUTPUT:
$ trellis ci outputspackages=["lat_core","lat_mid","lat_cli","package_a"]releasable=["lat_core","lat_mid","lat_cli"]version_files=["packages/lat_core/gleam.toml","packages/lat_mid/gleam.toml","packages/lat_cli/gleam.toml"]tags=["lat_core-v1.2.0","lat_mid-v0.5.0","lat_cli-v0.3.1"]series_tags=[]tags lists the immutable per-version tags and series_tags the moving ones,
each covering only the packages whose
package_tags includes that level. A
workspace with no exact entry reports an empty tags. Repository tags are
deliberately absent from both outputs because they do not identify packages.
ci matrix and ci outputs omit schema to match GitHub Actions formats.
See JSON output for their compatibility guarantees.
PR gates
Section titled “PR gates”Run doctor on PRs to check the workspace; errors fail the command.
Pair it with changelog check to require entries for changed releasable packages:
# on: pull_request- run: trellis doctor- run: trellis changelog check --base "origin/${{ github.base_ref }}"A workspace with pinned git dependencies can add trellis pin --check, which fails the PR when a pinned SHA is no longer reachable from its tracked ref. doctor reports the same drift, but only as a warning.
Run trellis doctor --fix locally to create missing changelog stubs, import
existing changelog history, or update stale locked versions. It reports other
findings without changing them, including path dependencies outside the workspace,
tag collisions, and versions behind their changelogs. Review the resulting diff
and keep the read-only trellis doctor command in CI.
The changelog comment
Section titled “The changelog comment”A failing gate in a log is easy to miss. changelog check --format github
emits key=value lines for $GITHUB_OUTPUT, so the same run that gates the
PR also drives a sticky comment, with no jq and no second tool:
# on: pull_requestpermissions: pull-requests: write
steps: - uses: actions/checkout@v4 with: fetch-depth: 0 # the diff needs the base commit - id: changelog # The gate exits 1 on a missing entry. Let it, but keep going, so the # comment lands before the job fails. continue-on-error: true run: | trellis changelog check \ --base "${{ github.event.pull_request.base.sha }}" \ --head "${{ github.event.pull_request.head.sha }}" \ --format github >> "$GITHUB_OUTPUT" - name: Post the changelog comment if: >- steps.changelog.outputs.has_entries == 'true' || steps.changelog.outputs.needs_entry == 'true' || steps.changelog.outputs.invalid_fragments != '[]' uses: marocchino/sticky-pull-request-comment@v3 with: header: changelog message: ${{ steps.changelog.outputs.preview }} - name: Remove it when there is nothing to say if: >- steps.changelog.outputs.has_entries == 'false' && steps.changelog.outputs.needs_entry == 'false' && steps.changelog.outputs.invalid_fragments == '[]' uses: marocchino/sticky-pull-request-comment@v3 with: header: changelog delete: true - name: Fail if the check did if: steps.changelog.outputs.ok != 'true' run: exit 1The comment appears when there is something to say (entries to preview, an
entry missing, or a fragment that doesn’t parse) and is deleted when there
isn’t, so a fixed PR doesn’t keep a stale complaint. It shows each changed
package’s fragment count and planned next version, plus a collapsible release
preview of the changelog sections this PR’s own fragments would produce,
ripple bumps included. Everything it counts is scoped to the
branch: fragments already unreleased on the base
branch do not count toward this PR. ok records the check’s result despite
continue-on-error, and is empty if trellis could not run
at all, which fails the job either way.
The preview uses local release configuration: auto_pre = true continues an
existing candidate cycle rather than showing stable promotion. Pass --pre,
--bump, or --set to match explicit preparation options. It does not query
pending release intent or workflow overrides; the comment states that
assumption. If the prerelease mode cannot be selected, it reports an unavailable
preview without changing the coverage verdict. See
Preview policy.
preview is already the comment body, rendered from the same data as the
--format json field of that name. needs_entry_packages and
invalid_fragments are JSON arrays if you would rather compose your own:
- run: echo "Missing: ${{ join(fromJSON(steps.changelog.outputs.needs_entry_packages), ', ') }}"A workspace that wants the comment without the gate sets
changelog.strictness to warn, which makes
ok true even when needs_entry is true. Then drop both the
continue-on-error line and the final step.
Annotating the diff
Section titled “Annotating the diff”A doctor failure in a log tells a contributor a file is wrong; an annotation puts the message on the file itself in the PR’s Files tab. --format github emits one workflow command per finding and nothing else, so it drops straight into the gate:
# on: pull_request- run: trellis doctor --format githubErrors become ::error, advisory warnings become ::warning, and the exit
code is unchanged, so the job still fails on any error. A healthy workspace
prints nothing at all.
For anything richer than annotations, such as grouping findings by package,
rendering them into a sticky comment, or filtering to the ones --fix would
clear, use --format json and read check, severity, file, and fixable
off each finding:
- id: doctor run: trellis doctor --format json > doctor.json || true- run: jq -r '.findings[] | select(.fixable) | .message' doctor.jsonThe payload is stable; the message prose is not.
The release pipeline
Section titled “The release pipeline”Use the Gleam/Hex release workflow
for automatic stable releases, manual candidates, and stable promotion.
Copy it to .github/workflows/gleam-hex-release.yml in your Gleam workspace.
It is an example for packages on Hex, not trellis’s own Cargo release pipeline.
Copyable Gleam/Hex workflow
# Copy to .github/workflows/gleam-hex-release.yml in a Gleam workspace.# Set TRELLIS_VERSION to 1.4.0 or a later compatible release.# For unreleased changes, leave it empty and use a reviewed .github/trellis snapshot.name: Gleam Hex release
on: push: branches: [main] workflow_dispatch: inputs: pre: description: "Prerelease label (rc), promotion (none), or empty for stable" type: string default: "" set: description: "Exact targets, one package=version per line" type: string default: "" bump: description: "Bumps, one package=major|minor|patch per line" type: string default: "" pull_request: types: [closed] branches: [main]
concurrency: group: trellis-release queue: max cancel-in-progress: false
permissions: contents: write pull-requests: read statuses: write
env: TRELLIS_VERSION: ${{ vars.TRELLIS_VERSION }}
jobs: release: runs-on: ubuntu-latest steps: - name: Select trusted release id: select uses: actions/github-script@v8 with: script: | // script: select const repo = context.repo; const trusted = pr => pr.merged && pr.head.ref === "release/pending" && pr.base.ref === "main" && pr.head.repo?.full_name === `${repo.owner}/${repo.repo}` && pr.base.repo?.full_name === `${repo.owner}/${repo.repo}`; if (context.eventName === "pull_request") { const event_pr = context.payload.pull_request; const { data: pr } = await github.rest.pulls.get({ ...repo, pull_number: event_pr.number, }); if (!trusted(pr) || !pr.merge_commit_sha || pr.merge_commit_sha !== event_pr.merge_commit_sha) return; const statuses = await github.paginate(github.rest.repos.listCommitStatusesForRef, { ...repo, ref: pr.merge_commit_sha, }); if (statuses.find(s => s.context === "trellis/release")?.state === "success") { core.info("Already published and tagged; retry only current-main preparation."); core.setOutput("prepare", "true"); return; } core.setOutput("publish_sha", pr.merge_commit_sha); } else { if (context.ref !== "refs/heads/main") { throw new Error("Dispatch release preparation on main."); } core.setOutput("prepare", "true"); } // end-script
- name: Check out approved merge if: steps.select.outputs.publish_sha != '' uses: actions/checkout@v4 with: ref: ${{ steps.select.outputs.publish_sha }} fetch-depth: 0
- name: Check out preparation tools if: steps.select.outputs.prepare == 'true' uses: actions/checkout@v4 with: ref: main fetch-depth: 0
- name: Install Gleam and Erlang if: steps.select.outputs.publish_sha != '' || steps.select.outputs.prepare == 'true' uses: erlef/setup-beam@v1.24.1 with: otp-version: "28.1" gleam-version: "1.13.0"
- name: Install trellis if: steps.select.outputs.publish_sha != '' || steps.select.outputs.prepare == 'true' run: | # script: install set -euo pipefail if [ -n "$TRELLIS_VERSION" ]; then curl --proto '=https' --tlsv1.2 -LsSf \ "https://github.com/tylerbutler/trellis/releases/download/v${TRELLIS_VERSION}/trellis-gleam-installer.sh" | sh else test -f .github/trellis/Cargo.toml rustup toolchain install 1.94.1 --profile minimal export CARGO_TARGET_DIR="$RUNNER_TEMP/trellis-target" cargo +1.94.1 install --locked --path .github/trellis --root "$RUNNER_TEMP/trellis" echo "$RUNNER_TEMP/trellis/bin" >> "$GITHUB_PATH" fi # end-script
- name: Publish, then tag the approved commit id: publish if: steps.select.outputs.publish_sha != '' uses: actions/github-script@v8 env: RELEASE_SHA: ${{ steps.select.outputs.publish_sha }} HEXPM_API_KEY: ${{ secrets.HEXPM_API_KEY }} GITHUB_TOKEN: ${{ github.token }} with: script: | // script: publish const sha = process.env.RELEASE_SHA; const checkout = await exec.getExecOutput("git", ["rev-parse", "HEAD"]); if (checkout.stdout.trim() !== sha) throw new Error("Release checkout changed."); const status = state => github.rest.repos.createCommitStatus({ ...context.repo, sha, context: "trellis/release", state, description: `Hex publication and GitHub tagging: ${state}`, target_url: `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`, }); await status("pending"); try { await exec.exec("trellis", ["publish", "--all-untagged"]); await exec.exec("trellis", ["tag", "create", "--push", "--github-release"]); await status("success"); core.setOutput("complete", "true"); } catch (error) { await status("failure"); throw error; } // end-script
- name: Create preparation token if: steps.select.outputs.prepare == 'true' || steps.publish.outputs.complete == 'true' id: app uses: actions/create-github-app-token@v2 with: app-id: ${{ secrets.RELEASE_APP_ID }} private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
# A symbolic main checkout happens inside the concurrency guard, including # after publication: never prepare from a stale push-event SHA. - name: Check out current main if: steps.select.outputs.prepare == 'true' || steps.publish.outputs.complete == 'true' uses: actions/checkout@v4 with: ref: main fetch-depth: 0 token: ${{ steps.app.outputs.token }}
- name: Prepare or refresh the single release PR if: steps.select.outputs.prepare == 'true' || steps.publish.outputs.complete == 'true' uses: actions/github-script@v8 env: GITHUB_TOKEN: ${{ steps.app.outputs.token }} INPUT_PRE: ${{ inputs.pre }} INPUT_SET: ${{ inputs.set }} INPUT_BUMP: ${{ inputs.bump }} with: github-token: ${{ steps.app.outputs.token }} script: | // script: prepare const repo = context.repo; const same_repo = pr => pr.head.ref === "release/pending" && pr.base.ref === "main" && pr.head.repo?.full_name === `${repo.owner}/${repo.repo}` && pr.base.repo?.full_name === `${repo.owner}/${repo.repo}`; const closed = await github.paginate(github.rest.pulls.list, { ...repo, state: "closed", base: "main", sort: "updated", direction: "desc", }); const latest = closed.filter(pr => pr.merged_at && same_repo(pr)) .sort((a, b) => Date.parse(b.merged_at) - Date.parse(a.merged_at))[0]; const statuses = async ref => github.paginate(github.rest.repos.listCommitStatusesForRef, { ...repo, ref, }); if (latest && (await statuses(latest.merge_commit_sha)) .find(s => s.context === "trellis/release")?.state !== "success") { core.info("Previous release has not finished publication and tagging; rerun its merge workflow."); return; } const open = (await github.paginate(github.rest.pulls.list, { ...repo, state: "open", base: "main", head: `${repo.owner}:release/pending`, })).filter(same_repo); if (open.length > 1) throw new Error("Expected at most one release PR."); const manual = context.eventName === "workflow_dispatch"; if (!manual) { // Reservation statuses survive a failed command before PR creation // or metadata updates, and unrelated later pushes to main. for await (const page of github.paginate.iterator(github.rest.repos.listCommits, { ...repo, sha: "main", per_page: 100, })) { let reached_release = false; for (const commit of page.data) { if ((await statuses(commit.sha)) .find(s => s.context === "trellis/release_request")?.state === "pending") { core.info("A manual release request owns preparation until its PR merges."); return; } if (commit.sha === latest?.merge_commit_sha) { reached_release = true; break; } } if (reached_release) break; } } const versions = async () => JSON.parse((await exec.getExecOutput( "trellis", ["list", "--releasable", "--json"], )).stdout).packages; if (!manual) { if ((await versions()).some(pkg => pkg.version.split("+")[0].includes("-"))) { core.info("Main contains prereleases; dispatch a candidate or promotion."); return; } if (open[0]) { await exec.exec("git", ["fetch", "origin", open[0].head.sha]); await exec.exec("git", ["checkout", "--detach", open[0].head.sha]); const candidate = (await versions()).some(pkg => pkg.version.split("+")[0].includes("-")); await exec.exec("git", ["checkout", "main"]); if (candidate) { core.info("The pending PR contains prereleases; leave it unchanged."); return; } } } const args = ["release", "pr", "--base", "main", "--branch", "release/pending"]; if (manual) { const pre = process.env.INPUT_PRE?.trim(); if (pre) args.push("--pre", pre); for (const flag of ["set", "bump"]) { for (const value of (process.env[`INPUT_${flag.toUpperCase()}`] ?? "").split(/\r?\n/)) { if (value.trim()) args.push(`--${flag}`, value.trim()); } } } const sha = (await exec.getExecOutput("git", ["rev-parse", "HEAD"])).stdout.trim(); const reservation = state => github.rest.repos.createCommitStatus({ ...repo, sha, context: "trellis/release_request", state, description: "Manual release preparation owns release/pending", target_url: `${context.serverUrl}/${repo.owner}/${repo.repo}/actions/runs/${context.runId}`, }); if (manual) await reservation("pending"); await exec.exec("trellis", args); if (manual) { const pending = await github.paginate(github.rest.pulls.list, { ...repo, state: "open", base: "main", head: `${repo.owner}:release/pending`, }); if (!pending.some(same_repo)) await reservation("success"); // Successful no-op. } // end-script- Set the repository variable
TRELLIS_VERSIONto1.4.0or a later release that supports these release PR options; do not uselatest. For an unreleased change, use a reviewed source snapshot. The example also pins Gleam and Erlang/OTP; change those pins to versions supported by your packages. - Install a GitHub App on the workspace repository with Contents,
Pull requests, and Commit statuses read/write permissions. Store its
ID and private key as
RELEASE_APP_IDandRELEASE_APP_PRIVATE_KEY. Preparation uses the App token so its branch push and PR creation trigger ordinary validation workflows; the default Actions token does not. - Store a Hex API key that can publish the workspace’s packages as
HEXPM_API_KEY. The workflow exposes it only to the merge publication step. The workflow token needscontents: write,pull-requests: read, andstatuses: writefor tags, releases, merge checks, and publication status. - Protect
mainwith your normal required checks and reviews, including forrelease/pending. Restrict who can push that release branch and dispatch releases. Treat a merge from that same-repository branch as permission to publish; a matching branch name on a fork is not trusted. - Keep
mainandrelease/pendingas shown, or change all branch checks, triggers, and command arguments together. Do not add a separate tag-triggered publishing workflow for this flow.
Optional source installation
Section titled “Optional source installation”To use an unreleased change, leave TRELLIS_VERSION unset and check a reviewed
source snapshot into your Gleam repository at .github/trellis. Copy it from
the reviewed checkout:
TRELLIS_SOURCE=/path/to/reviewed/trellis-checkoutmkdir -p .github/trelliscp "$TRELLIS_SOURCE/Cargo.toml" "$TRELLIS_SOURCE/Cargo.lock" \ "$TRELLIS_SOURCE/build.rs" "$TRELLIS_SOURCE/LICENSE" .github/trellis/cp -R "$TRELLIS_SOURCE/src" .github/trellis/Record the source revision and keep the snapshot and lockfile together.
The current install target needs no website, man pages, tests, or build output.
When updating the snapshot, check its include_str!/include_bytes! paths
and copy any required build assets at the same relative paths.
The workflow checks out the approved merge for publication, or current main
for preparation, before installing. It builds the checked-in snapshot with
Rust 1.94.1 and cargo install --locked. Both CARGO_TARGET_DIR and the
installation root are under RUNNER_TEMP, not the source tree, so build
artifacts cannot break release pr’s clean-tree check. Source installation
fails if the snapshot is absent or cannot compile; it never silently falls
back to an older binary.
To return to prebuilt binaries, set TRELLIS_VERSION to a release that
includes the changes you need.
Adopting existing releases
Section titled “Adopting existing releases”If the repository already has merged release PRs from release/pending, the
latest one must have a successful trellis/release commit status before the
example prepares another release. During adoption, verify that every
package at that PR’s merge commit is published as required, and that its tags
and GitHub releases are complete. Only then record success on that exact commit:
# Set RELEASE_SHA to the verified historical release PR's merge commit.gh api --method POST "repos/OWNER/REPO/statuses/$RELEASE_SHA" \ -f context=trellis/release -f state=success \ -f description='Historical publication and tagging verified'Never mark an unknown or partial release successful. Recover it at its approved
merge commit first, not at current main. With no historical matching release
PR, there is no adoption status to seed.
Dispatch and ownership
Section titled “Dispatch and ownership”Select main in the Actions Run workflow menu. For the first candidate,
enter rc in pre and targets such as lat_core=1.3.0 in set, one per line.
This starts lat_core at 1.3.0-rc.0.
Use bump for repeatable package=major|minor|patch overrides instead.
The inputs are passed as argument arrays; they are not shell commands.
After that candidate merges and publication succeeds, dispatch pre: rc
again for the next candidate, or pre: none for stable promotion. See the
candidate lifecycle.
All preparation and publication runs share trellis-release concurrency with
queue: max and no in-progress cancellation. GitHub permits up to 100 pending
runs; further runs are canceled. Queue order follows when runs begin waiting,
not dispatch order. Dispatch the next candidate only after the previous one
has merged and published; a queue is not a sequence of version requests.
External callers of release pr must follow the same ownership policy.
Automatic pushes refresh ordinary stable release PRs. They pause when a pending
PR contains a prerelease, when releasable manifests on main contain
prereleases, or when a manual request owns preparation. Manual requests write a
durable trellis/release_request pending status on their base commit before
running release pr. That reservation protects even a stable promotion PR and
the failure window before a PR exists; later unrelated pushes do not erase it.
It stays in force until a subsequent release PR merges, or a successful manual
no-op clears it. Fix a failed manual request and rerun or dispatch it again.
To abandon it, close its pending PR and explicitly clear its reservation status
on the recorded base commit; do not silently hand an unfinished request to
automatic preparation.
The ownership check scans commit statuses back through the latest merged release. Before the first matching release PR, it scans main’s full history; large repositories can hit GitHub’s API rate limit. Such an API failure stops preparation rather than bypassing ownership. In a large repository with no matching release PR, dispatch the first stable release manually with empty inputs. Once that PR merges and publishes, later automatic scans stop at its merge commit.
Publication and recovery
Section titled “Publication and recovery”Only a merged release/pending PR targeting main from the same repository
publishes. The workflow checks out its immutable merge_commit_sha, writes
trellis/release: pending, and runs:
trellis publish --all-untaggedtrellis tag create --push --github-releaseSuccess means both commands completed. Failure leaves a failed or pending
status, never a successful fallback. Before preparing another release, the
workflow finds the most recently merged release PR and requires that commit’s
trellis/release status to be success. Missing status also blocks, including
the window before the merge-triggered run starts.
Recover by rerunning the failed merge-event workflow, not by dispatching a
new version. Its checkout remains the same approved merge commit even if
main has advanced. Hex checks skip already-published versions; tagging
reconciles existing remote tags and skips existing GitHub releases. Completed
old publication runs skip publication and tagging, so they cannot move series
tags backward. They still retry gated preparation from current main;
rerunning also recovers an App-token, checkout, or preparation failure that
happened after publication succeeded.
After successful publication, the same serialized run checks out current
main and rechecks the preparation gates. A candidate keeps automatic
preparation paused. A published stable promotion restores it immediately,
without needing an unrelated push.
The tag-then-publish alternative remains
supported for stable-only pipelines. It needs immutable exact package tags;
publish --tag rejects moving series tags.
Reusable coordinator phases
Section titled “Reusable coordinator phases”Custom native builds do not need a repository-specific GitHub release coordinator. Use the shared workflow’s selection and completion gates and five-target native example. Pin every call to the same reviewed actions commit containing those interfaces; older pins do not accept the new inputs. Keep one coordinator trigger workflow per repository.
phase: select returns the immutable release_sha, publication_state,
complete, and preparation_eligible. The last output checks only the preceding
release’s completion; phase: prepare still enforces candidate and manual
ownership. Skip qualification when complete is 'true'; otherwise, every
build, archive check, and consumer proof must check out release_sha.
Pass required_jobs and qualification_results: ${{ toJSON(needs) }} to
phase: publish. The call job must directly need every required matrix,
assembly, and consumer-proof job. A missing, skipped, failed, or cancelled job
blocks publication. For native package assembly, also pass package_artifact,
required_targets, and artifact_paths. The
qualified native package contract
checks repository, revision, workflow run and attempt, target coverage, file
inventory, hashes, and permitted destination paths before copying any file.
Artifact overlays support shared libraries and data, not preserved Unix
executable modes.
The shared publisher retains publication → tags → completion ordering.
For required assets and draft releases,
keep package-specific upload and finalization in custom tagging jobs, then
call phase: complete with the actual publication_result, tagging_result,
and required job results. Default phase: publish uses the unscoped tag
command; it does not finalize drafts. Use a trellis build containing the asset
controls, through a released pin or a reviewed source snapshot.
Qualification jobs receive neither publication nor App secrets. Their workflow code and package proofs remain trusted repository configuration. Recover by rerunning all jobs of the original merge-event run: artifacts are bound to the run attempt, so reusing a successful job from an earlier attempt is refused. Keep the historical completion-marker migration for releases that predate these gates.