Search code examples
nixnixos

How to make global variable (or function) in nix file?


I want to declare variable dotfiles_dir so all other files can see and use it.

For example (not working)

In /etc/nixos/configuration.nix (it's root file, right?)

dotfiles_dir="/home/bjorn/.config/dotfiles";

import "${dotfiles_dir}/nixos/root/default.nix"

and use it also in ~/.config/nixpkgs/home.nix (with https://github.com/rycee/home-manager)

import "${dotfiles_dir}/nixos/home/default.nix"

Solution

  • I want to declare variable dotfiles_dir so all other files can see and use it.

    Sorry, but that's not possible. In Nix, there's no such thing as global variables. If there were, it would ruin it's ability to provide reproducible builds because then Nix expressions would have access to undeclared inputs.

    /etc/nixos/configuration.nix is not place store global information, it's technically a NixOS module. But more importantly, it's a function.

    However... there's a way to define a value in one place and use it where ever you need it. Something like this:

    /etc/nixos/dotfiles-dir.nix

    "/home/bjorn/.config/dotfiles"
    

    ~/.config/nixpkgs/home.nix

    let 
      dotfiles_dir = import /etc/nixos/dotfiles-dir.nix;
      dotfiles = import (builtins.toPath "${dotfiles_dir}/nixos/home/default.nix");
    in 
    ...
    

    You could also get more fancy...

    /etc/nixos/my-settings.nix

    { dotfiles_dir = "/home/bjorn/.config/dotfiles";
    , some_other_value = "whatever";
    }
    

    ~/.config/nixpkgs/home.nix

    let 
      dotfiles_dir = (import /etc/nixos/my-settings.nix).dirfiles_dir;
      dotfiles = import (builtins.toPath "${dotfiles_dir}/nixos/home/default.nix");
    in 
    ...