How to conditional include a configuration?

Given the config bellow, how can I only set the GOPATH if the pkg.go is present at the system? There is any way of doing that?

{
  programs.fish = {
    enable = true;

    promptInit = ''
      # Set GOPATH
      set -Ux GOPATH ~/Source/go
    '';
  }
}

Since there are multiple ways to install a package, I can’t give you an exact answer without knowing how you installed the go package. But you’d use lib.mkIf together with a condition that checks whether pkgs.go is present.

If, for example, you have installed go with environment.systemPackages = [ pkgs.go ];, you could do

{
  programs.fish = {
    enable = true;

    promptInit = lib.mkIf (lib.elem pkgs.go config.environment.systemPackages) ''
      # Set GOPATH
      set -Ux GOPATH ~/Source/go
    '';
  }
}

That said, it might be easier to just check if there is a go executable in your PATH, and only set the GOPATH variable depending on that.

1 Like

I did the Go installation with home-manager. I have something like this in another part of the code:

home.packages = with pkgs; [
  go
];

Thanks for your suggestion, it definitively solves the problem.

One last question, it’s possible to embed a conditional inside a string or maybe construct the string that is used by promptInit? Something like a template, if the condition doesn’t match what I’m expecting that piece of code never gets injected at the result file.

Maybe, and possibly, this is explained at the manual. I’m just trying to figure out faster what I can or cannot do with Nix.

The proper way would probably to wrap installation of go, as well as adding the GOPATH to the environment, into a module that provides a programs.go.enable option and then applies home.packages = [ pkgs.go ] and the environment variable if and only if the option is set to true.

When I’m back at a computer I’ll provide a more complete example.

1 Like