### Nix Configuration Example Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/daemon-operation.md Example of the trusted-users configuration format used by Nix. ```text trusted-users = nixbld @admin root ``` -------------------------------- ### List Nix Store Example Output Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/types.md Sample output format for the list-nix-store.sh script. ```text /nix/store/2kb9j7q5pg0m50z7hjxyd9p81iw8bqil-bash-5.2.26 /nix/store/52qyd8b2n0ysqpn3q6p5g3k0y4x1w2v5-gcc-13.2.0 ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/cachix/cachix-action/blob/master/CONTRIBUTING.md Run this command within the devenv shell to install all project dependencies using pnpm. Ensure you are in the development environment before executing. ```console pnpm install ``` -------------------------------- ### Store Path List Output Format Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/store-scan-mode.md Example of the newline-separated list of store paths generated by the pre-build snapshot script. ```text /nix/store/2kb9j7q5pg0m50z7hjxyd9p81iw8bqil-bash-5.2.26 /nix/store/52qyd8b2n0ysqpn3q6p5g3k0y4x1w2v5-gcc-13.2.0 /nix/store/abcdef0123456789xyz...-derivation-result ``` -------------------------------- ### Default Configuration Example Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/configuration.md Example YAML configuration for the cachix-action showing default values and available inputs. ```yaml - uses: cachix/cachix-action@v17 with: name: my-cache # Effective configuration: # authToken: "" (must provide for push) # signingKey: "" # skipPush: false # useDaemon: true (if compatible) # pathsToPush: "" (push all) # pushFilter: "" # skipAddingSubstituter: false # cachixArgs: "-j8" # cachixBin: "" (auto-discover) # installCommand: "nix-env --quiet -j8 -iA cachix -f https://cachix.org/api/v1/install" ``` -------------------------------- ### Initialize Pre-Build Snapshot Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/store-scan-mode.md Executes the store scan setup logic when PushMode is set to StoreScan, saving the current store state to a temporary file. ```typescript case PushMode.StoreScan: { const preBuildPathsFile = `${tmpdir}/store-path-pre-build`; core.saveState("preBuildPathsFile", preBuildPathsFile); await exec.exec("sh", [ "-c", `${__dirname}/list-nix-store.sh > ${preBuildPathsFile}`, ]); break; } ``` -------------------------------- ### Install Cachix via Nix Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/workflow-execution.md The default command used to install Cachix from nixpkgs. ```bash nix-env --quiet -j8 -iA cachix -f https://cachix.org/api/v1/install ``` -------------------------------- ### Get User Config Files Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/api-reference-functions.md Computes the paths to Nix configuration files based on the XDG Base Directory Specification. ```typescript function getUserConfigFiles(): string[] ``` -------------------------------- ### Verify Cachix Binary Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/troubleshooting.md Confirm the installed version and availability of the Cachix binary. ```bash which cachix cachix --version cachix show-config # If not already shown by action ``` -------------------------------- ### Get User Config Directories Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/api-reference-functions.md Resolves the locations of XDG configuration directories. ```typescript function getUserConfigDirs(): string[] ``` -------------------------------- ### Configure Workflow Step Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/workflow-execution.md Example YAML configuration for invoking the cachix-action within a GitHub Actions workflow. ```yaml - name: Run cachix-action steps: - uses: cachix/cachix-action@v17 with: name: my-cache ``` -------------------------------- ### Dispatch Logic via State Storage Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/workflow-execution.md Uses GitHub Actions state to determine whether the current execution is the pre-job setup or the post-job upload. ```typescript export async function run(): Promise { const isPost = !!core.getState("isPost"); if (!isPost) { core.saveState("isPost", "true"); // Mark for post-job await setup(); } else { await upload(); } } ``` -------------------------------- ### Propagate Environment Variables Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/workflow-execution.md Exports variables during the setup phase to make them accessible as environment variables in subsequent phases. ```typescript // setup phase core.exportVariable("CACHIX_DAEMON_DIR", daemonDir); core.exportVariable("CACHIX_SIGNING_KEY", signingKey); // upload phase const daemonDir = process.env["CACHIX_DAEMON_DIR"]; // Available ``` -------------------------------- ### Persist State Across Job Phases Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/workflow-execution.md Utilizes core.saveState and core.getState to share data between the setup and post-job process invocations. ```typescript // In setup phase core.saveState("key", "value"); // In post-job phase (same job, different process) const value = core.getState("key"); // Returns "value" ``` -------------------------------- ### Configure Write Cache with Auth Token Source: https://github.com/cachix/cachix-action/blob/master/README.md This setup allows pushing build results to a Cachix cache. It requires an authentication token, typically stored as a GitHub secret, for private cache access or to push to any cache. ```yaml - uses: cachix/cachix-action@v17 with: name: mycache authToken: "${{ secrets.CACHIX_AUTH_TOKEN }}" ``` -------------------------------- ### Override Cachix Installation Command Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/examples-and-patterns.md Define a custom command to install Cachix if it is not found. Useful for air-gapped CI or environments like NixOS where standard installation methods may not apply. ```yaml name: Custom Install on: [push] jobs: build: runs-on: ubuntu-latest container: image: nixos/nix:latest steps: - uses: actions/checkout@v4 - uses: cachix/cachix-action@v17 with: name: mycache authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} installCommand: "nix profile install --impure nixpkgs#cachix" - run: nix build ``` -------------------------------- ### Check Nix Configuration Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/troubleshooting.md Verify the Nix configuration and post-build-hook registration. ```bash nix show-config | head -50 cat $NIX_USER_CONF_FILES echo $NIX_CONF ``` -------------------------------- ### Full Script Implementation Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/store-scan-mode.md The complete source code for the push-paths.sh utility. ```bash #!/usr/bin/env bash set -euo pipefail cachix=$1 cachixArgs=${2:--j8} cache=$3 preBuildPathsFile=$4 pushFilter=$5 filterPaths() { local regex=$1 local paths=$2 for path in $paths; do echo "$path" | grep -vEe "$regex" done | xargs } pathsToPush="" if preBuildPaths=$(sort "$preBuildPathsFile"); then if postBuildPaths=$("$(dirname "$0")"/list-nix-store.sh | sort); then pathsToPush=$(comm -13 <(echo "$preBuildPaths") <(echo "$postBuildPaths")) else echo "::error::Failed to list post-build store paths." fi else printf "::error::Failed to find pre-build store paths. Expected cached paths in %s\n" "$preBuildPathsFile" fi if [[ -n $pushFilter ]]; then pathsToPush=$(filterPaths "$pushFilter" "$pathsToPush") fi echo "$pathsToPush" | "$cachix" push "$cachixArgs" "$cache" ``` -------------------------------- ### Project File Structure Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/overview.md Overview of the source and distribution directory layout for the action. ```text src/ index.ts # Entry point: exports run() main.ts # All core logic dist/ index.js # Bundled output list-nix-store.sh # Store enumeration utility push-paths.sh # Path filtering and push script action.yml # GitHub Actions metadata ``` -------------------------------- ### Read Pre-Build Snapshot Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/store-scan-mode.md Reads and sorts the pre-build paths file to prepare for comparison. ```bash pathsToPush="" if preBuildPaths=$(sort "$preBuildPathsFile"); then # Continue if file read and sorted successfully else printf "::error::Failed to find pre-build store paths...\n" fi ``` -------------------------------- ### Get PID File Path Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/api-reference-functions.md Constructs the file path for the daemon PID file within the provided directory. ```typescript function pidFilePath(daemonDir: string): string ``` -------------------------------- ### Align local development and CI caching Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/examples-and-patterns.md Demonstrates how to configure local environments and CI pipelines to share the same Cachix cache. ```bash # Local development cachix use -d mycache nix build # Pushes via post-hook if developer has signing key nix build --out-link result-local ``` ```yaml # CI (GitHub Actions) - uses: cachix/cachix-action@v17 with: name: mycache authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} signingKey: ${{ secrets.CACHIX_SIGNING_KEY }} - run: nix build ``` -------------------------------- ### Execute Action Entry Point Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/api-reference-functions.md The main entry point for the GitHub Action, typically invoked in the index file. ```typescript import { run } from "./main"; // In src/index.ts run(); ``` -------------------------------- ### registerPostBuildHook(cachixBin, daemonDir) Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/api-reference-functions.md Configures Nix to invoke the Cachix daemon on store path completion by writing a post-build-hook script and updating Nix configuration files. ```APIDOC ## registerPostBuildHook(cachixBin, daemonDir) ### Description Configures Nix to invoke the Cachix daemon on store path completion. ### Signature `async function registerPostBuildHook(cachixBin: string, daemonDir: string): Promise` ### Parameters - **cachixBin** (string) - Required - Path to Cachix binary - **daemonDir** (string) - Required - Temp directory for socket and config files ``` -------------------------------- ### Matrix Build with Multiple Outputs Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/examples-and-patterns.md Configures a cross-platform CI pipeline that pushes build results from different OS and Nix versions to a single shared cache. ```yaml name: Matrix Build on: [push] jobs: build: runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-latest, macos-latest] nix: [2.15.1, 2.16] steps: - uses: actions/checkout@v4 - name: Install Nix ${{ matrix.nix }} uses: cachix/nix-action@v25 with: nix_version: ${{ matrix.nix }} - uses: cachix/cachix-action@v17 with: name: multiplatform-cache authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} - run: nix build ``` -------------------------------- ### Localize Cachix Binary Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/workflow-execution.md Determines the Cachix executable path by checking user input, system PATH, or installing it via a bash command. ```typescript let cachixBin = cachixBinInput; // User-provided custom path if (cachixBin !== "") { core.debug(`Using Cachix executable from input: ${cachixBin}`); } else { let resolvedCachixBin = which.sync("cachix", { nothrow: true }); if (resolvedCachixBin) { cachixBin = resolvedCachixBin; } else { core.startGroup("Cachix: installing"); await exec.exec("bash", ["-c", installCommand]); cachixBin = which.sync("cachix"); // Find after install core.endGroup(); } } core.saveState("cachixBin", cachixBin); ``` -------------------------------- ### Compute Post-Build Paths Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/store-scan-mode.md Generates the list of new paths by comparing current store state against the pre-build snapshot. ```bash if postBuildPaths=$("$(dirname "$0")"/list-nix-store.sh | sort); then pathsToPush=$(comm -13 <(echo "$preBuildPaths") <(echo "$postBuildPaths")) else echo "::error::Failed to list post-build store paths." fi ``` -------------------------------- ### Handle missing pre-build paths file Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/store-scan-mode.md Logs a GitHub Actions error if the pre-build paths file cannot be read, allowing the script to continue execution. ```bash if preBuildPaths=$(sort "$preBuildPathsFile"); then ... else printf "::error::Failed to find pre-build store paths. Expected cached paths in %s\n" "$preBuildPathsFile" fi ``` -------------------------------- ### Define PushMode Enum Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/types.md Enumeration defining the available push strategies for the action. Used to bridge setup and upload phases via GitHub Actions state. ```typescript enum PushMode { None = "None", PushPaths = "PushPaths", StoreScan = "StoreScan", Daemon = "Daemon", } ``` -------------------------------- ### Push to Cache Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/store-scan-mode.md Pipes the final list of paths to the Cachix binary. ```bash echo "$pathsToPush" | "$cachix" push "$cachixArgs" "$cache" ``` -------------------------------- ### Multi-user store scan risk scenario Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/store-scan-mode.md Illustrates how concurrent builds in a multi-user environment can lead to unauthorized exposure of store paths. ```text User A builds secret-project before job User A's build creates: /nix/store/secret123-mylib User B runs cachix-action Store scan captures: /nix/store/secret123-mylib User B's cache now exposes User A's secret ``` -------------------------------- ### Nix Configuration Snippet Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/types.md The configuration line required in nix.conf to register the post-build hook. ```text post-build-hook = /path/to/post-build-hook.sh ``` -------------------------------- ### List Nix Store Implementation Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/store-scan-mode.md Iterates through /nix/store and filters out non-artifact files like derivations and locks. ```bash set -euo pipefail for file in /nix/store/*; do case "$file" in *.drv) continue # Skip derivation files ;; *.drv.chroot) continue # Skip derivation chroot dirs ;; *.check) continue # Skip --keep-failed checkpoint files ;; *.lock) continue # Skip lock files ;; *) echo "$file" # Output store path ;; esac done ``` -------------------------------- ### Resolve Nix Configuration Conflicts Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/troubleshooting.md Avoid manual post-build-hook configuration when using the action. ```yaml steps: # Don't manually set post-build-hook if using cachix-action - name: Bad - conflicts with action run: | echo 'post-build-hook = /my/hook.sh' >> ~/.config/nix/nix.conf # Instead, let action manage it, or use skipAddingSubstituter - uses: cachix/cachix-action@v17 with: name: mycache skipAddingSubstituter: true # If you're managing all substituters manually ``` -------------------------------- ### Configure Authentication Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/workflow-execution.md Sets the authentication token and exports the signing key as an environment variable. ```typescript if (authToken !== "") { await exec.exec(cachixBin, ["authtoken", authToken]); } if (signingKey !== "") { core.exportVariable("CACHIX_SIGNING_KEY", signingKey); } ``` -------------------------------- ### Create and Push New Tag Source: https://github.com/cachix/cachix-action/blob/master/RELEASE.md Use these commands to create a new Git tag for the release and push it to the remote repository. ```console git tag v17 git push origin v17 ``` -------------------------------- ### Push NixOS system configurations in GitHub Actions Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/examples-and-patterns.md Configures a workflow to build and cache specific NixOS system closures using a push filter. ```yaml name: Build Hosts on: [push] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: cachix/cachix-action@v17 with: name: nixos-infra authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} pushFilter: "^(/nix/store/[a-z0-9]{32}-(system-closure|nixos-system--))" - run: nix build '.#nixosConfigurations.prod-server.config.system.build.toplevel' - run: nix build '.#nixosConfigurations.staging-server.config.system.build.toplevel' ``` -------------------------------- ### Query Registered Substituters Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/troubleshooting.md List all currently registered Nix substituters to debug cache connectivity. ```bash nix-store --query --substituters ``` -------------------------------- ### Register post-build hook in Nix configuration Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/daemon-operation.md Writes the post-build hook path to a nix.conf file and updates environment variables to ensure Nix picks up the configuration. ```typescript const postBuildHookConfigPath = `${daemonDir}/nix.conf`; await fs.writeFile( postBuildHookConfigPath, `post-build-hook = ${postBuildHookScriptPath}`, ); ``` ```typescript const existingNixConf = process.env["NIX_CONF"]; if (existingNixConf) { // Append to existing NIX_CONF var core.exportVariable( "NIX_CONF", `${existingNixConf}\npost-build-hook = ${postBuildHookScriptPath}`, ); } else { // Add to NIX_USER_CONF_FILES with priority const existingUserConfEnv = process.env["NIX_USER_CONF_FILES"] ?? ""; let nixUserConfFilesEnv = ""; if (existingUserConfEnv) { nixUserConfFilesEnv = postBuildHookConfigPath + ":" + existingUserConfEnv; } else { const userConfigFiles = getUserConfigFiles(); nixUserConfFilesEnv = [postBuildHookConfigPath, ...userConfigFiles] .filter((x) => x !== "") .join(":"); } core.exportVariable("NIX_USER_CONF_FILES", nixUserConfFilesEnv); } ``` -------------------------------- ### Snapshot Nix Store Paths Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/workflow-execution.md Captures the current state of the Nix store to a file for later diff computation during the post-job phase. ```typescript const preBuildPathsFile = `${tmpdir}/store-path-pre-build`; core.saveState("preBuildPathsFile", preBuildPathsFile); await exec.exec("sh", [ "-c", `${__dirname}/list-nix-store.sh > ${preBuildPathsFile}`, ]); ``` -------------------------------- ### Build the Action Source: https://github.com/cachix/cachix-action/blob/master/CONTRIBUTING.md Execute this command to build the Cachix Action. This process compiles the necessary code and prepares the action for testing or deployment. ```console pnpm build ``` -------------------------------- ### Enter Development Shell Source: https://github.com/cachix/cachix-action/blob/master/CONTRIBUTING.md Use this command to enter the development shell managed by devenv. This environment provides all necessary tools and configurations for development. ```console devenv shell ``` -------------------------------- ### Define Action Phases in YAML Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/workflow-execution.md Configures the action to run the same script for both the main and post-job phases. ```yaml runs: using: "node24" main: "dist/index.js" # Pre-job phase post: "dist/index.js" # Post-job phase ``` -------------------------------- ### Check Nix Configuration Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/troubleshooting.md Verify the current user's trusted status in the Nix configuration. ```bash nix show-config | grep trusted-users ``` -------------------------------- ### Register Post-Build Hook Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/api-reference-functions.md Configures Nix to invoke the Cachix daemon upon completion of store path builds. ```typescript async function registerPostBuildHook( cachixBin: string, daemonDir: string, ): Promise ``` -------------------------------- ### Configure Matrix Strategy in YAML Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/github-actions-integration.md Demonstrates using the cachix-action within a GitHub Actions matrix strategy. ```yaml strategy: matrix: os: [ubuntu-latest, macos-latest] nix-version: [2.15, 2.16] jobs: build: runs-on: ${{ matrix.os }} steps: - uses: cachix/cachix-action@v17 with: name: my-cache ``` -------------------------------- ### Enable Daemon Mode to Avoid StoreScan Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/troubleshooting.md Use the daemon mode to bypass pre-build store path requirements. ```yaml - uses: cachix/cachix-action@v17 with: name: mycache authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} useDaemon: true # Avoids pre-build file requirement ``` -------------------------------- ### getUserConfigFiles() Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/api-reference-functions.md Computes user Nix config file paths based on the XDG Base Directory Specification. ```APIDOC ## getUserConfigFiles() ### Description Computes user Nix config file paths per XDG Base Directory Specification. ### Signature `function getUserConfigFiles(): string[]` ### Return Type `string[]` - Array of paths like `~/.config/nix/nix.conf`, `/etc/xdg/nix/nix.conf` ``` -------------------------------- ### @actions/core State and Environment Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/github-actions-integration.md Methods for persisting data across job phases and exporting environment variables. ```APIDOC ## core.saveState(name, value) Saves a value to be retrieved in the post-job phase. ## core.getState(name) Retrieves a value saved in a previous phase. ## core.exportVariable(name, value) Exports an environment variable for subsequent steps. ``` -------------------------------- ### List Nix Store Script Signature Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/types.md The signature for the script that enumerates and filters Nix store paths. ```bash #!/usr/bin/env bash # Stdin: (none) # Stdout: Newline-separated store paths # Exits: 0 on success, non-zero on error ``` -------------------------------- ### Upload Phase Store Scan Logic Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/store-scan-mode.md Executes the push-paths.sh script when the push mode is set to StoreScan. ```typescript case PushMode.StoreScan: { const preBuildPathsFile = core.getState("preBuildPathsFile"); await exec.exec(`${__dirname}/push-paths.sh`, [ cachixBin, cachixArgs, name, preBuildPathsFile, pushFilter, ]); break; } ``` -------------------------------- ### Action Metadata Specification Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/github-actions-integration.md Defines the action's entry points and execution environment in action.yml. ```yaml name: "Cachix" description: "Build and cache Nix packages using Cachix binary caches..." author: "Domen Kožar" runs: using: "node24" main: "dist/index.js" post: "dist/index.js" ``` -------------------------------- ### fetchTrustedUsers() Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/api-reference-functions.md Queries the Nix configuration to retrieve the 'trusted-users' setting. ```APIDOC ## fetchTrustedUsers() ### Description Queries Nix configuration for `trusted-users` setting. ### Signature `async function fetchTrustedUsers(): Promise` ### Return Type `Promise` - Space-separated list from Nix config, or empty array on error ``` -------------------------------- ### Configure Write Cache with Signing Key Source: https://github.com/cachix/cachix-action/blob/master/README.md To push build results and sign store paths for self-signed caches, provide both the authentication token and the signing key. Both are typically managed as GitHub secrets. ```yaml - uses: cachix/cachix-action@v17 with: name: mycache authToken: "${{ secrets.CACHIX_AUTH_TOKEN }}" signingKey: "${{ secrets.CACHIX_SIGNING_KEY }}" ``` -------------------------------- ### Fetch and Partition Trusted Users Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/daemon-operation.md Helper functions to retrieve the trusted-users configuration from Nix and separate them into individual users and groups. ```typescript async function fetchTrustedUsers(): Promise { try { let conf = await execToVariable("nix", ["show-config"], { silent: true }); let match = conf.match(/trusted-users = (.+)/m); return match?.length === 2 ? match[1].split(" ") : []; } catch (error) { core.warning("Failed to read the Nix configuration"); return []; } } function partitionUsersAndGroups(mixedUsers: string[]): [string[], string[]] { let users: string[] = []; let groups: string[] = []; mixedUsers.forEach((item) => { if (item.startsWith("@")) { groups.push(item.slice(1)); } else { users.push(item); } }); return [users, groups]; } ``` -------------------------------- ### Enable Debug Output Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/troubleshooting.md Set the ACTIONS_STEP_DEBUG environment variable to true to enable verbose logging. ```yaml steps: - uses: cachix/cachix-action@v17 env: ACTIONS_STEP_DEBUG: true with: name: mycache ``` -------------------------------- ### Debug Nix Multi-User Store Access Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/troubleshooting.md Commands to verify user permissions and trust settings for the Nix daemon. ```bash # In job id -Gn $USER # Show all groups nix show-config | grep trusted nix show-config | grep trusted-groups ``` ```bash # Add user directly echo "trusted-users = $(whoami)" | sudo tee -a /etc/nix/nix.conf sudo systemctl restart nix-daemon # On NixOS ``` -------------------------------- ### Test Substituter Directly Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/troubleshooting.md Verify that the cache is being utilized by checking substituters and monitoring build output. ```bash nix-store --query --substituters nix-build --no-out-link --print-out-paths -A nixpkgs.hello 2>&1 | grep -E "^(downloading|copying|substituting)" ``` -------------------------------- ### Post-build Hook Script Signature Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/types.md The signature for the generated post-build hook script that processes Nix store paths. ```bash #!/usr/bin/env bash # Receives: $OUT_PATHS environment variable (space-separated store paths) # Executes: cachix daemon push with optional filtering ``` -------------------------------- ### Configure Monorepo CI with Multiple Caches Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/examples-and-patterns.md Optimizes build times in monorepos by pulling from multiple shared caches and pushing signed artifacts to a project-specific cache. ```yaml name: Monorepo CI on: [push] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: cachix/cachix-action@v17 with: name: project-cache extraPullNames: "infra-cache, nixos-cache, nix-community" authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} signingKey: ${{ secrets.CACHIX_SIGNING_KEY }} cachixArgs: "-j16 --log-level info" - run: nix flake update - run: nix build .#packages.x86_64-linux.cli - run: nix build .#packages.x86_64-linux.server - run: nix flake check ``` -------------------------------- ### Configure Cachix Cache Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/types.md Adds the specified cache as a Nix substituter in the local nix.conf file. ```bash cachix use mycache ``` -------------------------------- ### Notify Daemon of New Paths Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/types.md Used by the post-build-hook to notify the running daemon about new store paths. ```bash cachix daemon push --socket /tmp/cachix.sock /nix/store/path ``` -------------------------------- ### Nix Daemon Build Communication Flow Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/daemon-operation.md Visual representation of the communication sequence between the Nix daemon, the post-build-hook, and the Cachix daemon during a build. ```text Nix daemon builds store path ↓ Completes successfully ↓ Invokes post-build-hook script ↓ Sets $OUT_PATHS environment variable ↓ Script runs: cachix daemon push --socket ↓ Communicates via Unix socket to Cachix daemon process ↓ Daemon receives paths, pushes to Cachix API asynchronously ``` -------------------------------- ### getUserConfigDirs() Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/api-reference-functions.md Resolves the XDG configuration directory locations. ```APIDOC ## getUserConfigDirs() ### Description Resolves XDG config directory locations. ### Signature `function getUserConfigDirs(): string[]` ### Return Type `string[]` - `[XDG_CONFIG_HOME, ...XDG_CONFIG_DIRS]` ``` -------------------------------- ### Configure Custom Cachix Binary Path Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/configuration.md Override the default Cachix binary with a pre-installed custom version. ```yaml - uses: cachix/cachix-action@v17 with: name: my-cache cachixBin: /usr/local/bin/cachix-custom authToken: ${{ secrets.CACHIX_TOKEN }} # Uses pre-installed custom Cachix binary ``` -------------------------------- ### Push Paths to Cache Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/types.md Pushes specific store paths to the named cache, optionally including additional arguments. ```bash cachix push -j8 mycache /nix/store/path1 /nix/store/path2 ``` -------------------------------- ### Configure Daemon Socket Path Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/workflow-execution.md Handles Unix socket path length limitations by recreating the directory in the system temp folder if the path exceeds platform-specific limits. ```typescript const daemonDirPrefix = "cachix"; const socketName = "daemon.sock"; let daemonDir = await fs.mkdtemp(path.join(tmpdir, daemonDirPrefix)); let socketPath = path.join(daemonDir, socketName); // Handle socket path length limits const maxSocketPathLen = os.platform() === "linux" ? 108 : 104; if (socketPath.length > maxSocketPathLen) { await fs.rm(daemonDir, { recursive: true }); daemonDir = await fs.mkdtemp(path.join(os.tmpdir(), daemonDirPrefix)); socketPath = path.join(daemonDir, socketName); core.warning(`Socket path too long, using shorter path`); } ``` -------------------------------- ### Test Cachix Connection Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/troubleshooting.md Verify the connection to Cachix by checking the version. ```bash cachix authtoken --version ``` -------------------------------- ### Signed Push Configuration Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/examples-and-patterns.md Configures a private cache requiring cryptographic signing keys for secure package verification. ```yaml name: Build and Sign on: [push] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: cachix/cachix-action@v17 with: name: private-cache authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} signingKey: ${{ secrets.CACHIX_SIGNING_KEY }} - run: nix build ``` -------------------------------- ### Generate post-build hook script Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/daemon-operation.md This bash script filters output paths and notifies the daemon socket of new paths. It is designed to be non-fatal to the build process. ```bash #!/usr/bin/env bash set -eu set -f # disable globbing PUSH_FILTER="${pushFilter}" filterPaths() { local regex=$1 local paths=$2 for path in $paths; do echo $path | grep -vEe $regex done | xargs } if [ -n "$PUSH_FILTER" ]; then OUT_PATHS=$(filterPaths $PUSH_FILTER "$OUT_PATHS") fi ${cachixBin} daemon push \ --socket ${daemonDir}/daemon.sock \ $OUT_PATHS || echo "cachix: daemon push failed with exit $?; continuing." >&2 exit 0 ``` -------------------------------- ### Basic Cache Pull Configuration Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/examples-and-patterns.md Configures a read-only cache connection for consuming public packages without requiring authentication. ```yaml name: Build on: [push] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: cachix/cachix-action@v17 with: name: mycache - run: nix build ``` -------------------------------- ### Configure Multi-Cache Pulling Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/examples-and-patterns.md Use extraPullNames to define fallback caches. The action queries caches in the specified order, with the primary cache receiving all push operations. ```yaml name: Build on: [push] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: cachix/cachix-action@v17 with: name: primary-cache extraPullNames: "shared-cache, nix-community" authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} - run: nix build ``` -------------------------------- ### Determine Push Mode Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/workflow-execution.md Selects the appropriate push strategy based on credentials, daemon support, and user configuration. ```typescript let pushMode = PushMode.None; if (hasPushTokens && !skipPush) { // Has credentials and push enabled if (pathsToPush) { pushMode = PushMode.PushPaths; // Explicit paths provided } else if (useDaemon) { let supportsDaemonInterface = cachixVersion ? semver.gte(cachixVersion, "1.7.0") : false; let supportsPostBuildHook = await isTrustedUser(); if (!supportsDaemonInterface) { core.warning(`Cachix Daemon not supported (${cachixVersion})`); } if (!supportsPostBuildHook) { core.warning("User not allowed to set post-build-hook"); } pushMode = supportsDaemonInterface && supportsPostBuildHook ? PushMode.Daemon : PushMode.StoreScan; // Fallback } else { pushMode = PushMode.StoreScan; // useDaemon=false } } core.saveState("pushMode", pushMode); ``` -------------------------------- ### pidFilePath(daemonDir) Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/api-reference-functions.md Constructs the file path to the daemon PID file. ```APIDOC ## pidFilePath(daemonDir) ### Description Constructs path to daemon PID file. ### Signature `function pidFilePath(daemonDir: string): string` ### Return Type `string` - `${daemonDir}/daemon.pid` ``` -------------------------------- ### Script Signature Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/store-scan-mode.md Defines the expected arguments and behavior of the push-paths.sh script. ```bash #!/usr/bin/env bash # Args: # $1: cachix binary path # $2: cachix additional args (e.g., "-j8") # $3: cache name # $4: pre-build snapshot file # $5: push filter regex (or empty string) # Stdout: cachix push output # Exit: cachix push exit code ``` -------------------------------- ### Configure Multi-Cache Substitution Order Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/troubleshooting.md Define the order in which caches are queried for substitutions. ```yaml extraPullNames: "cache1, cache2" # Pulls in this order: cache1, cache2, name # But pushes only to: name ``` ```yaml extraPullNames: "fast-cache, slow-fallback" name: my-cache # This is primary, queried last ``` -------------------------------- ### Register Caches Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/workflow-execution.md Adds primary and extra pull caches as Nix substituters. ```typescript if (!skipAddingSubstituter) { core.startGroup(`Cachix: using cache ` + name); await exec.exec(cachixBin, ["use", name]); core.endGroup(); } if (extraPullNames != "") { const extraPullNameList = extraPullNames.split(","); for (let itemName of extraPullNameList) { const trimmedItemName = itemName.trim(); await exec.exec(cachixBin, ["use", trimmedItemName]); } core.endGroup(); } ``` -------------------------------- ### Resolve XDG base directories for Nix configuration Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/daemon-operation.md Helper functions to locate user-specific Nix configuration files based on XDG standards. ```typescript function getUserConfigDirs(): string[] { const xdgConfigHome = process.env["XDG_CONFIG_HOME"] ?? `${os.homedir()}/.config`; const xdgConfigDirs = (process.env["XDG_CONFIG_DIRS"] ?? "/etc/xdg").split(":"); return [xdgConfigHome, ...xdgConfigDirs]; } function getUserConfigFiles(): string[] { const userConfigDirs = getUserConfigDirs(); return userConfigDirs.map((dir) => `${dir}/nix/nix.conf`); } ``` -------------------------------- ### @actions/exec Execution Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/github-actions-integration.md Methods for executing external shell commands with output handling and configuration. ```APIDOC ## exec.exec(command, args, options) ### Description Executes an external command. ### Parameters - **command** (string) - Required - The command to execute. - **args** (string[]) - Optional - Arguments for the command. - **options** (object) - Optional - Execution options including `listeners`, `silent`, `ignoreReturnCode`, `cwd`, and `env`. ``` -------------------------------- ### Inspect GitHub State Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/troubleshooting.md Display the contents of the GITHUB_STATE file to view saved key-value pairs. ```bash # In upload phase cat $GITHUB_STATE | head -20 ``` -------------------------------- ### Skip Push Entirely Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/examples-and-patterns.md Configures the action to pull from the cache without pushing any artifacts. Ideal for PR builds or testing cache infrastructure safely. ```yaml name: Test on: [pull_request] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: cachix/cachix-action@v17 with: name: public-cache skipPush: true - run: nix build ``` -------------------------------- ### Configure Daemon Mode for Cachix Action Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/examples-and-patterns.md Toggle between daemon mode for performance and store scan mode for compatibility. Daemon mode is the default and attempts to use the daemon before falling back to a store scan. ```yaml # Daemon mode (default, efficient) - uses: cachix/cachix-action@v17 with: name: mycache authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} useDaemon: true cachixArgs: "-j16" # Increase parallelism # Store scan mode (fallback, compatible) - uses: cachix/cachix-action@v17 with: name: mycache authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} useDaemon: false cachixArgs: "-j8" ``` -------------------------------- ### Execute Direct Path Push Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/workflow-execution.md Pushes specified paths directly using the Cachix binary without diffing. ```typescript await exec.exec(cachixBin, [ "push", ...splitArgs(cachixArgs), name, ...splitArgs(pathsToPush), ]); ``` -------------------------------- ### Command Execution with @actions/exec Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/github-actions-integration.md Executes external commands with options for output capture, suppression, and environment configuration. ```typescript import * as exec from "@actions/exec"; // Simple execution await exec.exec("cachix", ["use", "mycache"]); // Capture output let output = ""; await exec.exec("cachix", ["--version"], { listeners: { stdout: (data: Buffer) => { output += data.toString(); }, }, }); // Suppress output await exec.exec("id", ["-Gn", user], { silent: true, }); ``` -------------------------------- ### Fetch Trusted Users Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/api-reference-functions.md Queries the Nix configuration to retrieve the list of trusted users. ```typescript async function fetchTrustedUsers(): Promise ``` -------------------------------- ### Handle store enumeration failure Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/store-scan-mode.md Logs a GitHub Actions error if the store listing script or sorting operation fails, typically indicating filesystem issues. ```bash if postBuildPaths=$("$(dirname "$0")"/list-nix-store.sh | sort); then ... else echo "::error::Failed to list post-build store paths." fi ``` -------------------------------- ### Format Signing Key Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/troubleshooting.md Convert a multi-line signing key to a single-line base64 format to avoid GitHub secret escaping issues. ```bash echo $key | base64 | tr -d '\n' ``` -------------------------------- ### GitHub Actions Job Phases Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/github-actions-integration.md Visual representation of the job lifecycle phases where the action executes. ```text 1. Pre-job setup ↓ 2. Run step action (main: "dist/index.js") ↓ 3. User workflow steps ↓ 4. Post-job cleanup ↓ 5. Run post actions (post: "dist/index.js") ↓ 6. Cleanup ``` -------------------------------- ### Configure Workflow Run for PRs Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/troubleshooting.md Use workflow_run to handle cache access for forked PRs by triggering on completed builds. ```yaml on: pull_request: workflow_run: workflows: ["Build"] types: [completed] ``` -------------------------------- ### isTrustedUser() Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/api-reference-functions.md Determines if the current user has sufficient permissions to set Nix post-build hooks. ```APIDOC ## isTrustedUser() ### Description Determines if current user can set Nix post-build hooks. ### Signature `async function isTrustedUser(): Promise` ### Return Type `Promise` ``` -------------------------------- ### @actions/core Logging Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/github-actions-integration.md Methods for outputting logs and managing step status in the GitHub Actions UI. ```APIDOC ## Logging Methods - **core.debug(message)**: Outputs a debug message. - **core.info(message)**: Outputs an info message. - **core.warning(message)**: Outputs a warning annotation. - **core.error(message)**: Outputs an error annotation. - **core.setFailed(message)**: Marks the current step as failed. ``` -------------------------------- ### Push Specific Paths to Cache Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/examples-and-patterns.md Use pathsToPush to explicitly define which store paths to upload. This bypasses automatic store scanning and is ideal for scenarios where build outputs are known in advance. ```yaml name: Build Selective on: [push] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: cachix/cachix-action@v17 with: name: mycache authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} pathsToPush: | /nix/store/abc123-my-package /nix/store/def456-my-library - run: nix build ``` -------------------------------- ### Logging and Annotations Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/github-actions-integration.md Writes messages to job logs and GitHub UI, including support for marking steps as failed. ```typescript core.debug("Debug message"); // GitHub Actions Debug annotations core.info("Info message"); // Step output core.warning("Warning message"); // Warning annotation in UI core.error("Error message"); // Error annotation in UI core.setFailed("Error message"); // Mark step as failed ``` -------------------------------- ### Derive Push Strategy Logic Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/configuration.md Logic used to determine the push mode based on provided inputs and environment conditions. ```text if authToken or signingKey provided AND not skipPush: if pathsToPush: pushMode = PushPaths else if useDaemon AND cachixVersion >= 1.7.0 AND user is trusted: pushMode = Daemon else: pushMode = StoreScan (fallback) else: pushMode = None ``` -------------------------------- ### Execute Store Scan Push Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/workflow-execution.md Invokes a shell script to perform a store scan, compute differences, and push results. ```typescript const preBuildPathsFile = core.getState("preBuildPathsFile"); await exec.exec(`${__dirname}/push-paths.sh`, [ cachixBin, cachixArgs, name, preBuildPathsFile, pushFilter, ]); ``` -------------------------------- ### partitionUsersAndGroups(mixedUsers) Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/api-reference-functions.md Splits a list of users and groups into two separate arrays. ```APIDOC ## partitionUsersAndGroups(mixedUsers) ### Description Splits list of users and groups (groups prefixed with `@`) into two arrays. ### Signature `function partitionUsersAndGroups(mixedUsers: string[]): [string[], string[]]` ### Parameters - **mixedUsers** (string[]) - Required - Mixed list of usernames and `@groupname` entries ### Return Type `[string[], string[]]` - Tuple of `[users, groups]` with `@` prefix removed from groups ``` -------------------------------- ### Authenticated Push Configuration Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/examples-and-patterns.md Enables writing to a cache by providing an authentication token via GitHub secrets. ```yaml name: Build and Cache on: [push] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: cachix/cachix-action@v17 with: name: mycache authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} - run: nix build - run: nix flake check # Optional post-build steps ``` -------------------------------- ### Enable Verbose Debugging for Cachix Action Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/examples-and-patterns.md Use these configurations to increase log verbosity for both the Cachix CLI and the GitHub Actions runner. ```yaml - uses: cachix/cachix-action@v17 with: name: mycache authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} cachixArgs: "-j8 --log-level debug" - run: ACTIONS_STEP_DEBUG=true nix build # Also enables GitHub Actions debug output ``` -------------------------------- ### Read inputs at module load time Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/types.md Inputs are retrieved using the core library at the top of the main module. ```typescript const name = core.getInput("name", { required: true }); const extraPullNames = core.getInput("extraPullNames"); const authToken = core.getInput("authToken"); const skipPush = core.getBooleanInput("skipPush"); // ... etc ``` -------------------------------- ### Partition Users and Groups Source: https://github.com/cachix/cachix-action/blob/master/_autodocs/api-reference-functions.md Separates a mixed list of usernames and group names (prefixed with @) into distinct arrays. ```typescript function partitionUsersAndGroups(mixedUsers: string[]): [string[], string[]] ```