Search code examples
environment-variablesnixhome-manager

Why can't home-manager read environment variables using function builtins.getEnv?


Why can't home-manager read environment variables $USER and $HOME using Nix function builtins.getEnv in ~/.config/home-manager/home.nix?

# Excerpt from ~/.config/home-manager/home.nix
...
# Home Manager needs a bit of information about you and the paths it should
# manage.
#home.username = "derek";
home.username = builtins.getEnv "USER";
home.homeDirectory = "/home/derek";
#home.homeDirectory = builtins.getEnv "HOME";
...
alpine-2:~$ home-manager switch

error:
       … while evaluating a branch condition

         at /nix/store/z6w242l49pbrdawkz5vdhfxh2mvsj36c-source/lib/lists.nix:57:9:

           56|       fold' = n:
           57|         if n == len
             |         ^
           58|         then nul

       … while calling the 'length' builtin

         at /nix/store/z6w242l49pbrdawkz5vdhfxh2mvsj36c-source/lib/lists.nix:55:13:

           54|     let
           55|       len = length list;
             |             ^
           56|       fold' = n:

       (stack trace truncated; use '--show-trace' to show the full trace)

       error:
       Failed assertions:
       - Username could not be determined
alpine-2:~$ echo $USER
derek

Solution

  • Using the command home-manager switch --impure, home-manager was able to read environment variables $USER and $HOME. --impure places home-manager in "impure" mode which allows Nix expressions to contain "impure" function references which don't respect referential transparency (i.e. that may return different results for different input values or environments).