JMM’s

Notes on direnv

direnv—as the name implies—lets you set up an environment for a directory (and its subdirectories). Handy if you don’t want to install binaries globally, but just for a certain project.

Setting up a direnv

Make an “.envrc” file in the directory. I tend to use a simple file with the following:

PATH_add myenv/bin

where “myenv” is made with Nix, using a “default.nix” that looks something like:

# TODO: I should just learn how to make a shell.nix
{ pkgs ? import <nixpkgs> {}
, ... }:

with pkgs;
{
  r-env = let
    my-R-packages = with rPackages; [
      R
      tidyverse
      devtools
      jsonlite
      data_table
      rstan
      ggplot2
      rsvg
      RSQLite
      RPostgreSQL
    ];
    newR = rWrapper.override {
      packages = my-R-packages;
    };
  in
    symlinkJoin {
      name = "R-stdenv-wrapper";
      paths = [ newR ];
      buildInputs = [ makeWrapper ];
      postBuild = ''
    wrapProgram $out/bin/R --prefix PATH : ${lib.makeBinPath [ gcc gnumake ]}
    wrapProgram $out/bin/Rscript --prefix PATH : ${lib.makeBinPath [ gcc gnumake ]}
  '';
    };

  r-env2 = let
    my-R-packages = with rPackages; [
      R
      rsvg
    ];
    newR = rWrapper.override {
      packages = my-R-packages;
    };
  in
    newR;
}

Another .envrc

Here’s another .envrc, but one that demonstrates more of its usage:

#!/usr/bin/env bash
# .envrc files are run in bash,
# They just set any variables that are exported.

if [ ! -d "myenv" ]; then
    echo "You should build the myenv directory"
    echo "Probably using: nix build -vL -f . myenv -o myenv"
else
    :
fi

PATH_add myenv/bin

# Local Variables:
# mode: bash-ts
# End:

Commands

Just a cheatsheet of commands I forget.

Command Description
eval "$(direnv hook bash)"
eval "$(direnv hook zsh)"
Set up direnv in a Bash or Zsh shell.
direnv allow .
Mark current .envrc as trusted.