Featured image of post Nix Recipe: Setup Rust

Nix Recipe: Setup Rust

Nix recipe to setup rust in a cross platform virtual nix environment

This is a nix recipe for building and running rust in a virtual nix environment.

Step 1: Create rust-toolchain

Create a file rust-toolchain with following:

1
1.61.0

We are specifying rust version to install, here using 1.61.0.
If using heroku, rust-toolchain file will determine which version will be used to build the application.

Step 2: Create shell.nix

Create shell.nix with following:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
let
# Mozilla Overlay
moz_overlay = import (
  builtins.fetchTarball
    "https://github.com/mozilla/nixpkgs-mozilla/archive/master.tar.gz"
);

nixpkgs = import (builtins.fetchTarball https://github.com/NixOS/nixpkgs/archive/22.05.tar.gz) {
  overlays = [ moz_overlay ];
  config = {};
};

frameworks = nixpkgs.darwin.apple_sdk.frameworks;
rust =
  (nixpkgs.rustChannelOf {
    rustToolchain = ./rust-toolchain;
  }).rust.override {
    extensions = [
      "clippy-preview"
      "rust-src"
    ];
  };

in
with nixpkgs;

stdenv.mkDerivation {
  name = "wilspi-rust-env";
  buildInputs = [ rust ];

  nativeBuildInputs = [
    clang
    llvm
    zsh
    vim
  ] ++ (
    stdenv.lib.optionals stdenv.isDarwin [
      frameworks.Security
      frameworks.CoreServices
      frameworks.CoreFoundation
      frameworks.Foundation
    ]
  );

  # ENV Variables
  RUST_BACKTRACE = 1;
  SOURCE_DATE_EPOCH = 315532800;
  LIBCLANG_PATH = "${llvmPackages.libclang}/lib";

  # Post Shell Hook
  shellHook = ''
    echo "Using ${rust.name}"

  '' + (
    if !pkgs.stdenv.isDarwin then
      ""
    else ''
      # Cargo wasn't able to find CF during a `cargo test` run on Darwin.
      export NIX_LDFLAGS="-F${frameworks.CoreFoundation}/Library/Frameworks -framework CoreFoundation $NIX_LDFLAGS";
    ''
  );
}  

Note:

  • Here, the nix packages are installed from 22.05 release.
  • moz_overlay is configured which contains all the latest rust releases.
  • LIBCLANG_PATH is required, see this.
  • SOURCE_DATE_EPOCH is required for clippy.
  • apple_sdk libraries are installed if the system is macos.

Step 3: Run nix shell

Run below command to build and start using rust-1.61.0 in your virtual environment.

1
nix-shell --pure shell.nix