### Basic Rust Cache Action Setup Source: https://github.com/swatinem/rust-cache/blob/master/README.md This example demonstrates the basic setup for the Rust Cache Action. It includes checking out the code, installing a Rust toolchain, and then using the action with default settings. Ensure the toolchain is installed before the action runs, as the cache key depends on the current rustc version. ```yaml - uses: actions/checkout@v6 # selecting a toolchain either by action or manual `rustup` calls should happen # before the plugin, as the cache uses the current rustc version as its cache key - run: rustup toolchain install stable --profile minimal - uses: Swatinem/rust-cache@v2 ``` -------------------------------- ### Example Cache Key Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/README.md A concrete example of a cache key, demonstrating the combination of prefix, job type, platform, and environment hash. ```text v0-rust-job-123-Linux-x64-abc12345 ``` -------------------------------- ### Workspace Configuration Example Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/README.md Shows how to configure multiple Cargo workspaces, specifying independent target directories for each. This is useful for monorepos. ```yaml workspaces: | . backend -> target frontend -> custom-build ``` -------------------------------- ### Concrete Cache Key Example Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/architecture.md A specific example of a cache key, demonstrating the application of the defined components. ```text v0-rust-job_id-Linux-x64-a1b2c3d4 ``` -------------------------------- ### Workspace Configuration Example Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/architecture.md Defines how to configure multi-workspace projects by mapping paths to target directories. Each line specifies a workspace root and its corresponding target directory. ```yaml workspaces: | . backend -> target frontend -> ../shared-target ``` -------------------------------- ### Cache Key Structure Example Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/README.md Illustrates the multi-component structure of cache keys used by the action. Components are automatically derived from project details and environment. ```text [prefix] - [job/shared] - [platform] - [environment-hash] ``` -------------------------------- ### Example Usage of GhCache Interface Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/types.md Demonstrates how to use the GhCache interface to restore a cache. It first checks if the feature is available, then attempts to restore the cache using specified paths and keys. This example is useful for retrieving previously stored dependencies. ```typescript const provider = await getCacheProvider(); if (provider.cache.isFeatureAvailable()) { const restoredKey = await provider.cache.restoreCache( ["/home/user/.cargo/registry"], "v0-rust-primary-key", ["v0-rust-fallback-key"] ); if (restoredKey) { console.log(`Restored from ${restoredKey}`); } } ``` -------------------------------- ### Example Usage of PackageDefinition Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/types.md Demonstrates how to iterate through package definitions obtained from workspace methods and log their details. Ensure you have a workspace instance and command format available. ```typescript const members = await workspace.getWorkspaceMembers(cmdFormat); members.forEach(pkg => { console.log(`Package: ${pkg.name}`); console.log(` Version: ${pkg.version}`); console.log(` Path: ${pkg.path}`); console.log(` Targets: ${pkg.targets.join(", ")}`); }); ``` -------------------------------- ### Workspace Input Parsing Example Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/modules.md Shows how the 'workspaces' input string is parsed into a list of Workspace objects, defining root directories and their respective target paths. ```plaintext Input: ". \n backend -> target \n frontend -> build" Result: - Workspace: root=".", target="./target" - Workspace: root="backend", target="backend/target" - Workspace: root="frontend", target="frontend/build" ``` -------------------------------- ### Example RustVersion Parsing Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/types.md Shows the raw output of `rustc -vV` and its corresponding parsed TypeScript object representation for the RustVersion interface. ```text rustc 1.75.0 (1d8b05fc5 2023-12-21) binary: rustc commit-hash: 1d8b05fc5d7fcc4b126e3b659ed28648ad15c796 commit-date: 2023-12-21 host: x86_64-unknown-linux-gnu release: 1.75.0 LLVM version: 17.0.6 ``` ```typescript { host: "x86_64-unknown-linux-gnu", release: "1.75.0", "commit-hash": "1d8b05fc5d7fcc4b126e3b659ed28648ad15c796" } ``` -------------------------------- ### Example Usage of CacheProvider Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/types.md Demonstrates how to obtain a cache provider and use its methods to restore a cache. It logs the provider name and indicates whether the cache hit was exact or partial. ```typescript const provider = await getCacheProvider(); console.log(`Using cache provider: ${provider.name}`); const result = await provider.cache.restoreCache(paths, key, [fallbackKey]); if (result) { console.log(`Cache hit: ${result === key ? "exact" : "partial"}`); } ``` -------------------------------- ### Cache Key Construction Example Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/modules.md Illustrates how the cache key is constructed by concatenating a prefix, a job or shared key, platform information, and an optional environment hash. ```typescript const key = "v0-rust" // prefix + "-my-key" // from shared-key or key input + "-Linux-x64" // os and arch + "-abc12345"; // environment hash ``` -------------------------------- ### Cache Restoration Example in YAML Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/modules.md Demonstrates how to use the Swatinem/rust-cache@v2 action and conditionally echo a message if an exact cache hit is achieved. This is useful for setting up cache-dependent steps in GitHub Actions. ```yaml - uses: Swatinem/rust-cache@v2 id: cache - if: steps.cache.outputs.cache-hit == 'true' run: echo "Got exact cache hit!" ``` -------------------------------- ### Complex Configuration Example Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/usage-patterns.md A comprehensive configuration demonstrating multiple features of the rust-cache action, including per-OS/toolchain caching, conditional saving, workspace crate caching, environment variable caching, and additional directory caching. ```yaml test: runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-latest, macos-latest] toolchain: [stable, beta] steps: - uses: actions/checkout@v6 - uses: dtolnay/rust-toolchain@master with: toolchain: ${{ matrix.toolchain }} - uses: Swatinem/rust-cache@v2 with: # Separate caches per OS and toolchain key: "test-${{ matrix.toolchain }}" # Only save from main branch to avoid cache fill-up save-if: ${{ github.ref == 'refs/heads/main' }} # Cache workspace crates for faster rebuilds cache-workspace-crates: "true" # Include custom environment variables env-vars: "CARGO_BUILD_JOBS" # Cache additional test artifacts cache-directories: ~/.miri - run: cargo test --all build: needs: test runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 - uses: dtolnay/rust-toolchain@master with: toolchain: stable - uses: Swatinem/rust-cache@v2 with: # Reuse test job cache shared-key: "deps-stable" - run: cargo build --release ``` -------------------------------- ### cleanBin Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/api-reference.md Removes newly installed cargo binaries while preserving pre-existing ones. ```APIDOC ## cleanBin(oldBins: Array) ### Description Removes newly installed cargo binaries while preserving pre-existing ones. ### Parameters #### Path Parameters - **oldBins** (string[]) - Required - Filenames of binaries that existed before the action ran ### Request Example ```typescript const existingBins = await getCargoBins(); const oldBinsArray = Array.from(existingBins); // ... later, after build ... await cleanBin(oldBinsArray); // Remove pre-existing binaries ``` ### Response #### Success Response (200) - **void** - This function does not return a value. ### Source `src/cleanup.ts:84` ``` -------------------------------- ### Get Cargo Binaries Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/api-reference.md Lists all executable files in the `$CARGO_HOME/bin` directory. This is used to track binaries present before the action runs, allowing them to be excluded from caching. ```typescript async function getCargoBins(): Promise> ``` ```typescript const existingBins = await getCargoBins(); console.log(`Found ${existingBins.size} existing cargo binaries`); ``` -------------------------------- ### Get External Dependencies Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/api-reference.md Retrieve all packages that are dependencies of the workspace but not members themselves. Requires a command format string. ```typescript const deps = await workspace.getPackagesOutsideWorkspaceRoot("{0}"); console.log(`Workspace depends on ${deps.length} crates`); ``` -------------------------------- ### Example Usage of Packages Type Alias Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/types.md Shows how to declare a variable with the Packages type alias when fetching packages outside the workspace root. This improves code readability and type safety. ```typescript const packages: Packages = await workspace.getPackagesOutsideWorkspaceRoot(cmdFormat); ``` -------------------------------- ### Monitor and Delete Caches using GitHub CLI Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/usage-patterns.md Use the GitHub CLI to list and delete cache entries. This is helpful for managing cache size and troubleshooting specific cache keys. Ensure you have the gh CLI installed and authenticated with a repository token. ```bash # List caches (requires gh CLI and repo token) gh actions-cache list --repo owner/repo # Delete specific cache gh actions-cache delete --repo owner/repo -k "cache-key" ``` -------------------------------- ### Clean Cargo Binaries Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/api-reference.md Removes newly installed cargo binaries while preserving pre-existing ones. Pass an array of filenames that existed before the action ran to avoid removing them. ```typescript async function cleanBin(oldBins: Array): void ``` ```typescript const existingBins = await getCargoBins(); const oldBinsArray = Array.from(existingBins); // ... later, after build ... await cleanBin(oldBinsArray); // Remove pre-existing binaries ``` -------------------------------- ### Get Workspace Members Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/api-reference.md Retrieve all local packages within the Cargo workspace. Requires a command format string for execution. ```typescript const members = await workspace.getWorkspaceMembers("{0}"); console.log(`Workspace has ${members.length} members`); members.forEach(pkg => { console.log(` ${pkg.name} v${pkg.version} at ${pkg.path}`); }); ``` -------------------------------- ### Workspace Constructor Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/api-reference.md Creates a new workspace configuration with the specified root and target directories. ```APIDOC ## Workspace Constructor ### Description Creates a new workspace configuration. ### Parameters #### Path Parameters - **root** (string) - Required - Absolute path to the workspace root directory - **target** (string) - Required - Absolute path to the workspace target directory ### Request Example ```typescript const ws = new Workspace("/path/to/project", "/path/to/project/target"); ``` ``` -------------------------------- ### Print Cache Configuration Details Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/api-reference.md Prints detailed configuration information to the GitHub Actions log. Requires a CacheProvider instance. ```typescript const provider = await getCacheProvider(); config.printInfo(provider); ``` -------------------------------- ### Cargo Metadata Command Formatting Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/modules.md Demonstrates how to format the `cargo metadata` command using `cmd-format` to support different execution environments like Nix develop or Docker. ```typescript // Without formatting: cargo metadata --all-features // With "nix develop -c {0}": nix develop -c cargo metadata --all-features // With "docker exec app {0}": docker exec app cargo metadata --all-features ``` -------------------------------- ### Get Cache Provider Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/api-reference.md Retrieves the configured cache provider based on the 'cache-provider' action input. Supports 'github' and 'warpbuild' providers. Throws an error for invalid provider names. ```typescript async function getCacheProvider(): Promise ``` ```typescript const provider = await getCacheProvider(); console.log(`Using ${provider.name} cache provider`); const cacheKey = await provider.cache.restoreCache(paths, key, [fallbackKey]); ``` -------------------------------- ### getCargoBins() Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/api-reference.md Lists all executable files within the `$CARGO_HOME/bin` directory. This is used to identify binaries present before the action runs, for exclusion from caching. ```APIDOC ## getCargoBins() ### Description Lists all executable files currently in the `$CARGO_HOME/bin` directory. Used to track which binaries were present before the action runs, so they can be excluded from caching. ### Method ```typescript async function getCargoBins(): Promise> ``` ### Returns `Promise>` - Set of binary filenames (e.g., `{"rustc", "cargo", "clippy-driver"}`) ### Example ```typescript const existingBins = await getCargoBins(); console.log(`Found ${existingBins.size} existing cargo binaries`); ``` ``` -------------------------------- ### Key Utility Functions Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/README.md Provides essential utility functions for interacting with the cache, environment, and file system. ```APIDOC ## Key Functions ### Cache Provider - `async getCacheProvider(): Promise`: Retrieves the configured cache provider. ### Command Execution - `async getCmdOutput(format: string, cmd: string): Promise`: Executes a command and returns its output. ### File System Operations - `async exists(path: string): Promise`: Checks if a file or directory exists. ### Cache Status - `isCacheUpToDate(): boolean`: Checks if the cache is up-to-date. ### Binary Management - `async getCargoBins(): Promise>`: Retrieves a set of Cargo binary names. ### Cleanup Operations - `async cleanTargetDir(target: string, packages: Packages): void`: Cleans the target directory. - `async cleanRegistry(packages: Packages, crates?: boolean): void`: Cleans the package registry. - `async cleanBin(oldBins: string[]): void`: Cleans old binary files. - `async cleanGit(packages: Packages): void`: Cleans Git-related cache entries. ``` -------------------------------- ### Get Filtered Packages Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/api-reference.md Internal method to retrieve packages matching a specific filter using `cargo metadata`. Accepts a command format, a filter function, and optional extra arguments. ```typescript async getPackages( cmdFormat: string, filter: (p: Meta["packages"][0]) => boolean, extraArgs?: string ): Promise ``` -------------------------------- ### CacheConfig.printInfo() Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/api-reference.md Prints detailed configuration information to the GitHub Actions log, organized into collapsible groups for better readability. ```APIDOC ## printInfo(cacheProvider: CacheProvider) ### Description Prints the complete configuration details to the GitHub Actions log, organized into groups. ### Method `printInfo(cacheProvider: CacheProvider): void` ### Parameters #### Parameters - **cacheProvider** (`CacheProvider`) - The cache provider being used (github or warpbuild) ### Output Logs the following information to GitHub Actions: - Cache provider name - Workspace roots - Cache paths - Restore key - Full cache key - Key prefix - Rust versions considered - Environment variables considered - Manifest files considered ### Example ```typescript const provider = await getCacheProvider(); config.printInfo(provider); ``` ``` -------------------------------- ### CacheConfig.new() Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/api-reference.md Constructs a new CacheConfig instance by reading GitHub Action inputs. It computes cache keys, workspace configurations, and determines paths to cache. ```APIDOC ## CacheConfig.new() ### Description Constructs a new `CacheConfig` instance with all the paths and keys based on GitHub Action inputs. This method is called during the main restore phase to read action inputs and compute cache keys. ### Method `static async new(): Promise` ### Returns `Promise` - A fully initialized configuration object ### Throws - Error if `cmd-format` contains invalid placeholder (must contain exactly one `{0}`) - Error if command execution fails during rust version detection ### Example ```typescript const config = await CacheConfig.new(); config.printInfo(cacheProvider); console.log(`Cache key: ${config.cacheKey}`); console.log(`Paths to cache: ${config.cachePaths}`); ``` ``` -------------------------------- ### Format Command Execution Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/configuration.md Use `cmd-format` to specify a format string for running commands, allowing execution within specific environments like Nix shells or Docker containers. The string must contain exactly one `{0}` placeholder. ```yaml - uses: Swatinem/rust-cache@v2 with: cmd-format: "nix develop -c {0}" # All cargo/rustc commands run in Nix shell ``` -------------------------------- ### Cache Configuration State Management Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/modules.md Demonstrates how to save and retrieve cache configuration state between the restore and save phases of the GitHub Action. This avoids re-reading inputs and re-computing keys in the post-action phase. ```typescript // In restore phase: const config = await CacheConfig.new(); config.saveState(); // Persists to GitHub Actions state // In save phase: const config = CacheConfig.fromState(); // Retrieves saved config ``` -------------------------------- ### Dynamic Cache Provider Import Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/architecture.md Demonstrates how the cache provider is dynamically imported at runtime based on the 'cache-provider' input. It handles 'github' and 'warpbuild' providers, throwing an error for invalid inputs. ```typescript const cacheProvider = core.getInput("cache-provider"); switch (cacheProvider) { case "github": cache = await import("@actions/cache"); break; case "warpbuild": cache = await import("@actions/warpbuild-cache"); break; default: throw new Error(`Invalid cache provider: ${cacheProvider}`); } ``` -------------------------------- ### Create Workspace Configuration Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/api-reference.md Instantiate a Workspace object with the root and target directories of your Cargo project. ```typescript const ws = new Workspace("/path/to/project", "/path/to/project/target"); ``` -------------------------------- ### Cargo Metadata for Package Discovery Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/architecture.md Illustrates commands to discover workspace members and external dependencies using `cargo metadata`. The `--all-features` and `--format-version 1` flags are used for comprehensive metadata retrieval. ```typescript // Workspace members (local packages) cargo metadata --all-features --format-version 1 --no-deps → Returns only local crates in Cargo.toml ``` ```typescript // External dependencies (remote packages) cargo metadata --all-features --format-version 1 → Returns all packages; filter for non-workspace ones ``` -------------------------------- ### Execute Command and Capture Output Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/api-reference.md Executes a command, optionally with formatting, and captures its standard output. Useful for running shell commands within the action. ```typescript async function getCmdOutput( cmdFormat: string, cmd: string, options?: exec.ExecOptions ): Promise ``` ```typescript // Basic usage const version = await getCmdOutput("{0}", "rustc --version"); console.log(version); // "rustc 1.75.0 ..." // With command formatting (e.g., for Nix) const output = await getCmdOutput( "nix develop -c {0}", "cargo metadata", { cwd: "/path/to/project" } ); ``` -------------------------------- ### Restore Phase Data Flow in Rust Cache Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/modules.md Illustrates the data flow during the cache restore phase. This includes user interaction, GitHub Actions calls, and internal module operations like cache retrieval and state saving. ```mermaid graph TD User[User runs workflow] GA[GitHub Actions calls dist/restore.js] run[restore.ts:run()] getProvider[getCacheProvider() → CacheProvider] configNew[CacheConfig.new() → Reads inputs, computes keys] getRustVersions[getRustVersions() → ["1.75.0", "1.76.0"]] getCargoBins[getCargoBins() → ["rustc", "cargo"]] globFiles[globFiles() → Manifest files] restoreCache[cacheProvider.cache.restoreCache() → Download cache] saveState[config.saveState() → Persist to GitHub state] setOutput[setOutput("cache-hit", true/false)] Build[Build happens (CARGO_INCREMENTAL=0)] User --> GA --> run run --> getProvider run --> configNew configNew --> getRustVersions configNew --> getCargoBins configNew --> globFiles run --> restoreCache run --> saveState run --> setOutput setOutput --> Build ``` -------------------------------- ### Dynamically Import Cache Provider Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/modules.md Use `getCacheProvider` to dynamically import and resolve the configured cache provider. It supports 'github' (using '@actions/cache') and 'warpbuild' (using '@actions/warpbuild-cache') providers, both implementing the `GhCache` interface. ```typescript const provider = await getCacheProvider(); ``` -------------------------------- ### getCmdOutput() Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/api-reference.md Executes a command with optional formatting and captures its standard output. It's useful for running shell commands and processing their results within the application. ```APIDOC ## getCmdOutput() ### Description Executes a command with optional formatting and captures its stdout output. ### Method ```typescript async function getCmdOutput( cmdFormat: string, cmd: string, options?: exec.ExecOptions ): Promise ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **cmdFormat** (`string`) - Required - Format string where `{0}` is replaced with the command - **cmd** (`string`) - Required - The command to execute - **options** (`exec.ExecOptions`) - Optional - Additional options for exec (cwd, env, etc.) ### Returns `Promise` - Captured stdout, trimmed ### Request Example ```typescript // Basic usage const version = await getCmdOutput("{0}", "rustc --version"); console.log(version); // "rustc 1.75.0 ..." // With command formatting (e.g., for Nix) const output = await getCmdOutput( "nix develop -c {0}", "cargo metadata", { cwd: "/path/to/project" } ); ``` ### Response #### Success Response (200) `string` - Captured stdout, trimmed #### Response Example ```json "rustc 1.75.0 ..." ``` ``` -------------------------------- ### exists() Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/api-reference.md Checks if a file or directory exists at the specified path. Returns a boolean indicating existence. ```APIDOC ## exists() ### Description Checks if a file or directory exists at the given path. ### Method ```typescript async function exists(path: string): Promise ``` ### Parameters - **path** (`string`) - Required - Path to check ### Returns `Promise` - True if the path exists and is accessible ### Example ```typescript if (await exists("/path/to/file.txt")) { console.log("File exists"); } ``` ``` -------------------------------- ### Key Utility Functions Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/README.md Provides a collection of essential asynchronous and synchronous utility functions for cache management, command execution, and file system operations. ```typescript async function getCacheProvider(): Promise async function getCmdOutput(format: string, cmd: string): Promise async function exists(path: string): Promise function isCacheUpToDate(): boolean async function getCargoBins(): Promise> ``` ```typescript async function cleanTargetDir(target: string, packages: Packages): void async function cleanRegistry(packages: Packages, crates?: boolean): void async function cleanBin(oldBins: string[]): void async function cleanGit(packages: Packages): void ``` -------------------------------- ### Enable Caching on Failure Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/usage-patterns.md Configure the action to save the cache even if the build process fails. This is beneficial for debugging purposes, preserving partial artifacts. ```yaml - uses: Swatinem/rust-cache@v2 with: cache-on-failure: "true" ``` -------------------------------- ### Docker Container Command Format Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/architecture.md This command format allows running cargo/rustc commands inside a Docker container, mounting the local .cargo directory to the container. ```yaml cmd-format: "docker run -v /home/user/.cargo:/root/.cargo app {0}" ``` -------------------------------- ### Configure Multiple Workspaces and Target Directories Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/configuration.md Define multiple Cargo workspaces and their corresponding target directories. Each entry specifies a workspace path and its relative target path. ```yaml - uses: Swatinem/rust-cache@v2 with: workspaces: | . backend -> target frontend -> custom_build ``` -------------------------------- ### Nix Flake Environment Command Format Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/architecture.md Use this command format to execute cargo/rustc commands within a Nix flake environment. It prepends 'nix develop -c ' to the command. ```yaml cmd-format: "nix develop -c {0}" ``` -------------------------------- ### Configuring Rust Cache Action Options Source: https://github.com/swatinem/rust-cache/blob/master/README.md This snippet shows various configuration options for the Rust Cache Action. It covers setting custom cache keys, including environment variables in the cache key, specifying workspaces and additional directories to cache, and controlling whether targets and crates are cached. Use these options to fine-tune caching behavior. ```yaml with: # The prefix cache key, this can be changed to start a new cache manually. # default: "v0-rust" prefix-key: "" # A cache key that is used instead of the automatic `job`-based key, # and is stable over multiple jobs. # default: empty shared-key: "" # An additional cache key that is added alongside the automatic `job`-based # cache key and can be used to further differentiate jobs. # default: empty key: "" # If the automatic `job`-based cache key should include the job id. # default: "true" add-job-id-key: "" # Whether the a hash of the rust environment should be included in the cache key. # This includes a hash of all Cargo.toml/Cargo.lock files, rust-toolchain files, # and .cargo/config.toml files (if present), as well as the specified 'env-vars'. # default: "true" add-rust-environment-hash-key: "" # A whitespace separated list of env-var *prefixes* who's value contributes # to the environment cache key. # The env-vars are matched by *prefix*, so the default `RUST` var will # match all of `RUSTC`, `RUSTUP_*`, `RUSTFLAGS`, `RUSTDOC_*`, etc. # default: "CARGO CC CFLAGS CXX CMAKE RUST" env-vars: "" # The cargo workspaces and target directory configuration. # These entries are separated by newlines and have the form # `$workspace -> $target`. The `$target` part is treated as a directory # relative to the `$workspace` and defaults to "target" if not explicitly given. # default: ". -> target" workspaces: "" # Additional non workspace directories to be cached, separated by newlines. cache-directories: "" # Determines whether workspace `target` directories are cached. # If `false`, only the cargo registry will be cached. # default: "true" cache-targets: "" # Determines if the cache should be saved even when the workflow has failed. # default: "false" cache-on-failure: "" # Determines which crates are cached. # If `true` all crates will be cached, otherwise only dependent crates will be cached. # Useful if additional crates are used for CI tooling. # default: "false" cache-all-crates: "" # Similar to cache-all-crates. # If `true` the workspace crates will be cached. # Useful if the workspace contains libraries that are only updated sporadically. # default: "false" cache-workspace-crates: "" # Determines whether the cache should be saved. # If `false`, the cache is only restored. # Useful for jobs where the matrix is additive e.g. additional Cargo features, # or when only runs from `master` should be saved to the cache. # default: "true" save-if: "" # To only cache runs from `master`: save-if: ${{ github.ref == 'refs/heads/master' }} # Determines whether the cache should be restored. # If `true` the cache key will be checked and the `cache-hit` output will be set # but the cache itself won't be restored # default: "false" lookup-only: "" # Specifies what to use as the backend providing cache # Can be set to "github", or "warpbuild" # default: "github" cache-provider: "" # Determines whether to cache the ~/.cargo/bin directory. # default: "true" cache-bin: "" # A format string used to format commands to be run, i.e. `rustc` and `cargo`. # Must contain exactly one occurance of `{0}`, which is the formatting fragment # that will be replaced with the `rustc` or `cargo` command. This is necessary # when using Nix or other setup that requires running these commands within a # specific shell, otherwise the system `rustc` and `cargo` will be run. # default: "{0}" cmd-format: "" # To run within a Nix shell (using the default dev shell of a flake in the repo root): cmd-format: nix develop -c {0} ``` -------------------------------- ### Create New CacheConfig Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/api-reference.md Constructs a new CacheConfig instance using GitHub Actions inputs. Use this during the main restore phase. ```typescript const config = await CacheConfig.new(); config.printInfo(cacheProvider); console.log(`Cache key: ${config.cacheKey}`); console.log(`Paths to cache: ${config.cachePaths}`); ``` -------------------------------- ### CacheConfig.fromState() Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/api-reference.md Retrieves the cache configuration from the GitHub Actions state store. This is used in the post-action phase to restore configuration saved during the main phase. ```APIDOC ## CacheConfig.fromState() ### Description Reads and returns the cache configuration from the GitHub Actions state store. This is called in the post-action phase to restore the configuration that was saved during the main phase. ### Method `static fromState(): CacheConfig` ### Returns `CacheConfig` - The configuration as saved by `saveState()` ### Throws Error if the state is not present in the actions state store ### Example ```typescript try { const config = CacheConfig.fromState(); console.log(`Restoring with key: ${config.cacheKey}`); } catch (e) { console.error('Config not found in state'); } ``` ``` -------------------------------- ### Select Cache Provider Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/configuration.md Specify the `cache-provider` to use either GitHub Actions cache (default) or WarpBuild cache. This allows selection of alternative cache providers for different CI backends. ```yaml - uses: Swatinem/rust-cache@v2 with: cache-provider: "warpbuild" ``` -------------------------------- ### Rust Cache for Multi-Workspace Projects Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/usage-patterns.md Manage caching for monorepos or projects with multiple workspaces. Each workspace's target directory is cached independently, allowing for granular cache management. ```yaml - uses: Swatinem/rust-cache@v2 with: workspaces: | backend -> target frontend -> target shared -> target ``` -------------------------------- ### CacheConfig Class Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/README.md Provides configuration for the cache, including keys, paths, and workspace settings. It offers methods to create, load, and manage cache state. ```APIDOC ## CacheConfig ### Description Manages cache configuration, including cache keys, restore keys, cache paths, workspace definitions, and binary caching options. ### Static Methods - `static async new(): Promise`: Creates a new CacheConfig instance. - `static fromState(): CacheConfig`: Creates a CacheConfig instance from the current state. ### Instance Methods - `printInfo(provider: CacheProvider): void`: Prints cache information for a given provider. - `saveState(): void`: Saves the current cache state. ### Properties - `cacheKey: string`: The key used for caching. - `restoreKey: string`: The key used for restoring from cache. - `cachePaths: string[]`: An array of paths to be cached. - `workspaces: Workspace[]`: An array of Workspace objects. - `cacheBin: boolean`: Flag to indicate if binaries should be cached. - `cargoBins: string[]`: An array of Cargo binary paths to be cached. ``` -------------------------------- ### Rust Cache with Nix Environment Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/configuration.md Configures the rust-cache action to execute all Cargo and Rustc commands within a Nix development environment. This ensures consistent build environments managed by Nix. ```yaml - uses: Swatinem/rust-cache@v2 with: cmd-format: "nix develop -c {0}" ``` -------------------------------- ### Docker Container Environment for Rust Cache Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/usage-patterns.md Configure the Rust cache action to run commands within a Docker container, assuming the cargo home is mounted from the host. This is useful for consistent build environments. ```yaml - uses: Swatinem/rust-cache@v2 with: cmd-format: "docker exec builder {0}" ``` -------------------------------- ### Verify Cache Hit Status in GitHub Actions Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/usage-patterns.md Check the 'cache-hit' output from the Swatinem/rust-cache action to determine if a cache hit occurred. This is crucial for verifying that the cache is being used effectively. ```yaml - uses: Swatinem/rust-cache@v2 id: cache - run: | if [ "${{ steps.cache.outputs.cache-hit }}" = "true" ]; then echo "Cache HIT" else echo "Cache MISS" fi ``` -------------------------------- ### Execute Command and Capture Output Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/modules.md Use `getCmdOutput` to execute shell commands. Supports direct execution or execution within a specified context like Nix shells. The format string is essential for environments requiring specific execution contexts. ```typescript const version = await getCmdOutput("{0}", "rustc --version"); ``` ```typescript const output = await getCmdOutput( "nix develop -c {0}", "cargo metadata", { cwd: "/workspace" } ); ``` -------------------------------- ### Basic Rust Cache Configuration Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/configuration.md Caches all Rust dependencies and build artifacts with default settings. A cache hit occurs if the Rust version and manifests remain unchanged between jobs. ```yaml - uses: Swatinem/rust-cache@v2 ``` -------------------------------- ### Nix Flake Integration for Rust Commands Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/usage-patterns.md Integrate the Rust cache action with Nix flakes. This ensures all cargo and rustc commands are executed within the Nix development shell, using the specified command format. ```yaml - uses: actions/checkout@v6 - uses: Swatinem/rust-cache@v2 with: cmd-format: "nix develop -c {0}" ``` ```shell nix develop -c cargo metadata nix develop -c rustc -vV ``` -------------------------------- ### Discover Workspace Members and External Dependencies Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/modules.md Use `getWorkspaceMembers` to retrieve local packages within the workspace and `getPackagesOutsideWorkspaceRoot` to fetch external packages from registries or git. ```typescript const members = await workspace.getWorkspaceMembers(cmdFormat); // Returns only packages from Cargo.toml [workspace.members] const deps = await workspace.getPackagesOutsideWorkspaceRoot(cmdFormat); // Returns all packages not in the workspace root ``` -------------------------------- ### Add Specific Key Component with `key` Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/configuration.md Use the `key` input to add an extra component to the cache key, differentiating jobs further. This is only used if `shared-key` is not set. ```yaml - uses: Swatinem/rust-cache@v2 with: key: "postgres" # Adds "postgres" to cache key for database-specific tests ``` -------------------------------- ### Check File/Directory Existence Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/api-reference.md Asynchronously checks if a file or directory exists at a given path. Returns a boolean indicating existence. ```typescript async function exists(path: string): Promise ``` ```typescript if (await exists("/path/to/file.txt")) { console.log("File exists"); } ``` -------------------------------- ### CacheConfig.saveState() Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/api-reference.md Saves the current configuration to the GitHub Actions state store, allowing it to be retrieved later in the post-action phase. ```APIDOC ## saveState() ### Description Saves the configuration to the GitHub Actions state store. This persists the configuration so it can be retrieved in the post-action phase via `fromState()`. ### Method `saveState(): void` ### Returns `void` ### Usage Called at the end of the restore phase to preserve configuration for the save phase. ### Example ```typescript const config = await CacheConfig.new(); // ... process cache restoration ... config.saveState(); // Persist for post-action phase ``` ``` -------------------------------- ### Cache All Downloaded Crates Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/configuration.md Set `cache-all-crates` to `true` to cache all downloaded crates, including those used for CI tooling or utility purposes, not just project dependencies. ```yaml - uses: Swatinem/rust-cache@v2 with: cache-all-crates: "true" # Cache all crates including CI tools ``` -------------------------------- ### Workspace Class Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/README.md Represents a workspace within the project, used for managing package information and retrieving members. ```APIDOC ## Workspace ### Description Represents a project workspace, allowing retrieval of workspace members and packages outside the root. ### Constructor - `constructor(root: string, target: string)`: Initializes a new Workspace instance. ### Methods - `async getWorkspaceMembers(cmdFormat: string): Promise`: Retrieves all members of the workspace. - `async getPackagesOutsideWorkspaceRoot(cmdFormat: string): Promise`: Retrieves packages that are not located within the workspace root. ``` -------------------------------- ### Rust Cache with Custom Target Directory Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/usage-patterns.md Configure the cache to use a custom directory for build artifacts instead of the default './target'. This is useful for projects with non-standard directory structures. ```yaml - uses: Swatinem/rust-cache@v2 with: workspaces: ". -> build" ``` -------------------------------- ### Save and Retrieve GitHub Actions State Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/architecture.md Demonstrates saving configuration to GitHub Actions state in the restore phase and retrieving it in the save phase. State is persisted between workflow steps for the duration of the run. ```typescript // In restore phase config.saveState(); // Stores JSON in GitHub Actions internal state ``` ```typescript // In save phase const config = CacheConfig.fromState(); // Retrieves saved config ``` -------------------------------- ### getPackages Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/api-reference.md Internal method that retrieves packages matching the provided filter using `cargo metadata`. ```APIDOC ## getPackages() ### Description Internal method that retrieves packages matching the provided filter using `cargo metadata`. ### Parameters #### Query Parameters - **cmdFormat** (string) - Required - Format string for command execution - **filter** ((p) => boolean) - Required - Predicate function to filter packages - **extraArgs** (string) - Optional - Additional arguments to pass to `cargo metadata` ### Returns - **Promise** - Filtered array of package definitions ### Note This method uses `cargo metadata --all-features --format-version 1`. Only packages with saveable targets (lib, cdylib, dylib, rlib, staticlib, proc-macro) are included. ``` -------------------------------- ### Include Custom Environment Variables in Cache Keys Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/usage-patterns.md Customize cache keys by including specific environment variables. This ensures that changes in these variables are reflected in the cache, aiding in cache invalidation and management. ```yaml - uses: Swatinem/rust-cache@v2 with: env-vars: "MYLIB_VERSION TARGET_PLATFORM" env: MYLIB_VERSION: "2.1.0" TARGET_PLATFORM: "wasm32-unknown-unknown" ``` -------------------------------- ### Share Cache Across GitHub Actions Matrix Builds Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/usage-patterns.md Configure the Rust cache action with 'shared-key' and 'add-job-id-key: "false"' to ensure all matrix combinations utilize a single, shared cache. ```yaml test: runs-on: ubuntu-latest strategy: matrix: feature: [feature1, feature2, feature3] steps: - uses: Swatinem/rust-cache@v2 with: shared-key: "all-features" add-job-id-key: "false" - run: cargo test --features ${{ matrix.feature }} ``` -------------------------------- ### CARGO_HOME Constant Definition Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/api-reference.md Defines the path to the Cargo home directory. It defaults to '~/.cargo' but can be overridden by the CARGO_HOME environment variable. ```typescript export const CARGO_HOME = process.env.CARGO_HOME || path.join(HOME, ".cargo") ``` -------------------------------- ### Restore CacheConfig from State Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/api-reference.md Reads and returns the cache configuration from the GitHub Actions state store. Use this in the post-action phase. ```typescript try { const config = CacheConfig.fromState(); console.log(`Restoring with key: ${config.cacheKey}`); } catch (e) { console.error('Config not found in state'); } ``` -------------------------------- ### getCacheProvider() Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/api-reference.md Retrieves the configured cache provider based on the `cache-provider` action input. It supports 'github' and 'warpbuild' providers and throws an error for invalid provider names. ```APIDOC ## getCacheProvider() ### Description Returns the configured cache provider based on the `cache-provider` action input. ### Method ```typescript async function getCacheProvider(): Promise ``` ### Returns `Promise` - Object with `name` and `cache` properties ### Supported Providers - `"github"` - GitHub Actions cache (@actions/cache) - `"warpbuild"` - WarpBuild cache (@actions/warpbuild-cache) ### Throws Error if the provider name is invalid ### Example ```typescript const provider = await getCacheProvider(); console.log(`Using ${provider.name} cache provider`); const cacheKey = await provider.cache.restoreCache(paths, key, [fallbackKey]); ``` ``` -------------------------------- ### Minimal Rust Cache (Registry Only) Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/configuration.md Configures the action to only cache the Cargo registry, excluding build artifacts. This is useful for reducing cache size when build artifacts are not frequently reused. ```yaml - uses: Swatinem/rust-cache@v2 with: cache-targets: "false" cache-bin: "false" ``` -------------------------------- ### Save Phase Data Flow in Rust Cache Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/modules.md Details the data flow during the cache save phase, triggered after a post-action. It covers checking if saving is needed, restoring configuration, cleaning artifacts, and uploading the cache. ```mermaid graph TD Trigger[Post-action triggered (success or cache-on-failure)] GA[GitHub Actions calls dist/save.js] run[save.ts:run()] isCacheUpToDate[isCacheUpToDate() → Check if save needed] configFromState[CacheConfig.fromState() → Restore persisted config] getPackages[workspace.getPackagesOutsideWorkspaceRoot() → Get dependencies] cleanTargetDir[cleanTargetDir(packages) → Remove unused artifacts] cleanRegistry[cleanRegistry(packages) → Remove unused crates] cleanBin[cleanBin(oldBins) → Remove pre-existing binaries] cleanGit[cleanGit(packages) → Remove unused git repos] saveCache[cacheProvider.cache.saveCache() → Upload cleaned cache] Success[Cache saved and available for next run] Trigger --> GA --> run run --> isCacheUpToDate run --> configFromState run --> getPackages run --> cleanTargetDir run --> cleanRegistry run --> cleanBin run --> cleanGit run --> saveCache saveCache --> Success ``` -------------------------------- ### Configuration Flags for Rust Cache Module Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/modules.md Reads configuration flags from the GitHub Actions environment to determine caching behavior. Use 'true' to enable workspace crate caching or caching of all crates. ```typescript const workspaceCrates = core.getInput("cache-workspace-crates") === "true"; const allCrates = core.getInput("cache-all-crates") === "true"; // Only clean if cache wasn't up-to-date if (isCacheUpToDate()) return; // Cache already saved, skip save phase ``` -------------------------------- ### Bash Script Wrapper Command Format Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/architecture.md Use this format to wrap cargo/rustc commands within a bash script. This can be useful for more complex command execution logic. ```yaml cmd-format: "bash -c '{0}'" ``` -------------------------------- ### Define RustVersion Interface Source: https://github.com/swatinem/rust-cache/blob/master/_autodocs/types.md Represents a Rust toolchain version parsed from `rustc -vV` output. It includes host, release version, and commit hash. ```typescript interface RustVersion { host: string; release: string; "commit-hash": string; } ```