Cargo2nix: Dramatically simpler Rust inside Nix

There is an existing tool by that name already:

This approach looks very similar to @edolstra 's import-cargo:

From the blog post:

Sure it doesn’t support private registries or Git dependencies, but how much bigger does it has to be to support them?

Not much, as can be seen in import-cargo ;).

At any rate, to summarize the differences:

  • import-cargo and this linked cargo2nix are simple, but require that the Cargo lock file is available. This is typically the case if you deliver the Nix file with a Rust project, but not in nixpkgs. The big downside of these approaches is that changing a source file in the project requires recompiling the Rust crate and every transitive Rust dependency.

  • buildRustPackage avoids the need for having a Cargo.lock file. It does so by pretending that the vendoring is a fixed-output derivation (which is probably a stretch). buildRustPackage suffers from the same issues a the former two approaches in that any project change also recompiles all dependencies. Also, it is not so nice to use in projects directly, because it requires a hash for the ‘fixed-output derivation’ or a vendor directory. This is not very practical for frequently-changing projects.

  • naersk solves the recompile problem by compiling the vendored dependencies separately from the main crate. So, changes to the crate will only result in recompiling the crate. If Cargo.lock is touched all dependencies are recompiled.

  • buildRustCrate + crate2nix is probably the most complex, but also the most Nix-native approach. It compiles a crate and every dependent crate as a separate Nix derivation + output path. This has the large benefit that crates are only (re-)compiled when necessary. Changing the main crate never recompiles dependencies. Changing dependencies only compiles dependencies that are affected. Also, output paths are (potentially) shared between different Rust projects. Finally, non-Rust dependencies can be specified per crate and in a nixpkgs-wide manner (see pkgs/build-support/rust/default-crate-overrides.nix).

Can’t say much about the original cargo2nix, since I don’t really know it.

3 Likes