Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

26.8 KB
Raw Blame
//! Reusable workflow building blocks: a small fluent-builder trait plus typed
//! helpers that return `Step`s and `Job`s, composed by the workflow files.
//!
//! Third-party actions are pinned to a SHA with the human-readable version in a
//! trailing comment, matching the rest of the repo's workflows.

use gh_workflow::{Env, Expression, Job, Run, Step, Use};
use xtask_paths::{RepoDir, RuntimePath};

use crate::workflows::vars;

#[cfg(test)]
mod test;

/// Namespace's sccache setup mints a short-lived workspace credential. GitHub
/// withholds repository secrets from fork PRs, but this runner-minted token is
/// not a `secrets.*` value, so enforce the equivalent trust boundary here.
pub(crate) const TRUSTED_NAMESPACE_SCCACHE_CONTEXT: &str = concat!(
    "(github.event_name != 'pull_request' && ",
    "github.event_name != 'pull_request_target') || ",
    "github.event.pull_request.head.repo.full_name == github.repository"
);

/// `.map` / `.when` combinators for fluent conditional composition
/// ("push ifs up"): centralize branching in the builder chain instead of
/// building values imperatively.
pub trait FluentBuilder: Sized {
    /// Apply `f` to `self`.
    fn map<U>(self, f: impl FnOnce(Self) -> U) -> U {
        f(self)
    }
    /// Apply `f` only when `cond` holds.
    fn when(self, cond: bool, f: impl FnOnce(Self) -> Self) -> Self {
        if cond { f(self) } else { self }
    }
}

impl FluentBuilder for gh_workflow::Workflow {}
impl FluentBuilder for Job {}
impl<T> FluentBuilder for Step<T> {}

/// Reference a repo-local composite action (`uses: ./path`). The base
/// `gh-workflow` `uses()` only builds `owner/repo@version`, so we set the raw
/// `uses` field directly. Kept in one place so the workaround is contained.
pub(crate) fn uses_local(name: &str, path: RepoDir<'_>) -> Step<Use> {
    let mut step = Step::new(name).uses("local", "local", "0");
    step.value.uses = Some(format!("./{}", path.as_str()));
    step
}

/// Namespace remote BuildKit, pinned. Multi-arch `docker buildx --push` goes
/// through it so nix-in-Docker work does not land on a Small runner's local
/// daemon.
pub fn setup_namespace_buildx() -> Step<Use> {
    Step::new("Set up Namespace Docker builder").uses(
        "namespacelabs",
        "nscloud-setup-buildx-action",
        "d059ed7184f0bc7c8b27e8810cea153d02bcc6dd",
    ) // v0.0.23
}

/// `actions/checkout`, pinned. `full_history` fetches the full history, which
/// the path-filter diff in `path-check` needs. `persist_credentials` controls
/// whether checkout leaves the token in git config for later steps.
pub fn checkout(full_history: bool, persist_credentials: bool) -> Step<Use> {
    Step::new("Checkout")
        .uses(
            "actions",
            "checkout",
            "de0fac2e4500dabe0009e67214ff5f5447ce83dd",
        ) // v4
        .add_with(("clean", false))
        .when(full_history, |step| step.add_with(("fetch-depth", 0)))
        .when(!persist_credentials, |step| {
            step.add_with(("persist-credentials", false))
        })
}

/// `oven-sh/setup-bun` — installs Bun on the runner. Version-tagged (not
/// SHA-pinned) to match the JS deploy/publish workflows.
pub fn setup_bun() -> Step<Use> {
    Step::new("Setup Bun").uses("oven-sh", "setup-bun", "v2")
}

/// `oven-sh/setup-bun`, SHA-pinned with an exact Bun version, for the native
/// release workflows that run the `apps/web/scripts` release helpers.
pub fn setup_bun_pinned() -> Step<Use> {
    Step::new("Setup Bun")
        .uses(
            "oven-sh",
            "setup-bun",
            "0c5077e51419868618aeaa5fe8019c62421857d6",
        ) // v2.2.0
        .add_with(("bun-version", "1.3.13"))
}

/// Keyless Google Play access (Workload Identity Federation through the
/// repository variables `GOOGLE_PLAY_WORKLOAD_IDENTITY_PROVIDER` /
/// `GOOGLE_PLAY_SERVICE_ACCOUNT`), as step `auth`: an `androidpublisher`
/// access token, plus a credentials file for actions that want one. The job
/// needs `id-token: write`. Google's provider admits only workflows that run
/// `main`'s copy (see "Keyless publishing credentials" in
/// docs/development/android.md), so never use this in a `pull_request` job:
/// it would run the PR's code with the publishing identity, and the provider
/// rejects it anyway.
pub fn google_play_auth(credentials_file: bool) -> Step<Use> {
    Step::new("Authenticate to Google Play")
        .uses(
            "google-github-actions",
            "auth",
            "7c6bc770dae815cd3e89ee6cdf493a5fab2cc093",
        ) // v3
        .id("auth")
        .add_with((
            "workload_identity_provider",
            "${{ vars.GOOGLE_PLAY_WORKLOAD_IDENTITY_PROVIDER }}",
        ))
        .add_with(("service_account", "${{ vars.GOOGLE_PLAY_SERVICE_ACCOUNT }}"))
        .add_with(("token_format", "access_token"))
        .add_with((
            "access_token_scopes",
            "https://www.googleapis.com/auth/androidpublisher",
        ))
        .when(!credentials_file, |step| {
            step.add_with(("create_credentials_file", false))
        })
        .add_with(("export_environment_variables", false))
}

/// Install the Rust toolchain only (no sccache, no cache) — for the lightweight
/// `path-check` and workflow-drift jobs.
pub fn setup_rust_light() -> Step<Use> {
    uses_local(
        "Setup Rust",
        xtask_paths::repo_dir!(".github/actions/setup-rust"),
    )
    .add_with(("sccache", "false"))
    .add_with(("rust-cache", "false"))
}

/// A `bash` step whose output the job's closing "Comment on the PR" step
/// quotes when the job fails. The step records its name in
/// `$RUNNER_TEMP/last-step.name` and tees its stdout and stderr into
/// `$RUNNER_TEMP/last-step.log`, both truncated at the step's start, so the
/// files describe the failed step when the comment step runs (it checks the
/// name against the API's failed step first: an unlogged step may have
/// failed since). Only for steps whose output is messages — the comment is
/// not secret-masked the way the log is, so a step that handles credentials
/// or runs a build stays an ordinary step.
pub fn logged_run(name: &str, script: impl AsRef<str>) -> Step<Run> {
    Step::new(name)
        .run(format!(
            "printf '%s\\n' \"$LOGGED_STEP\" > \"$RUNNER_TEMP/last-step.name\"\n\
             exec > >(tee \"$RUNNER_TEMP/last-step.log\") 2>&1\n\
             {}",
            script.as_ref()
        ))
        .shell("bash")
        .add_env(("LOGGED_STEP", name))
}

/// Install Nix on a macOS runner. The Linux [`setup_nix`] action doesn't apply
/// there, so Apple jobs (DMG signing, the iOS simulator preview) install it
/// with the same script instead.
pub fn install_nix_macos() -> Step<Run> {
    Step::new("Install Nix")
        .run(include_str!("scripts/install_nix_macos.sh"))
        .shell("bash")
}

/// Install + initialise Nix on the runner. Namespace profiles don't ship Nix,
/// so this must run before [`setup_dev_shell`] (which shells out to `nix`). The
/// `/nix` cache volume mounted by [`mount_cache_volume`] keeps the store warm,
/// so it re-inits the daemon rather than doing a full install.
pub fn setup_nix() -> Step<Use> {
    uses_local(
        "Setup Nix",
        xtask_paths::repo_dir!(".github/actions/setup-nix"),
    )
}

/// [`setup_nix`] with the private S3 binary cache configured as a substituter,
/// so a /nix cache-volume miss degrades to a download instead of a rebuild.
/// Only for trusted jobs with access to the AWS secrets (never PR-triggered
/// jobs). No-ops back to plain [`setup_nix`] behavior while the
/// `NIX_CACHE_*` repo variables are unset.
pub fn setup_nix_with_cache() -> Step<Use> {
    setup_nix()
        .add_with(("nix-cache-url", vars::NIX_CACHE_URL))
        .add_with(("nix-cache-public-key", vars::NIX_CACHE_PUBLIC_KEY))
        .add_with(("aws-access-key-id", vars::AWS_ACCESS_KEY))
        .add_with(("aws-secret-access-key", vars::AWS_SECRET_ACCESS_KEY))
}

/// [`setup_nix`] restoring `/nix` from Namespace's HTTP cache when the volume is
/// empty. PR jobs write that copy, so this is only for PR check jobs: never a job
/// that deploys or holds deploy secrets.
pub fn setup_nix_with_seed() -> Step<Use> {
    setup_nix().add_with(("seed-cache", vars::CI_SCCACHE_NAME))
}

/// Push built store paths to the private S3 binary cache, signing on upload —
/// the `cachix watch-store` role. `targets` lands in the step's `TARGETS` env
/// (space-separated flake refs or store paths; GH expressions fine) and is
/// word-split on purpose. Skips silently while the cache vars/secret are
/// unset, and never fails the job: the cache is an optimization, and the paths
/// were already handed off via Namespace artifacts.
pub fn push_nix_cache(targets: &str) -> Step<Run> {
    Step::new("Push to nix cache")
        .run(indoc::indoc! {r#"
            set -uo pipefail
            if [[ -z "${NIX_CACHE_URL:-}" || -z "${NIX_CACHE_SIGNING_KEY:-}" ]]; then
              echo "nix cache not configured; skipping push"
              exit 0
            fi
            key="$RUNNER_TEMP/nix-cache-signing-key"
            printf '%s\n' "$NIX_CACHE_SIGNING_KEY" > "$key"
            sep='?'; [[ "$NIX_CACHE_URL" == *\?* ]] && sep='&'
            # shellcheck disable=SC2086 # TARGETS is a list on purpose
            nix copy --to "${NIX_CACHE_URL}${sep}secret-key=${key}" $TARGETS \
              || echo "::warning::nix cache push failed (non-fatal)"
            rm -f "$key"
        "#})
        .shell("bash")
        .add_env(Env::new("TARGETS", targets))
        .add_env(Env::new("NIX_CACHE_URL", vars::NIX_CACHE_URL))
        .add_env(Env::new(
            "NIX_CACHE_SIGNING_KEY",
            vars::NIX_CACHE_SIGNING_KEY,
        ))
        .add_env(Env::new("AWS_ACCESS_KEY_ID", vars::AWS_ACCESS_KEY))
        .add_env(Env::new(
            "AWS_SECRET_ACCESS_KEY",
            vars::AWS_SECRET_ACCESS_KEY,
        ))
}

/// Enter the repo's Nix dev shell (toolchain, mold, just, the sccache binary,
/// and `RUSTC_WRAPPER=sccache`) without selecting an sccache provider or
/// configuring an external Nix binary cache. Jobs that compile Rust can follow
/// this with [`configure_namespace_sccache`] to use Namespace's official remote
/// cache. Requires [`setup_nix`] first. The composite action defaults to the
/// `default` flake shell when no `shell` input is passed.
pub fn setup_dev_shell() -> Step<Use> {
    uses_local(
        "Setup Nix dev shell",
        xtask_paths::repo_dir!(".github/actions/setup-nix-dev-shell"),
    )
}

/// [`setup_dev_shell`] for a named `devShells.<name>` flake output.
pub fn setup_dev_shell_named(name: &str) -> Step<Use> {
    setup_dev_shell().add_with(("shell", name))
}

/// Mount the Namespace profile's persisted cache volume: cargo's registry, git
/// checkouts and `target/`, and the Nix store. Listing the paths mounts in under a
/// second, where the action's `cache: rust` mode took about 12 s to find the same
/// ones. Compiled objects deliberately use Namespace's official remote sccache
/// instead of this volume.
/// `continue-on-error` because the volume is a pure optimization — a failure
/// just means cold Cargo/Nix state, never a wrong build.
pub fn mount_cache_volume() -> Step<Use> {
    nscloud_cache_action("Mount Namespace cache volume").add_with((
        "path",
        "/nix\n./target\n/home/runner/.cargo/registry\n/home/runner/.cargo/git\n/home/runner/.cargo/.global-cache",
    ))
}

/// Mount a scratch directory for building the nextest filter, plus cargo's registry
/// and git checkouts. `cargo metadata` fetches every crate in the lockfile, which took
/// most of the filter's time when `path-check` had no registry to start from.
pub fn mount_nextest_filter_cache(filter_cache_dir: RuntimePath<'_>) -> Step<Use> {
    let paths = format!(
        "{}\n{}\n{}",
        filter_cache_dir.as_str(),
        xtask_paths::runtime_path!("/home/runner/.cargo/registry").as_str(),
        xtask_paths::runtime_path!("/home/runner/.cargo/git").as_str(),
    );

    nscloud_cache_action("Mount nextest-filter and cargo registry cache").add_with(("path", paths))
}

/// The pinned `nscloud-cache-action`, shared by every mount helper below.
/// `continue-on-error` because a cache volume is always a pure optimization — a
/// failure just means cold state, never a wrong build.
fn nscloud_cache_action(name: &str) -> Step<Use> {
    Step::new(name)
        .uses(
            "namespacelabs",
            "nscloud-cache-action",
            "15799a6b54e5765f85b2aac25b3f0df43ed571c0", // v1.4.3
        )
        .continue_on_error(true)
}

/// [`mount_cache_volume`] for the wasm worker build. `target/` is listed
/// explicitly so cargo fingerprints survive across runs. The last two paths
/// are what wrangler's `[build]` line otherwise redoes every run: the pinned
/// `worker-build` binary and wasm-pack's downloaded `wasm-opt`.
pub fn mount_wasm_cache_volume() -> Step<Use> {
    nscloud_cache_action("Mount Namespace cache volume")
        .add_with(("cache", "rust"))
        .add_with((
            "path",
            format!(
                "${{{{ github.workspace }}}}/target\n{}\n{}",
                xtask_paths::runtime_path!("/home/runner/.cargo/bin").as_str(),
                xtask_paths::runtime_path!("/home/runner/.cache/.wasm-pack").as_str(),
            ),
        ))
}

/// Configure Namespace's official artifact-backed remote sccache. Call this
/// after [`setup_dev_shell`] or [`setup_reqs_web`], which install sccache and
/// export `RUSTC_WRAPPER=sccache`. The short-lived WebDAV credentials work
/// across runners and cache-volume misses. Fork PRs skip this step and retain
/// the setup action's local fallback so untrusted code never receives the
/// runner-minted Namespace workspace token.
pub fn configure_namespace_sccache(cache_name: &str) -> Step<Run> {
    namespace_sccache_step(cache_name)
        .if_condition(Expression::new(TRUSTED_NAMESPACE_SCCACHE_CONTEXT))
}

fn namespace_sccache_step(cache_name: &str) -> Step<Run> {
    Step::new("Configure Namespace remote sccache").run(format!(
        r#"set -euo pipefail
env_file="$(mktemp "$RUNNER_TEMP/namespace-sccache.XXXXXX")"
trap 'rm -f "$env_file"' EXIT
if nsc cache sccache setup --cache_name {cache_name} > "$env_file"; then
  # Register credential values as masked BEFORE exporting: GitHub only
  # masks `secrets.*`, so without this SCCACHE_WEBDAV_TOKEN — a broad,
  # ~24h Namespace workspace token (registry + cache write) — printed
  # verbatim in every subsequent step's env dump. Masking is selective by
  # key name: masking non-secrets like the endpoint URL or key prefix
  # would redact those strings everywhere in the logs.
  while IFS= read -r line; do
    k="${{line%%=*}}"
    v="${{line#*=}}"
    [ -n "$v" ] && [ "$k" != "$line" ] || continue
    case "$k" in
      *TOKEN*|*SECRET*|*PASSWORD*) echo "::add-mask::$v" ;;
    esac
  done < "$env_file"
  cat "$env_file" >> "$GITHUB_ENV"
  # The server checks the WebDAV backend before it reports ready, and the
  # client's default 10s wait can run out. This limit has no env var.
  sccache_conf="$RUNNER_TEMP/sccache.toml"
  echo 'server_startup_timeout_ms = 60000' > "$sccache_conf"
  echo "SCCACHE_CONF=$sccache_conf" >> "$GITHUB_ENV"
  # Force the next compiler invocation to start a server with the new remote
  # backend even if a setup hook happened to launch one already.
  sccache --stop-server >/dev/null 2>&1 || true
else
  echo "::warning::Namespace remote sccache setup failed; using local cache fallback"
fi"#
    ))
}

/// Mount the web-app cache volume using Namespace's native Nix integration.
/// Bun's install cache is mounted as an explicit path because Bun comes from
/// the Nix dev shell and is not available when this step runs. `with_rust`
/// additionally persists cargo registry/git data for the `gen-api`
/// OpenAPI-binary build; compiled objects live in Namespace's remote sccache.
/// `continue-on-error` for the same reason as [`mount_cache_volume`].
pub fn mount_web_cache_volume(with_rust: bool) -> Step<Use> {
    nscloud_cache_action("Mount Namespace cache volume")
        .add_with(("cache", "nix"))
        .map(|step| {
            if with_rust {
                step.add_with((
                    "path",
                    format!(
                        "{}\n/home/runner/.cargo/registry\n/home/runner/.cargo/git",
                        vars::BUN_CACHE_VOLUME_DIR,
                    ),
                ))
            } else {
                step.add_with(("path", vars::BUN_CACHE_VOLUME_DIR))
            }
        })
}

/// [`mount_web_cache_volume`] plus Vitest's module cache, so the web `Test`
/// job reuses transforms from earlier runs instead of redoing them all.
pub fn mount_web_test_cache_volume() -> Step<Use> {
    nscloud_cache_action("Mount Namespace cache volume")
        .add_with(("cache", "nix"))
        .add_with((
            "path",
            format!(
                "{}\n/home/runner/.cargo/registry\n/home/runner/.cargo/git\n{}\n{}\n{}",
                vars::BUN_CACHE_VOLUME_DIR,
                xtask_paths::runtime_path!("/home/runner/.cache/.wasm-pack").as_str(),
                vars::VITEST_MODULE_CACHE_VOLUME_DIR,
                vars::WASM_PKG_CACHE_DIR,
            ),
        ))
}

/// [`mount_web_cache_volume`] for jobs that compile the browser wasm packages
/// (`just build-*`). Cargo registry/git feed wasm-pack; `.wasm-pack` is the
/// downloaded `wasm-opt` the same way [`mount_wasm_cache_volume`] keeps the
/// worker build warm. Compiled objects use Namespace remote sccache.
pub fn mount_web_build_cache_volume() -> Step<Use> {
    nscloud_cache_action("Mount Namespace cache volume")
        .add_with(("cache", "nix"))
        .add_with((
            "path",
            format!(
                "{}\n/home/runner/.cargo/registry\n/home/runner/.cargo/git\n{}",
                vars::BUN_CACHE_VOLUME_DIR,
                xtask_paths::runtime_path!("/home/runner/.cache/.wasm-pack").as_str(),
            ),
        ))
}

/// [`mount_web_build_cache_volume`] plus [`vars::WASM_PKG_CACHE_DIR`], for the PR
/// build that reuses unchanged wasm packages. Deploy builds always rebuild them.
pub fn mount_web_build_check_cache_volume() -> Step<Use> {
    nscloud_cache_action("Mount Namespace cache volume")
        .add_with(("cache", "nix"))
        .add_with((
            "path",
            format!(
                "{}\n/home/runner/.cargo/registry\n/home/runner/.cargo/git\n{}\n{}",
                vars::BUN_CACHE_VOLUME_DIR,
                xtask_paths::runtime_path!("/home/runner/.cache/.wasm-pack").as_str(),
                vars::WASM_PKG_CACHE_DIR,
            ),
        ))
}

/// The web-app composite: Nix dev shell (bun, biome, just) + `bun install`.
/// Jobs that run `gen-api` follow this with [`configure_namespace_sccache`].
/// Requires [`setup_nix`] first.
pub fn setup_reqs_web(name: &str, playwright: bool) -> Step<Use> {
    uses_local(
        name,
        xtask_paths::repo_dir!(".github/actions/setup-reqs-web"),
    )
    .when(playwright, |step| step.add_with(("playwright", "true")))
}

/// Build the code-mode assets (`crates/code_mode_assets`) in Nix, or restore them
/// from Namespace's remote cache, and point later cargo steps at them, so Rust jobs
/// need no bun install. Any job that compiles that crate or a dependent (DSS, the
/// agent harness) needs this. Goes after [`configure_namespace_sccache`], whose
/// credentials it reuses.
pub fn code_mode_assets() -> Step<Run> {
    Step::new("Build code-mode assets").run(include_str!("scripts/code_mode_assets.sh"))
}

/// Start the server before parallel compiler invocations can race to launch it.
/// Keep this in a separate step after remote configuration so `GITHUB_ENV`
/// has supplied the selected backend's credentials to the process.
pub fn start_sccache_server() -> Step<Run> {
    Step::new("Start sccache server").run("sccache --start-server")
}

/// Run embedded TypeScript on the hosted image's Node, which strips types
/// itself, so the step needs no checkout, build or dependency. The script
/// exports `main`.
pub fn node_script(source: &str) -> String {
    format!(
        "node --disable-warning=ExperimentalWarning --input-type=module-typescript <<'NODE_SCRIPT'\n{source}\nawait main();\nNODE_SCRIPT\n"
    )
}

/// `sccache --show-stats` at the end of a job (never fails the job).
pub fn show_sccache_stats() -> Step<Run> {
    Step::new("show sccache stats")
        .run("sccache --show-stats || true")
        .if_condition(Expression::new("always()"))
}

/// Base for jobs gated behind `path-check`: depends on it and runs only where
/// the path filter matched. Shared by `check` and `test`.
pub fn gated_job() -> Job {
    Job::default()
        .needs(vec!["path-check".to_string()])
        .cond(Expression::new(
            "needs.path-check.outputs.should_run == 'true'",
        ))
}

// ---------------------------------------------------------------------------
// Deploy family (deploy_all_services / reusable_deploy_service) shared steps
// ---------------------------------------------------------------------------

/// `actions/checkout` pinned to the v4 SHA the deploy pipelines use. Compose
/// options at the call site (`clean: false` on jobs reusing a mounted /nix
/// volume, `sparse-checkout` for action-only jobs).
pub fn checkout_v4() -> Step<Use> {
    Step::new("Checkout Repo")
        .uses(
            "actions",
            "checkout",
            "de0fac2e4500dabe0009e67214ff5f5447ce83dd",
        ) // v4
        .add_with(("persist-credentials", false))
}

/// Build Nix targets using Namespace's mounted `/nix` cache volume.
pub fn nix_build(name: &str, targets: &str, done_msg: &str) -> Step<Run> {
    Step::new(name)
        .run(format!(
            "set -euo pipefail\nnix build --print-build-logs {targets}\necho \"{done_msg}\""
        ))
        .shell("bash")
}

/// Upload a build's handoff tarball to Namespace artifact storage: strongly
/// consistent object storage that rides Namespace's network rather than the
/// GitHub artifacts API. Attempt-scoped path so re-runs never collide with
/// stale uploads; the deploy job logs the same hash on read.
pub fn upload_handoff_artifact(file: &str, service_expr: &str) -> Step<Run> {
    Step::new("Upload handoff artifact")
        .run(format!("nsc artifact upload {file} \"$DEST\" --expires_in=24h"))
        .shell("bash")
        .add_env(Env::new(
            "DEST",
            format!("handoff/${{{{ github.run_id }}}}-${{{{ github.run_attempt }}}}/{service_expr}/{file}"),
        ))
}

/// Mount Pulumi's provider-plugin dir on a Namespace cache volume. Plugins are
/// version-pinned by infra/ and identical across services; a cold volume just
/// re-downloads (~45s). Requires the job to pin `PULUMI_HOME: /pulumi`.
pub fn cache_pulumi_plugins() -> Step<Use> {
    nscloud_cache_action("Cache Pulumi plugins").add_with(("path", "/pulumi/plugins"))
}

/// Make PULUMI_HOME (/pulumi) and its mounted plugins subdir writable so
/// pulumi can write credentials + plugins as the runner (no-op when already
/// root). `mkdir -p` first: the plugin cache mount is continue-on-error, so on
/// a mount failure /pulumi may not exist yet — create it so the cold-cache
/// fallback works instead of the chown hard-failing the deploy.
pub fn ensure_pulumi_home_writable() -> Step<Run> {
    Step::new("Ensure Pulumi home is writable")
        .run(indoc::indoc! {r#"
            set -euo pipefail
            sudo mkdir -p /pulumi
            if [ "$(id -u)" -ne 0 ]; then sudo chown -R "$(id -u):$(id -g)" /pulumi; fi
        "#})
        .shell("bash")
}

// ---------------------------------------------------------------------------
// Desktop (AppImage / DMG) shared steps
// ---------------------------------------------------------------------------

/// `actions/checkout` with a dynamic ref (for tag-triggered builds). Uses the
/// same pinned SHA as [`checkout`].
pub fn checkout_ref(ref_expr: &str) -> Step<Use> {
    Step::new("Checkout Repo")
        .uses(
            "actions",
            "checkout",
            "df4cb1c069e1874edd31b4311f1884172cec0e10",
        ) // v6
        .add_with(("ref", ref_expr))
        .add_with(("persist-credentials", false))
}

/// Mount only the `/nix` store cache volume (no cargo/sccache). Used by the
/// desktop builds that delegate entirely to Nix.
pub fn mount_nix_cache_volume() -> Step<Use> {
    nscloud_cache_action("Mount /nix cache volume").add_with(("cache", "nix"))
}

/// macOS cache mounts are symlinks, which Nix does not support for `/nix`.
/// Persist a file binary cache instead, leaving the live store to the installer.
pub fn mount_macos_nix_cache_volume() -> Step<Use> {
    nscloud_cache_action("Mount macOS Nix binary cache")
        .add_with(("path", "~/.cache/macro-desktop-nix"))
}

/// Derive a safe tag name from the git ref for use in artifact names.
pub fn derive_artifact_metadata(raw_ref_expr: &str) -> Step<Run> {
    Step::new("Derive artifact metadata")
        .run(indoc::indoc! {r#"
            set -euo pipefail
            tag="${RAW_REF#refs/tags/}"
            if [ -z "$tag" ]; then
              tag="${GITHUB_REF_NAME:-untagged}"
            fi
            safe_tag=$(printf '%s' "$tag" | sed 's#[/\\:*?"<>|]#-#g' | tr -d '\r\n')
            echo "tag=$tag" >> "$GITHUB_OUTPUT"
            echo "safe_tag=$safe_tag" >> "$GITHUB_OUTPUT"
        "#})
        .id("metadata")
        .shell("bash")
        .add_env(("RAW_REF", raw_ref_expr))
}

/// Upload build artifacts within the workflow run for a later publish job.
pub fn upload_artifact(name: &str, path: RuntimePath<'_>) -> Step<Use> {
    Step::new(format!("Upload {name} artifact"))
        .uses(
            "actions",
            "upload-artifact",
            "ea165f8d65b6e75b540449e92b4886f43607fa02",
        ) // v4
        .add_with(("name", name))
        .add_with(("path", path.as_str()))
        .add_with(("if-no-files-found", "error"))
        .add_with(("retention-days", 30))
}

/// Download all build artifacts into one directory for release publishing.
pub fn download_artifacts(path: RuntimePath<'_>) -> Step<Use> {
    Step::new("Download Build Artifacts")
        .uses(
            "actions",
            "download-artifact",
            "634f93cb2916e3fdff6788551b99b062d0335ce0",
        ) // v5
        .add_with(("path", path.as_str()))
        .add_with(("merge-multiple", true))
}

/// Attach build artifacts to the GitHub release for the resolved release tag.
pub fn upload_release_artifacts(path: RuntimePath<'_>) -> Step<Use> {
    Step::new("Upload Release Artifacts")
        .uses(
            "softprops",
            "action-gh-release",
            "3bb12739c298aeb8a4eeaf626c5b8d85266b0e65",
        ) // v2
        .if_condition(Expression::new(
            "startsWith(steps.metadata.outputs.tag, 'v')",
        ))
        .add_with(("tag_name", "${{ steps.metadata.outputs.tag }}"))
        .add_with(("files", path.as_str()))
        .add_with(("fail_on_unmatched_files", true))
}

/// Teardown Nix (always runs).
pub fn teardown_nix() -> Step<Use> {
    uses_local(
        "Teardown Nix",
        xtask_paths::repo_dir!(".github/actions/teardown-nix"),
    )
    .if_condition(Expression::new("always()"))
}