Nix Recipe: Setup Rust

2-minute read

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

  • Create a file rust-toolchain with following:

    1.43.0
    

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

  • Create shell.nix with following:

    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/20.03.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 20.03 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.
  • Run nix-shell --pure shell.nix to build and start using rust-1.43.0 in your virtual environment.