Skip to content

Direnv

direnv is a tool which allows you to load/unload enviroment vars when you enter/leave a folder (directory enviroment manager).

This tutorial is about how to use it with Nix/NixOS as it is far more powerful when combined with devshells (TODO: page on devshells).
As such this will follow on from the Colmena tutorial as that flake.nix contains a devshell (its why ye could use nix develop in the update step).
Although this does work with any project which has a devshell in a flake.nix

Additionally if you are using flakes (ye are, you have a flake.nix) then it ensures that the devshells are cached, that they wont be garbage collected.

Installation

The flavor of direnv we are going to use is nix-direnv, one specifically for nix systems.

If you followed on from Colmena you should have machines/base.nix and machines/$HOSTNAME/configuration.nix.
Add the following to either one depending on preference, then save and rebuild.

programs.direnv = {
  enable = true;
  nix-direnv.enable = true;
};
# install it for every computer
xdg-open machines/base.nix
# OR
## $HOSTNAME the hostname of the system we want it on
xdg-open machines/$HOSTNAME/configuration.nix

Then follow the rebuild command to get it on your system.

Adding to a Project

To add to a project follow these commands.

# crates the .envrc file with use flake in it
echo "use flake" >> .envrc

# enables direnv for the project.
# each user has to do this
direnv allow

# commit it to teh repo
git add -A
git commit -sm "Added direnv"

Usage

For the most part you wont notice direnv working (it is mostly a background thing).
Like most good software it just works.

When you enter a directory with a config you will see something like what is below.
You will now be able to use any tool/binary that is defined in teh devshell.
If you are using flakes (ye prob are) then the devshell files wont be removed when doing a garbage collection. (TODO: disk cleanup)

direnv: loading /_college/CompSoc/Skynet/wiki/.envrc
direnv: using flake
direnv: nix-direnv: Using cached dev shell
direnv: export +AR +AS +CC +CONFIG_SHELL ...
When you leave you will see this:
direnv: unloading