Building rust projects using nix flakes

I have a nix flake that’s supposed to build a rust project it’s placed in:

{
  description = "test";
  inputs = {
    nixpkgs.url = "github:nixos/nixpkgs/nixos-22.11";
  };
  outputs = { self, nixpkgs } : rec {
    pkgs = import <nixpkgs> { system = "x86_64-linux"; };
    defaultPackage.x86_64-linux = pkgs.stdenv.mkDerivation {
      name = "test";
      src = "${self}";
      phases = [
        "buildPhase"
      ];
      buildPhase = with pkgs; ''
        CARGO_TARGET_DIR=$out ${pkgs.cargo}/bin/cargo build --manifest-path $src/Cargo.toml --release 
        ${binutils}/bin/strip $out/release/flakes -o /tmp/test
        rm -rf $out
        mv /tmp/test $out
        '';
      };
  };
}

An attempt to build it results in following error:

> nix build
warning: Git tree '/home/sagartiwari/src/pgs/flakes' is dirty
error: cannot look up '<nixpkgs>' in pure evaluation mode (use '--impure' to override)

       at /nix/store/xaaagz1gzzidwxdc9mmb2g65l1g169hp-source/flake.nix:7:19:

            6|   outputs = { self, nixpkgs } : rec {
            7|     pkgs = import <nixpkgs> { system = "x86_64-linux"; };
             |                   ^
            8|     defaultPackage.x86_64-linux = pkgs.stdenv.mkDerivation {
(use '--show-trace' to show detailed location information)

It works as expected when I build it using nix build --impure.

I would like to know how to build a rust project using nix flakes without using any third party tools like naerk.

It may be sufficient to replace <nixpkgs> with nixpkgs. If not then replace

with something more like

  outputs = { self, nixpkgs }:
    let
      system = "x86_64-linux";
      pkgs = import nixpkgs { localSystem = "${system}"; };
    in {

The issue is that <nixpkgs> references the NIX_PATH environment variable, which is impure. Using nixpkgs references the nixpkgs input parameter, which is not impure.

1 Like

I use buildRustPackage for this. You can see an example in one of my flakes here.

2 Likes