How to detect whether an option exists

I have code in a file which is always loaded but contains parts which are linked to a file which are not loaded. How can I detect whether an option is available or ignore the code otherwise.

Error:

error: The option `ncfg.persist' does not exist. Definition values:
       - In `/nix/store/xxx-source/modules/scripts':
           {
             _type = "if";
             condition = false;
             content = {
               homeLinks = [

persist.nix file which is not always loaded and gives an error building. For machines they are loaded, not for building an iso.

  options.ncfg.persist.enable = lib.mkEnableOption "a root with explicit opt-in state";:

scripts.nix file which is always loaded:

..
  options.ncfg.scripts.something.enable = lib.mkEnableOption "Enable something";

  config = lib.mkMerge [
..
   # This doesn't seem to work
   (lib.mkIf (config.ncfg.scripts.something.enable && config ? "ncfg" && config.ncfg ? "persist") {
     ncfg.persist.homeLinks = [{ path = "somepath"; type = "persist"; }];
   })
..
  ];
..
1 Like

Always load it and introduce an enable option, which you set where you’d usually import.

Or if you have a repo with config shared between stable and unstable, where you end up eval’ing the whole thing and not all options exist in both versions:

{ config, lib, pkgs, options, ... }:

{
  services.foo = {
    enable = true;
  }
  // optionalAttrs (builtins.hasAttr "bar" options.services.foo) {
    bar = "baz";
  };
}

1 Like

This seems to work

    (lib.mkIf config.ncfg.scripts.something.enable {
      ncfg = { }
        // lib.optionalAttrs (builtins.hasAttr "persist" config.ncfg) {
        persist.homeLinks = [{ path = "somepath"; type = "persist"; }];
      };
    })