A Nix flake for a Rust crate. purr builds the flake outputs from the files in develop/.
- The latest stable Rust from rust-overlay, with
rust-src - A package built with crane
- A dev shell with the toolchain,
pkg-config,openssland the lint tools - Pre-commit hooks from git-hooks.nix:
nixfmt,deadnix,statix,cargo-check,clippy,rustfmt nixfmt-treeas the flake formatter
nix flake init -t "github:nixcafe/develop-templates#rust" --refresh
git init
git add -ATo use a shorter registry name:
nix registry add beans "github:nixcafe/develop-templates"
nix flake init -t beans#rust
git init
git add -AIf you use cattery-modules, the beans registry entry already exists.
Nix only sees files that git tracks, so add new files before you build. The first nix command writes flake.lock. Commit it.
You can also create a GitHub repository from this one:
gh repo create my-rust-project --template nixcafe-develop/rust --clonenix develop # enter the dev shell and install the git hooks
nix fmt # format the Nix files
nix flake check # run the hooks on all files
nix build # build the crate and run its tests
nix run # run the binaryWith direnv, run direnv allow once and the shell loads when you enter the directory.
Inside the shell, use cargo as usual. cargo fmt formats the Rust code.
flake.nix inputs and the purr call
Cargo.toml
Cargo.lock
statix.toml
src/main.rs
develop/
overlays/rust-toolchain/default.nix toolchain, available as pkgs.rustToolchain
packages/default/default.nix crane build
shells/default/default.nix dev shell
checks/git-hooks/default.nix hooks
Edit develop/overlays/rust-toolchain/default.nix. The package, the shell and the hooks all use it.
# a fixed release
final.rust-bin.stable."1.90.0".default.override { extensions = [ "rust-src" ]; }
# the latest nightly
final.rust-bin.selectLatestNightlyWith (
toolchain: toolchain.default.override { extensions = [ "rust-src" ]; }
)
# whatever rust-toolchain.toml says
final.rust-bin.fromRustupToolchainFile ../../../rust-toolchain.tomlKeep rust-src in the toolchain, because RUST_SRC_PATH points to it. With rust-toolchain.toml, list it under components.
To move to a newer stable release, run nix flake update rust-overlay.
Add them to nativeBuildInputs or buildInputs in develop/packages/default/default.nix. The dev shell and the cargo hooks pick them up.
The build only copies Cargo and Rust sources. If the crate reads other files, for example through include_str!, widen src in the package. The crane docs explain source filtering.
Change name in Cargo.toml, run cargo build to update Cargo.lock, and commit both.
Edit develop/checks/git-hooks/default.nix. The hook list shows what is available. statix.toml holds the statix settings.
Add develop/packages/<name>/default.nix, develop/shells/<name>/default.nix or develop/checks/<name>/default.nix. purr picks them up without changes to flake.nix.