aboutsummaryrefslogtreecommitdiff

cargo2nix

Build Rust packages inside Nix builds using Cargo directly.

This is the smallest possible "*2nix" tool for Rust and Cargo packaging.

Usage

Install with niv:

niv init
niv add git --name cargo2nix --repo https://git.euandreh.xyz/cargo2nix

Create a default.nix with:

let
  niv-sources = import ./nix/sources.nix;
  mozilla-overlay = import niv-sources.nixpkgs-mozilla;
  pkgs = import niv-sources.nixpkgs { overlays = [ mozilla-overlay ]; };
  src = pkgs.nix-gitignore.gitignoreSource [ ] ./.;
  cargo2nix = pkgs.callPackage niv-sources.cargo2nix {
    lockfile = ./Cargo.lock;
  };
in pkgs.stdenv.mkDerivation {
  inherit src;
  name = "cargo-test";
  buildInputs = [ pkgs.latest.rustChannels.nightly.rust ];
  phases = [ "unpackPhase" "buildPhase" ];
  buildPhase = ''
    # Setup dependencies path to satisfy Cargo
    mkdir .cargo/
    ln -s ${cargo2nix.env.cargo-config} .cargo/config
    ln -s ${cargo2nix.env.vendor} vendor

    # Run the tests
    cargo test
    touch $out
  '';
}

And than run nix-build:

nix-build

Demo

You may also try the demo repository:

pushd "$(mktemp -d)"
git clone https://git.euandreh.xyz/cargo2nix-demo
cd cargo2nix-demo/
nix-build

Limitations

The cargo2nix function (the contents of default.nix) only tries to replicate the minimum environment and make it available so you can add it to a build.

There is no support for 3rd party registries or Git repositories, yet. Patches welcome.

Contributing

Patches welcome! Send them to my public-inbox[^1] via the git send-email command (see git-send-email.io for a friendly tutorial).

[^1]: I haven't set up a dedicated mailing list for this project, due to it being so small. Feedback is welcome.