cargo-purifier full guide

Detailed setup, dependency management, build commands, and troubleshooting. Start with the overview for the initial commands; use the sections below for the complete setup and behavior. cargo-purifier is classified at maturity tier 2 (see tier assessment for details).

Contents

Setup and activation

Use the overview’s Quickstart for the initial command sequence. The setup details below apply to that workflow.

Commit the lockfiles that the lock command writes, including the build tool’s own lockfile when it has one. Keep using the project’s usual build, test and editor commands with this setup. Nix provides the locked dependencies; the development commands above run outside the Nix sandbox. No project Nix files are needed for this workflow.

Sandboxed builds are an optional next step.

The shell provides the cargo wrapper. Use it for the locked development workflow. With no purifier lockfile, it warns on standard error and runs the ordinary tool with impure resolution.

Install these packages through your usual Nix configuration.

Version compatibility

Tool or language Packaged defaults Tested versions
Cargo 1.99.0 1.41.0
Rust 1.99.0 1.41.0

Operating systems and architectures

OS CPU architecture Packaged toolchain Recorded workflow
macOS ARM64 Yes Tested
Linux ARM64 Yes Not recorded
Linux x86-64 Yes Tested

Development loop

The cargo-purifier package holds the command, a cargo wrapper and a rust-analyzer wrapper. In a workspace with a cargo-purifier.lock.json, the wrapper’s cargo build, check, run, test, bench, doc, clippy, rustc, rustdoc, tree, metadata, package and fix read every registry and git source from a vendored copy that Nix builds from the two lockfiles, and run with --offline. Incremental compilation works as usual. In projects with Nix inputs, add, remove and update also resolve against those inputs. Run cargo-purifier lock after changing dependencies.

To add a dependency, run cargo add, then cargo-purifier lock. To upgrade, run cargo-purifier update, which runs cargo update for every package, or for the packages it names, and then locks the result. Commit both lockfiles either way. cargo-purifier lock keeps cargo’s resolution: it runs cargo fetch, which brings Cargo.lock up to date with the manifests and changes no more than it must. It then hashes each git checkout with nix-prefetch-git, submodules included, and reads the index configuration of each registry other than crates.io. A relock of an unchanged workspace reproduces the lockfile byte for byte, and hashes only the git checkouts that changed. A command that needs a download the lockfiles do not record stops, and names cargo-purifier lock. CARGO_PURIFIER=0 runs plain cargo, which downloads what it needs.

The Nix build

cargo-purifier.buildCargoProject { src, lockFile ? …, cargoLock ? …, fetchers ? { }, ... } returns:

Attribute What it is
packages.<package> every workspace package with a binary or an installable library, built with cargo build --package <package>
packages.<package>.bins.<binary> $out/bin/<binary>
packages.<package>.libs."lib<name>.so", ."lib<name>.a" the libraries of cdylib, dylib and staticlib targets
tests cargo test --workspace, in the sandbox
release.<package> the .crate of cargo package --package <package>; release.<package>.crate is its path
fetches every download: the entries of the lock in memory
vendor the vendored sources every build reads

Evaluation knows every attribute and path from the lockfiles, without building anything or importing generated Nix code. A plain Rust library (rlib) is only usable compiled into something, so it has a release and no package.

The lock in memory

lib.cargo-purifier.readLock { src, workspace ? ".", lockFile ? …, cargoLock ? … } reads both lockfiles into the shape every purifier shares: purifier, entries, outputs and problems. entries are download entries of the purifier library: a file entry per registry crate, from the checksum in Cargo.lock, and a git entry per checkout. Each also carries cargo = { source, name, version }. Cargo downloads are the same on every system, so no entry has systems. outputs names every workspace package, with its binaries, library and version, and problems holds the reasons the lockfiles cannot be used. Reading never fails, except on a purifier lockfile that looks like a JSON object and does not parse, which Nix cannot catch; that error still names the file and the fix. The builder passes the lock to the library’s checkLock, and builds the entries entriesFor gives for the host system.

fetchers.fetchurl and fetchers.fetchgit replace nixpkgs’ fetchers for every download, crates.io included, for a mirror or credentials. nix/lib/build-cargo-project.nix documents the other arguments: doCheck also runs each package’s tests in its build, and srcFilter chooses the files of a path src the builds see. The builder takes the packages it builds with by name from the scope, so cargo-purifier.overrideScope (final: prev: { rustPlatform = …; }) builds with another Rust toolchain, and buildCargoProject.override replaces a package for the builder alone.

Lockfiles outside the source

An external build is an option for a workspace whose repository does not hold the lockfiles: a packaging flake that builds a workspace its author does not change, or a library that does not commit Cargo.lock. The packaging flake keeps the lockfiles and passes them to the builder. lockFile names the purifier lockfile, and cargoLock names a Cargo.lock that the builds use in place of any copy in src.

Every command takes --lockfile <path> and --tool-lockfile <path>, or reads the same paths from CARGO_PURIFIER_LOCKFILE and CARGO_PURIFIER_TOOL_LOCKFILE. A development shell of the packaging flake can set both variables to the paths it passes to the builder. With an outside Cargo.lock, cargo-purifier lock and update run cargo on it, write the result there, and leave the workspace’s own Cargo.lock as it was. When the outside file does not exist yet, they start from the workspace’s copy. cargo reads Cargo.lock only from the workspace root, so the cargo wrapper copies the outside Cargo.lock there before it runs cargo.

Using locked dependencies

cargo keeps planning and compiling the build. Cargo.lock already pins every registry download by name, version and checksum, so cargo-purifier reuses it, and writes cargo-purifier.lock.json beside it only for what Cargo.lock cannot record.

Working offline

cargo-purifier prefetch builds, in the Nix store, everything the development loop and the editor need: the vendored sources, the cargo-purifier package with its cargo, rustc, C compiler and rust-analyzer, and the standard library’s sources. It keeps them alive with a garbage-collector root at target/cargo-purifier/prefetch, and records the vendored sources for the wrapper, which then needs no Nix call. After a prefetch, cargo build, run, test and rust-analyzer work with the network cut off.

cargo clean removes the root with the rest of target, so prefetch again before the next stretch of offline work.

The toolchain that a prefetch keeps is the Rust of the package set the cargo-purifier package was built from. A rust-toolchain.toml file in the workspace names a toolchain that rustup downloads, and cargo-purifier builds with the package set’s Rust instead; to build with another one, pass it to cargo-purifier.overrideScope.

Language tooling integration

Point the editor at the rust-analyzer of the cargo-purifier package, for example target/cargo-purifier/prefetch/tools/bin/rust-analyzer after a prefetch. It runs cargo metadata and cargo check through the cargo wrapper, so it loads the workspace and its dependencies from the vendored sources, and it reads the standard library’s sources from the package set’s rust-src.

Nix builds

Once the native development workflow is working, you can also build and test the whole project in the Nix sandbox. For this step, keep a flake or another Nix build definition in the project’s repository, or maintain an external packaging repository that points at its sources and lockfiles. The builder consumes the same lockfiles as the development workflow.

A flake can package the workspace by calling the builder directly. It can live in the repository of the workspace or in another one:

{
  inputs.cargo-purifier.url =
    "github:nix-purifiers/cargo-purifier";
  inputs.nixpkgs.follows = "cargo-purifier/nixpkgs";

  outputs =
    { nixpkgs, cargo-purifier, ... }:
    let
      system = "x86_64-linux";
      pkgs = import nixpkgs {
        inherit system;
        overlays = [ cargo-purifier.overlays.default ];
      };
      project = pkgs.cargo-purifier.buildCargoProject {
        src = ./.;
      };
    in
    {
      packages.${system}.hello = project.packages.hello;
      checks.${system}.tests = project.tests;
    };
}

For the development loop and the editor, put the cargo-purifier package of the scope on the PATH, for example in a development shell as pkgs.cargo-purifier.cargo-purifier, and prefetch once:

cargo-purifier prefetch

One-off builds without a project Nix file

For an ad hoc build, the builder can also be evaluated directly from the project root. Replace the example package name with one from your project:

nix build --impure --expr 'let
  purifier = builtins.getFlake "github:nix-purifiers/cargo-purifier";
  pkgs = import purifier.inputs.nixpkgs {
    system = builtins.currentSystem;
    overlays = [ purifier.overlays.default ];
  };
in
(pkgs.cargo-purifier.buildCargoProject { src = ./.; })
.packages.hello'

This uses the purifier’s pinned nixpkgs, matching the lock command above. To build with ambient <nixpkgs> from your Nix search path instead, replace import purifier.inputs.nixpkgs with import <nixpkgs>. Both forms need no Nix files in your project. The build tool and language versions must match the lockfile; with ambient nixpkgs, lock with the purifier from that package set or pass a compatible toolchain to the builder.

Project projections

cargo-purifier lock --input github:example/library
cargo run

The input exports projections.cargo from a package built with buildCargoProject. Its Nix source pin covers the supplied crates; their package records stay out of Cargo.lock, and their download hashes stay out of the purifier lock. Cargo receives a temporary native lock reconstructed from the current Nix inputs and captured ordinary dependencies. Existing dependency requirements are bound automatically, and the working manifest keeps its original versions. Use --refresh-inputs to advance source pins or --no-inputs to remove them.

In a Nix build, pass producer packages with dependencies = [ producer ];. When the consumer lock already records the inputs, the builder loads those pins automatically. Each package and release exposes projections.cargo, a native local registry with the complete crate closure. Nix-derived versions and exact dependency requirements keep ordinary downstream resolution on that closure.

Publish

cargo-purifier publish --package greet

cargo-purifier publish has Nix build release.<package> from the workspace, and uploads that .crate file to crates.io, or to the registry --registry <name> names in cargo’s configuration. The upload is a request to the registry’s publish API, of the kind cargo publish sends, with the metadata read from the normalized Cargo.toml inside the crate. The token comes from where cargo keeps it: CARGO_REGISTRY_TOKEN or CARGO_REGISTRIES_<NAME>_TOKEN, or credentials.toml as cargo login writes it. --dry-run prints the metadata and uploads nothing.

For a project with Nix inputs, publication includes the reachable projected dependencies. Existing coordinates are reused only when their checksums and downloaded bytes match. Ordinary Cargo projects can consume the resulting registry without the purifier. Cargo’s install --registry path treats the installed root’s unqualified manifest dependencies as crates.io dependencies; installing those binaries from an alternative registry requires a crates.io source replacement pointing at that registry.

Decisions

Supported scope

Supported language repositories

Source in Cargo.lock How the build gets it
crates.io nixpkgs importCargoLock, by the checksum in Cargo.lock
Another registry, git or sparse index the URL its dl template gives, with all of cargo’s markers, by the checksum in Cargo.lock
git, over HTTPS or any URL Nix can fetch fetchgit with submodules, by the hash in the purifier lockfile
git over ssh:// the same repository over HTTPS from the same host, since the sandbox holds no SSH keys; a private repository needs a credentialed fetchers.fetchgit
path the build’s src

A path dependency outside the workspace root builds when src is a directory that holds both, and workspace names the workspace inside it, as in { src = ./.; workspace = "app"; }. The builds use the package set’s Rust toolchain, and do not read rust-toolchain.toml. cargo-purifier runs on x86_64-linux and aarch64-linux.

What the purifier lockfile holds

Each field of cargo-purifier.lock.json is something Nix cannot get from Cargo.lock or Cargo.toml at evaluation time. crates.io crates appear only in Cargo.lock.

Field Why Cargo.lock cannot supply it
version the purifier lockfile’s own format
contentHash the hash of the file’s own content, which shows a hand edit
cargoLock the hash of the Cargo.lock it was made from; a Cargo.lock cannot vouch that it is unchanged
git[] Cargo.lock records a git dependency’s commit, but a fixed-output fetch needs the checkout’s NAR hash, with submodules
registries.<source>.dl a registry’s download URL template is in its index’s config.json, which evaluation cannot fetch without import-from-derivation
packages.<package>.bins, .lib the outputs: cargo finds binaries in src/main.rs and src/bin/ without manifest entries, members may be globs, and the library’s name and crate types decide its file names

Target systems

  • x86_64-linux
  • aarch64-linux

Troubleshooting

Mistake What happens
Cargo.lock changed since the lock (an upgrade, or a hand edit) “… was made from a different Cargo.lock. Run cargo-purifier lock and commit both files.” The wrapper stops with the same reason.
A dependency added to Cargo.toml but not locked The wrapper stops: “Cargo.toml needs dependencies that Cargo.lock lacks. Run cargo-purifier lock to lock them.”
The purifier lockfile edited by hand “… was changed after cargo-purifier lock wrote it. Run cargo-purifier lock to write it again.”
A git dependency missing from the purifier lockfile “… has no hash for the git dependency . Run `cargo-purifier lock`."
A registry missing from the purifier lockfile “… has no entry for the registry . Run cargo-purifier lock.”
A malformed or incomplete purifier lockfile The error names the file, with “run cargo-purifier lock to write it again”.
Offline, with sources never prefetched The wrapper stops with Nix’s reason, and says to run cargo-purifier prefetch while online.
A hash that does not match the download Nix reports a hash mismatch for the crate or checkout. The upstream changed what it serves under that version or commit; cargo-purifier lock records what it serves now.

Examples

For day-to-day work on these projects, use the native-tool setup and commands in Quickstart and Development loop. The Nix expressions below show optional sandboxed packaging of those projects.

ripgrep in its own checkout

ripgrep is a cargo workspace whose rg binary comes from its root package. To work on it with cargo-purifier, lock it once at the root of a checkout, and build it from there:

nix shell \
  'github:nix-purifiers/cargo-purifier#cargo' \
  'github:nix-purifiers/cargo-purifier#cargo-purifier'
git clone https://github.com/BurntSushi/ripgrep
cd ripgrep
cargo-purifier lock
nix build --impure --expr 'let
  purifier = builtins.getFlake "github:nix-purifiers/cargo-purifier";
  pkgs = import purifier.inputs.nixpkgs {
    system = builtins.currentSystem;
    overlays = [ purifier.overlays.default ];
  };
in
(pkgs.cargo-purifier.buildCargoProject { src = ./.; })
.packages.ripgrep'

nix build leaves rg at result/bin/rg. For the development loop, prefetch once with the cargo-purifier package on the PATH, and run cargo build, cargo test and rust-analyzer as usual, online or offline.

ripgrep packaged from outside

A packaging flake can build ripgrep without changing ripgrep’s repository. Keep the purifier lockfile in the packaging flake, and write it from a checkout of the release you package:

cargo-purifier lock --manifest-path ~/src/ripgrep/Cargo.toml \
  --lockfile ./ripgrep.lock.json
{
  inputs.cargo-purifier.url =
    "github:nix-purifiers/cargo-purifier";
  inputs.nixpkgs.follows = "cargo-purifier/nixpkgs";
  inputs.ripgrep = {
    url = "github:BurntSushi/ripgrep/14.1.1";
    flake = false;
  };

  outputs =
    {
      nixpkgs,
      cargo-purifier,
      ripgrep,
      ...
    }:
    let
      system = "x86_64-linux";
      pkgs = import nixpkgs {
        inherit system;
        overlays = [ cargo-purifier.overlays.default ];
      };
      project = pkgs.cargo-purifier.buildCargoProject {
        src = ripgrep;
        lockFile = ./ripgrep.lock.json;
      };
    in
    {
      packages.${system}.ripgrep =
        project.packages.ripgrep;
    };
}

When ripgrep releases a new version, move the ripgrep input to it, run the same cargo-purifier lock on a checkout of that version, and commit both files.