diff --git a/lib/tests/misc.nix b/lib/tests/misc.nix index f0c4b6f2c5e1c..e2b4c397e716e 100644 --- a/lib/tests/misc.nix +++ b/lib/tests/misc.nix @@ -2425,67 +2425,67 @@ runTests { }; testTypeDescriptionInt = { - expr = (with types; int).description; + expr = (with lib.types; int).description; expected = "signed integer"; }; testTypeDescriptionIntsPositive = { - expr = (with types; ints.positive).description; + expr = (with lib.types; ints.positive).description; expected = "positive integer, meaning >0"; }; testTypeDescriptionIntsPositiveOrEnumAuto = { - expr = (with types; either ints.positive (enum ["auto"])).description; + expr = (with lib.types; either ints.positive (enum ["auto"])).description; expected = ''positive integer, meaning >0, or value "auto" (singular enum)''; }; testTypeDescriptionListOfPositive = { - expr = (with types; listOf ints.positive).description; + expr = (with lib.types; listOf ints.positive).description; expected = "list of (positive integer, meaning >0)"; }; testTypeDescriptionListOfInt = { - expr = (with types; listOf int).description; + expr = (with lib.types; listOf int).description; expected = "list of signed integer"; }; testTypeDescriptionListOfListOfInt = { - expr = (with types; listOf (listOf int)).description; + expr = (with lib.types; listOf (listOf int)).description; expected = "list of list of signed integer"; }; testTypeDescriptionListOfEitherStrOrBool = { - expr = (with types; listOf (either str bool)).description; + expr = (with lib.types; listOf (either str bool)).description; expected = "list of (string or boolean)"; }; testTypeDescriptionEitherListOfStrOrBool = { - expr = (with types; either (listOf bool) str).description; + expr = (with lib.types; either (listOf bool) str).description; expected = "(list of boolean) or string"; }; testTypeDescriptionEitherStrOrListOfBool = { - expr = (with types; either str (listOf bool)).description; + expr = (with lib.types; either str (listOf bool)).description; expected = "string or list of boolean"; }; testTypeDescriptionOneOfListOfStrOrBool = { - expr = (with types; oneOf [ (listOf bool) str ]).description; + expr = (with lib.types; oneOf [ (listOf bool) str ]).description; expected = "(list of boolean) or string"; }; testTypeDescriptionOneOfListOfStrOrBoolOrNumber = { - expr = (with types; oneOf [ (listOf bool) str number ]).description; + expr = (with lib.types; oneOf [ (listOf bool) str number ]).description; expected = "(list of boolean) or string or signed integer or floating point number"; }; testTypeDescriptionEitherListOfBoolOrEitherStringOrNumber = { - expr = (with types; either (listOf bool) (either str number)).description; + expr = (with lib.types; either (listOf bool) (either str number)).description; expected = "(list of boolean) or string or signed integer or floating point number"; }; testTypeDescriptionEitherEitherListOfBoolOrStringOrNumber = { - expr = (with types; either (either (listOf bool) str) number).description; + expr = (with lib.types; either (either (listOf bool) str) number).description; expected = "(list of boolean) or string or signed integer or floating point number"; }; testTypeDescriptionEitherNullOrBoolOrString = { - expr = (with types; either (nullOr bool) str).description; + expr = (with lib.types; either (nullOr bool) str).description; expected = "null or boolean or string"; }; testTypeDescriptionEitherListOfEitherBoolOrStrOrInt = { - expr = (with types; either (listOf (either bool str)) int).description; + expr = (with lib.types; either (listOf (either bool str)) int).description; expected = "(list of (boolean or string)) or signed integer"; }; testTypeDescriptionEitherIntOrListOrEitherBoolOrStr = { - expr = (with types; either int (listOf (either bool str))).description; + expr = (with lib.types; either int (listOf (either bool str))).description; expected = "signed integer or list of (boolean or string)"; }; diff --git a/lib/tests/modules/merge-module-with-key.nix b/lib/tests/modules/merge-module-with-key.nix index 3f1663dd937ef..91ac2203c5346 100644 --- a/lib/tests/modules/merge-module-with-key.nix +++ b/lib/tests/modules/merge-module-with-key.nix @@ -1,7 +1,5 @@ { lib, ... }: let - inherit (lib) mkOption types; - moduleWithoutKey = { config = { raw = "pear"; @@ -17,16 +15,16 @@ let decl = { options = { - raw = mkOption { - type = types.lines; + raw = lib.mkOption { + type = lib.types.lines; }; }; }; in { options = { - once = mkOption { - type = types.submodule { + once = lib.mkOption { + type = lib.types.submodule { imports = [ decl moduleWithKey @@ -35,8 +33,8 @@ in }; default = { }; }; - twice = mkOption { - type = types.submodule { + twice = lib.mkOption { + type = lib.types.submodule { imports = [ decl moduleWithoutKey diff --git a/nixos/doc/manual/default.nix b/nixos/doc/manual/default.nix index 5b171420b24d4..c52102bf5d989 100644 --- a/nixos/doc/manual/default.nix +++ b/nixos/doc/manual/default.nix @@ -10,19 +10,7 @@ }: let - inherit (pkgs) buildPackages runCommand docbook_xsl_ns; - - inherit (pkgs.lib) - hasPrefix - removePrefix - flip - foldr - types - mkOption - escapeShellArg - concatMapStringsSep - sourceFilesBySuffices - ; + inherit (pkgs) buildPackages runCommand docbook_xsl_ns lib; common = import ./common.nix; @@ -35,7 +23,7 @@ let # E.g. if some `options` came from modules in ${pkgs.customModules}/nix, # you'd need to include `extraSources = [ pkgs.customModules ]` prefixesToStrip = map (p: "${toString p}/") ([ prefix ] ++ extraSources); - stripAnyPrefixes = flip (foldr removePrefix) prefixesToStrip; + stripAnyPrefixes = lib.flip (lib.foldr lib.removePrefix) prefixesToStrip; optionsDoc = buildPackages.nixosOptionsDoc { inherit options revision baseOptionsJSON warningsAreErrors; @@ -50,8 +38,8 @@ let testOptionsDoc = let eval = nixos-lib.evalTest { # Avoid evaluating a NixOS config prototype. - config.node.type = types.deferredModule; - options._module.args = mkOption { internal = true; }; + config.node.type = lib.types.deferredModule; + options._module.args = lib.mkOption { internal = true; }; }; in buildPackages.nixosOptionsDoc { inherit (eval) options; @@ -61,9 +49,9 @@ let declarations = map (decl: - if hasPrefix (toString ../../..) (toString decl) + if lib.hasPrefix (toString ../../..) (toString decl) then - let subpath = removePrefix "/" (removePrefix (toString ../../..) (toString decl)); + let subpath = lib.removePrefix "/" (lib.removePrefix (toString ../../..) (toString decl)); in { url = "https://github.com/NixOS/nixpkgs/blob/master/${subpath}"; name = subpath; } else decl) opt.declarations; @@ -86,7 +74,7 @@ let substituteInPlace ./configuration/configuration.md \ --replace-fail \ '@MODULE_CHAPTERS@' \ - ${escapeShellArg (concatMapStringsSep "\n" (p: "${p.value}") config.meta.doc)} + ${lib.escapeShellArg (lib.concatMapStringsSep "\n" (p: "${p.value}") config.meta.doc)} substituteInPlace ./nixos-options.md \ --replace-fail \ '@NIXOS_OPTIONS_JSON@' \ @@ -105,7 +93,7 @@ in rec { # Generate the NixOS manual. manualHTML = runCommand "nixos-manual-html" { nativeBuildInputs = [ buildPackages.nixos-render-docs ]; - inputs = sourceFilesBySuffices ./. [ ".md" ]; + inputs = lib.sourceFilesBySuffices ./. [ ".md" ]; meta.description = "The NixOS manual in HTML format"; allowedReferences = ["out"]; } @@ -125,7 +113,7 @@ in rec { nixos-render-docs -j $NIX_BUILD_CORES manual html \ --manpage-urls ${manpageUrls} \ --redirects ${./redirects.json} \ - --revision ${escapeShellArg revision} \ + --revision ${lib.escapeShellArg revision} \ --generator "nixos-render-docs ${pkgs.lib.version}" \ --stylesheet style.css \ --stylesheet highlightjs/mono-blue.css \ @@ -210,7 +198,7 @@ in rec { # Generate manpages. mkdir -p $out/share/man/man5 nixos-render-docs -j $NIX_BUILD_CORES options manpage \ - --revision ${escapeShellArg revision} \ + --revision ${lib.escapeShellArg revision} \ ${optionsJSON}/${common.outputPath}/options.json \ $out/share/man/man5/configuration.nix.5 ''; diff --git a/nixos/lib/eval-config.nix b/nixos/lib/eval-config.nix index 49b9e483ad2b2..9613dc2bb0cfb 100644 --- a/nixos/lib/eval-config.nix +++ b/nixos/lib/eval-config.nix @@ -56,8 +56,6 @@ evalConfigArgs@ }: let - inherit (lib) optional; - evalModulesMinimal = (import ./default.nix { inherit lib; # Implicit use of feature is noted in implementation. @@ -68,7 +66,7 @@ let _file = ./eval-config.nix; key = _file; config = lib.mkMerge ( - (optional (system != null) { + (lib.optional (system != null) { # Explicit `nixpkgs.system` or `nixpkgs.localSystem` should override # this. Since the latter defaults to the former, the former should # default to the argument. That way this new default could propagate all @@ -76,7 +74,7 @@ let nixpkgs.system = lib.mkDefault system; }) ++ - (optional (pkgs != null) { + (lib.optional (pkgs != null) { # This should be default priority, so it conflicts with any user-defined pkgs. nixpkgs.pkgs = pkgs; }) diff --git a/nixos/lib/make-disk-image.nix b/nixos/lib/make-disk-image.nix index 648f2f774ddfb..b167dade484d3 100644 --- a/nixos/lib/make-disk-image.nix +++ b/nixos/lib/make-disk-image.nix @@ -115,7 +115,7 @@ To solve this, you can run `fdisk -l $image` and generate `dd if=$image of=$imag # grafted in the file system at path `target', `mode' is a string containing # the permissions that will be set (ex. "755"), `user' and `group' are the # user and group name that will be set as owner of the files. - # `mode', `user', and `group' are optional. + # `mode', `user', and `group' are lib.optional. # When setting one of `user' or `group', the other needs to be set too. contents ? [] diff --git a/nixos/lib/make-options-doc/default.nix b/nixos/lib/make-options-doc/default.nix index a6ff4be92c802..e3d92ab83c9e1 100644 --- a/nixos/lib/make-options-doc/default.nix +++ b/nixos/lib/make-options-doc/default.nix @@ -133,7 +133,7 @@ let # - a list: that will be interpreted as an attribute path from `pkgs` and turned into a link # to search.nixos.org, # - an attrset: that can specify `name`, `path`, `comment` - # (either of `name`, `path` is required, the rest are optional). + # (either of `name`, `path` is required, the rest are lib.optional). # # NOTE: No checks against `pkgs` are made to ensure that the referenced package actually exists. # Such checks are not compatible with option docs caching. diff --git a/nixos/lib/systemd-lib.nix b/nixos/lib/systemd-lib.nix index b8848f56a6c0b..c4d68d1c70152 100644 --- a/nixos/lib/systemd-lib.nix +++ b/nixos/lib/systemd-lib.nix @@ -1,54 +1,6 @@ { config, lib, pkgs, utils }: let - inherit (lib) - all - attrByPath - attrNames - concatLists - concatMap - concatMapStrings - concatStrings - concatStringsSep - const - elem - elemAt - filter - filterAttrs - flatten - flip - hasPrefix - head - isInt - isFloat - isList - isPath - isString - length - makeBinPath - makeSearchPathOutput - mapAttrs - mapAttrsToList - mapNullable - match - mkAfter - mkIf - optional - optionalAttrs - optionalString - pipe - range - replaceStrings - reverseList - splitString - stringLength - stringToCharacters - tail - toIntBase10 - trace - types - ; - inherit (lib.strings) toJSON; cfg = config.systemd; @@ -56,12 +8,12 @@ let systemd = cfg.package; in rec { - shellEscape = s: (replaceStrings [ "\\" ] [ "\\\\" ] s); + shellEscape = s: (lib.replaceStrings [ "\\" ] [ "\\\\" ] s); - mkPathSafeName = replaceStrings ["@" ":" "\\" "[" "]"] ["-" "-" "-" "" ""]; + mkPathSafeName = lib.replaceStrings ["@" ":" "\\" "[" "]"] ["-" "-" "-" "" ""]; # a type for options that take a unit name - unitNameType = types.strMatching "[a-zA-Z0-9@%:_.\\-]+[.](service|socket|device|mount|automount|swap|target|path|timer|scope|slice)"; + unitNameType = lib.types.strMatching "[a-zA-Z0-9@%:_.\\-]+[.](service|socket|device|mount|automount|swap|target|path|timer|scope|slice)"; makeUnit = name: unit: if unit.enable then @@ -71,7 +23,7 @@ in rec { # unit.text can be null. But variables that are null listed in # passAsFile are ignored by nix, resulting in no file being created, # making the mv operation fail. - text = optionalString (unit.text != null) unit.text; + text = lib.optionalString (unit.text != null) unit.text; passAsFile = [ "text" ]; } '' @@ -92,128 +44,128 @@ in rec { boolValues = [true false "yes" "no"]; - digits = map toString (range 0 9); + digits = map toString (lib.range 0 9); isByteFormat = s: let - l = reverseList (stringToCharacters s); - suffix = head l; - nums = tail l; + l = lib.reverseList (lib.stringToCharacters s); + suffix = lib.head l; + nums = lib.tail l; in builtins.isInt s - || (elem suffix (["K" "M" "G" "T"] ++ digits) - && all (num: elem num digits) nums); + || (lib.elem suffix (["K" "M" "G" "T"] ++ digits) + && lib.all (num: lib.elem num digits) nums); assertByteFormat = name: group: attr: - optional (attr ? ${name} && ! isByteFormat attr.${name}) + lib.optional (attr ? ${name} && ! isByteFormat attr.${name}) "Systemd ${group} field `${name}' must be in byte format [0-9]+[KMGT]."; - toIntBaseDetected = value: assert (match "[0-9]+|0x[0-9a-fA-F]+" value) != null; (builtins.fromTOML "v=${value}").v; + toIntBaseDetected = value: assert (lib.match "[0-9]+|0x[0-9a-fA-F]+" value) != null; (builtins.fromTOML "v=${value}").v; - hexChars = stringToCharacters "0123456789abcdefABCDEF"; + hexChars = lib.stringToCharacters "0123456789abcdefABCDEF"; - isMacAddress = s: stringLength s == 17 - && flip all (splitString ":" s) (bytes: - all (byte: elem byte hexChars) (stringToCharacters bytes) + isMacAddress = s: lib.stringLength s == 17 + && lib.flip lib.all (lib.splitString ":" s) (bytes: + lib.all (byte: lib.elem byte hexChars) (lib.stringToCharacters bytes) ); assertMacAddress = name: group: attr: - optional (attr ? ${name} && ! isMacAddress attr.${name}) + lib.optional (attr ? ${name} && ! isMacAddress attr.${name}) "Systemd ${group} field `${name}' must be a valid MAC address."; assertNetdevMacAddress = name: group: attr: - optional (attr ? ${name} && (! isMacAddress attr.${name} && attr.${name} != "none")) + lib.optional (attr ? ${name} && (! isMacAddress attr.${name} && attr.${name} != "none")) "Systemd ${group} field `${name}` must be a valid MAC address or the special value `none`."; isNumberOrRangeOf = check: v: - if isInt v + if lib.isInt v then check v else let - parts = splitString "-" v; - lower = toIntBase10 (head parts); - upper = if tail parts != [] then toIntBase10 (head (tail parts)) else lower; + parts = lib.splitString "-" v; + lower = lib.toIntBase10 (lib.head parts); + upper = if lib.tail parts != [] then lib.toIntBase10 (lib.head (lib.tail parts)) else lower; in - length parts <= 2 && lower <= upper && check lower && check upper; + lib.length parts <= 2 && lower <= upper && check lower && check upper; isPort = i: i >= 0 && i <= 65535; isPortOrPortRange = isNumberOrRangeOf isPort; assertPort = name: group: attr: - optional (attr ? ${name} && ! isPort attr.${name}) + lib.optional (attr ? ${name} && ! isPort attr.${name}) "Error on the systemd ${group} field `${name}': ${attr.name} is not a valid port number."; assertPortOrPortRange = name: group: attr: - optional (attr ? ${name} && ! isPortOrPortRange attr.${name}) + lib.optional (attr ? ${name} && ! isPortOrPortRange attr.${name}) "Error on the systemd ${group} field `${name}': ${attr.name} is not a valid port number or range of port numbers."; assertValueOneOf = name: values: group: attr: - optional (attr ? ${name} && !elem attr.${name} values) + lib.optional (attr ? ${name} && !lib.elem attr.${name} values) "Systemd ${group} field `${name}' cannot have value `${toString attr.${name}}'."; assertValuesSomeOfOr = name: values: default: group: attr: - optional (attr ? ${name} && !(all (x: elem x values) (splitString " " attr.${name}) || attr.${name} == default)) + lib.optional (attr ? ${name} && !(lib.all (x: lib.elem x values) (lib.splitString " " attr.${name}) || attr.${name} == default)) "Systemd ${group} field `${name}' cannot have value `${toString attr.${name}}'."; assertHasField = name: group: attr: - optional (!(attr ? ${name})) + lib.optional (!(attr ? ${name})) "Systemd ${group} field `${name}' must exist."; assertRange = name: min: max: group: attr: - optional (attr ? ${name} && !(min <= attr.${name} && max >= attr.${name})) + lib.optional (attr ? ${name} && !(min <= attr.${name} && max >= attr.${name})) "Systemd ${group} field `${name}' is outside the range [${toString min},${toString max}]"; assertRangeOrOneOf = name: min: max: values: group: attr: - optional (attr ? ${name} && !(((isInt attr.${name} || isFloat attr.${name}) && min <= attr.${name} && max >= attr.${name}) || elem attr.${name} values)) + lib.optional (attr ? ${name} && !(((lib.isInt attr.${name} || lib.isFloat attr.${name}) && min <= attr.${name} && max >= attr.${name}) || lib.elem attr.${name} values)) "Systemd ${group} field `${name}' is not a value in range [${toString min},${toString max}], or one of ${toString values}"; assertRangeWithOptionalMask = name: min: max: group: attr: if (attr ? ${name}) then - if isInt attr.${name} then + if lib.isInt attr.${name} then assertRange name min max group attr - else if isString attr.${name} then + else if lib.isString attr.${name} then let - fields = match "([0-9]+|0x[0-9a-fA-F]+)(/([0-9]+|0x[0-9a-fA-F]+))?" attr.${name}; + fields = lib.match "([0-9]+|0x[0-9a-fA-F]+)(/([0-9]+|0x[0-9a-fA-F]+))?" attr.${name}; in if fields == null then ["Systemd ${group} field `${name}' must either be an integer or two integers separated by a slash (/)."] else let - value = toIntBaseDetected (elemAt fields 0); - mask = mapNullable toIntBaseDetected (elemAt fields 2); + value = toIntBaseDetected (lib.elemAt fields 0); + mask = lib.mapNullable toIntBaseDetected (lib.elemAt fields 2); in - optional (!(min <= value && max >= value)) "Systemd ${group} field `${name}' has main value outside the range [${toString min},${toString max}]." - ++ optional (mask != null && !(min <= mask && max >= mask)) "Systemd ${group} field `${name}' has mask outside the range [${toString min},${toString max}]." + lib.optional (!(min <= value && max >= value)) "Systemd ${group} field `${name}' has main value outside the range [${toString min},${toString max}]." + ++ lib.optional (mask != null && !(min <= mask && max >= mask)) "Systemd ${group} field `${name}' has mask outside the range [${toString min},${toString max}]." else ["Systemd ${group} field `${name}' must either be an integer or a string."] else []; assertMinimum = name: min: group: attr: - optional (attr ? ${name} && attr.${name} < min) + lib.optional (attr ? ${name} && attr.${name} < min) "Systemd ${group} field `${name}' must be greater than or equal to ${toString min}"; assertOnlyFields = fields: group: attr: - let badFields = filter (name: ! elem name fields) (attrNames attr); in - optional (badFields != [ ]) - "Systemd ${group} has extra fields [${concatStringsSep " " badFields}]."; + let badFields = lib.filter (name: ! lib.elem name fields) (lib.attrNames attr); in + lib.optional (badFields != [ ]) + "Systemd ${group} has extra fields [${lib.concatStringsSep " " badFields}]."; assertInt = name: group: attr: - optional (attr ? ${name} && !isInt attr.${name}) + lib.optional (attr ? ${name} && !lib.isInt attr.${name}) "Systemd ${group} field `${name}' is not an integer"; assertRemoved = name: see: group: attr: - optional (attr ? ${name}) + lib.optional (attr ? ${name}) "Systemd ${group} field `${name}' has been removed. See ${see}"; assertKeyIsSystemdCredential = name: group: attr: - optional (attr ? ${name} && !(hasPrefix "@" attr.${name})) + lib.optional (attr ? ${name} && !(lib.hasPrefix "@" attr.${name})) "Systemd ${group} field `${name}' is not a systemd credential"; checkUnitConfig = group: checks: attrs: let # We're applied at the top-level type (attrsOf unitOption), so the actual # unit options might contain attributes from mkOverride and mkIf that we need to # convert into single values before checking them. - defs = mapAttrs (const (v: + defs = lib.mapAttrs (lib.const (v: if v._type or "" == "override" then v.content else if v._type or "" == "if" then v.content else v )) attrs; - errors = concatMap (c: c group defs) checks; + errors = lib.concatMap (c: c group defs) checks; in if errors == [] then true - else trace (concatStringsSep "\n" errors) false; + else lib.trace (lib.concatStringsSep "\n" errors) false; checkUnitConfigWithLegacyKey = legacyKey: group: checks: attrs: let @@ -245,11 +197,11 @@ in rec { else toString x; attrsToSection = as: - concatStrings (concatLists (mapAttrsToList (name: value: + lib.concatStrings (lib.concatLists (lib.mapAttrsToList (name: value: map (x: '' ${name}=${toOption x} '') - (if isList value then value else [value])) + (if lib.isList value then value else [value])) as)); generateUnits = { allowCollisions ? true, type, units, upstreamUnits, upstreamWants, packages ? cfg.packages, package ? cfg.package }: @@ -322,9 +274,9 @@ in rec { # systemd or systemd.packages, then add them as # .d/overrides.conf, which makes them extend the # upstream unit. - for i in ${toString (mapAttrsToList + for i in ${toString (lib.mapAttrsToList (n: v: v.unit) - (filterAttrs (n: v: (attrByPath [ "overrideStrategy" ] "asDropinIfExists" v) == "asDropinIfExists") units))}; do + (lib.filterAttrs (n: v: (lib.attrByPath [ "overrideStrategy" ] "asDropinIfExists" v) == "asDropinIfExists") units))}; do fn=$(basename $i/*) if [ -e $out/$fn ]; then if [ "$(readlink -f $i/$fn)" = /dev/null ]; then @@ -345,41 +297,41 @@ in rec { # Symlink units defined by systemd.units which shall be # treated as drop-in file. - for i in ${toString (mapAttrsToList + for i in ${toString (lib.mapAttrsToList (n: v: v.unit) - (filterAttrs (n: v: v ? overrideStrategy && v.overrideStrategy == "asDropin") units))}; do + (lib.filterAttrs (n: v: v ? overrideStrategy && v.overrideStrategy == "asDropin") units))}; do fn=$(basename $i/*) mkdir -p $out/$fn.d ln -s $i/$fn $out/$fn.d/overrides.conf done # Create service aliases from aliases option. - ${concatStrings (mapAttrsToList (name: unit: - concatMapStrings (name2: '' + ${lib.concatStrings (lib.mapAttrsToList (name: unit: + lib.concatMapStrings (name2: '' ln -sfn '${name}' $out/'${name2}' '') (unit.aliases or [])) units)} # Create .wants, .upholds and .requires symlinks from the wantedBy, upheldBy and # requiredBy options. - ${concatStrings (mapAttrsToList (name: unit: - concatMapStrings (name2: '' + ${lib.concatStrings (lib.mapAttrsToList (name: unit: + lib.concatMapStrings (name2: '' mkdir -p $out/'${name2}.wants' ln -sfn '../${name}' $out/'${name2}.wants'/ '') (unit.wantedBy or [])) units)} - ${concatStrings (mapAttrsToList (name: unit: - concatMapStrings (name2: '' + ${lib.concatStrings (lib.mapAttrsToList (name: unit: + lib.concatMapStrings (name2: '' mkdir -p $out/'${name2}.upholds' ln -sfn '../${name}' $out/'${name2}.upholds'/ '') (unit.upheldBy or [])) units)} - ${concatStrings (mapAttrsToList (name: unit: - concatMapStrings (name2: '' + ${lib.concatStrings (lib.mapAttrsToList (name: unit: + lib.concatMapStrings (name2: '' mkdir -p $out/'${name2}.requires' ln -sfn '../${name}' $out/'${name2}.requires'/ '') (unit.requiredBy or [])) units)} - ${optionalString (type == "system") '' + ${lib.optionalString (type == "system") '' # Stupid misc. symlinks. ln -s ${cfg.defaultUnit} $out/default.target ln -s ${cfg.ctrlAltDelUnit} $out/ctrl-alt-del.target @@ -394,7 +346,7 @@ in rec { makeJobScript = { name, text, enableStrictShellChecks }: let - scriptName = replaceStrings [ "\\" "@" ] [ "-" "_" ] (shellEscape name); + scriptName = lib.replaceStrings [ "\\" "@" ] [ "-" "_" ] (shellEscape name); out = ( if ! enableStrictShellChecks then pkgs.writeShellScriptBin scriptName '' @@ -417,47 +369,47 @@ in rec { unitConfig = { config, name, options, ... }: { config = { unitConfig = - optionalAttrs (config.requires != []) + lib.optionalAttrs (config.requires != []) { Requires = toString config.requires; } - // optionalAttrs (config.wants != []) + // lib.optionalAttrs (config.wants != []) { Wants = toString config.wants; } - // optionalAttrs (config.upholds != []) + // lib.optionalAttrs (config.upholds != []) { Upholds = toString config.upholds; } - // optionalAttrs (config.after != []) + // lib.optionalAttrs (config.after != []) { After = toString config.after; } - // optionalAttrs (config.before != []) + // lib.optionalAttrs (config.before != []) { Before = toString config.before; } - // optionalAttrs (config.bindsTo != []) + // lib.optionalAttrs (config.bindsTo != []) { BindsTo = toString config.bindsTo; } - // optionalAttrs (config.partOf != []) + // lib.optionalAttrs (config.partOf != []) { PartOf = toString config.partOf; } - // optionalAttrs (config.conflicts != []) + // lib.optionalAttrs (config.conflicts != []) { Conflicts = toString config.conflicts; } - // optionalAttrs (config.requisite != []) + // lib.optionalAttrs (config.requisite != []) { Requisite = toString config.requisite; } - // optionalAttrs (config ? restartTriggers && config.restartTriggers != []) - { X-Restart-Triggers = "${pkgs.writeText "X-Restart-Triggers-${name}" (pipe config.restartTriggers [ - flatten - (map (x: if isPath x then "${x}" else x)) + // lib.optionalAttrs (config ? restartTriggers && config.restartTriggers != []) + { X-Restart-Triggers = "${pkgs.writeText "X-Restart-Triggers-${name}" (lib.pipe config.restartTriggers [ + lib.flatten + (map (x: if lib.isPath x then "${x}" else x)) toString ])}"; } - // optionalAttrs (config ? reloadTriggers && config.reloadTriggers != []) - { X-Reload-Triggers = "${pkgs.writeText "X-Reload-Triggers-${name}" (pipe config.reloadTriggers [ - flatten - (map (x: if isPath x then "${x}" else x)) + // lib.optionalAttrs (config ? reloadTriggers && config.reloadTriggers != []) + { X-Reload-Triggers = "${pkgs.writeText "X-Reload-Triggers-${name}" (lib.pipe config.reloadTriggers [ + lib.flatten + (map (x: if lib.isPath x then "${x}" else x)) toString ])}"; } - // optionalAttrs (config.description != "") { + // lib.optionalAttrs (config.description != "") { Description = config.description; } - // optionalAttrs (config.documentation != []) { + // lib.optionalAttrs (config.documentation != []) { Documentation = toString config.documentation; } - // optionalAttrs (config.onFailure != []) { + // lib.optionalAttrs (config.onFailure != []) { OnFailure = toString config.onFailure; } - // optionalAttrs (config.onSuccess != []) { + // lib.optionalAttrs (config.onSuccess != []) { OnSuccess = toString config.onSuccess; } - // optionalAttrs (options.startLimitIntervalSec.isDefined) { + // lib.optionalAttrs (options.startLimitIntervalSec.isDefined) { StartLimitIntervalSec = toString config.startLimitIntervalSec; - } // optionalAttrs (options.startLimitBurst.isDefined) { + } // lib.optionalAttrs (options.startLimitBurst.isDefined) { StartLimitBurst = toString config.startLimitBurst; }; }; @@ -470,7 +422,7 @@ in rec { { name, lib, config, ... }: { config = { name = "${name}.service"; - environment.PATH = mkIf (config.path != []) "${makeBinPath config.path}:${makeSearchPathOutput "bin" "sbin" config.path}"; + environment.PATH = lib.mkIf (config.path != []) "${lib.makeBinPath config.path}:${lib.makeSearchPathOutput "bin" "sbin" config.path}"; enableStrictShellChecks = lib.mkOptionDefault nixosConfig.systemd.enableStrictShellChecks; }; @@ -509,7 +461,7 @@ in rec { stage2ServiceConfig = { imports = [ serviceConfig ]; # Default path for systemd services. Should be quite minimal. - config.path = mkAfter [ + config.path = lib.mkAfter [ pkgs.coreutils pkgs.findutils pkgs.gnugrep @@ -526,9 +478,9 @@ in rec { mountConfig = { What = config.what; Where = config.where; - } // optionalAttrs (config.type != "") { + } // lib.optionalAttrs (config.type != "") { Type = config.type; - } // optionalAttrs (config.options != "") { + } // lib.optionalAttrs (config.options != "") { Options = config.options; }; }; @@ -546,10 +498,10 @@ in rec { commonUnitText = def: lines: '' [Unit] ${attrsToSection def.unitConfig} - '' + lines + optionalString (def.wantedBy != [ ]) '' + '' + lines + lib.optionalString (def.wantedBy != [ ]) '' [Install] - WantedBy=${concatStringsSep " " def.wantedBy} + WantedBy=${lib.concatStringsSep " " def.wantedBy} ''; targetToUnit = def: @@ -566,21 +518,21 @@ in rec { text = commonUnitText def ('' [Service] '' + (let env = cfg.globalEnvironment // def.environment; - in concatMapStrings (n: - let s = optionalString (env.${n} != null) + in lib.concatMapStrings (n: + let s = lib.optionalString (env.${n} != null) "Environment=${toJSON "${n}=${env.${n}}"}\n"; # systemd max line length is now 1MiB # https://github.com/systemd/systemd/commit/e6dde451a51dc5aaa7f4d98d39b8fe735f73d2af - in if stringLength s >= 1048576 then throw "The value of the environment variable ‘${n}’ in systemd service ‘${def.name}.service’ is too long." else s) (attrNames env)) + in if lib.stringLength s >= 1048576 then throw "The value of the environment variable ‘${n}’ in systemd service ‘${def.name}.service’ is too long." else s) (lib.attrNames env)) + (if def ? reloadIfChanged && def.reloadIfChanged then '' X-ReloadIfChanged=true '' else if (def ? restartIfChanged && !def.restartIfChanged) then '' X-RestartIfChanged=false '' else "") - + optionalString (def ? stopIfChanged && !def.stopIfChanged) '' + + lib.optionalString (def ? stopIfChanged && !def.stopIfChanged) '' X-StopIfChanged=false '' - + optionalString (def ? notSocketActivated && def.notSocketActivated) '' + + lib.optionalString (def ? notSocketActivated && def.notSocketActivated) '' X-NotSocketActivated=true '' + attrsToSection def.serviceConfig); }; @@ -590,8 +542,8 @@ in rec { text = commonUnitText def '' [Socket] ${attrsToSection def.socketConfig} - ${concatStringsSep "\n" (map (s: "ListenStream=${s}") def.listenStreams)} - ${concatStringsSep "\n" (map (s: "ListenDatagram=${s}") def.listenDatagrams)} + ${lib.concatStringsSep "\n" (map (s: "ListenStream=${s}") def.listenStreams)} + ${lib.concatStringsSep "\n" (map (s: "ListenDatagram=${s}") def.listenDatagrams)} ''; }; @@ -640,13 +592,13 @@ in rec { # in that attrset are determined by the supplied format. definitions = directoryName: format: definitionAttrs: let - listOfDefinitions = mapAttrsToList + listOfDefinitions = lib.mapAttrsToList (name: format.generate "${name}.conf") definitionAttrs; in pkgs.runCommand directoryName { } '' mkdir -p $out - ${(concatStringsSep "\n" + ${(lib.concatStringsSep "\n" (map (pkg: "cp ${pkg} $out/${pkg.name}") listOfDefinitions) )} ''; diff --git a/nixos/lib/systemd-network-units.nix b/nixos/lib/systemd-network-units.nix index ffaefa972767f..525ac12fd99d7 100644 --- a/nixos/lib/systemd-network-units.nix +++ b/nixos/lib/systemd-network-units.nix @@ -1,17 +1,10 @@ { lib, systemdUtils }: let - inherit (lib) - concatMapStrings - concatStringsSep - flip - optionalString - ; - attrsToSection = systemdUtils.lib.attrsToSection; commonMatchText = def: - optionalString (def.matchConfig != { }) '' + lib.optionalString (def.matchConfig != { }) '' [Match] ${attrsToSection def.matchConfig} ''; @@ -33,83 +26,83 @@ in [NetDev] ${attrsToSection def.netdevConfig} '' - + optionalString (def.bridgeConfig != { }) '' + + lib.optionalString (def.bridgeConfig != { }) '' [Bridge] ${attrsToSection def.bridgeConfig} '' - + optionalString (def.vlanConfig != { }) '' + + lib.optionalString (def.vlanConfig != { }) '' [VLAN] ${attrsToSection def.vlanConfig} '' - + optionalString (def.ipvlanConfig != { }) '' + + lib.optionalString (def.ipvlanConfig != { }) '' [IPVLAN] ${attrsToSection def.ipvlanConfig} '' - + optionalString (def.ipvtapConfig != { }) '' + + lib.optionalString (def.ipvtapConfig != { }) '' [IPVTAP] ${attrsToSection def.ipvtapConfig} '' - + optionalString (def.macvlanConfig != { }) '' + + lib.optionalString (def.macvlanConfig != { }) '' [MACVLAN] ${attrsToSection def.macvlanConfig} '' - + optionalString (def.vxlanConfig != { }) '' + + lib.optionalString (def.vxlanConfig != { }) '' [VXLAN] ${attrsToSection def.vxlanConfig} '' - + optionalString (def.tunnelConfig != { }) '' + + lib.optionalString (def.tunnelConfig != { }) '' [Tunnel] ${attrsToSection def.tunnelConfig} '' - + optionalString (def.fooOverUDPConfig != { }) '' + + lib.optionalString (def.fooOverUDPConfig != { }) '' [FooOverUDP] ${attrsToSection def.fooOverUDPConfig} '' - + optionalString (def.peerConfig != { }) '' + + lib.optionalString (def.peerConfig != { }) '' [Peer] ${attrsToSection def.peerConfig} '' - + optionalString (def.tunConfig != { }) '' + + lib.optionalString (def.tunConfig != { }) '' [Tun] ${attrsToSection def.tunConfig} '' - + optionalString (def.tapConfig != { }) '' + + lib.optionalString (def.tapConfig != { }) '' [Tap] ${attrsToSection def.tapConfig} '' - + optionalString (def.l2tpConfig != { }) '' + + lib.optionalString (def.l2tpConfig != { }) '' [L2TP] ${attrsToSection def.l2tpConfig} '' - + flip concatMapStrings def.l2tpSessions (x: '' + + lib.flip lib.concatMapStrings def.l2tpSessions (x: '' [L2TPSession] ${attrsToSection x} '') - + optionalString (def.wireguardConfig != { }) '' + + lib.optionalString (def.wireguardConfig != { }) '' [WireGuard] ${attrsToSection def.wireguardConfig} '' - + flip concatMapStrings def.wireguardPeers (x: '' + + lib.flip lib.concatMapStrings def.wireguardPeers (x: '' [WireGuardPeer] ${attrsToSection x} '') - + optionalString (def.bondConfig != { }) '' + + lib.optionalString (def.bondConfig != { }) '' [Bond] ${attrsToSection def.bondConfig} '' - + optionalString (def.xfrmConfig != { }) '' + + lib.optionalString (def.xfrmConfig != { }) '' [Xfrm] ${attrsToSection def.xfrmConfig} '' - + optionalString (def.vrfConfig != { }) '' + + lib.optionalString (def.vrfConfig != { }) '' [VRF] ${attrsToSection def.vrfConfig} '' - + optionalString (def.wlanConfig != { }) '' + + lib.optionalString (def.wlanConfig != { }) '' [WLAN] ${attrsToSection def.wlanConfig} '' - + optionalString (def.batmanAdvancedConfig != { }) '' + + lib.optionalString (def.batmanAdvancedConfig != { }) '' [BatmanAdvanced] ${attrsToSection def.batmanAdvancedConfig} '' @@ -118,7 +111,7 @@ in networkToUnit = def: commonMatchText def - + optionalString (def.linkConfig != { }) '' + + lib.optionalString (def.linkConfig != { }) '' [Link] ${attrsToSection def.linkConfig} '' @@ -126,223 +119,223 @@ in [Network] '' + attrsToSection def.networkConfig - + optionalString (def.address != [ ]) '' - ${concatStringsSep "\n" (map (s: "Address=${s}") def.address)} + + lib.optionalString (def.address != [ ]) '' + ${lib.concatStringsSep "\n" (map (s: "Address=${s}") def.address)} '' - + optionalString (def.gateway != [ ]) '' - ${concatStringsSep "\n" (map (s: "Gateway=${s}") def.gateway)} + + lib.optionalString (def.gateway != [ ]) '' + ${lib.concatStringsSep "\n" (map (s: "Gateway=${s}") def.gateway)} '' - + optionalString (def.dns != [ ]) '' - ${concatStringsSep "\n" (map (s: "DNS=${s}") def.dns)} + + lib.optionalString (def.dns != [ ]) '' + ${lib.concatStringsSep "\n" (map (s: "DNS=${s}") def.dns)} '' - + optionalString (def.ntp != [ ]) '' - ${concatStringsSep "\n" (map (s: "NTP=${s}") def.ntp)} + + lib.optionalString (def.ntp != [ ]) '' + ${lib.concatStringsSep "\n" (map (s: "NTP=${s}") def.ntp)} '' - + optionalString (def.bridge != [ ]) '' - ${concatStringsSep "\n" (map (s: "Bridge=${s}") def.bridge)} + + lib.optionalString (def.bridge != [ ]) '' + ${lib.concatStringsSep "\n" (map (s: "Bridge=${s}") def.bridge)} '' - + optionalString (def.bond != [ ]) '' - ${concatStringsSep "\n" (map (s: "Bond=${s}") def.bond)} + + lib.optionalString (def.bond != [ ]) '' + ${lib.concatStringsSep "\n" (map (s: "Bond=${s}") def.bond)} '' - + optionalString (def.vrf != [ ]) '' - ${concatStringsSep "\n" (map (s: "VRF=${s}") def.vrf)} + + lib.optionalString (def.vrf != [ ]) '' + ${lib.concatStringsSep "\n" (map (s: "VRF=${s}") def.vrf)} '' - + optionalString (def.vlan != [ ]) '' - ${concatStringsSep "\n" (map (s: "VLAN=${s}") def.vlan)} + + lib.optionalString (def.vlan != [ ]) '' + ${lib.concatStringsSep "\n" (map (s: "VLAN=${s}") def.vlan)} '' - + optionalString (def.macvlan != [ ]) '' - ${concatStringsSep "\n" (map (s: "MACVLAN=${s}") def.macvlan)} + + lib.optionalString (def.macvlan != [ ]) '' + ${lib.concatStringsSep "\n" (map (s: "MACVLAN=${s}") def.macvlan)} '' - + optionalString (def.macvtap != [ ]) '' - ${concatStringsSep "\n" (map (s: "MACVTAP=${s}") def.macvtap)} + + lib.optionalString (def.macvtap != [ ]) '' + ${lib.concatStringsSep "\n" (map (s: "MACVTAP=${s}") def.macvtap)} '' - + optionalString (def.vxlan != [ ]) '' - ${concatStringsSep "\n" (map (s: "VXLAN=${s}") def.vxlan)} + + lib.optionalString (def.vxlan != [ ]) '' + ${lib.concatStringsSep "\n" (map (s: "VXLAN=${s}") def.vxlan)} '' - + optionalString (def.tunnel != [ ]) '' - ${concatStringsSep "\n" (map (s: "Tunnel=${s}") def.tunnel)} + + lib.optionalString (def.tunnel != [ ]) '' + ${lib.concatStringsSep "\n" (map (s: "Tunnel=${s}") def.tunnel)} '' - + optionalString (def.xfrm != [ ]) '' - ${concatStringsSep "\n" (map (s: "Xfrm=${s}") def.xfrm)} + + lib.optionalString (def.xfrm != [ ]) '' + ${lib.concatStringsSep "\n" (map (s: "Xfrm=${s}") def.xfrm)} '' + "\n" - + flip concatMapStrings def.addresses (x: '' + + lib.flip lib.concatMapStrings def.addresses (x: '' [Address] ${attrsToSection x} '') - + flip concatMapStrings def.routingPolicyRules (x: '' + + lib.flip lib.concatMapStrings def.routingPolicyRules (x: '' [RoutingPolicyRule] ${attrsToSection x} '') - + flip concatMapStrings def.routes (x: '' + + lib.flip lib.concatMapStrings def.routes (x: '' [Route] ${attrsToSection x} '') - + optionalString (def.dhcpV4Config != { }) '' + + lib.optionalString (def.dhcpV4Config != { }) '' [DHCPv4] ${attrsToSection def.dhcpV4Config} '' - + optionalString (def.dhcpV6Config != { }) '' + + lib.optionalString (def.dhcpV6Config != { }) '' [DHCPv6] ${attrsToSection def.dhcpV6Config} '' - + optionalString (def.dhcpPrefixDelegationConfig != { }) '' + + lib.optionalString (def.dhcpPrefixDelegationConfig != { }) '' [DHCPPrefixDelegation] ${attrsToSection def.dhcpPrefixDelegationConfig} '' - + optionalString (def.ipv6AcceptRAConfig != { }) '' + + lib.optionalString (def.ipv6AcceptRAConfig != { }) '' [IPv6AcceptRA] ${attrsToSection def.ipv6AcceptRAConfig} '' - + optionalString (def.dhcpServerConfig != { }) '' + + lib.optionalString (def.dhcpServerConfig != { }) '' [DHCPServer] ${attrsToSection def.dhcpServerConfig} '' - + optionalString (def.ipv6SendRAConfig != { }) '' + + lib.optionalString (def.ipv6SendRAConfig != { }) '' [IPv6SendRA] ${attrsToSection def.ipv6SendRAConfig} '' - + flip concatMapStrings def.ipv6PREF64Prefixes (x: '' + + lib.flip lib.concatMapStrings def.ipv6PREF64Prefixes (x: '' [IPv6PREF64Prefix] ${attrsToSection x} '') - + flip concatMapStrings def.ipv6Prefixes (x: '' + + lib.flip lib.concatMapStrings def.ipv6Prefixes (x: '' [IPv6Prefix] ${attrsToSection x} '') - + flip concatMapStrings def.ipv6RoutePrefixes (x: '' + + lib.flip lib.concatMapStrings def.ipv6RoutePrefixes (x: '' [IPv6RoutePrefix] ${attrsToSection x} '') - + flip concatMapStrings def.dhcpServerStaticLeases (x: '' + + lib.flip lib.concatMapStrings def.dhcpServerStaticLeases (x: '' [DHCPServerStaticLease] ${attrsToSection x} '') - + optionalString (def.bridgeConfig != { }) '' + + lib.optionalString (def.bridgeConfig != { }) '' [Bridge] ${attrsToSection def.bridgeConfig} '' - + flip concatMapStrings def.bridgeFDBs (x: '' + + lib.flip lib.concatMapStrings def.bridgeFDBs (x: '' [BridgeFDB] ${attrsToSection x} '') - + flip concatMapStrings def.bridgeMDBs (x: '' + + lib.flip lib.concatMapStrings def.bridgeMDBs (x: '' [BridgeMDB] ${attrsToSection x} '') - + optionalString (def.lldpConfig != { }) '' + + lib.optionalString (def.lldpConfig != { }) '' [LLDP] ${attrsToSection def.lldpConfig} '' - + optionalString (def.canConfig != { }) '' + + lib.optionalString (def.canConfig != { }) '' [CAN] ${attrsToSection def.canConfig} '' - + optionalString (def.ipoIBConfig != { }) '' + + lib.optionalString (def.ipoIBConfig != { }) '' [IPoIB] ${attrsToSection def.ipoIBConfig} '' - + optionalString (def.qdiscConfig != { }) '' + + lib.optionalString (def.qdiscConfig != { }) '' [QDisc] ${attrsToSection def.qdiscConfig} '' - + optionalString (def.networkEmulatorConfig != { }) '' + + lib.optionalString (def.networkEmulatorConfig != { }) '' [NetworkEmulator] ${attrsToSection def.networkEmulatorConfig} '' - + optionalString (def.tokenBucketFilterConfig != { }) '' + + lib.optionalString (def.tokenBucketFilterConfig != { }) '' [TokenBucketFilter] ${attrsToSection def.tokenBucketFilterConfig} '' - + optionalString (def.pieConfig != { }) '' + + lib.optionalString (def.pieConfig != { }) '' [PIE] ${attrsToSection def.pieConfig} '' - + optionalString (def.flowQueuePIEConfig != { }) '' + + lib.optionalString (def.flowQueuePIEConfig != { }) '' [FlowQueuePIE] ${attrsToSection def.flowQueuePIEConfig} '' - + optionalString (def.stochasticFairBlueConfig != { }) '' + + lib.optionalString (def.stochasticFairBlueConfig != { }) '' [StochasticFairBlue] ${attrsToSection def.stochasticFairBlueConfig} '' - + optionalString (def.stochasticFairnessQueueingConfig != { }) '' + + lib.optionalString (def.stochasticFairnessQueueingConfig != { }) '' [StochasticFairnessQueueing] ${attrsToSection def.stochasticFairnessQueueingConfig} '' - + optionalString (def.bfifoConfig != { }) '' + + lib.optionalString (def.bfifoConfig != { }) '' [BFIFO] ${attrsToSection def.bfifoConfig} '' - + optionalString (def.pfifoConfig != { }) '' + + lib.optionalString (def.pfifoConfig != { }) '' [PFIFO] ${attrsToSection def.pfifoConfig} '' - + optionalString (def.pfifoHeadDropConfig != { }) '' + + lib.optionalString (def.pfifoHeadDropConfig != { }) '' [PFIFOHeadDrop] ${attrsToSection def.pfifoHeadDropConfig} '' - + optionalString (def.pfifoFastConfig != { }) '' + + lib.optionalString (def.pfifoFastConfig != { }) '' [PFIFOFast] ${attrsToSection def.pfifoFastConfig} '' - + optionalString (def.cakeConfig != { }) '' + + lib.optionalString (def.cakeConfig != { }) '' [CAKE] ${attrsToSection def.cakeConfig} '' - + optionalString (def.controlledDelayConfig != { }) '' + + lib.optionalString (def.controlledDelayConfig != { }) '' [ControlledDelay] ${attrsToSection def.controlledDelayConfig} '' - + optionalString (def.deficitRoundRobinSchedulerConfig != { }) '' + + lib.optionalString (def.deficitRoundRobinSchedulerConfig != { }) '' [DeficitRoundRobinScheduler] ${attrsToSection def.deficitRoundRobinSchedulerConfig} '' - + optionalString (def.deficitRoundRobinSchedulerClassConfig != { }) '' + + lib.optionalString (def.deficitRoundRobinSchedulerClassConfig != { }) '' [DeficitRoundRobinSchedulerClass] ${attrsToSection def.deficitRoundRobinSchedulerClassConfig} '' - + optionalString (def.enhancedTransmissionSelectionConfig != { }) '' + + lib.optionalString (def.enhancedTransmissionSelectionConfig != { }) '' [EnhancedTransmissionSelection] ${attrsToSection def.enhancedTransmissionSelectionConfig} '' - + optionalString (def.genericRandomEarlyDetectionConfig != { }) '' + + lib.optionalString (def.genericRandomEarlyDetectionConfig != { }) '' [GenericRandomEarlyDetection] ${attrsToSection def.genericRandomEarlyDetectionConfig} '' - + optionalString (def.fairQueueingControlledDelayConfig != { }) '' + + lib.optionalString (def.fairQueueingControlledDelayConfig != { }) '' [FairQueueingControlledDelay] ${attrsToSection def.fairQueueingControlledDelayConfig} '' - + optionalString (def.fairQueueingConfig != { }) '' + + lib.optionalString (def.fairQueueingConfig != { }) '' [FairQueueing] ${attrsToSection def.fairQueueingConfig} '' - + optionalString (def.trivialLinkEqualizerConfig != { }) '' + + lib.optionalString (def.trivialLinkEqualizerConfig != { }) '' [TrivialLinkEqualizer] ${attrsToSection def.trivialLinkEqualizerConfig} '' - + optionalString (def.hierarchyTokenBucketConfig != { }) '' + + lib.optionalString (def.hierarchyTokenBucketConfig != { }) '' [HierarchyTokenBucket] ${attrsToSection def.hierarchyTokenBucketConfig} '' - + optionalString (def.hierarchyTokenBucketClassConfig != { }) '' + + lib.optionalString (def.hierarchyTokenBucketClassConfig != { }) '' [HierarchyTokenBucketClass] ${attrsToSection def.hierarchyTokenBucketClassConfig} '' - + optionalString (def.heavyHitterFilterConfig != { }) '' + + lib.optionalString (def.heavyHitterFilterConfig != { }) '' [HeavyHitterFilter] ${attrsToSection def.heavyHitterFilterConfig} '' - + optionalString (def.quickFairQueueingConfig != { }) '' + + lib.optionalString (def.quickFairQueueingConfig != { }) '' [QuickFairQueueing] ${attrsToSection def.quickFairQueueingConfig} '' - + optionalString (def.quickFairQueueingConfigClass != { }) '' + + lib.optionalString (def.quickFairQueueingConfigClass != { }) '' [QuickFairQueueingClass] ${attrsToSection def.quickFairQueueingConfigClass} '' - + flip concatMapStrings def.bridgeVLANs (x: '' + + lib.flip lib.concatMapStrings def.bridgeVLANs (x: '' [BridgeVLAN] ${attrsToSection x} '') diff --git a/nixos/lib/systemd-types.nix b/nixos/lib/systemd-types.nix index e3926c14252fc..911499e2d2561 100644 --- a/nixos/lib/systemd-types.nix +++ b/nixos/lib/systemd-types.nix @@ -39,52 +39,30 @@ let stage2TimerOptions ; - inherit (lib) - mkDefault - mkDerivedConfig - mkEnableOption - mkIf - mkOption - ; - - inherit (lib.types) - attrsOf - coercedTo - enum - lines - listOf - nullOr - oneOf - package - path - singleLineStr - submodule - ; - initrdStorePathModule = { config, ... }: { options = { - enable = (mkEnableOption "copying of this file and symlinking it") // { + enable = (lib.mkEnableOption "copying of this file and symlinking it") // { default = true; }; - target = mkOption { - type = nullOr path; + target = lib.mkOption { + type = lib.types.nullOr lib.types.path; description = '' Path of the symlink. ''; default = null; }; - source = mkOption { - type = path; + source = lib.mkOption { + type = lib.types.path; description = "Path of the source file."; }; dlopen = { - usePriority = mkOption { - type = enum [ + usePriority = lib.mkOption { + type = lib.types.enum [ "required" "recommended" "suggested" @@ -99,8 +77,8 @@ let ''; }; - features = mkOption { - type = listOf singleLineStr; + features = lib.mkOption { + type = lib.types.listOf lib.types.singleLineStr; default = [ ]; description = '' Features to enable via dlopen ELF notes. These will be in @@ -115,116 +93,116 @@ let in { - units = attrsOf ( - submodule ( + units = lib.types.attrsOf ( + lib.types.submodule ( { name, config, ... }: { options = concreteUnitOptions; config = { - name = mkDefault name; - unit = mkDefault (makeUnit name config); + name = lib.mkDefault name; + unit = lib.mkDefault (makeUnit name config); }; } ) ); - services = attrsOf (submodule [ + services = lib.types.attrsOf (lib.types.submodule [ stage2ServiceOptions unitConfig stage2ServiceConfig ]); - initrdServices = attrsOf (submodule [ + initrdServices = lib.types.attrsOf (lib.types.submodule [ stage1ServiceOptions unitConfig stage1ServiceConfig ]); - targets = attrsOf (submodule [ + targets = lib.types.attrsOf (lib.types.submodule [ stage2CommonUnitOptions unitConfig targetConfig ]); - initrdTargets = attrsOf (submodule [ + initrdTargets = lib.types.attrsOf (lib.types.submodule [ stage1CommonUnitOptions unitConfig targetConfig ]); - sockets = attrsOf (submodule [ + sockets = lib.types.attrsOf (lib.types.submodule [ stage2SocketOptions unitConfig socketConfig ]); - initrdSockets = attrsOf (submodule [ + initrdSockets = lib.types.attrsOf (lib.types.submodule [ stage1SocketOptions unitConfig socketConfig ]); - timers = attrsOf (submodule [ + timers = lib.types.attrsOf (lib.types.submodule [ stage2TimerOptions unitConfig timerConfig ]); - initrdTimers = attrsOf (submodule [ + initrdTimers = lib.types.attrsOf (lib.types.submodule [ stage1TimerOptions unitConfig timerConfig ]); - paths = attrsOf (submodule [ + paths = lib.types.attrsOf (lib.types.submodule [ stage2PathOptions unitConfig pathConfig ]); - initrdPaths = attrsOf (submodule [ + initrdPaths = lib.types.attrsOf (lib.types.submodule [ stage1PathOptions unitConfig pathConfig ]); - slices = attrsOf (submodule [ + slices = lib.types.attrsOf (lib.types.submodule [ stage2SliceOptions unitConfig sliceConfig ]); - initrdSlices = attrsOf (submodule [ + initrdSlices = lib.types.attrsOf (lib.types.submodule [ stage1SliceOptions unitConfig sliceConfig ]); - mounts = listOf (submodule [ + mounts = lib.types.listOf (lib.types.submodule [ stage2MountOptions unitConfig mountConfig ]); - initrdMounts = listOf (submodule [ + initrdMounts = lib.types.listOf (lib.types.submodule [ stage1MountOptions unitConfig mountConfig ]); - automounts = listOf (submodule [ + automounts = lib.types.listOf (lib.types.submodule [ stage2AutomountOptions unitConfig automountConfig ]); - initrdAutomounts = attrsOf (submodule [ + initrdAutomounts = lib.types.attrsOf (lib.types.submodule [ stage1AutomountOptions unitConfig automountConfig ]); - initrdStorePath = listOf ( - coercedTo (oneOf [ - singleLineStr - package - ]) (source: { inherit source; }) (submodule initrdStorePathModule) + initrdStorePath = lib.types.listOf ( + lib.types.coercedTo (lib.types.oneOf [ + lib.types.singleLineStr + lib.types.package + ]) (source: { inherit source; }) (lib.types.submodule initrdStorePathModule) ); - initrdContents = attrsOf ( - submodule ( + initrdContents = lib.types.attrsOf ( + lib.types.submodule ( { config, options, @@ -234,20 +212,20 @@ in { imports = [ initrdStorePathModule ]; options = { - text = mkOption { + text = lib.mkOption { default = null; - type = nullOr lines; + type = lib.types.nullOr lib.types.lines; description = "Text of the file."; }; }; config = { - target = mkDefault name; - source = mkIf (config.text != null) ( + target = lib.mkDefault name; + source = lib.mkIf (config.text != null) ( let name' = "initrd-" + baseNameOf name; in - mkDerivedConfig options.text (pkgs.writeText name') + lib.mkDerivedConfig options.text (pkgs.writeText name') ); }; } diff --git a/nixos/lib/systemd-unit-options.nix b/nixos/lib/systemd-unit-options.nix index b158ab7fca96c..d52a7752616cd 100644 --- a/nixos/lib/systemd-unit-options.nix +++ b/nixos/lib/systemd-unit-options.nix @@ -3,31 +3,11 @@ let inherit (systemdUtils.lib) assertValueOneOf - automountConfig checkUnitConfig makeJobScript - mountConfig - serviceConfig - unitConfig unitNameType ; - inherit (lib) - any - concatMap - filterOverrides - isList - literalExpression - mergeEqualOption - mkIf - mkMerge - mkOption - mkOptionType - singleton - toList - types - ; - checkService = checkUnitConfig "Service" [ (assertValueOneOf "Type" [ "exec" "simple" "forking" "oneshot" "dbus" "notify" "notify-reload" "idle" @@ -39,22 +19,22 @@ let in rec { - unitOption = mkOptionType { + unitOption = lib.mkOptionType { name = "systemd option"; merge = loc: defs: let - defs' = filterOverrides defs; + defs' = lib.filterOverrides defs; in - if any (def: isList def.value) defs' - then concatMap (def: toList def.value) defs' - else mergeEqualOption loc defs'; + if lib.any (def: lib.isList def.value) defs' + then lib.concatMap (def: lib.toList def.value) defs' + else lib.mergeEqualOption loc defs'; }; sharedOptions = { - enable = mkOption { + enable = lib.mkOption { default = true; - type = types.bool; + type = lib.types.bool; description = '' If set to false, this unit will be a symlink to /dev/null. This is primarily useful to prevent specific @@ -74,9 +54,9 @@ in rec { ''; }; - overrideStrategy = mkOption { + overrideStrategy = lib.mkOption { default = "asDropinIfExists"; - type = types.enum [ "asDropinIfExists" "asDropin" ]; + type = lib.types.enum [ "asDropinIfExists" "asDropin" ]; description = '' Defines how unit configuration is provided for systemd: @@ -90,9 +70,9 @@ in rec { ''; }; - requiredBy = mkOption { + requiredBy = lib.mkOption { default = []; - type = types.listOf unitNameType; + type = lib.types.listOf unitNameType; description = '' Units that require (i.e. depend on and need to go down with) this unit. As discussed in the `wantedBy` option description this also creates @@ -100,18 +80,18 @@ in rec { ''; }; - upheldBy = mkOption { + upheldBy = lib.mkOption { default = []; - type = types.listOf unitNameType; + type = lib.types.listOf unitNameType; description = '' Keep this unit running as long as the listed units are running. This is a continuously enforced version of wantedBy. ''; }; - wantedBy = mkOption { + wantedBy = lib.mkOption { default = []; - type = types.listOf unitNameType; + type = lib.types.listOf unitNameType; description = '' Units that want (i.e. depend on) this unit. The default method for starting a unit by default at boot time is to set this option to @@ -127,9 +107,9 @@ in rec { ''; }; - aliases = mkOption { + aliases = lib.mkOption { default = []; - type = types.listOf unitNameType; + type = lib.types.listOf unitNameType; description = "Aliases of that unit."; }; @@ -137,13 +117,13 @@ in rec { concreteUnitOptions = sharedOptions // { - text = mkOption { - type = types.nullOr types.str; + text = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; description = "Text of this systemd unit."; }; - unit = mkOption { + unit = lib.mkOption { internal = true; description = "The generated unit."; }; @@ -153,101 +133,101 @@ in rec { commonUnitOptions = { options = sharedOptions // { - description = mkOption { + description = lib.mkOption { default = ""; - type = types.singleLineStr; + type = lib.types.singleLineStr; description = "Description of this unit used in systemd messages and progress indicators."; }; - documentation = mkOption { + documentation = lib.mkOption { default = []; - type = types.listOf types.str; + type = lib.types.listOf lib.types.str; description = "A list of URIs referencing documentation for this unit or its configuration."; }; - requires = mkOption { + requires = lib.mkOption { default = []; - type = types.listOf unitNameType; + type = lib.types.listOf unitNameType; description = '' Start the specified units when this unit is started, and stop this unit when the specified units are stopped or fail. ''; }; - wants = mkOption { + wants = lib.mkOption { default = []; - type = types.listOf unitNameType; + type = lib.types.listOf unitNameType; description = '' Start the specified units when this unit is started. ''; }; - upholds = mkOption { + upholds = lib.mkOption { default = []; - type = types.listOf unitNameType; + type = lib.types.listOf unitNameType; description = '' Keeps the specified running while this unit is running. A continuous version of `wants`. ''; }; - after = mkOption { + after = lib.mkOption { default = []; - type = types.listOf unitNameType; + type = lib.types.listOf unitNameType; description = '' If the specified units are started at the same time as this unit, delay this unit until they have started. ''; }; - before = mkOption { + before = lib.mkOption { default = []; - type = types.listOf unitNameType; + type = lib.types.listOf unitNameType; description = '' If the specified units are started at the same time as this unit, delay them until this unit has started. ''; }; - bindsTo = mkOption { + bindsTo = lib.mkOption { default = []; - type = types.listOf unitNameType; + type = lib.types.listOf unitNameType; description = '' Like ‘requires’, but in addition, if the specified units unexpectedly disappear, this unit will be stopped as well. ''; }; - partOf = mkOption { + partOf = lib.mkOption { default = []; - type = types.listOf unitNameType; + type = lib.types.listOf unitNameType; description = '' If the specified units are stopped or restarted, then this unit is stopped or restarted as well. ''; }; - conflicts = mkOption { + conflicts = lib.mkOption { default = []; - type = types.listOf unitNameType; + type = lib.types.listOf unitNameType; description = '' If the specified units are started, then this unit is stopped and vice versa. ''; }; - requisite = mkOption { + requisite = lib.mkOption { default = []; - type = types.listOf unitNameType; + type = lib.types.listOf unitNameType; description = '' Similar to requires. However if the units listed are not started, they will not be started and the transaction will fail. ''; }; - unitConfig = mkOption { + unitConfig = lib.mkOption { default = {}; example = { RequiresMountsFor = "/data"; }; - type = types.attrsOf unitOption; + type = lib.types.attrsOf unitOption; description = '' Each attribute in this set specifies an option in the `[Unit]` section of the unit. See @@ -255,26 +235,26 @@ in rec { ''; }; - onFailure = mkOption { + onFailure = lib.mkOption { default = []; - type = types.listOf unitNameType; + type = lib.types.listOf unitNameType; description = '' A list of one or more units that are activated when this unit enters the "failed" state. ''; }; - onSuccess = mkOption { + onSuccess = lib.mkOption { default = []; - type = types.listOf unitNameType; + type = lib.types.listOf unitNameType; description = '' A list of one or more units that are activated when this unit enters the "inactive" state. ''; }; - startLimitBurst = mkOption { - type = types.int; + startLimitBurst = lib.mkOption { + type = lib.types.int; description = '' Configure unit start rate limiting. Units which are started more than startLimitBurst times within an interval time @@ -282,8 +262,8 @@ in rec { ''; }; - startLimitIntervalSec = mkOption { - type = types.int; + startLimitIntervalSec = lib.mkOption { + type = lib.types.int; description = '' Configure unit start rate limiting. Units which are started more than startLimitBurst times within an interval time @@ -300,9 +280,9 @@ in rec { ]; options = { - restartTriggers = mkOption { + restartTriggers = lib.mkOption { default = []; - type = types.listOf types.unspecified; + type = lib.types.listOf lib.types.unspecified; description = '' An arbitrary list of items such as derivations. If any item in the list changes between reconfigurations, the service will @@ -310,9 +290,9 @@ in rec { ''; }; - reloadTriggers = mkOption { + reloadTriggers = lib.mkOption { default = []; - type = types.listOf unitOption; + type = lib.types.listOf unitOption; description = '' An arbitrary list of items such as derivations. If any item in the list changes between reconfigurations, the service will @@ -327,16 +307,16 @@ in rec { serviceOptions = { name, config, ... }: { options = { - environment = mkOption { + environment = lib.mkOption { default = {}; - type = with types; attrsOf (nullOr (oneOf [ str path package ])); + type = with lib.types; attrsOf (nullOr (oneOf [ str path package ])); example = { PATH = "/foo/bar/bin"; LANG = "nl_NL.UTF-8"; }; description = "Environment variables passed to the service's processes."; }; - path = mkOption { + path = lib.mkOption { default = []; - type = with types; listOf (oneOf [ package str ]); + type = with lib.types; listOf (oneOf [ package str ]); description = '' Packages added to the service's {env}`PATH` environment variable. Both the {file}`bin` @@ -345,12 +325,12 @@ in rec { ''; }; - serviceConfig = mkOption { + serviceConfig = lib.mkOption { default = {}; example = { RestartSec = 5; }; - type = types.addCheck (types.attrsOf unitOption) checkService; + type = lib.types.addCheck (lib.types.attrsOf unitOption) checkService; description = '' Each attribute in this set specifies an option in the `[Service]` section of the unit. See @@ -358,22 +338,22 @@ in rec { ''; }; - enableStrictShellChecks = mkOption { - type = types.bool; + enableStrictShellChecks = lib.mkOption { + type = lib.types.bool; description = "Enable running shellcheck on the generated scripts for this unit."; # The default gets set in systemd-lib.nix because we don't have access to # the full NixOS config here. - defaultText = literalExpression "config.systemd.enableStrictShellChecks"; + defaultText = lib.literalExpression "config.systemd.enableStrictShellChecks"; }; - script = mkOption { - type = types.lines; + script = lib.mkOption { + type = lib.types.lines; default = ""; description = "Shell commands executed as the service's main process."; }; - scriptArgs = mkOption { - type = types.str; + scriptArgs = lib.mkOption { + type = lib.types.str; default = ""; example = "%i"; description = '' @@ -382,8 +362,8 @@ in rec { ''; }; - preStart = mkOption { - type = types.lines; + preStart = lib.mkOption { + type = lib.types.lines; default = ""; description = '' Shell commands executed before the service's main process @@ -391,8 +371,8 @@ in rec { ''; }; - postStart = mkOption { - type = types.lines; + postStart = lib.mkOption { + type = lib.types.lines; default = ""; description = '' Shell commands executed after the service's main process @@ -400,8 +380,8 @@ in rec { ''; }; - reload = mkOption { - type = types.lines; + reload = lib.mkOption { + type = lib.types.lines; default = ""; description = '' Shell commands executed when the service's main process @@ -409,16 +389,16 @@ in rec { ''; }; - preStop = mkOption { - type = types.lines; + preStop = lib.mkOption { + type = lib.types.lines; default = ""; description = '' Shell commands executed to stop the service. ''; }; - postStop = mkOption { - type = types.lines; + postStop = lib.mkOption { + type = lib.types.lines; default = ""; description = '' Shell commands executed after the service's main process @@ -426,8 +406,8 @@ in rec { ''; }; - jobScripts = mkOption { - type = with types; coercedTo path singleton (listOf path); + jobScripts = lib.mkOption { + type = with lib.types; coercedTo path singleton (listOf path); internal = true; description = "A list of all job script derivations of this unit."; default = []; @@ -435,8 +415,8 @@ in rec { }; - config = mkMerge [ - (mkIf (config.preStart != "") rec { + config = lib.mkMerge [ + (lib.mkIf (config.preStart != "") rec { jobScripts = makeJobScript { name = "${name}-pre-start"; text = config.preStart; @@ -444,7 +424,7 @@ in rec { }; serviceConfig.ExecStartPre = [ jobScripts ]; }) - (mkIf (config.script != "") rec { + (lib.mkIf (config.script != "") rec { jobScripts = makeJobScript { name = "${name}-start"; text = config.script; @@ -452,7 +432,7 @@ in rec { }; serviceConfig.ExecStart = jobScripts + " " + config.scriptArgs; }) - (mkIf (config.postStart != "") rec { + (lib.mkIf (config.postStart != "") rec { jobScripts = makeJobScript { name = "${name}-post-start"; text = config.postStart; @@ -460,7 +440,7 @@ in rec { }; serviceConfig.ExecStartPost = [ jobScripts ]; }) - (mkIf (config.reload != "") rec { + (lib.mkIf (config.reload != "") rec { jobScripts = makeJobScript { name = "${name}-reload"; text = config.reload; @@ -468,7 +448,7 @@ in rec { }; serviceConfig.ExecReload = jobScripts; }) - (mkIf (config.preStop != "") rec { + (lib.mkIf (config.preStop != "") rec { jobScripts = makeJobScript { name = "${name}-pre-stop"; text = config.preStop; @@ -476,7 +456,7 @@ in rec { }; serviceConfig.ExecStop = jobScripts; }) - (mkIf (config.postStop != "") rec { + (lib.mkIf (config.postStop != "") rec { jobScripts = makeJobScript { name = "${name}-post-stop"; text = config.postStop; @@ -495,8 +475,8 @@ in rec { ]; options = { - restartIfChanged = mkOption { - type = types.bool; + restartIfChanged = lib.mkOption { + type = lib.types.bool; default = true; description = '' Whether the service should be restarted during a NixOS @@ -504,8 +484,8 @@ in rec { ''; }; - reloadIfChanged = mkOption { - type = types.bool; + reloadIfChanged = lib.mkOption { + type = lib.types.bool; default = false; description = '' Whether the service should be reloaded during a NixOS @@ -520,8 +500,8 @@ in rec { ''; }; - stopIfChanged = mkOption { - type = types.bool; + stopIfChanged = lib.mkOption { + type = lib.types.bool; default = true; description = '' If set, a changed unit is restarted by calling @@ -535,8 +515,8 @@ in rec { ''; }; - notSocketActivated = mkOption { - type = types.bool; + notSocketActivated = lib.mkOption { + type = lib.types.bool; default = false; description = '' If set, a changed unit is never assumed to be @@ -547,8 +527,8 @@ in rec { ''; }; - startAt = mkOption { - type = with types; either str (listOf str); + startAt = lib.mkOption { + type = with lib.types; either str (listOf str); default = []; example = "Sun 14:00:00"; description = '' @@ -558,7 +538,7 @@ in rec { to adding a corresponding timer unit with {option}`OnCalendar` set to the value given here. ''; - apply = v: if isList v then v else [ v ]; + apply = v: if lib.isList v then v else [ v ]; }; }; }; @@ -574,9 +554,9 @@ in rec { socketOptions = { options = { - listenStreams = mkOption { + listenStreams = lib.mkOption { default = []; - type = types.listOf types.str; + type = lib.types.listOf lib.types.str; example = [ "0.0.0.0:993" "/run/my-socket" ]; description = '' For each item in this list, a `ListenStream` @@ -584,9 +564,9 @@ in rec { ''; }; - listenDatagrams = mkOption { + listenDatagrams = lib.mkOption { default = []; - type = types.listOf types.str; + type = lib.types.listOf lib.types.str; example = [ "0.0.0.0:993" "/run/my-socket" ]; description = '' For each item in this list, a `ListenDatagram` @@ -594,10 +574,10 @@ in rec { ''; }; - socketConfig = mkOption { + socketConfig = lib.mkOption { default = {}; example = { ListenStream = "/run/my-socket"; }; - type = types.attrsOf unitOption; + type = lib.types.attrsOf unitOption; description = '' Each attribute in this set specifies an option in the `[Socket]` section of the unit. See @@ -626,10 +606,10 @@ in rec { timerOptions = { options = { - timerConfig = mkOption { + timerConfig = lib.mkOption { default = {}; example = { OnCalendar = "Sun 14:00:00"; Unit = "foo.service"; }; - type = types.attrsOf unitOption; + type = lib.types.attrsOf unitOption; description = '' Each attribute in this set specifies an option in the `[Timer]` section of the unit. See @@ -659,10 +639,10 @@ in rec { pathOptions = { options = { - pathConfig = mkOption { + pathConfig = lib.mkOption { default = {}; example = { PathChanged = "/some/path"; Unit = "changedpath.service"; }; - type = types.attrsOf unitOption; + type = lib.types.attrsOf unitOption; description = '' Each attribute in this set specifies an option in the `[Path]` section of the unit. See @@ -691,39 +671,39 @@ in rec { mountOptions = { options = { - what = mkOption { + what = lib.mkOption { example = "/dev/sda1"; - type = types.str; + type = lib.types.str; description = "Absolute path of device node, file or other resource. (Mandatory)"; }; - where = mkOption { + where = lib.mkOption { example = "/mnt"; - type = types.str; + type = lib.types.str; description = '' Absolute path of a directory of the mount point. Will be created if it doesn't exist. (Mandatory) ''; }; - type = mkOption { + type = lib.mkOption { default = ""; example = "ext4"; - type = types.str; + type = lib.types.str; description = "File system type."; }; - options = mkOption { + options = lib.mkOption { default = ""; example = "noatime"; - type = types.commas; + type = lib.types.commas; description = "Options used to mount the file system."; }; - mountConfig = mkOption { + mountConfig = lib.mkOption { default = {}; example = { DirectoryMode = "0775"; }; - type = types.attrsOf unitOption; + type = lib.types.attrsOf unitOption; description = '' Each attribute in this set specifies an option in the `[Mount]` section of the unit. See @@ -751,19 +731,19 @@ in rec { automountOptions = { options = { - where = mkOption { + where = lib.mkOption { example = "/mnt"; - type = types.str; + type = lib.types.str; description = '' Absolute path of a directory of the mount point. Will be created if it doesn't exist. (Mandatory) ''; }; - automountConfig = mkOption { + automountConfig = lib.mkOption { default = {}; example = { DirectoryMode = "0775"; }; - type = types.attrsOf unitOption; + type = lib.types.attrsOf unitOption; description = '' Each attribute in this set specifies an option in the `[Automount]` section of the unit. See @@ -791,10 +771,10 @@ in rec { sliceOptions = { options = { - sliceConfig = mkOption { + sliceConfig = lib.mkOption { default = {}; example = { MemoryMax = "2G"; }; - type = types.attrsOf unitOption; + type = lib.types.attrsOf unitOption; description = '' Each attribute in this set specifies an option in the `[Slice]` section of the unit. See diff --git a/nixos/lib/testing/call-test.nix b/nixos/lib/testing/call-test.nix index 9abcea07455ef..55eb70f3e3df0 100644 --- a/nixos/lib/testing/call-test.nix +++ b/nixos/lib/testing/call-test.nix @@ -1,10 +1,7 @@ { config, lib, ... }: -let - inherit (lib) mkOption types; -in { options = { - result = mkOption { + result = lib.mkOption { internal = true; default = config; }; diff --git a/nixos/lib/testing/driver.nix b/nixos/lib/testing/driver.nix index d4f8e0f0c6e38..93bfd1234d8cf 100644 --- a/nixos/lib/testing/driver.nix +++ b/nixos/lib/testing/driver.nix @@ -1,6 +1,5 @@ { config, lib, hostPkgs, ... }: let - inherit (lib) mkOption types literalMD; # Reifies and correctly wraps the python test driver for # the respective qemu version and with or without ocr support @@ -103,49 +102,49 @@ in { options = { - driver = mkOption { + driver = lib.mkOption { description = "Package containing a script that runs the test."; - type = types.package; - defaultText = literalMD "set by the test framework"; + type = lib.types.package; + defaultText = lib.literalMD "set by the test framework"; }; - hostPkgs = mkOption { + hostPkgs = lib.mkOption { description = "Nixpkgs attrset used outside the nodes."; - type = types.raw; + type = lib.types.raw; example = lib.literalExpression '' import nixpkgs { inherit system config overlays; } ''; }; - qemu.package = mkOption { + qemu.package = lib.mkOption { description = "Which qemu package to use for the virtualisation of [{option}`nodes`](#test-opt-nodes)."; - type = types.package; + type = lib.types.package; default = hostPkgs.qemu_test; defaultText = "hostPkgs.qemu_test"; }; - globalTimeout = mkOption { + globalTimeout = lib.mkOption { description = '' A global timeout for the complete test, expressed in seconds. Beyond that timeout, every resource will be killed and released and the test will fail. By default, we use a 1 hour timeout. ''; - type = types.int; + type = lib.types.int; default = 60 * 60; example = 10 * 60; }; - enableOCR = mkOption { + enableOCR = lib.mkOption { description = '' Whether to enable Optical Character Recognition functionality for testing graphical programs. See [`Machine objects`](#ssec-machine-objects). ''; - type = types.bool; + type = lib.types.bool; default = false; }; - extraPythonPackages = mkOption { + extraPythonPackages = lib.mkOption { description = '' Python packages to add to the test driver. @@ -154,30 +153,30 @@ in example = lib.literalExpression '' p: [ p.numpy ] ''; - type = types.functionTo (types.listOf types.package); + type = lib.types.functionTo (lib.types.listOf lib.types.package); default = ps: [ ]; }; - extraDriverArgs = mkOption { + extraDriverArgs = lib.mkOption { description = '' Extra arguments to pass to the test driver. They become part of [{option}`driver`](#test-opt-driver) via `wrapProgram`. ''; - type = types.listOf types.str; + type = lib.types.listOf lib.types.str; default = []; }; - skipLint = mkOption { - type = types.bool; + skipLint = lib.mkOption { + type = lib.types.bool; default = false; description = '' Do not run the linters. This may speed up your iteration cycle, but it is not something you should commit. ''; }; - skipTypeCheck = mkOption { - type = types.bool; + skipTypeCheck = lib.mkOption { + type = lib.types.bool; default = false; description = '' Disable type checking. This must not be enabled for new NixOS tests. diff --git a/nixos/lib/testing/interactive.nix b/nixos/lib/testing/interactive.nix index 959cf463160c3..d4210b942ee70 100644 --- a/nixos/lib/testing/interactive.nix +++ b/nixos/lib/testing/interactive.nix @@ -5,12 +5,10 @@ hostPkgs, ... }: -let - inherit (lib) mkOption types; -in + { options = { - interactive = mkOption { + interactive = lib.mkOption { description = '' Tests [can be run interactively](#sec-running-nixos-tests-interactively) using the program in the test derivation's `.driverInteractive` attribute. diff --git a/nixos/lib/testing/legacy.nix b/nixos/lib/testing/legacy.nix index 9c901ce061470..891066174949d 100644 --- a/nixos/lib/testing/legacy.nix +++ b/nixos/lib/testing/legacy.nix @@ -4,9 +4,7 @@ lib, ... }: -let - inherit (lib) mkIf mkOption types; -in + { # This needs options.warnings and options.assertions, which we don't have (yet?). # imports = [ @@ -15,14 +13,14 @@ in # ]; options = { - machine = mkOption { + machine = lib.mkOption { internal = true; - type = types.raw; + type = lib.types.raw; }; }; config = { - nodes = mkIf options.machine.isDefined ( + nodes = lib.mkIf options.machine.isDefined ( lib.warn "In test `${config.name}': The `machine' attribute in NixOS tests (pkgs.nixosTest / make-test-python.nix / testing-python.nix / makeTest) is deprecated. Please set the equivalent `nodes.machine'." { inherit (config) machine; } diff --git a/nixos/lib/testing/meta.nix b/nixos/lib/testing/meta.nix index 0a4c89ed4b063..43b3ff181f2ea 100644 --- a/nixos/lib/testing/meta.nix +++ b/nixos/lib/testing/meta.nix @@ -1,7 +1,5 @@ { lib, ... }: -let - inherit (lib) types mkOption; -in + { options = { meta = lib.mkOption { @@ -11,31 +9,31 @@ in Not all [`meta`](https://nixos.org/manual/nixpkgs/stable/#chap-meta) attributes are supported, but more can be added as desired. ''; apply = lib.filterAttrs (k: v: v != null); - type = types.submodule { + type = lib.types.submodule { options = { maintainers = lib.mkOption { - type = types.listOf types.raw; + type = lib.types.listOf lib.types.raw; default = [ ]; description = '' The [list of maintainers](https://nixos.org/manual/nixpkgs/stable/#var-meta-maintainers) for this test. ''; }; timeout = lib.mkOption { - type = types.nullOr types.int; + type = lib.types.nullOr lib.types.int; default = 3600; # 1 hour description = '' The [{option}`test`](#test-opt-test)'s [`meta.timeout`](https://nixos.org/manual/nixpkgs/stable/#var-meta-timeout) in seconds. ''; }; broken = lib.mkOption { - type = types.bool; + type = lib.types.bool; default = false; description = '' Sets the [`meta.broken`](https://nixos.org/manual/nixpkgs/stable/#var-meta-broken) attribute on the [{option}`test`](#test-opt-test) derivation. ''; }; platforms = lib.mkOption { - type = types.listOf types.raw; + type = lib.types.listOf lib.types.raw; default = lib.platforms.linux ++ lib.platforms.darwin; description = '' Sets the [`meta.platforms`](https://nixos.org/manual/nixpkgs/stable/#var-meta-platforms) attribute on the [{option}`test`](#test-opt-test) derivation. diff --git a/nixos/lib/testing/name.nix b/nixos/lib/testing/name.nix index 0682873c7bcd0..88f17b62d3781 100644 --- a/nixos/lib/testing/name.nix +++ b/nixos/lib/testing/name.nix @@ -1,14 +1,12 @@ { lib, ... }: -let - inherit (lib) mkOption types; -in + { - options.name = mkOption { + options.name = lib.mkOption { description = '' The name of the test. This is used in the derivation names of the [{option}`driver`](#test-opt-driver) and [{option}`test`](#test-opt-test) runner. ''; - type = types.str; + type = lib.types.str; }; } diff --git a/nixos/lib/testing/network.nix b/nixos/lib/testing/network.nix index c393056009d83..9d0728605426f 100644 --- a/nixos/lib/testing/network.nix +++ b/nixos/lib/testing/network.nix @@ -1,26 +1,8 @@ { lib, nodes, ... }: let - inherit (lib) - attrNames - concatMap - concatMapStrings - flip - forEach - head - listToAttrs - mkDefault - mkOption - nameValuePair - optionalString - range - toLower - types - zipListsWith - zipLists - ; - - nodeNumbers = listToAttrs (zipListsWith nameValuePair (attrNames nodes) (range 1 254)); + + nodeNumbers = lib.listToAttrs (lib.zipListsWith lib.nameValuePair (lib.attrNames nodes) (lib.range 1 254)); networkModule = { @@ -33,20 +15,20 @@ let qemu-common = import ../qemu-common.nix { inherit lib pkgs; }; # Convert legacy VLANs to named interfaces and merge with explicit interfaces. - vlansNumbered = forEach (zipLists config.virtualisation.vlans (range 1 255)) (v: { + vlansNumbered = lib.forEach (lib.zipLists config.virtualisation.vlans (lib.range 1 255)) (v: { name = "eth${toString v.snd}"; vlan = v.fst; assignIP = true; }); explicitInterfaces = lib.mapAttrsToList (n: v: v // { name = n; }) config.virtualisation.interfaces; interfaces = vlansNumbered ++ explicitInterfaces; - interfacesNumbered = zipLists interfaces (range 1 255); + interfacesNumbered = lib.zipLists interfaces (lib.range 1 255); # Automatically assign IP addresses to requested interfaces. assignIPs = lib.filter (i: i.assignIP) interfaces; - ipInterfaces = forEach assignIPs ( + ipInterfaces = lib.forEach assignIPs ( i: - nameValuePair i.name { + lib.nameValuePair i.name { ipv4.addresses = [ { address = "192.168.${toString i.vlan}.${toString config.virtualisation.test.nodeNumber}"; @@ -63,54 +45,54 @@ let ); qemuOptions = lib.flatten ( - forEach interfacesNumbered ( + lib.forEach interfacesNumbered ( { fst, snd }: qemu-common.qemuNICFlags snd fst.vlan config.virtualisation.test.nodeNumber ) ); - udevRules = forEach interfacesNumbered ( + udevRules = lib.forEach interfacesNumbered ( { fst, snd }: # MAC Addresses for QEMU network devices are lowercase, and udev string comparison is case-sensitive. - ''SUBSYSTEM=="net",ACTION=="add",ATTR{address}=="${toLower (qemu-common.qemuNicMac fst.vlan config.virtualisation.test.nodeNumber)}",NAME="${fst.name}"'' + ''SUBSYSTEM=="net",ACTION=="add",ATTR{address}=="${lib.toLower (qemu-common.qemuNicMac fst.vlan config.virtualisation.test.nodeNumber)}",NAME="${fst.name}"'' ); networkConfig = { - networking.hostName = mkDefault config.virtualisation.test.nodeName; + networking.hostName = lib.mkDefault config.virtualisation.test.nodeName; - networking.interfaces = listToAttrs ipInterfaces; + networking.interfaces = lib.listToAttrs ipInterfaces; networking.primaryIPAddress = - optionalString (ipInterfaces != [ ]) - (head (head ipInterfaces).value.ipv4.addresses).address; + lib.optionalString (ipInterfaces != [ ]) + (lib.head (lib.head ipInterfaces).value.ipv4.addresses).address; networking.primaryIPv6Address = - optionalString (ipInterfaces != [ ]) - (head (head ipInterfaces).value.ipv6.addresses).address; + lib.optionalString (ipInterfaces != [ ]) + (lib.head (lib.head ipInterfaces).value.ipv6.addresses).address; # Put the IP addresses of all VMs in this machine's # /etc/hosts file. If a machine has multiple # interfaces, use the IP address corresponding to # the first interface (i.e. the first network in its # virtualisation.vlans option). - networking.extraHosts = flip concatMapStrings (attrNames nodes) ( + networking.extraHosts = lib.flip lib.concatMapStrings (lib.attrNames nodes) ( m': let config = nodes.${m'}; hostnames = - optionalString ( + lib.optionalString ( config.networking.domain != null ) "${config.networking.hostName}.${config.networking.domain} " + "${config.networking.hostName}\n"; in - optionalString ( + lib.optionalString ( config.networking.primaryIPAddress != "" ) "${config.networking.primaryIPAddress} ${hostnames}" - + optionalString (config.networking.primaryIPv6Address != "") ( + + lib.optionalString (config.networking.primaryIPv6Address != "") ( "${config.networking.primaryIPv6Address} ${hostnames}" ) ); virtualisation.qemu.options = qemuOptions; - boot.initrd.services.udev.rules = concatMapStrings (x: x + "\n") udevRules; + boot.initrd.services.udev.rules = lib.concatMapStrings (x: x + "\n") udevRules; }; in @@ -127,7 +109,7 @@ let regular@{ config, name, ... }: { options = { - virtualisation.test.nodeName = mkOption { + virtualisation.test.nodeName = lib.mkOption { internal = true; default = name; # We need to force this in specilisations, otherwise it'd be @@ -136,9 +118,9 @@ let The `name` in `nodes.`; stable across `specialisations`. ''; }; - virtualisation.test.nodeNumber = mkOption { + virtualisation.test.nodeNumber = lib.mkOption { internal = true; - type = types.int; + type = lib.types.int; readOnly = true; default = nodeNumbers.${config.virtualisation.test.nodeName}; description = '' @@ -148,11 +130,11 @@ let # specialisations override the `name` module argument, # so we push the real `virtualisation.test.nodeName`. - specialisation = mkOption { - type = types.attrsOf ( - types.submodule { - options.configuration = mkOption { - type = types.submoduleWith { + specialisation = lib.mkOption { + type = lib.types.attrsOf ( + lib.types.submodule { + options.configuration = lib.mkOption { + type = lib.types.submoduleWith { modules = [ { config.virtualisation.test.nodeName = diff --git a/nixos/lib/testing/nixos-test-base.nix b/nixos/lib/testing/nixos-test-base.nix index 23358f2185b1f..52adcafeb5c28 100644 --- a/nixos/lib/testing/nixos-test-base.nix +++ b/nixos/lib/testing/nixos-test-base.nix @@ -31,7 +31,7 @@ in # Don't pull in switch-to-configuration by default, except when specialisations or early boot shenanigans are involved. # This is mostly a Hydra optimization, so we don't rebuild all the tests every time switch-to-configuration-ng changes. key = "no-switch-to-configuration"; - system.switch.enable = mkDefault ( + system.switch.enable = lib.mkDefault ( config.isSpecialisation || config.specialisation != { } || config.virtualisation.installBootLoader ); } diff --git a/nixos/lib/testing/nodes.nix b/nixos/lib/testing/nodes.nix index caefac6c748ca..4d02223226919 100644 --- a/nixos/lib/testing/nodes.nix +++ b/nixos/lib/testing/nodes.nix @@ -7,19 +7,6 @@ testModuleArgs@{ }: let - inherit (lib) - literalExpression - literalMD - mapAttrs - mkDefault - mkIf - mkOption - mkForce - optional - optionalAttrs - types - ; - inherit (hostPkgs.stdenv) hostPlatform; guestSystem = @@ -60,8 +47,8 @@ let { options, ... }: { key = "nodes.nix-pkgs"; - config = optionalAttrs (!config.node.pkgsReadOnly) ( - mkIf (!options.nixpkgs.pkgs.isDefined) { + config = lib.optionalAttrs (!config.node.pkgsReadOnly) ( + lib.mkIf (!options.nixpkgs.pkgs.isDefined) { # TODO: switch to nixpkgs.hostPlatform and make sure containers-imperative test still evaluates. nixpkgs.system = guestSystem; } @@ -77,14 +64,14 @@ in { options = { - node.type = mkOption { - type = types.raw; + node.type = lib.mkOption { + type = lib.types.raw; default = baseOS.type; internal = true; }; - nodes = mkOption { - type = types.lazyAttrsOf config.node.type; + nodes = lib.mkOption { + type = lib.types.lazyAttrsOf config.node.type; visible = "shallow"; description = '' An attribute set of NixOS configuration modules. @@ -97,48 +84,48 @@ in ''; }; - defaults = mkOption { + defaults = lib.mkOption { description = '' NixOS configuration that is applied to all [{option}`nodes`](#test-opt-nodes). ''; - type = types.deferredModule; + type = lib.types.deferredModule; default = { }; }; - extraBaseModules = mkOption { + extraBaseModules = lib.mkOption { description = '' NixOS configuration that, like [{option}`defaults`](#test-opt-defaults), is applied to all [{option}`nodes`](#test-opt-nodes) and can not be undone with [`specialisation..inheritParentConfig`](https://search.nixos.org/options?show=specialisation.%3Cname%3E.inheritParentConfig&from=0&size=50&sort=relevance&type=packages&query=specialisation). ''; - type = types.deferredModule; + type = lib.types.deferredModule; default = { }; }; - node.pkgs = mkOption { + node.pkgs = lib.mkOption { description = '' The Nixpkgs to use for the nodes. Setting this will make the `nixpkgs.*` options read-only, to avoid mistakenly testing with a Nixpkgs configuration that diverges from regular use. ''; - type = types.nullOr types.pkgs; + type = lib.types.nullOr lib.types.pkgs; default = null; - defaultText = literalMD '' + defaultText = lib.literalMD '' `null`, so construct `pkgs` according to the `nixpkgs.*` options as usual. ''; }; - node.pkgsReadOnly = mkOption { + node.pkgsReadOnly = lib.mkOption { description = '' Whether to make the `nixpkgs.*` options read-only. This is only relevant when [`node.pkgs`](#test-opt-node.pkgs) is set. Set this to `false` when any of the [`nodes`](#test-opt-nodes) needs to configure any of the `nixpkgs.*` options. This will slow down evaluation of your test a bit. ''; - type = types.bool; + type = lib.types.bool; default = config.node.pkgs != null; - defaultText = literalExpression ''node.pkgs != null''; + defaultText = lib.literalExpression ''node.pkgs != null''; }; - node.specialArgs = mkOption { - type = types.lazyAttrsOf types.raw; + node.specialArgs = lib.mkOption { + type = lib.types.lazyAttrsOf lib.types.raw; default = { }; description = '' An attribute set of arbitrary values that will be made available as module arguments during the resolution of module `imports`. @@ -147,7 +134,7 @@ in ''; }; - nodesCompat = mkOption { + nodesCompat = lib.mkOption { internal = true; description = '' Basically `_module.args.nodes`, but with backcompat and warnings added. @@ -159,7 +146,7 @@ in config = { _module.args.nodes = config.nodesCompat; - nodesCompat = mapAttrs ( + nodesCompat = lib.mapAttrs ( name: config: config // { @@ -172,7 +159,7 @@ in passthru.nodes = config.nodesCompat; - defaults = mkIf config.node.pkgsReadOnly { + defaults = lib.mkIf config.node.pkgsReadOnly { nixpkgs.pkgs = config.node.pkgs; imports = [ ../../modules/misc/nixpkgs/read-only.nix ]; }; diff --git a/nixos/lib/testing/run.nix b/nixos/lib/testing/run.nix index 4ea0b1e9a0348..7c5527ba45fdf 100644 --- a/nixos/lib/testing/run.nix +++ b/nixos/lib/testing/run.nix @@ -4,13 +4,10 @@ lib, ... }: -let - inherit (lib) types mkOption; -in { options = { - passthru = mkOption { - type = types.lazyAttrsOf types.raw; + passthru = lib.mkOption { + type = lib.types.lazyAttrsOf lib.types.raw; description = '' Attributes to add to the returned derivations, which are not necessarily part of the build. @@ -21,8 +18,8 @@ in ''; }; - rawTestDerivation = mkOption { - type = types.package; + rawTestDerivation = lib.mkOption { + type = lib.types.package; description = '' Unfiltered version of `test`, for troubleshooting the test framework and `testBuildFailure` in the test framework's test suite. This is not intended for general use. Use `test` instead. @@ -30,8 +27,8 @@ in internal = true; }; - test = mkOption { - type = types.package; + test = lib.mkOption { + type = lib.types.package; # TODO: can the interactive driver be configured to access the network? description = '' Derivation that runs the test as its "build" process. diff --git a/nixos/lib/testing/testScript.nix b/nixos/lib/testing/testScript.nix index bde7b78607b47..731b7ae05c61e 100644 --- a/nixos/lib/testing/testScript.nix +++ b/nixos/lib/testing/testScript.nix @@ -6,31 +6,27 @@ testModuleArgs@{ moduleType, ... }: -let - inherit (lib) mkOption types; - inherit (types) either str functionTo; -in { options = { - testScript = mkOption { - type = either str (functionTo str); + testScript = lib.mkOption { + type = lib.types.either lib.types.str (lib.types.functionTo lib.types.str); description = '' A series of python declarations and statements that you write to perform the test. ''; }; - testScriptString = mkOption { - type = str; + testScriptString = lib.mkOption { + type = lib.types.str; readOnly = true; internal = true; }; - includeTestScriptReferences = mkOption { - type = types.bool; + includeTestScriptReferences = lib.mkOption { + type = lib.types.bool; default = true; internal = true; }; - withoutTestScriptReferences = mkOption { + withoutTestScriptReferences = lib.mkOption { type = moduleType; description = '' A parallel universe where the testScript is invalid and has no references. diff --git a/nixos/lib/utils.nix b/nixos/lib/utils.nix index d0279083bcd71..1a0f1760f0829 100644 --- a/nixos/lib/utils.nix +++ b/nixos/lib/utils.nix @@ -5,37 +5,6 @@ }: let - inherit (lib) - any - attrNames - concatMapStringsSep - concatStringsSep - elem - escapeShellArg - filter - flatten - getName - hasPrefix - hasSuffix - imap0 - imap1 - isAttrs - isDerivation - isFloat - isInt - isList - isPath - isString - listToAttrs - mapAttrs - nameValuePair - optionalString - removePrefix - removeSuffix - replaceStrings - stringToCharacters - types - ; inherit (lib.strings) toJSON normalizePath escapeC; in @@ -64,7 +33,7 @@ let "/etc" "/usr" ]; - fsNeededForBoot = fs: fs.neededForBoot || elem fs.mountPoint pathsNeededForBoot; + fsNeededForBoot = fs: fs.neededForBoot || lib.elem fs.mountPoint pathsNeededForBoot; # Check whenever `b` depends on `a` as a fileSystem fsBefore = @@ -80,7 +49,7 @@ let # Here a.mountPoint *is* a prefix of b.device even though a.mountPoint is # *not* a parent of b.device. If we add a slash at the end of each string, # though, this is not a problem: "/aaa/" is not a prefix of "/aaaa/". - normalisePath = path: "${path}${optionalString (!(hasSuffix "/" path)) "/"}"; + normalisePath = path: "${path}${lib.optionalString (!(lib.hasSuffix "/" path)) "/"}"; normalise = mount: mount @@ -94,9 +63,9 @@ let b' = normalise b; in - hasPrefix a'.mountPoint b'.device - || hasPrefix a'.mountPoint b'.mountPoint - || any (hasPrefix a'.mountPoint) b'.depends; + lib.hasPrefix a'.mountPoint b'.device + || lib.hasPrefix a'.mountPoint b'.mountPoint + || lib.any (lib.hasPrefix a'.mountPoint) b'.depends; # Escape a path according to the systemd rules. FIXME: slow # The rules are described in systemd.unit(5) as follows: @@ -107,13 +76,13 @@ let let replacePrefix = p: r: s: - (if (hasPrefix p s) then r + (removePrefix p s) else s); - trim = s: removeSuffix "/" (removePrefix "/" s); + (if (lib.hasPrefix p s) then r + (lib.removePrefix p s) else s); + trim = s: lib.removeSuffix "/" (lib.removePrefix "/" s); normalizedPath = normalizePath s; in - replaceStrings [ "/" ] [ "-" ] ( + lib.replaceStrings [ "/" ] [ "-" ] ( replacePrefix "." (escapeC [ "." ] ".") ( - escapeC (stringToCharacters " !\"#$%&'()*+,;<=>=@[\\]^`{|}~-") ( + escapeC (lib.stringToCharacters " !\"#$%&'()*+,;<=>=@[\\]^`{|}~-") ( if normalizedPath == "/" then normalizedPath else trim normalizedPath ) ) @@ -130,27 +99,27 @@ let arg: let s = - if isPath arg then + if lib.isPath arg then "${arg}" - else if isString arg then + else if lib.isString arg then arg - else if isInt arg || isFloat arg || isDerivation arg then + else if lib.isInt arg || lib.isFloat arg || lib.isDerivation arg then toString arg else throw "escapeSystemdExecArg only allows strings, paths, numbers and derivations"; in - replaceStrings [ "%" "$" ] [ "%%" "$$" ] (toJSON s); + lib.replaceStrings [ "%" "$" ] [ "%%" "$$" ] (toJSON s); # Quotes a list of arguments into a single string for use in a Exec* # line. - escapeSystemdExecArgs = concatMapStringsSep " " escapeSystemdExecArg; + escapeSystemdExecArgs = lib.concatMapStringsSep " " escapeSystemdExecArg; # Returns a system path for a given shell package toShellPath = shell: - if types.shellPackage.check shell then + if lib.types.shellPackage.check shell then "/run/current-system/sw${shell.shellPath}" - else if types.package.check shell then + else if lib.types.package.check shell then throw "${shell} is not a shell package" else shell; @@ -179,7 +148,7 @@ let } "_secret" -> { ".example[1].relevant.secret" = "/path/to/secret"; } */ recursiveGetAttrWithJqPrefix = - item: attr: mapAttrs (_name: set: set.${attr}) (recursiveGetAttrsetWithJqPrefix item attr); + item: attr: lib.mapAttrs (_name: set: set.${attr}) (recursiveGetAttrsetWithJqPrefix item attr); /* Similar to `recursiveGetAttrWithJqPrefix`, but returns the whole @@ -210,23 +179,23 @@ let recurse = prefix: item: if item ? ${attr} then - nameValuePair prefix item - else if isDerivation item then + lib.nameValuePair prefix item + else if lib.isDerivation item then [ ] - else if isAttrs item then + else if lib.isAttrs item then map ( name: let - escapedName = ''"${replaceStrings [ ''"'' "\\" ] [ ''\"'' "\\\\" ] name}"''; + escapedName = ''"${lib.replaceStrings [ ''"'' "\\" ] [ ''\"'' "\\\\" ] name}"''; in recurse (prefix + "." + escapedName) item.${name} - ) (attrNames item) - else if isList item then - imap0 (index: item: recurse (prefix + "[${toString index}]") item) item + ) (lib.attrNames item) + else if lib.isList item then + lib.imap0 (index: item: recurse (prefix + "[${toString index}]") item) item else [ ]; in - listToAttrs (flatten (recurse "" item)); + lib.listToAttrs (lib.flatten (recurse "" item)); /* Takes an attrset and a file path and generates a bash snippet that @@ -339,7 +308,7 @@ let let secretsRaw = recursiveGetAttrsetWithJqPrefix set attr; # Set default option values - secrets = mapAttrs ( + secrets = lib.mapAttrs ( _name: set: { quote = true; @@ -357,20 +326,20 @@ let shopt -pq inherit_errexit && inherit_errexit_enabled=1 shopt -s inherit_errexit '' - + concatStringsSep "\n" ( - imap1 (index: name: '' + + lib.concatStringsSep "\n" ( + lib.imap1 (index: name: '' secret${toString index}=$(<'${secrets.${name}.${attr}}') export secret${toString index} - '') (attrNames secrets) + '') (lib.attrNames secrets) ) + "\n" + "${pkgs.jq}/bin/jq >'${output}' " - + escapeShellArg ( - stringOrDefault (concatStringsSep " | " ( - imap1 ( + + lib.escapeShellArg ( + stringOrDefault (lib.concatStringsSep " | " ( + lib.imap1 ( index: name: - ''${name} = ($ENV.secret${toString index}${optionalString (!secrets.${name}.quote) " | fromjson"})'' - ) (attrNames secrets) + ''${name} = ($ENV.secret${toString index}${lib.optionalString (!secrets.${name}.quote) " | fromjson"})'' + ) (lib.attrNames secrets) )) "." ) + '' @@ -394,9 +363,9 @@ let removePackagesByName = packages: packagesToRemove: let - namesToRemove = map getName packagesToRemove; + namesToRemove = map lib.getName packagesToRemove; in - filter (x: !(elem (getName x) namesToRemove)) packages; + lib.filter (x: !(lib.elem (lib.getName x) namesToRemove)) packages; /* Returns false if a package with the same name as the `package` is present in `packagesToDisable`. @@ -415,9 +384,9 @@ let disablePackageByName = package: packagesToDisable: let - namesToDisable = map getName packagesToDisable; + namesToDisable = map lib.getName packagesToDisable; in - !elem (getName package) namesToDisable; + !lib.elem (lib.getName package) namesToDisable; systemdUtils = { lib = import ./systemd-lib.nix { diff --git a/nixos/maintainers/scripts/ec2/amazon-image.nix b/nixos/maintainers/scripts/ec2/amazon-image.nix index d5b23d8a65f66..75b0d8bed0e54 100644 --- a/nixos/maintainers/scripts/ec2/amazon-image.nix +++ b/nixos/maintainers/scripts/ec2/amazon-image.nix @@ -6,13 +6,6 @@ }: let - inherit (lib) - mkOption - optionalString - types - versionAtLeast - ; - inherit (lib.options) literalExpression; cfg = config.amazonImage; amiBootMode = if config.ec2.efi then "uefi" else "legacy-bios"; in @@ -51,13 +44,13 @@ in config.boot.kernelParams = let timeout = - if versionAtLeast config.boot.kernelPackages.kernel.version "4.15" then "4294967295" else "255"; + if lib.versionAtLeast config.boot.kernelPackages.kernel.version "4.15" then "4294967295" else "255"; in [ "nvme_core.io_timeout=${timeout}" ]; options.amazonImage = { - contents = mkOption { - example = literalExpression '' + contents = lib.mkOption { + example = lib.literalExpression '' [ { source = pkgs.memtest86 + "/memtest.bin"; target = "boot/memtest.bin"; } @@ -70,8 +63,8 @@ in ''; }; - format = mkOption { - type = types.enum [ + format = lib.mkOption { + type = lib.types.enum [ "raw" "qcow2" "vpc" @@ -81,7 +74,7 @@ in }; }; - # Use a priority just below mkOptionDefault (1500) instead of lib.mkDefault + # Use a priority just below lib.mkOptionDefault (1500) instead of lib.mkDefault # to avoid breaking existing configs using that. config.virtualisation.diskSize = lib.mkOverride 1490 (3 * 1024); config.virtualisation.diskSizeAutoSupported = !config.ec2.zfs.enable; @@ -95,10 +88,10 @@ in configFile = pkgs.writeText "configuration.nix" '' { modulesPath, ... }: { imports = [ "''${modulesPath}/virtualisation/amazon-image.nix" ]; - ${optionalString config.ec2.efi '' + ${lib.optionalString config.ec2.efi '' ec2.efi = true; ''} - ${optionalString config.ec2.zfs.enable '' + ${lib.optionalString config.ec2.zfs.enable '' ec2.zfs.enable = true; networking.hostId = "${config.networking.hostId}"; ''} diff --git a/nixos/maintainers/scripts/openstack/openstack-image-zfs.nix b/nixos/maintainers/scripts/openstack/openstack-image-zfs.nix index 869d5a3c1fc3f..d9b62dcb33d69 100644 --- a/nixos/maintainers/scripts/openstack/openstack-image-zfs.nix +++ b/nixos/maintainers/scripts/openstack/openstack-image-zfs.nix @@ -7,7 +7,6 @@ ... }: let - inherit (lib) mkOption types; copyChannel = true; cfg = config.openstackImage; imageBootMode = if config.openstack.efi then "uefi" else "legacy-bios"; @@ -43,14 +42,14 @@ in ] ++ (lib.optional copyChannel ../../../modules/installer/cd-dvd/channel.nix); options.openstackImage = { - ramMB = mkOption { - type = types.int; + ramMB = lib.mkOption { + type = lib.types.int; default = (3 * 1024); description = "RAM allocation for build VM"; }; - format = mkOption { - type = types.enum [ + format = lib.mkOption { + type = lib.types.enum [ "raw" "qcow2" ]; @@ -74,7 +73,7 @@ in }; }; - # Use a priority just below mkOptionDefault (1500) instead of lib.mkDefault + # Use a priority just below lib.mkOptionDefault (1500) instead of lib.mkDefault # to avoid breaking existing configs using that. virtualisation.diskSize = lib.mkOverride 1490 (8 * 1024); virtualisation.diskSizeAutoSupported = false; diff --git a/nixos/modules/config/ldap.nix b/nixos/modules/config/ldap.nix index 3a63b6d5ca2c7..3bed9ea97de2b 100644 --- a/nixos/modules/config/ldap.nix +++ b/nixos/modules/config/ldap.nix @@ -6,15 +6,6 @@ }: let - inherit (lib) - mkEnableOption - mkIf - mkMerge - mkOption - mkRenamedOptionModule - types - ; - cfg = config.users.ldap; # Careful: OpenLDAP seems to be very picky about the indentation of @@ -67,34 +58,34 @@ in users.ldap = { - enable = mkEnableOption "authentication against an LDAP server"; + enable = lib.mkEnableOption "authentication against an LDAP server"; - loginPam = mkOption { - type = types.bool; + loginPam = lib.mkOption { + type = lib.types.bool; default = true; description = "Whether to include authentication against LDAP in login PAM."; }; - nsswitch = mkOption { - type = types.bool; + nsswitch = lib.mkOption { + type = lib.types.bool; default = true; description = "Whether to include lookup against LDAP in NSS."; }; - server = mkOption { - type = types.str; + server = lib.mkOption { + type = lib.types.str; example = "ldap://ldap.example.org/"; description = "The URL of the LDAP server."; }; - base = mkOption { - type = types.str; + base = lib.mkOption { + type = lib.types.str; example = "dc=example,dc=org"; description = "The distinguished name of the search base."; }; - useTLS = mkOption { - type = types.bool; + useTLS = lib.mkOption { + type = lib.types.bool; default = false; description = '' If enabled, use TLS (encryption) over an LDAP (port 389) @@ -104,9 +95,9 @@ in ''; }; - timeLimit = mkOption { + timeLimit = lib.mkOption { default = 0; - type = types.int; + type = lib.types.int; description = '' Specifies the time limit (in seconds) to use when performing searches. A value of zero (0), which is the default, is to @@ -115,8 +106,8 @@ in }; daemon = { - enable = mkOption { - type = types.bool; + enable = lib.mkOption { + type = lib.types.bool; default = false; description = '' Whether to let the nslcd daemon (nss-pam-ldapd) handle the @@ -130,29 +121,29 @@ in ''; }; - extraConfig = mkOption { + extraConfig = lib.mkOption { default = ""; - type = types.lines; + type = lib.types.lines; description = '' Extra configuration options that will be added verbatim at the end of the nslcd configuration file (`nslcd.conf(5)`). ''; }; - rootpwmoddn = mkOption { + rootpwmoddn = lib.mkOption { default = ""; example = "cn=admin,dc=example,dc=com"; - type = types.str; + type = lib.types.str; description = '' The distinguished name to use to bind to the LDAP server when the root user tries to modify a user's password. ''; }; - rootpwmodpwFile = mkOption { + rootpwmodpwFile = lib.mkOption { default = ""; example = "/run/keys/nslcd.rootpwmodpw"; - type = types.str; + type = lib.types.str; description = '' The path to a file containing the credentials with which to bind to the LDAP server if the root user tries to change a user's password. @@ -161,28 +152,28 @@ in }; bind = { - distinguishedName = mkOption { + distinguishedName = lib.mkOption { default = ""; example = "cn=admin,dc=example,dc=com"; - type = types.str; + type = lib.types.str; description = '' The distinguished name to bind to the LDAP server with. If this is not specified, an anonymous bind will be done. ''; }; - passwordFile = mkOption { + passwordFile = lib.mkOption { default = "/etc/ldap/bind.password"; - type = types.str; + type = lib.types.str; description = '' The path to a file containing the credentials to use when binding to the LDAP server (if not binding anonymously). ''; }; - timeLimit = mkOption { + timeLimit = lib.mkOption { default = 30; - type = types.int; + type = lib.types.int; description = '' Specifies the time limit (in seconds) to use when connecting to the directory server. This is distinct from the time limit @@ -191,9 +182,9 @@ in ''; }; - policy = mkOption { + policy = lib.mkOption { default = "hard_open"; - type = types.enum [ + type = lib.types.enum [ "hard_open" "hard_init" "soft" @@ -214,9 +205,9 @@ in }; }; - extraConfig = mkOption { + extraConfig = lib.mkOption { default = ""; - type = types.lines; + type = lib.types.lines; description = '' Extra configuration options that will be added verbatim at the end of the ldap configuration file (`ldap.conf(5)`). @@ -232,13 +223,13 @@ in ###### implementation - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { environment.etc = lib.optionalAttrs (!cfg.daemon.enable) { "ldap.conf" = ldapConfig; }; - system.nssModules = mkIf cfg.nsswitch ( + system.nssModules = lib.mkIf cfg.nsswitch ( lib.singleton (if cfg.daemon.enable then pkgs.nss_pam_ldapd else pkgs.nss_ldap) ); @@ -246,7 +237,7 @@ in system.nssDatabases.passwd = lib.optional cfg.nsswitch "ldap"; system.nssDatabases.shadow = lib.optional cfg.nsswitch "ldap"; - users = mkIf cfg.daemon.enable { + users = lib.mkIf cfg.daemon.enable { groups.nslcd = { gid = config.ids.gids.nslcd; }; @@ -258,8 +249,8 @@ in }; }; - systemd.services = mkMerge [ - (mkIf (!cfg.daemon.enable) { + systemd.services = lib.mkMerge [ + (lib.mkIf (!cfg.daemon.enable) { ldap-password = { wantedBy = [ "sysinit.target" ]; before = [ @@ -282,7 +273,7 @@ in }; }) - (mkIf cfg.daemon.enable { + (lib.mkIf cfg.daemon.enable { nslcd = { wantedBy = [ "multi-user.target" ]; @@ -322,7 +313,7 @@ in }; imports = [ - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "users" "ldap" "bind" "password" ] [ "users" "ldap" "bind" "passwordFile" ] ) diff --git a/nixos/modules/config/ldso.nix b/nixos/modules/config/ldso.nix index 5ea3842b6e041..cc4d7b8daac35 100644 --- a/nixos/modules/config/ldso.nix +++ b/nixos/modules/config/ldso.nix @@ -6,17 +6,9 @@ }: let - inherit (lib) - last - splitString - mkOption - types - optionals - ; - libDir = pkgs.stdenv.hostPlatform.libDir; ldsoBasename = builtins.unsafeDiscardStringContext ( - last (splitString "/" pkgs.stdenv.cc.bintools.dynamicLinker) + lib.last (lib.splitString "/" pkgs.stdenv.cc.bintools.dynamicLinker) ); # Hard-code to avoid creating another instance of nixpkgs. Also avoids eval errors in some cases. @@ -25,16 +17,16 @@ let in { options = { - environment.ldso = mkOption { - type = types.nullOr types.path; + environment.ldso = lib.mkOption { + type = lib.types.nullOr lib.types.path; default = null; description = '' The executable to link into the normal FHS location of the ELF loader. ''; }; - environment.ldso32 = mkOption { - type = types.nullOr types.path; + environment.ldso32 = lib.mkOption { + type = lib.types.nullOr lib.types.path; default = null; description = '' The executable to link into the normal FHS location of the 32-bit ELF loader. @@ -64,7 +56,7 @@ in "L+ /${libDir}/${ldsoBasename} - - - - ${config.environment.ldso}" ] ) - ++ optionals pkgs.stdenv.hostPlatform.isx86_64 ( + ++ lib.optionals pkgs.stdenv.hostPlatform.isx86_64 ( if isNull config.environment.ldso32 then [ "r /${libDir32}/${ldsoBasename32} - - - - -" diff --git a/nixos/modules/config/malloc.nix b/nixos/modules/config/malloc.nix index dfcc6c8159e53..73e4cd7901fbe 100644 --- a/nixos/modules/config/malloc.nix +++ b/nixos/modules/config/malloc.nix @@ -13,7 +13,7 @@ let libPath = "${pkgs.graphene-hardened-malloc}/lib/libhardened_malloc.so"; description = '' Hardened memory allocator coming from GrapheneOS project. - The default configuration template has all normal optional security + The default configuration template has all normal lib.optional security features enabled and is quite aggressive in terms of sacrificing performance and memory usage for security. ''; @@ -64,7 +64,7 @@ let libPath = "${pkgs.mimalloc}/lib/libmimalloc.so"; description = '' A compact and fast general purpose allocator, which may - optionally be built with mitigations against various heap + lib.optionally be built with mitigations against various heap vulnerabilities. ''; }; diff --git a/nixos/modules/config/nix-channel.nix b/nixos/modules/config/nix-channel.nix index de2c9407498e7..027674c6abbfd 100644 --- a/nixos/modules/config/nix-channel.nix +++ b/nixos/modules/config/nix-channel.nix @@ -8,13 +8,6 @@ */ { config, lib, ... }: let - inherit (lib) - mkDefault - mkIf - mkOption - stringAfter - types - ; cfg = config.nix; @@ -23,7 +16,7 @@ in options = { nix = { channel = { - enable = mkOption { + enable = lib.mkOption { description = '' Whether the `nix-channel` command and state files are made available on the machine. @@ -34,13 +27,13 @@ in Disabling this option will not remove the state files from the system. ''; - type = types.bool; + type = lib.types.bool; default = true; }; }; - nixPath = mkOption { - type = types.listOf types.str; + nixPath = lib.mkOption { + type = lib.types.listOf lib.types.str; default = if cfg.channel.enable then [ @@ -67,25 +60,25 @@ in }; system = { - defaultChannel = mkOption { + defaultChannel = lib.mkOption { internal = true; - type = types.str; + type = lib.types.str; default = "https://nixos.org/channels/nixos-24.11"; description = "Default NixOS channel to which the root user is subscribed."; }; }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { environment.extraInit = - mkIf cfg.channel.enable '' + lib.mkIf cfg.channel.enable '' if [ -e "$HOME/.nix-defexpr/channels" ]; then export NIX_PATH="$HOME/.nix-defexpr/channels''${NIX_PATH:+:$NIX_PATH}" fi ''; - environment.extraSetup = mkIf (!cfg.channel.enable) '' + environment.extraSetup = lib.mkIf (!cfg.channel.enable) '' rm --force $out/bin/nix-channel ''; @@ -99,7 +92,7 @@ in ''f /root/.nix-channels - - - - ${config.system.defaultChannel} nixos\n'' ]; - system.activationScripts.no-nix-channel = mkIf (!cfg.channel.enable) - (stringAfter [ "etc" "users" ] (builtins.readFile ./nix-channel/activation-check.sh)); + system.activationScripts.no-nix-channel = lib.mkIf (!cfg.channel.enable) + (lib.stringAfter [ "etc" "users" ] (builtins.readFile ./nix-channel/activation-check.sh)); }; } diff --git a/nixos/modules/config/nix-flakes.nix b/nixos/modules/config/nix-flakes.nix index 69388e791154f..3b7c313dea0e9 100644 --- a/nixos/modules/config/nix-flakes.nix +++ b/nixos/modules/config/nix-flakes.nix @@ -7,15 +7,6 @@ */ { config, lib, ... }: let - inherit (lib) - filterAttrs - literalExpression - mapAttrsToList - mkDefault - mkIf - mkOption - types - ; cfg = config.nix; @@ -23,12 +14,12 @@ in { options = { nix = { - registry = mkOption { - type = types.attrsOf ( - types.submodule ( + registry = lib.mkOption { + type = lib.types.attrsOf ( + lib.types.submodule ( let referenceAttrs = - with types; + with lib.types; attrsOf (oneOf [ str int @@ -40,7 +31,7 @@ in { config, name, ... }: { options = { - from = mkOption { + from = lib.mkOption { type = referenceAttrs; example = { type = "indirect"; @@ -48,7 +39,7 @@ in }; description = "The flake reference to be rewritten."; }; - to = mkOption { + to = lib.mkOption { type = referenceAttrs; example = { type = "github"; @@ -57,16 +48,16 @@ in }; description = "The flake reference {option}`from` is rewritten to."; }; - flake = mkOption { - type = types.nullOr types.attrs; + flake = lib.mkOption { + type = lib.types.nullOr lib.types.attrs; default = null; - example = literalExpression "nixpkgs"; + example = lib.literalExpression "nixpkgs"; description = '' The flake input {option}`from` is rewritten to. ''; }; - exact = mkOption { - type = types.bool; + exact = lib.mkOption { + type = lib.types.bool; default = true; description = '' Whether the {option}`from` reference needs to match exactly. If set, @@ -76,17 +67,17 @@ in }; }; config = { - from = mkDefault { + from = lib.mkDefault { type = "indirect"; id = name; }; - to = mkIf (config.flake != null) ( - mkDefault ( + to = lib.mkIf (config.flake != null) ( + lib.mkDefault ( { type = "path"; path = config.flake.outPath; } - // filterAttrs (n: _: n == "lastModified" || n == "rev" || n == "narHash") config.flake + // lib.filterAttrs (n: _: n == "lastModified" || n == "rev" || n == "narHash") config.flake ) ); }; @@ -101,10 +92,10 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { environment.etc."nix/registry.json".text = builtins.toJSON { version = 2; - flakes = mapAttrsToList (n: v: { inherit (v) from to exact; }) cfg.registry; + flakes = lib.mapAttrsToList (n: v: { inherit (v) from to exact; }) cfg.registry; }; }; } diff --git a/nixos/modules/config/nix-remote-build.nix b/nixos/modules/config/nix-remote-build.nix index 4786fef31d065..e6562409dedb3 100644 --- a/nixos/modules/config/nix-remote-build.nix +++ b/nixos/modules/config/nix-remote-build.nix @@ -8,39 +8,25 @@ { config, lib, ... }: let - inherit (lib) - any - concatMapStrings - concatStringsSep - filter - getVersion - mkIf - mkMerge - mkOption - optional - optionalString - types - versionAtLeast - ; cfg = config.nix; nixPackage = cfg.package.out; - isNixAtLeast = versionAtLeast (getVersion nixPackage); + isNixAtLeast = lib.versionAtLeast (lib.getVersion nixPackage); - buildMachinesText = concatMapStrings ( + buildMachinesText = lib.concatMapStrings ( machine: - (concatStringsSep " " ( + (lib.concatStringsSep " " ( [ - "${optionalString (machine.protocol != null) "${machine.protocol}://"}${ - optionalString (machine.sshUser != null) "${machine.sshUser}@" + "${lib.optionalString (machine.protocol != null) "${machine.protocol}://"}${ + lib.optionalString (machine.sshUser != null) "${machine.sshUser}@" }${machine.hostName}" ( if machine.system != null then machine.system else if machine.systems != [ ] then - concatStringsSep "," machine.systems + lib.concatStringsSep "," machine.systems else "-" ) @@ -51,16 +37,16 @@ let let res = (machine.supportedFeatures ++ machine.mandatoryFeatures); in - if (res == [ ]) then "-" else (concatStringsSep "," res) + if (res == [ ]) then "-" else (lib.concatStringsSep "," res) ) ( let res = machine.mandatoryFeatures; in - if (res == [ ]) then "-" else (concatStringsSep "," machine.mandatoryFeatures) + if (res == [ ]) then "-" else (lib.concatStringsSep "," machine.mandatoryFeatures) ) ] - ++ optional (isNixAtLeast "2.4pre") ( + ++ lib.optional (isNixAtLeast "2.4pre") ( if machine.publicHostKey != null then machine.publicHostKey else "-" ) )) @@ -71,19 +57,19 @@ in { options = { nix = { - buildMachines = mkOption { - type = types.listOf ( - types.submodule { + buildMachines = lib.mkOption { + type = lib.types.listOf ( + lib.types.submodule { options = { - hostName = mkOption { - type = types.str; + hostName = lib.mkOption { + type = lib.types.str; example = "nixbuilder.example.org"; description = '' The hostname of the build machine. ''; }; - protocol = mkOption { - type = types.enum [ + protocol = lib.mkOption { + type = lib.types.enum [ null "ssh" "ssh-ng" @@ -99,8 +85,8 @@ in without a protocol which is for example used by hydra. ''; }; - system = mkOption { - type = types.nullOr types.str; + system = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; example = "x86_64-linux"; description = '' @@ -110,8 +96,8 @@ in both are set. ''; }; - systems = mkOption { - type = types.listOf types.str; + systems = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; example = [ "x86_64-linux" @@ -124,8 +110,8 @@ in both are set. ''; }; - sshUser = mkOption { - type = types.nullOr types.str; + sshUser = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; example = "builder"; description = '' @@ -135,8 +121,8 @@ in {option}`nix.settings.trusted-users`. ''; }; - sshKey = mkOption { - type = types.nullOr types.str; + sshKey = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; example = "/root/.ssh/id_buildhost_builduser"; description = '' @@ -149,8 +135,8 @@ in in the local filesystem, *not* to the nix store. ''; }; - maxJobs = mkOption { - type = types.int; + maxJobs = lib.mkOption { + type = lib.types.int; default = 1; description = '' The number of concurrent jobs the build machine supports. The @@ -159,8 +145,8 @@ in machines. ''; }; - speedFactor = mkOption { - type = types.int; + speedFactor = lib.mkOption { + type = lib.types.int; default = 1; description = '' The relative speed of this builder. This is an arbitrary integer @@ -168,8 +154,8 @@ in builders. Higher is faster. ''; }; - mandatoryFeatures = mkOption { - type = types.listOf types.str; + mandatoryFeatures = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; example = [ "big-parallel" ]; description = '' @@ -179,8 +165,8 @@ in {var}`supportedFeatures`. ''; }; - supportedFeatures = mkOption { - type = types.listOf types.str; + supportedFeatures = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; example = [ "kvm" @@ -192,8 +178,8 @@ in list. ''; }; - publicHostKey = mkOption { - type = types.nullOr types.str; + publicHostKey = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; description = '' The (base64-encoded) public host key of this builder. The field @@ -214,8 +200,8 @@ in ''; }; - distributedBuilds = mkOption { - type = types.bool; + distributedBuilds = lib.mkOption { + type = lib.types.bool; default = false; description = '' Whether to distribute builds to the machines listed in @@ -227,14 +213,14 @@ in # distributedBuilds does *not* inhibit /etc/nix/machines generation; caller may # override that nix option. - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { assertions = let badMachine = m: m.system == null && m.systems == [ ]; in [ { - assertion = !(any badMachine cfg.buildMachines); + assertion = !(lib.any badMachine cfg.buildMachines); message = '' At least one system type (via system or @@ -242,16 +228,16 @@ in Invalid machine specifications: '' + " " - + (concatStringsSep "\n " (map (m: m.hostName) (filter (badMachine) cfg.buildMachines))); + + (lib.concatStringsSep "\n " (map (m: m.hostName) (lib.filter (badMachine) cfg.buildMachines))); } ]; # List of machines for distributed Nix builds - environment.etc."nix/machines" = mkIf (cfg.buildMachines != [ ]) { + environment.etc."nix/machines" = lib.mkIf (cfg.buildMachines != [ ]) { text = buildMachinesText; }; # Legacy configuration conversion. - nix.settings = mkIf (!cfg.distributedBuilds) { builders = null; }; + nix.settings = lib.mkIf (!cfg.distributedBuilds) { builders = null; }; }; } diff --git a/nixos/modules/config/nix.nix b/nixos/modules/config/nix.nix index 9505c60d4f630..8b95ab3b81a83 100644 --- a/nixos/modules/config/nix.nix +++ b/nixos/modules/config/nix.nix @@ -10,41 +10,12 @@ { config, lib, pkgs, ... }: let - inherit (lib) - concatStringsSep - boolToString - escape - filterAttrs - floatToString - getVersion - hasPrefix - isBool - isDerivation - isFloat - isInt - isList - isString - literalExpression - mapAttrsToList - mkAfter - mkDefault - mkIf - mkOption - mkRenamedOptionModuleWith - optionalString - optionals - strings - systems - toPretty - types - versionAtLeast - ; cfg = config.nix; nixPackage = cfg.package.out; - isNixAtLeast = versionAtLeast (getVersion nixPackage); + isNixAtLeast = lib.versionAtLeast (lib.getVersion nixPackage); legacyConfMappings = { useSandbox = "sandbox"; @@ -61,7 +32,7 @@ let systemFeatures = "system-features"; }; - semanticConfType = with types; + semanticConfType = with lib.types; let confAtom = nullOr (oneOf [ @@ -83,21 +54,21 @@ let mkValueString = v: if v == null then "" - else if isInt v then toString v - else if isBool v then boolToString v - else if isFloat v then floatToString v - else if isList v then toString v - else if isDerivation v then toString v + else if lib.isInt v then lib.toString v + else if lib.isBool v then lib.boolToString v + else if lib.isFloat v then lib.floatToString v + else if lib.isList v then lib.toString v + else if lib.isDerivation v then toString v else if builtins.isPath v then toString v - else if isString v then v - else if strings.isConvertibleWithToString v then toString v - else abort "The nix conf value: ${toPretty {} v} can not be encoded"; + else if lib.isString v then v + else if lib.strings.isConvertibleWithToString v then toString v + else abort "The nix conf value: ${lib.toPretty {} v} can not be encoded"; - mkKeyValue = k: v: "${escape [ "=" ] k} = ${mkValueString v}"; + mkKeyValue = k: v: "${lib.escape [ "=" ] k} = ${mkValueString v}"; - mkKeyValuePairs = attrs: concatStringsSep "\n" (mapAttrsToList mkKeyValue attrs); + mkKeyValuePairs = attrs: lib.concatStringsSep "\n" (lib.mapAttrsToList mkKeyValue attrs); - isExtra = key: hasPrefix "extra-" key; + isExtra = key: lib.hasPrefix "extra-" key; in pkgs.writeTextFile { @@ -108,8 +79,8 @@ let # WARNING: this file is generated from the nix.* options in # your NixOS configuration, typically # /etc/nixos/configuration.nix. Do not edit it! - ${mkKeyValuePairs (filterAttrs (key: value: !(isExtra key)) cfg.settings)} - ${mkKeyValuePairs (filterAttrs (key: value: isExtra key) cfg.settings)} + ${mkKeyValuePairs (lib.filterAttrs (key: value: !(isExtra key)) cfg.settings)} + ${mkKeyValuePairs (lib.filterAttrs (key: value: isExtra key) cfg.settings)} ${cfg.extraOptions} ''; checkPhase = lib.optionalString cfg.checkConfig ( @@ -126,8 +97,8 @@ let set -e set +o pipefail NIX_CONF_DIR=$PWD \ - ${cfg.package}/bin/nix ${showCommand} ${optionalString (isNixAtLeast "2.3pre") "--no-net"} \ - ${optionalString (isNixAtLeast "2.4pre") "--option experimental-features nix-command"} \ + ${cfg.package}/bin/nix ${showCommand} ${lib.optionalString (isNixAtLeast "2.3pre") "--no-net"} \ + ${lib.optionalString (isNixAtLeast "2.4pre") "--option experimental-features nix-command"} \ |& sed -e 's/^warning:/error:/' \ | (! grep '${if cfg.checkAllErrors then "^error:" else "^error: unknown setting"}') set -o pipefail @@ -137,12 +108,12 @@ let in { imports = [ - (mkRenamedOptionModuleWith { sinceRelease = 2003; from = [ "nix" "useChroot" ]; to = [ "nix" "useSandbox" ]; }) - (mkRenamedOptionModuleWith { sinceRelease = 2003; from = [ "nix" "chrootDirs" ]; to = [ "nix" "sandboxPaths" ]; }) + (lib.mkRenamedOptionModuleWith { sinceRelease = 2003; from = [ "nix" "useChroot" ]; to = [ "nix" "useSandbox" ]; }) + (lib.mkRenamedOptionModuleWith { sinceRelease = 2003; from = [ "nix" "chrootDirs" ]; to = [ "nix" "sandboxPaths" ]; }) ] ++ - mapAttrsToList + lib.mapAttrsToList (oldConf: newConf: - mkRenamedOptionModuleWith { + lib.mkRenamedOptionModuleWith { sinceRelease = 2205; from = [ "nix" oldConf ]; to = [ "nix" "settings" newConf ]; @@ -151,24 +122,24 @@ in options = { nix = { - checkConfig = mkOption { - type = types.bool; + checkConfig = lib.mkOption { + type = lib.types.bool; default = true; description = '' If enabled, checks that Nix can parse the generated nix.conf. ''; }; - checkAllErrors = mkOption { - type = types.bool; + checkAllErrors = lib.mkOption { + type = lib.types.bool; default = true; description = '' If enabled, checks the nix.conf parsing for any kind of error. When disabled, checks only for unknown settings. ''; }; - extraOptions = mkOption { - type = types.lines; + extraOptions = lib.mkOption { + type = lib.types.lines; default = ""; example = '' keep-outputs = true @@ -177,13 +148,13 @@ in description = "Additional text appended to {file}`nix.conf`."; }; - settings = mkOption { - type = types.submodule { + settings = lib.mkOption { + type = lib.types.submodule { freeformType = semanticConfType; options = { - max-jobs = mkOption { - type = types.either types.int (types.enum [ "auto" ]); + max-jobs = lib.mkOption { + type = lib.types.either lib.types.int (lib.types.enum [ "auto" ]); default = "auto"; example = 64; description = '' @@ -195,8 +166,8 @@ in ''; }; - auto-optimise-store = mkOption { - type = types.bool; + auto-optimise-store = lib.mkOption { + type = lib.types.bool; default = false; example = true; description = '' @@ -207,8 +178,8 @@ in ''; }; - cores = mkOption { - type = types.int; + cores = lib.mkOption { + type = lib.types.int; default = 0; example = 64; description = '' @@ -221,8 +192,8 @@ in ''; }; - sandbox = mkOption { - type = types.either types.bool (types.enum [ "relaxed" ]); + sandbox = lib.mkOption { + type = lib.types.either lib.types.bool (lib.types.enum [ "relaxed" ]); default = true; description = '' If set, Nix will perform builds in a sandboxed environment that it @@ -243,8 +214,8 @@ in ''; }; - extra-sandbox-paths = mkOption { - type = types.listOf types.str; + extra-sandbox-paths = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; example = [ "/dev" "/proc" ]; description = '' @@ -253,8 +224,8 @@ in ''; }; - substituters = mkOption { - type = types.listOf types.str; + substituters = lib.mkOption { + type = lib.types.listOf lib.types.str; description = '' List of binary cache URLs used to obtain pre-built binaries of Nix packages. @@ -263,8 +234,8 @@ in ''; }; - trusted-substituters = mkOption { - type = types.listOf types.str; + trusted-substituters = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; example = [ "https://hydra.nixos.org/" ]; description = '' @@ -275,8 +246,8 @@ in ''; }; - require-sigs = mkOption { - type = types.bool; + require-sigs = lib.mkOption { + type = lib.types.bool; default = true; description = '' If enabled (the default), Nix will only download binaries from binary caches if @@ -287,8 +258,8 @@ in ''; }; - trusted-public-keys = mkOption { - type = types.listOf types.str; + trusted-public-keys = lib.mkOption { + type = lib.types.listOf lib.types.str; example = [ "hydra.nixos.org-1:CNHJZBh9K4tP3EKF6FkkgeVYsS3ohTl+oS0Qa8bezVs=" ]; description = '' List of public keys used to sign binary caches. If @@ -300,8 +271,8 @@ in ''; }; - trusted-users = mkOption { - type = types.listOf types.str; + trusted-users = lib.mkOption { + type = lib.types.listOf lib.types.str; example = [ "root" "alice" "@wheel" ]; description = '' A list of names of users that have additional rights when @@ -314,8 +285,8 @@ in ''; }; - system-features = mkOption { - type = types.listOf types.str; + system-features = lib.mkOption { + type = lib.types.listOf lib.types.str; example = [ "kvm" "big-parallel" "gccarch-skylake" ]; description = '' The set of features supported by the machine. Derivations @@ -328,8 +299,8 @@ in ''; }; - allowed-users = mkOption { - type = types.listOf types.str; + allowed-users = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ "*" ]; example = [ "@wheel" "@builders" "alice" "bob" ]; description = '' @@ -345,7 +316,7 @@ in }; }; default = { }; - example = literalExpression '' + example = lib.literalExpression '' { use-sandbox = true; show-trace = true; @@ -371,18 +342,18 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { environment.etc."nix/nix.conf".source = nixConf; nix.settings = { trusted-public-keys = [ "cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY=" ]; trusted-users = [ "root" ]; - substituters = mkAfter [ "https://cache.nixos.org/" ]; - system-features = mkDefault ( + substituters = lib.mkAfter [ "https://cache.nixos.org/" ]; + system-features = lib.mkDefault ( [ "nixos-test" "benchmark" "big-parallel" "kvm" ] ++ - optionals (pkgs.stdenv.hostPlatform ? gcc.arch) ( + lib.optionals (pkgs.stdenv.hostPlatform ? gcc.arch) ( # a builder can run code for `gcc.arch` and inferior architectures [ "gccarch-${pkgs.stdenv.hostPlatform.gcc.arch}" ] ++ - map (x: "gccarch-${x}") (systems.architectures.inferiors.${pkgs.stdenv.hostPlatform.gcc.arch} or []) + map (x: "gccarch-${x}") (lib.lib.systems.architectures.inferiors.${pkgs.stdenv.hostPlatform.gcc.arch} or []) ) ); }; diff --git a/nixos/modules/config/stevenblack.nix b/nixos/modules/config/stevenblack.nix index 95f6c9e73eb3e..2669423ac4ffb 100644 --- a/nixos/modules/config/stevenblack.nix +++ b/nixos/modules/config/stevenblack.nix @@ -5,27 +5,17 @@ ... }: let - inherit (lib) - getOutput - maintainers - mkEnableOption - mkIf - mkOption - mkPackageOption - types - ; - cfg = config.networking.stevenblack; in { options.networking.stevenblack = { - enable = mkEnableOption "the stevenblack hosts file blocklist"; + enable = lib.mkEnableOption "the stevenblack hosts file blocklist"; - package = mkPackageOption pkgs "stevenblack-blocklist" { }; + package = lib.mkPackageOption pkgs "stevenblack-blocklist" { }; - block = mkOption { - type = types.listOf ( - types.enum [ + block = lib.mkOption { + type = lib.types.listOf ( + lib.types.enum [ "fakenews" "gambling" "porn" @@ -37,11 +27,11 @@ in }; }; - config = mkIf cfg.enable { - networking.hostFiles = map (x: "${getOutput x cfg.package}/hosts") ([ "ads" ] ++ cfg.block); + config = lib.mkIf cfg.enable { + networking.hostFiles = map (x: "${lib.getOutput x cfg.package}/hosts") ([ "ads" ] ++ cfg.block); }; - meta.maintainers = with maintainers; [ + meta.maintainers = with lib.maintainers; [ moni artturin frontear diff --git a/nixos/modules/config/stub-ld.nix b/nixos/modules/config/stub-ld.nix index 836cd129e22f5..b1cf20fbb220a 100644 --- a/nixos/modules/config/stub-ld.nix +++ b/nixos/modules/config/stub-ld.nix @@ -6,13 +6,6 @@ }: let - inherit (lib) - optionalString - mkOption - types - mkIf - mkDefault - ; cfg = config.environment.stub-ld; @@ -50,8 +43,8 @@ in { options = { environment.stub-ld = { - enable = mkOption { - type = types.bool; + enable = lib.mkOption { + type = lib.types.bool; default = true; example = false; description = '' @@ -63,9 +56,9 @@ in }; }; - config = mkIf cfg.enable { - environment.ldso = mkDefault stub-ld; - environment.ldso32 = mkIf pkgs.stdenv.hostPlatform.isx86_64 (mkDefault stub-ld32); + config = lib.mkIf cfg.enable { + environment.ldso = lib.mkDefault stub-ld; + environment.ldso32 = lib.mkIf pkgs.stdenv.hostPlatform.isx86_64 (lib.mkDefault stub-ld32); }; meta.maintainers = with lib.maintainers; [ tejing ]; diff --git a/nixos/modules/config/swap.nix b/nixos/modules/config/swap.nix index e945e18b1f258..f4b7656d3a931 100644 --- a/nixos/modules/config/swap.nix +++ b/nixos/modules/config/swap.nix @@ -1,7 +1,6 @@ { config, lib, pkgs, utils, ... }: let - inherit (lib) mkIf mkOption types; randomEncryptionCoerce = enable: { inherit enable; }; @@ -9,9 +8,9 @@ let options = { - enable = mkOption { + enable = lib.mkOption { default = false; - type = types.bool; + type = lib.types.bool; description = '' Encrypt swap device with a random key. This way you won't have a persistent swap device. @@ -25,10 +24,10 @@ let ''; }; - cipher = mkOption { + cipher = lib.mkOption { default = "aes-xts-plain64"; example = "serpent-xts-plain64"; - type = types.str; + type = lib.types.str; description = '' Use specified cipher for randomEncryption. @@ -36,10 +35,10 @@ let ''; }; - keySize = mkOption { + keySize = lib.mkOption { default = null; example = "512"; - type = types.nullOr types.int; + type = lib.types.nullOr lib.types.int; description = '' Set the encryption key size for the plain device. @@ -50,10 +49,10 @@ let ''; }; - sectorSize = mkOption { + sectorSize = lib.mkOption { default = null; example = "4096"; - type = types.nullOr types.int; + type = lib.types.nullOr lib.types.int; description = '' Set the sector size for the plain encrypted device type. @@ -64,18 +63,18 @@ let ''; }; - source = mkOption { + source = lib.mkOption { default = "/dev/urandom"; example = "/dev/random"; - type = types.str; + type = lib.types.str; description = '' Define the source of randomness to obtain a random key for encryption. ''; }; - allowDiscards = mkOption { + allowDiscards = lib.mkOption { default = false; - type = types.bool; + type = lib.types.bool; description = '' Whether to allow TRIM requests to the underlying device. This option has security implications; please read the LUKS documentation before @@ -90,24 +89,24 @@ let options = { - device = mkOption { + device = lib.mkOption { example = "/dev/sda3"; - type = types.nonEmptyStr; + type = lib.types.nonEmptyStr; description = "Path of the device or swap file."; }; - label = mkOption { + label = lib.mkOption { example = "swap"; - type = types.str; + type = lib.types.str; description = '' Label of the device. Can be used instead of {var}`device`. ''; }; - size = mkOption { + size = lib.mkOption { default = null; example = 2048; - type = types.nullOr types.int; + type = lib.types.nullOr lib.types.int; description = '' If this option is set, ‘device’ is interpreted as the path of a swapfile that will be created automatically @@ -115,10 +114,10 @@ let ''; }; - priority = mkOption { + priority = lib.mkOption { default = null; example = 2048; - type = types.nullOr types.int; + type = lib.types.nullOr lib.types.int; description = '' Specify the priority of the swap device. Priority is a value between 0 and 32767. Higher numbers indicate higher priority. @@ -126,14 +125,14 @@ let ''; }; - randomEncryption = mkOption { + randomEncryption = lib.mkOption { default = false; example = { enable = true; cipher = "serpent-xts-plain64"; source = "/dev/random"; }; - type = types.coercedTo types.bool randomEncryptionCoerce (types.submodule randomEncryptionOpts); + type = lib.types.coercedTo lib.types.bool randomEncryptionCoerce (lib.types.submodule randomEncryptionOpts); description = '' Encrypt swap device with a random key. This way you won't have a persistent swap device. @@ -149,10 +148,10 @@ let ''; }; - discardPolicy = mkOption { + discardPolicy = lib.mkOption { default = null; example = "once"; - type = types.nullOr (types.enum ["once" "pages" "both" ]); + type = lib.types.nullOr (lib.types.enum ["once" "pages" "both" ]); description = '' Specify the discard policy for the swap device. If "once", then the whole swap space is discarded at swapon invocation. If "pages", @@ -162,29 +161,29 @@ let ''; }; - options = mkOption { + options = lib.mkOption { default = [ "defaults" ]; example = [ "nofail" ]; - type = types.listOf types.nonEmptyStr; + type = lib.types.listOf lib.types.nonEmptyStr; description = '' Options used to mount the swap. ''; }; - deviceName = mkOption { - type = types.str; + deviceName = lib.mkOption { + type = lib.types.str; internal = true; }; - realDevice = mkOption { - type = types.path; + realDevice = lib.mkOption { + type = lib.types.path; internal = true; }; }; config = { - device = mkIf options.label.isDefined + device = lib.mkIf options.label.isDefined "/dev/disk/by-label/${config.label}"; deviceName = lib.replaceStrings ["\\"] [""] (utils.escapeSystemdPath config.device); realDevice = if config.randomEncryption.enable then "/dev/mapper/${config.deviceName}" else config.device; @@ -200,7 +199,7 @@ in options = { - swapDevices = mkOption { + swapDevices = lib.mkOption { default = []; example = [ { device = "/dev/hda7"; } @@ -217,12 +216,12 @@ in recommended. ''; - type = types.listOf (types.submodule swapCfg); + type = lib.types.listOf (lib.types.submodule swapCfg); }; }; - config = mkIf ((lib.length config.swapDevices) != 0) { + config = lib.mkIf ((lib.length config.swapDevices) != 0) { assertions = lib.map (sw: { assertion = sw.randomEncryption.enable -> builtins.match "/dev/disk/by-(uuid|label)/.*" sw.device == null; message = '' diff --git a/nixos/modules/config/terminfo.nix b/nixos/modules/config/terminfo.nix index c81d9fe0d8e39..77b45d114687c 100644 --- a/nixos/modules/config/terminfo.nix +++ b/nixos/modules/config/terminfo.nix @@ -8,7 +8,7 @@ }: { - options = with lib; { + options = { environment.enableAllTerminfo = lib.mkOption { default = false; type = lib.types.bool; diff --git a/nixos/modules/config/users-groups.nix b/nixos/modules/config/users-groups.nix index 38d40e99abd6d..5f8ed713cbbec 100644 --- a/nixos/modules/config/users-groups.nix +++ b/nixos/modules/config/users-groups.nix @@ -1,45 +1,6 @@ { config, lib, utils, pkgs, ... }: let - inherit (lib) - any - attrNames - attrValues - concatMap - concatMapStringsSep - concatStrings - elem - filter - filterAttrs - flatten - flip - foldr - generators - getAttr - hasAttr - id - length - listToAttrs - literalExpression - mapAttrs' - mapAttrsToList - match - mkAliasOptionModuleMD - mkDefault - mkIf - mkMerge - mkOption - mkRenamedOptionModule - optional - optionals - sort - stringAfter - stringLength - trace - types - xor - ; - ids = config.ids; cfg = config.users; @@ -124,17 +85,17 @@ let options = { - name = mkOption { - type = types.passwdEntry types.str; - apply = x: assert (stringLength x < 32 || abort "Username '${x}' is longer than 31 characters which is not allowed!"); x; + name = lib.mkOption { + type = lib.types.passwdEntry lib.types.str; + apply = x: assert (lib.stringLength x < 32 || abort "Username '${x}' is longer than 31 characters which is not allowed!"); x; description = '' The name of the user account. If undefined, the name of the attribute set will be used. ''; }; - description = mkOption { - type = types.passwdEntry types.str; + description = lib.mkOption { + type = lib.types.passwdEntry lib.types.str; default = ""; example = "Alice Q. User"; description = '' @@ -144,8 +105,8 @@ let ''; }; - uid = mkOption { - type = with types; nullOr int; + uid = lib.mkOption { + type = with lib.types; nullOr int; default = null; description = '' The account UID. If the UID is null, a free UID is picked on @@ -153,8 +114,8 @@ let ''; }; - isSystemUser = mkOption { - type = types.bool; + isSystemUser = lib.mkOption { + type = lib.types.bool; default = false; description = '' Indicates if the user is a system user or not. This option @@ -168,8 +129,8 @@ let ''; }; - isNormalUser = mkOption { - type = types.bool; + isNormalUser = lib.mkOption { + type = lib.types.bool; default = false; description = '' Indicates whether this is an account for a “real” user. @@ -182,33 +143,33 @@ let ''; }; - group = mkOption { - type = types.str; - apply = x: assert (stringLength x < 32 || abort "Group name '${x}' is longer than 31 characters which is not allowed!"); x; + group = lib.mkOption { + type = lib.types.str; + apply = x: assert (lib.stringLength x < 32 || abort "Group name '${x}' is longer than 31 characters which is not allowed!"); x; default = ""; description = "The user's primary group."; }; - extraGroups = mkOption { - type = types.listOf types.str; + extraGroups = lib.mkOption { + type = lib.types.listOf lib.types.str; default = []; description = "The user's auxiliary groups."; }; - home = mkOption { - type = types.passwdEntry types.path; + home = lib.mkOption { + type = lib.types.passwdEntry lib.types.path; default = "/var/empty"; description = "The user's home directory."; }; - homeMode = mkOption { - type = types.strMatching "[0-7]{1,5}"; + homeMode = lib.mkOption { + type = lib.types.strMatching "[0-7]{1,5}"; default = "700"; description = "The user's home directory mode in numeric format. See chmod(1). The mode is only applied if {option}`users.users..createHome` is true."; }; - cryptHomeLuks = mkOption { - type = with types; nullOr str; + cryptHomeLuks = lib.mkOption { + type = with lib.types; nullOr str; default = null; description = '' Path to encrypted luks device that contains @@ -216,8 +177,8 @@ let ''; }; - pamMount = mkOption { - type = with types; attrsOf str; + pamMount = lib.mkOption { + type = with lib.types; attrsOf str; default = {}; description = '' Attributes for user's entry in @@ -229,11 +190,11 @@ let ''; }; - shell = mkOption { - type = types.nullOr (types.either types.shellPackage (types.passwdEntry types.path)); + shell = lib.mkOption { + type = lib.types.nullOr (lib.types.either lib.types.shellPackage (lib.types.passwdEntry lib.types.path)); default = pkgs.shadow; - defaultText = literalExpression "pkgs.shadow"; - example = literalExpression "pkgs.bashInteractive"; + defaultText = lib.literalExpression "pkgs.shadow"; + example = lib.literalExpression "pkgs.bashInteractive"; description = '' The path to the user's shell. Can use shell derivations, like `pkgs.bashInteractive`. Don’t @@ -243,8 +204,8 @@ let ''; }; - ignoreShellProgramCheck = mkOption { - type = types.bool; + ignoreShellProgramCheck = lib.mkOption { + type = lib.types.bool; default = false; description = '' By default, nixos will check that programs.SHELL.enable is set to @@ -254,8 +215,8 @@ let ''; }; - subUidRanges = mkOption { - type = with types; listOf (submodule subordinateUidRange); + subUidRanges = lib.mkOption { + type = with lib.types; listOf (submodule subordinateUidRange); default = []; example = [ { startUid = 1000; count = 1; } @@ -268,8 +229,8 @@ let ''; }; - subGidRanges = mkOption { - type = with types; listOf (submodule subordinateGidRange); + subGidRanges = lib.mkOption { + type = with lib.types; listOf (submodule subordinateGidRange); default = []; example = [ { startGid = 100; count = 1; } @@ -282,8 +243,8 @@ let ''; }; - autoSubUidGidRange = mkOption { - type = types.bool; + autoSubUidGidRange = lib.mkOption { + type = lib.types.bool; default = false; example = true; description = '' @@ -292,8 +253,8 @@ let ''; }; - createHome = mkOption { - type = types.bool; + createHome = lib.mkOption { + type = lib.types.bool; default = false; description = '' Whether to create the home directory and ensure ownership as well as @@ -301,8 +262,8 @@ let ''; }; - useDefaultShell = mkOption { - type = types.bool; + useDefaultShell = lib.mkOption { + type = lib.types.bool; default = false; description = '' If true, the user's shell will be set to @@ -310,8 +271,8 @@ let ''; }; - hashedPassword = mkOption { - type = with types; nullOr (passwdEntry str); + hashedPassword = lib.mkOption { + type = with lib.types; nullOr (passwdEntry str); default = null; description = '' Specifies the hashed password for the user. @@ -321,8 +282,8 @@ let ''; }; - password = mkOption { - type = with types; nullOr str; + password = lib.mkOption { + type = with lib.types; nullOr str; default = null; description = '' Specifies the (clear text) password for the user. @@ -334,10 +295,10 @@ let ''; }; - hashedPasswordFile = mkOption { - type = with types; nullOr str; + hashedPasswordFile = lib.mkOption { + type = with lib.types; nullOr str; default = cfg.users.${name}.passwordFile; - defaultText = literalExpression "null"; + defaultText = lib.literalExpression "null"; description = '' The full path to a file that contains the hash of the user's password. The password file is read on each system activation. The @@ -348,15 +309,15 @@ let ''; }; - passwordFile = mkOption { - type = with types; nullOr str; + passwordFile = lib.mkOption { + type = with lib.types; nullOr str; default = null; visible = false; description = "Deprecated alias of hashedPasswordFile"; }; - initialHashedPassword = mkOption { - type = with types; nullOr (passwdEntry str); + initialHashedPassword = lib.mkOption { + type = with lib.types; nullOr (passwdEntry str); default = null; description = '' Specifies the initial hashed password for the user, i.e. the @@ -371,8 +332,8 @@ let ''; }; - initialPassword = mkOption { - type = with types; nullOr str; + initialPassword = lib.mkOption { + type = with lib.types; nullOr str; default = null; description = '' Specifies the initial password for the user, i.e. the @@ -390,10 +351,10 @@ let ''; }; - packages = mkOption { - type = types.listOf types.package; + packages = lib.mkOption { + type = lib.types.listOf lib.types.package; default = []; - example = literalExpression "[ pkgs.firefox pkgs.thunderbird ]"; + example = lib.literalExpression "[ pkgs.firefox pkgs.thunderbird ]"; description = '' The set of packages that should be made available to the user. This is in contrast to {option}`environment.systemPackages`, @@ -401,8 +362,8 @@ let ''; }; - expires = mkOption { - type = types.nullOr (types.strMatching "[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}"); + expires = lib.mkOption { + type = lib.types.nullOr (lib.types.strMatching "[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}"); default = null; description = '' Set the date on which the user's account will no longer be @@ -413,8 +374,8 @@ let ''; }; - linger = mkOption { - type = types.bool; + linger = lib.mkOption { + type = lib.types.bool; default = false; description = '' Whether to enable lingering for this user. If true, systemd user @@ -428,28 +389,28 @@ let }; }; - config = mkMerge - [ { name = mkDefault name; - shell = mkIf config.useDefaultShell (mkDefault cfg.defaultUserShell); + config = lib.mkMerge + [ { name = lib.mkDefault name; + shell = lib.mkIf config.useDefaultShell (lib.mkDefault cfg.defaultUserShell); } - (mkIf config.isNormalUser { - group = mkDefault "users"; - createHome = mkDefault true; - home = mkDefault "/home/${config.name}"; - homeMode = mkDefault "700"; - useDefaultShell = mkDefault true; - isSystemUser = mkDefault false; + (lib.mkIf config.isNormalUser { + group = lib.mkDefault "users"; + createHome = lib.mkDefault true; + home = lib.mkDefault "/home/${config.name}"; + homeMode = lib.mkDefault "700"; + useDefaultShell = lib.mkDefault true; + isSystemUser = lib.mkDefault false; }) # If !mutableUsers, setting ‘initialPassword’ is equivalent to # setting ‘password’ (and similarly for hashed passwords). - (mkIf (!cfg.mutableUsers && config.initialPassword != null) { - password = mkDefault config.initialPassword; + (lib.mkIf (!cfg.mutableUsers && config.initialPassword != null) { + password = lib.mkDefault config.initialPassword; }) - (mkIf (!cfg.mutableUsers && config.initialHashedPassword != null) { - hashedPassword = mkDefault config.initialHashedPassword; + (lib.mkIf (!cfg.mutableUsers && config.initialHashedPassword != null) { + hashedPassword = lib.mkDefault config.initialHashedPassword; }) - (mkIf (config.isNormalUser && config.subUidRanges == [] && config.subGidRanges == []) { - autoSubUidGidRange = mkDefault true; + (lib.mkIf (config.isNormalUser && config.subUidRanges == [] && config.subGidRanges == []) { + autoSubUidGidRange = lib.mkDefault true; }) ]; @@ -459,16 +420,16 @@ let options = { - name = mkOption { - type = types.passwdEntry types.str; + name = lib.mkOption { + type = lib.types.passwdEntry lib.types.str; description = '' The name of the group. If undefined, the name of the attribute set will be used. ''; }; - gid = mkOption { - type = with types; nullOr int; + gid = lib.mkOption { + type = with lib.types; nullOr int; default = null; description = '' The group GID. If the GID is null, a free GID is picked on @@ -476,8 +437,8 @@ let ''; }; - members = mkOption { - type = with types; listOf (passwdEntry str); + members = lib.mkOption { + type = with lib.types; listOf (passwdEntry str); default = []; description = '' The user names of the group members, added to the @@ -488,10 +449,10 @@ let }; config = { - name = mkDefault name; + name = lib.mkDefault name; - members = mapAttrsToList (n: u: u.name) ( - filterAttrs (n: u: elem config.name u.extraGroups) cfg.users + members = lib.mapAttrsToList (n: u: u.name) ( + lib.filterAttrs (n: u: lib.elem config.name u.extraGroups) cfg.users ); }; @@ -499,15 +460,15 @@ let subordinateUidRange = { options = { - startUid = mkOption { - type = types.int; + startUid = lib.mkOption { + type = lib.types.int; description = '' Start of the range of subordinate user ids that user is allowed to use. ''; }; - count = mkOption { - type = types.int; + count = lib.mkOption { + type = lib.types.int; default = 1; description = "Count of subordinate user ids"; }; @@ -516,41 +477,41 @@ let subordinateGidRange = { options = { - startGid = mkOption { - type = types.int; + startGid = lib.mkOption { + type = lib.types.int; description = '' Start of the range of subordinate group ids that user is allowed to use. ''; }; - count = mkOption { - type = types.int; + count = lib.mkOption { + type = lib.types.int; default = 1; description = "Count of subordinate group ids"; }; }; }; - idsAreUnique = set: idAttr: !(foldr (name: args@{ dup, acc }: + idsAreUnique = set: idAttr: !(lib.foldr (name: args@{ dup, acc }: let - id = toString (getAttr idAttr (getAttr name set)); - exists = hasAttr id acc; - newAcc = acc // (listToAttrs [ { name = id; value = true; } ]); + id = toString (lib.getAttr idAttr (lib.getAttr name set)); + exists = lib.hasAttr id acc; + newAcc = acc // (lib.listToAttrs [ { name = id; value = true; } ]); in if dup then args else if exists - then trace "Duplicate ${idAttr} ${id}" { dup = true; acc = null; } + then lib.trace "Duplicate ${idAttr} ${id}" { dup = true; acc = null; } else { dup = false; acc = newAcc; } - ) { dup = false; acc = {}; } (attrNames set)).dup; + ) { dup = false; acc = {}; } (lib.attrNames set)).dup; - uidsAreUnique = idsAreUnique (filterAttrs (n: u: u.uid != null) cfg.users) "uid"; - gidsAreUnique = idsAreUnique (filterAttrs (n: g: g.gid != null) cfg.groups) "gid"; - sdInitrdUidsAreUnique = idsAreUnique (filterAttrs (n: u: u.uid != null) config.boot.initrd.systemd.users) "uid"; - sdInitrdGidsAreUnique = idsAreUnique (filterAttrs (n: g: g.gid != null) config.boot.initrd.systemd.groups) "gid"; + uidsAreUnique = idsAreUnique (lib.filterAttrs (n: u: u.uid != null) cfg.users) "uid"; + gidsAreUnique = idsAreUnique (lib.filterAttrs (n: g: g.gid != null) cfg.groups) "gid"; + sdInitrdUidsAreUnique = idsAreUnique (lib.filterAttrs (n: u: u.uid != null) config.boot.initrd.systemd.users) "uid"; + sdInitrdGidsAreUnique = idsAreUnique (lib.filterAttrs (n: g: g.gid != null) config.boot.initrd.systemd.groups) "gid"; groupNames = lib.mapAttrsToList (n: g: g.name) cfg.groups; usersWithoutExistingGroup = lib.filterAttrs (n: u: u.group != "" && !lib.elem u.group groupNames) cfg.users; spec = pkgs.writeText "users-groups.json" (builtins.toJSON { inherit (cfg) mutableUsers; - users = mapAttrsToList (_: u: + users = lib.mapAttrsToList (_: u: { inherit (u) name uid group description home homeMode createHome isSystemUser password hashedPasswordFile hashedPassword @@ -558,28 +519,28 @@ let initialPassword initialHashedPassword expires; shell = utils.toShellPath u.shell; }) cfg.users; - groups = attrValues cfg.groups; + groups = lib.attrValues cfg.groups; }); systemShells = let - shells = mapAttrsToList (_: u: u.shell) cfg.users; + shells = lib.mapAttrsToList (_: u: u.shell) cfg.users; in - filter types.shellPackage.check shells; + lib.filter lib.types.shellPackage.check shells; - lingeringUsers = map (u: u.name) (attrValues (flip filterAttrs cfg.users (n: u: u.linger))); + lingeringUsers = map (u: u.name) (lib.attrValues (lib.flip lib.filterAttrs cfg.users (n: u: u.linger))); in { imports = [ - (mkAliasOptionModuleMD [ "users" "extraUsers" ] [ "users" "users" ]) - (mkAliasOptionModuleMD [ "users" "extraGroups" ] [ "users" "groups" ]) - (mkRenamedOptionModule ["security" "initialRootPassword"] ["users" "users" "root" "initialHashedPassword"]) + (lib.mkAliasOptionModuleMD [ "users" "extraUsers" ] [ "users" "users" ]) + (lib.mkAliasOptionModuleMD [ "users" "extraGroups" ] [ "users" "groups" ]) + (lib.mkRenamedOptionModule ["security" "initialRootPassword"] ["users" "users" "root" "initialHashedPassword"]) ]; ###### interface options = { - users.mutableUsers = mkOption { - type = types.bool; + users.mutableUsers = lib.mkOption { + type = lib.types.bool; default = true; description = '' If set to `true`, you are free to add new users and groups to the system @@ -603,17 +564,17 @@ in { ''; }; - users.enforceIdUniqueness = mkOption { - type = types.bool; + users.enforceIdUniqueness = lib.mkOption { + type = lib.types.bool; default = true; description = '' Whether to require that no two users/groups share the same uid/gid. ''; }; - users.users = mkOption { + users.users = lib.mkOption { default = {}; - type = with types; attrsOf (submodule userOpts); + type = with lib.types; attrsOf (submodule userOpts); example = { alice = { uid = 1234; @@ -631,21 +592,21 @@ in { ''; }; - users.groups = mkOption { + users.groups = lib.mkOption { default = {}; example = { students.gid = 1001; hackers = { }; }; - type = with types; attrsOf (submodule groupOpts); + type = with lib.types; attrsOf (submodule groupOpts); description = '' Additional groups to be created automatically by the system. ''; }; - users.allowNoPasswordLogin = mkOption { - type = types.bool; + users.allowNoPasswordLogin = lib.mkOption { + type = lib.types.bool; default = false; description = '' Disable checking that at least the `root` user or a user in the `wheel` group can log in using @@ -656,51 +617,51 @@ in { }; # systemd initrd - boot.initrd.systemd.users = mkOption { + boot.initrd.systemd.users = lib.mkOption { description = '' Users to include in initrd. ''; default = {}; - type = types.attrsOf (types.submodule ({ name, ... }: { - options.uid = mkOption { - type = types.int; + type = lib.types.attrsOf (lib.types.submodule ({ name, ... }: { + options.uid = lib.mkOption { + type = lib.types.int; description = '' ID of the user in initrd. ''; - defaultText = literalExpression "config.users.users.\${name}.uid"; + defaultText = lib.literalExpression "config.users.users.\${name}.uid"; default = cfg.users.${name}.uid; }; - options.group = mkOption { - type = types.singleLineStr; + options.group = lib.mkOption { + type = lib.types.singleLineStr; description = '' Group the user belongs to in initrd. ''; - defaultText = literalExpression "config.users.users.\${name}.group"; + defaultText = lib.literalExpression "config.users.users.\${name}.group"; default = cfg.users.${name}.group; }; - options.shell = mkOption { - type = types.passwdEntry types.path; + options.shell = lib.mkOption { + type = lib.types.passwdEntry lib.types.path; description = '' The path to the user's shell in initrd. ''; default = "${pkgs.shadow}/bin/nologin"; - defaultText = literalExpression "\${pkgs.shadow}/bin/nologin"; + defaultText = lib.literalExpression "\${pkgs.shadow}/bin/nologin"; }; })); }; - boot.initrd.systemd.groups = mkOption { + boot.initrd.systemd.groups = lib.mkOption { description = '' Groups to include in initrd. ''; default = {}; - type = types.attrsOf (types.submodule ({ name, ... }: { - options.gid = mkOption { - type = types.int; + type = lib.types.attrsOf (lib.types.submodule ({ name, ... }: { + options.gid = lib.mkOption { + type = lib.types.int; description = '' ID of the group in initrd. ''; - defaultText = literalExpression "config.users.groups.\${name}.gid"; + defaultText = lib.literalExpression "config.users.groups.\${name}.gid"; default = cfg.groups.${name}.gid; }; })); @@ -719,7 +680,7 @@ in { uid = ids.uids.root; description = "System administrator"; home = "/root"; - shell = mkDefault cfg.defaultUserShell; + shell = lib.mkDefault cfg.defaultUserShell; group = "root"; }; nobody = { @@ -767,7 +728,7 @@ in { ''; } else ""; # keep around for backwards compatibility - systemd.services.linger-users = lib.mkIf ((length lingeringUsers) > 0) { + systemd.services.linger-users = lib.mkIf ((lib.length lingeringUsers) > 0) { wantedBy = ["multi-user.target"]; after = ["systemd-logind.service"]; requires = ["systemd-logind.service"]; @@ -775,8 +736,8 @@ in { script = let lingerDir = "/var/lib/systemd/linger"; lingeringUsersFile = builtins.toFile "lingering-users" - (concatStrings (map (s: "${s}\n") - (sort (a: b: a < b) lingeringUsers))); # this sorting is important for `comm` to work correctly + (lib.concatStrings (map (s: "${s}\n") + (lib.sort (a: b: a < b) lingeringUsers))); # this sorting is important for `comm` to work correctly in '' mkdir -vp ${lingerDir} cd ${lingerDir} @@ -817,12 +778,12 @@ in { } else ""; # keep around for backwards compatibility # for backwards compatibility - system.activationScripts.groups = stringAfter [ "users" ] ""; + system.activationScripts.groups = lib.stringAfter [ "users" ] ""; # Install all the user shells environment.systemPackages = systemShells; - environment.etc = mapAttrs' (_: { packages, name, ... }: { + environment.etc = lib.mapAttrs' (_: { packages, name, ... }: { name = "profiles/per-user/${name}"; value.source = pkgs.buildEnv { name = "user-environment"; @@ -830,7 +791,7 @@ in { inherit (config.environment) pathsToLink extraOutputsToInstall; inherit (config.system.path) ignoreCollisions postBuild; }; - }) (filterAttrs (_: u: u.packages != []) cfg.users); + }) (lib.filterAttrs (_: u: u.packages != []) cfg.users); environment.profiles = [ "$HOME/.nix-profile" @@ -908,10 +869,10 @@ in { # The check does not apply when users.disableLoginPossibilityAssertion # The check does not apply when users.mutableUsers assertion = !cfg.mutableUsers -> !cfg.allowNoPasswordLogin -> - any id (mapAttrsToList (name: cfg: + lib.any lib.id (lib.mapAttrsToList (name: cfg: (name == "root" || cfg.group == "wheel" - || elem "wheel" cfg.extraGroups) + || lib.elem "wheel" cfg.extraGroups) && (allowsLogin cfg.hashedPassword || cfg.password != null @@ -929,11 +890,11 @@ in { manually running passwd root to set the root password. ''; } - ] ++ flatten (flip mapAttrsToList cfg.users (name: user: + ] ++ lib.flatten (lib.flip lib.mapAttrsToList cfg.users (name: user: [ { assertion = (user.hashedPassword != null) - -> (match ".*:.*" user.hashedPassword == null); + -> (lib.match ".*:.*" user.hashedPassword == null); message = '' The password hash of user "${user.name}" contains a ":" character. This is invalid and would break the login system because the fields @@ -943,7 +904,7 @@ in { { assertion = let isEffectivelySystemUser = user.isSystemUser || (user.uid != null && user.uid < 1000); - in xor isEffectivelySystemUser user.isNormalUser; + in lib.xor isEffectivelySystemUser user.isNormalUser; message = '' Exactly one of users.users.${user.name}.isSystemUser and users.users.${user.name}.isNormalUser must be set. ''; @@ -979,20 +940,20 @@ in { )); warnings = - flip concatMap (attrValues cfg.users) (user: let + lib.flip lib.concatMap (lib.attrValues cfg.users) (user: let passwordOptions = [ "hashedPassword" "hashedPasswordFile" "password" - ] ++ optionals cfg.mutableUsers [ + ] ++ lib.optionals cfg.mutableUsers [ # For immutable users, initialHashedPassword is set to hashedPassword, # so using these options would always trigger the assertion. "initialHashedPassword" "initialPassword" ]; - unambiguousPasswordConfiguration = 1 >= length - (filter (x: x != null) (map (flip getAttr user) passwordOptions)); - in optional (!unambiguousPasswordConfiguration) '' + unambiguousPasswordConfiguration = 1 >= lib.length + (lib.filter (x: x != null) (map (lib.flip lib.getAttr user) passwordOptions)); + in lib.optional (!unambiguousPasswordConfiguration) '' The user '${user.name}' has multiple of the options `initialHashedPassword`, `hashedPassword`, `initialPassword`, `password` & `hashedPasswordFile` set to a non-null value. @@ -1000,14 +961,14 @@ in { ${multiplePasswordsWarning} ${overrideOrderText cfg.mutableUsers} The values of these options are: - ${concatMapStringsSep + ${lib.concatMapStringsSep "\n" (value: - "* users.users.\"${user.name}\".${value}: ${generators.toPretty {} user.${value}}") + "* users.users.\"${user.name}\".${value}: ${lib.generators.toPretty {} user.${value}}") passwordOptions} '') - ++ filter (x: x != null) ( - flip mapAttrsToList cfg.users (_: user: + ++ lib.filter (x: x != null) ( + lib.flip lib.mapAttrsToList cfg.users (_: user: # This regex matches a subset of the Modular Crypto Format (MCF)[1] # informal standard. Since this depends largely on the OS or the # specific implementation of crypt(3) we only support the (sane) @@ -1029,13 +990,13 @@ in { in if (allowsLogin user.hashedPassword && user.hashedPassword != "" # login without password - && match mcf user.hashedPassword == null) + && lib.match mcf user.hashedPassword == null) then '' The password hash of user "${user.name}" may be invalid. You must set a valid hash or the user will be locked out of their account. Please check the value of option `users.users."${user.name}".hashedPassword`.'' else null) - ++ flip mapAttrsToList cfg.users (name: user: + ++ lib.flip lib.mapAttrsToList cfg.users (name: user: if user.passwordFile != null then ''The option `users.users."${name}".passwordFile' has been renamed '' + ''to `users.users."${name}".hashedPasswordFile'.'' diff --git a/nixos/modules/config/xdg/portal.nix b/nixos/modules/config/xdg/portal.nix index 617a342c1a70e..c1cd2c85e2124 100644 --- a/nixos/modules/config/xdg/portal.nix +++ b/nixos/modules/config/xdg/portal.nix @@ -6,25 +6,15 @@ }: let - inherit (lib) - mkEnableOption - mkIf - mkOption - mkRenamedOptionModule - mkRemovedOptionModule - teams - types - ; - associationOptions = - with types; + with lib.types; attrsOf (coercedTo (either (listOf str) str) (x: lib.concatStringsSep ";" (lib.toList x)) str); in { imports = [ - (mkRenamedOptionModule [ "services" "flatpak" "extraPortals" ] [ "xdg" "portal" "extraPortals" ]) - (mkRemovedOptionModule [ + (lib.mkRenamedOptionModule [ "services" "flatpak" "extraPortals" ] [ "xdg" "portal" "extraPortals" ]) + (lib.mkRemovedOptionModule [ "xdg" "portal" "gtkUsePortal" @@ -32,18 +22,18 @@ in ]; meta = { - maintainers = teams.freedesktop.members; + maintainers = lib.teams.freedesktop.members; }; options.xdg.portal = { enable = - mkEnableOption ''[xdg desktop integration](https://github.com/flatpak/xdg-desktop-portal)'' + lib.mkEnableOption ''[xdg desktop integration](https://github.com/flatpak/xdg-desktop-portal)'' // { default = false; }; - extraPortals = mkOption { - type = types.listOf types.package; + extraPortals = lib.mkOption { + type = lib.types.listOf lib.types.package; default = [ ]; description = '' List of additional portals to add to path. Portals allow interaction @@ -55,8 +45,8 @@ in ''; }; - xdgOpenUsePortal = mkOption { - type = types.bool; + xdgOpenUsePortal = lib.mkOption { + type = lib.types.bool; default = false; description = '' Sets environment variable `NIXOS_XDG_OPEN_USE_PORTAL` to `1` @@ -66,8 +56,8 @@ in ''; }; - config = mkOption { - type = types.attrsOf associationOptions; + config = lib.mkOption { + type = lib.types.attrsOf associationOptions; default = { }; example = { x-cinnamon = { @@ -97,8 +87,8 @@ in ''; }; - configPackages = mkOption { - type = types.listOf types.package; + configPackages = lib.mkOption { + type = lib.types.listOf lib.types.package; default = [ ]; example = lib.literalExpression "[ pkgs.gnome-session ]"; description = '' @@ -115,7 +105,7 @@ in cfg = config.xdg.portal; packages = [ pkgs.xdg-desktop-portal ] ++ cfg.extraPortals; in - mkIf cfg.enable { + lib.mkIf cfg.enable { warnings = lib.optional (cfg.configPackages == [ ] && cfg.config == { }) '' xdg-desktop-portal 1.17 reworked how portal implementations are loaded, you should either set `xdg.portal.config` or `xdg.portal.configPackages` @@ -149,7 +139,7 @@ in ]; sessionVariables = { - NIXOS_XDG_OPEN_USE_PORTAL = mkIf cfg.xdgOpenUsePortal "1"; + NIXOS_XDG_OPEN_USE_PORTAL = lib.mkIf cfg.xdgOpenUsePortal "1"; NIX_XDG_DESKTOP_PORTAL_DIR = "/run/current-system/sw/share/xdg-desktop-portal/portals"; }; diff --git a/nixos/modules/config/xdg/terminal-exec.nix b/nixos/modules/config/xdg/terminal-exec.nix index 0c8381bc2cde9..e2477cc9b573c 100644 --- a/nixos/modules/config/xdg/terminal-exec.nix +++ b/nixos/modules/config/xdg/terminal-exec.nix @@ -7,13 +7,6 @@ let cfg = config.xdg.terminal-exec; - inherit (lib) - mkIf - mkEnableOption - mkOption - mkPackageOption - types - ; in { meta.maintainers = with lib.maintainers; [ Cryolitia ]; @@ -22,10 +15,10 @@ in options = { xdg.terminal-exec = { - enable = mkEnableOption "xdg-terminal-exec, the [proposed](https://gitlab.freedesktop.org/xdg/xdg-specs/-/merge_requests/46) Default Terminal Execution Specification"; - package = mkPackageOption pkgs "xdg-terminal-exec" { }; - settings = mkOption { - type = with types; attrsOf (listOf str); + enable = lib.mkEnableOption "xdg-terminal-exec, the [proposed](https://gitlab.freedesktop.org/xdg/xdg-specs/-/merge_requests/46) Default Terminal Execution Specification"; + package = lib.mkPackageOption pkgs "xdg-terminal-exec" { }; + settings = lib.mkOption { + type = with lib.types; attrsOf (listOf str); default = { }; description = '' Configuration options for the Default Terminal Execution Specification. @@ -47,7 +40,7 @@ in ###### implementation - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { environment = { systemPackages = [ cfg.package ]; diff --git a/nixos/modules/hardware/coral.nix b/nixos/modules/hardware/coral.nix index 4b0cadfc3cf00..400a11683a145 100644 --- a/nixos/modules/hardware/coral.nix +++ b/nixos/modules/hardware/coral.nix @@ -17,18 +17,18 @@ in { options.hardware.coral = { - usb.enable = mkEnableOption "Coral USB support"; - pcie.enable = mkEnableOption "Coral PCIe support"; + usb.enable = lib.mkEnableOption "Coral USB support"; + pcie.enable = lib.mkEnableOption "Coral PCIe support"; }; - config = mkMerge [ - (mkIf (cfg.usb.enable || cfg.pcie.enable) { + config = lib.mkMerge [ + (lib.mkIf (cfg.usb.enable || cfg.pcie.enable) { users.groups.coral = { }; }) - (mkIf cfg.usb.enable { + (lib.mkIf cfg.usb.enable { services.udev.packages = with pkgs; [ libedgetpu ]; }) - (mkIf cfg.pcie.enable { + (lib.mkIf cfg.pcie.enable { boot.extraModulePackages = with config.boot.kernelPackages; [ gasket ]; services.udev.extraRules = '' SUBSYSTEM=="apex",MODE="0660",GROUP="coral" diff --git a/nixos/modules/hardware/corectrl.nix b/nixos/modules/hardware/corectrl.nix index 6e680ddc846ef..d50d645d192ac 100644 --- a/nixos/modules/hardware/corectrl.nix +++ b/nixos/modules/hardware/corectrl.nix @@ -5,31 +5,24 @@ ... }: let - inherit (lib) - mkEnableOption - mkIf - mkOption - mkPackageOption - ; - cfg = config.programs.corectrl; in { options.programs.corectrl = { - enable = mkEnableOption '' + enable = lib.mkEnableOption '' CoreCtrl, a tool to overclock amd graphics cards and processors. Add your user to the corectrl group to run corectrl without needing to enter your password ''; - package = mkPackageOption pkgs "corectrl" { + package = lib.mkPackageOption pkgs "corectrl" { extraDescription = "Useful for overriding the configuration options used for the package."; }; gpuOverclock = { - enable = mkEnableOption '' + enable = lib.mkEnableOption '' GPU overclocking ''; - ppfeaturemask = mkOption { + ppfeaturemask = lib.mkOption { type = lib.types.str; default = "0xfffd7fff"; example = "0xffffffff"; @@ -43,7 +36,7 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { environment.systemPackages = [ cfg.package ]; services.dbus.packages = [ cfg.package ]; @@ -64,7 +57,7 @@ in # https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/drivers/gpu/drm/amd/include/amd_shared.h#n169 # The overdrive bit - boot.kernelParams = mkIf cfg.gpuOverclock.enable [ + boot.kernelParams = lib.mkIf cfg.gpuOverclock.enable [ "amdgpu.ppfeaturemask=${cfg.gpuOverclock.ppfeaturemask}" ]; }; diff --git a/nixos/modules/hardware/cpu/amd-ryzen-smu.nix b/nixos/modules/hardware/cpu/amd-ryzen-smu.nix index c87805b18a750..74157b24c8b5b 100644 --- a/nixos/modules/hardware/cpu/amd-ryzen-smu.nix +++ b/nixos/modules/hardware/cpu/amd-ryzen-smu.nix @@ -10,14 +10,14 @@ let in { options.hardware.cpu.amd.ryzen-smu = { - enable = mkEnableOption '' + enable = lib.mkEnableOption '' ryzen_smu, a linux kernel driver that exposes access to the SMU (System Management Unit) for certain AMD Ryzen Processors. WARNING: Damage cause by use of your AMD processor outside of official AMD specifications or outside of factory settings are not covered under any AMD product warranty and may not be covered by your board or system manufacturer's warranty ''; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { boot.kernelModules = [ "ryzen-smu" ]; boot.extraModulePackages = [ ryzen-smu ]; environment.systemPackages = [ ryzen-smu ]; diff --git a/nixos/modules/hardware/cpu/amd-sev.nix b/nixos/modules/hardware/cpu/amd-sev.nix index 4bf43f70c70c1..526be9a9807cf 100644 --- a/nixos/modules/hardware/cpu/amd-sev.nix +++ b/nixos/modules/hardware/cpu/amd-sev.nix @@ -27,7 +27,6 @@ let }; }; in -with lib; { options.hardware.cpu.amd.sev = optionsFor "SEV" "sev"; diff --git a/nixos/modules/hardware/cpu/x86-msr.nix b/nixos/modules/hardware/cpu/x86-msr.nix index 56f6e23812abc..1d98026135a5d 100644 --- a/nixos/modules/hardware/cpu/x86-msr.nix +++ b/nixos/modules/hardware/cpu/x86-msr.nix @@ -41,33 +41,33 @@ in with lib.options; with lib.types; { - enable = mkEnableOption "the `msr` (Model-Specific Registers) kernel module and configure `udev` rules for its devices (usually `/dev/cpu/*/msr`)"; - owner = mkOption { + enable = lib.mkEnableOption "the `msr` (Model-Specific Registers) kernel module and configure `udev` rules for its devices (usually `/dev/cpu/*/msr`)"; + owner = lib.mkOption { type = str; default = "root"; example = "nobody"; description = "Owner ${set}"; }; - group = mkOption { + group = lib.mkOption { type = str; default = defaultGroup; example = "nobody"; description = "Group ${set}"; }; - mode = mkOption { + mode = lib.mkOption { type = str; default = "0640"; example = "0660"; description = "Mode ${set}"; }; - settings = mkOption { + settings = lib.mkOption { type = submodule { freeformType = attrsOf (oneOf [ bool int str ]); - options.allow-writes = mkOption { + options.allow-writes = lib.mkOption { type = nullOr (enum [ "on" "off" @@ -81,7 +81,7 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { assertions = [ { assertion = hasAttr cfg.owner config.users.users; @@ -100,14 +100,14 @@ in ); }; - users.groups.${cfg.group} = mkIf isDefaultGroup { }; + users.groups.${cfg.group} = lib.mkIf isDefaultGroup { }; services.udev.extraRules = '' SUBSYSTEM=="msr", OWNER="${cfg.owner}", GROUP="${cfg.group}", MODE="${cfg.mode}" ''; }; - meta = with lib; { - maintainers = with maintainers; [ lorenzleutgeb ]; + meta = { + maintainers = [ lib.maintainers.lorenzleutgeb ]; }; } diff --git a/nixos/modules/hardware/keyboard/qmk.nix b/nixos/modules/hardware/keyboard/qmk.nix index 6690deca35062..b15ba0582ef56 100644 --- a/nixos/modules/hardware/keyboard/qmk.nix +++ b/nixos/modules/hardware/keyboard/qmk.nix @@ -12,10 +12,10 @@ let in { options.hardware.keyboard.qmk = { - enable = mkEnableOption "non-root access to the firmware of QMK keyboards"; + enable = lib.mkEnableOption "non-root access to the firmware of QMK keyboards"; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { services.udev.packages = [ pkgs.qmk-udev-rules ]; users.groups.plugdev = { }; }; diff --git a/nixos/modules/hardware/keyboard/teck.nix b/nixos/modules/hardware/keyboard/teck.nix index ed1c8abd00777..0dc1fa4176094 100644 --- a/nixos/modules/hardware/keyboard/teck.nix +++ b/nixos/modules/hardware/keyboard/teck.nix @@ -12,10 +12,10 @@ let in { options.hardware.keyboard.teck = { - enable = mkEnableOption "non-root access to the firmware of TECK keyboards"; + enable = lib.mkEnableOption "non-root access to the firmware of TECK keyboards"; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { services.udev.packages = [ pkgs.teck-udev-rules ]; }; } diff --git a/nixos/modules/hardware/keyboard/uhk.nix b/nixos/modules/hardware/keyboard/uhk.nix index 4332cefe3f9e7..8c69c163867ca 100644 --- a/nixos/modules/hardware/keyboard/uhk.nix +++ b/nixos/modules/hardware/keyboard/uhk.nix @@ -12,7 +12,7 @@ let in { options.hardware.keyboard.uhk = { - enable = mkEnableOption '' + enable = lib.mkEnableOption '' non-root access to the firmware of UHK keyboards. You need it when you want to flash a new firmware on the keyboard. Access to the keyboard is granted to users in the "input" group. @@ -21,7 +21,7 @@ in }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { services.udev.packages = [ pkgs.uhk-udev-rules ]; }; } diff --git a/nixos/modules/hardware/keyboard/zsa.nix b/nixos/modules/hardware/keyboard/zsa.nix index 607d1a5dfec0c..a10ac41b28fb5 100644 --- a/nixos/modules/hardware/keyboard/zsa.nix +++ b/nixos/modules/hardware/keyboard/zsa.nix @@ -12,7 +12,7 @@ let in { options.hardware.keyboard.zsa = { - enable = mkEnableOption '' + enable = lib.mkEnableOption '' udev rules for keyboards from ZSA like the ErgoDox EZ, Planck EZ and Moonlander Mark I. You need it when you want to flash a new configuration on the keyboard or use their live training in the browser. @@ -20,7 +20,7 @@ in ''; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { services.udev.packages = [ pkgs.zsa-udev-rules ]; }; } diff --git a/nixos/modules/hardware/network/eg25-manager.nix b/nixos/modules/hardware/network/eg25-manager.nix index 485c1da68f0aa..d4360553cef8c 100644 --- a/nixos/modules/hardware/network/eg25-manager.nix +++ b/nixos/modules/hardware/network/eg25-manager.nix @@ -11,11 +11,11 @@ let in { options.services.eg25-manager = { - enable = mkEnableOption "Quectel EG25 modem manager service"; + enable = lib.mkEnableOption "Quectel EG25 modem manager service"; - package = mkPackageOption pkgs "eg25-manager" { }; + package = lib.mkPackageOption pkgs "eg25-manager" { }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { systemd.packages = [ cfg.package ]; services.udev.packages = [ cfg.package ]; systemd.services.eg25-manager.wantedBy = [ "multi-user.target" ]; diff --git a/nixos/modules/hardware/raid/hpsa.nix b/nixos/modules/hardware/raid/hpsa.nix index effac77bdd5aa..25efbe74070cc 100644 --- a/nixos/modules/hardware/raid/hpsa.nix +++ b/nixos/modules/hardware/raid/hpsa.nix @@ -37,10 +37,10 @@ let dontStrip = true; - meta = with lib; { + meta = { description = "HP Smart Array CLI"; homepage = "https://downloads.linux.hpe.com/SDR/downloads/MCP/Ubuntu/pool/non-free/"; - license = licenses.unfreeRedistributable; + license = lib.licenses.unfreeRedistributable; platforms = [ "x86_64-linux" ]; maintainers = [ ]; }; diff --git a/nixos/modules/hardware/sata.nix b/nixos/modules/hardware/sata.nix index 752a1a4de8ff3..33cf576269a2f 100644 --- a/nixos/modules/hardware/sata.nix +++ b/nixos/modules/hardware/sata.nix @@ -5,13 +5,6 @@ ... }: let - inherit (lib) - mkEnableOption - mkIf - mkOption - types - ; - cfg = config.hardware.sata.timeout; buildRule = @@ -44,11 +37,11 @@ in meta.maintainers = with lib.maintainers; [ peterhoeg ]; options.hardware.sata.timeout = { - enable = mkEnableOption "SATA drive timeouts"; + enable = lib.mkEnableOption "SATA drive timeouts"; - deciSeconds = mkOption { + deciSeconds = lib.mkOption { example = 70; - type = types.int; + type = lib.types.int; description = '' Set SCT Error Recovery Control timeout in deciseconds for use in RAID configurations. @@ -60,19 +53,19 @@ in ''; }; - drives = mkOption { + drives = lib.mkOption { description = "List of drives for which to configure the timeout."; - type = types.listOf ( - types.submodule { + type = lib.types.listOf ( + lib.types.submodule { options = { - name = mkOption { + name = lib.mkOption { description = "Drive name without the full path."; - type = types.str; + type = lib.types.str; }; - idBy = mkOption { + idBy = lib.mkOption { description = "The method to identify the drive."; - type = types.enum [ + type = lib.types.enum [ "path" "wwn" ]; @@ -84,7 +77,7 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { services.udev.extraRules = lib.concatMapStringsSep "\n" buildRule cfg.drives; systemd.services = lib.listToAttrs ( diff --git a/nixos/modules/hardware/sensor/hddtemp.nix b/nixos/modules/hardware/sensor/hddtemp.nix index 8a8a3ad838c31..c837f665eed25 100644 --- a/nixos/modules/hardware/sensor/hddtemp.nix +++ b/nixos/modules/hardware/sensor/hddtemp.nix @@ -5,8 +5,6 @@ ... }: let - inherit (lib) mkIf mkOption types; - cfg = config.hardware.sensor.hddtemp; wrapper = pkgs.writeShellScript "hddtemp-wrapper" '' @@ -34,37 +32,37 @@ in options = { hardware.sensor.hddtemp = { - enable = mkOption { + enable = lib.mkOption { description = '' Enable this option to support HDD/SSD temperature sensors. ''; - type = types.bool; + type = lib.types.bool; default = false; }; - drives = mkOption { + drives = lib.mkOption { description = "List of drives to monitor. If you pass /dev/disk/by-path/* entries the symlinks will be resolved as hddtemp doesn't like names with colons."; - type = types.listOf types.str; + type = lib.types.listOf lib.types.str; }; - unit = mkOption { + unit = lib.mkOption { description = "Celsius or Fahrenheit"; - type = types.enum [ + type = lib.types.enum [ "C" "F" ]; default = "C"; }; - dbEntries = mkOption { + dbEntries = lib.mkOption { description = "Additional DB entries"; - type = types.listOf types.str; + type = lib.types.listOf lib.types.str; default = [ ]; }; - extraArgs = mkOption { + extraArgs = lib.mkOption { description = "Additional arguments passed to the daemon."; - type = types.listOf types.str; + type = lib.types.listOf lib.types.str; default = [ ]; }; }; @@ -72,7 +70,7 @@ in ###### implementation - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { systemd.services.hddtemp = { description = "HDD/SSD temperature"; wantedBy = [ "multi-user.target" ]; diff --git a/nixos/modules/hardware/system-76.nix b/nixos/modules/hardware/system-76.nix index 4dc71b9a50988..39535c777a123 100644 --- a/nixos/modules/hardware/system-76.nix +++ b/nixos/modules/hardware/system-76.nix @@ -7,16 +7,6 @@ }: let - inherit (lib) - literalExpression - mkOption - mkEnableOption - types - mkIf - mkMerge - optional - versionOlder - ; cfg = config.hardware.system76; opt = options.hardware.system76; @@ -24,9 +14,9 @@ let modules = [ "system76" "system76-io" - ] ++ (optional (versionOlder kpkgs.kernel.version "5.5") "system76-acpi"); + ] ++ (lib.optional (lib.versionOlder kpkgs.kernel.version "5.5") "system76-acpi"); modulePackages = map (m: kpkgs.${m}) modules; - moduleConfig = mkIf cfg.kernel-modules.enable { + moduleConfig = lib.mkIf cfg.kernel-modules.enable { boot.extraModulePackages = modulePackages; boot.kernelModules = modules; @@ -35,7 +25,7 @@ let }; firmware-pkg = pkgs.system76-firmware; - firmwareConfig = mkIf cfg.firmware-daemon.enable { + firmwareConfig = lib.mkIf cfg.firmware-daemon.enable { # Make system76-firmware-cli usable by root from the command line. environment.systemPackages = [ firmware-pkg ]; @@ -55,7 +45,7 @@ let }; power-pkg = pkgs.system76-power; - powerConfig = mkIf cfg.power-daemon.enable { + powerConfig = lib.mkIf cfg.power-daemon.enable { # Make system76-power usable by root from the command line. environment.systemPackages = [ power-pkg ]; @@ -76,35 +66,35 @@ in { options = { hardware.system76 = { - enableAll = mkEnableOption "all recommended configuration for system76 systems"; + enableAll = lib.mkEnableOption "all recommended configuration for system76 systems"; - firmware-daemon.enable = mkOption { + firmware-daemon.enable = lib.mkOption { default = cfg.enableAll; - defaultText = literalExpression "config.${opt.enableAll}"; + defaultText = lib.literalExpression "config.${opt.enableAll}"; example = true; description = "Whether to enable the system76 firmware daemon"; - type = types.bool; + type = lib.types.bool; }; - kernel-modules.enable = mkOption { + kernel-modules.enable = lib.mkOption { default = cfg.enableAll; - defaultText = literalExpression "config.${opt.enableAll}"; + defaultText = lib.literalExpression "config.${opt.enableAll}"; example = true; description = "Whether to make the system76 out-of-tree kernel modules available"; - type = types.bool; + type = lib.types.bool; }; - power-daemon.enable = mkOption { + power-daemon.enable = lib.mkOption { default = cfg.enableAll; - defaultText = literalExpression "config.${opt.enableAll}"; + defaultText = lib.literalExpression "config.${opt.enableAll}"; example = true; description = "Whether to enable the system76 power daemon"; - type = types.bool; + type = lib.types.bool; }; }; }; - config = mkMerge [ + config = lib.mkMerge [ moduleConfig firmwareConfig powerConfig diff --git a/nixos/modules/hardware/uni-sync.nix b/nixos/modules/hardware/uni-sync.nix index 2fc93772562d6..5f0bd91f854ec 100644 --- a/nixos/modules/hardware/uni-sync.nix +++ b/nixos/modules/hardware/uni-sync.nix @@ -4,20 +4,19 @@ pkgs, ... }: -with lib; let cfg = config.hardware.uni-sync; in { - meta.maintainers = with maintainers; [ yunfachi ]; + meta.maintainers = with lib.maintainers; [ yunfachi ]; options.hardware.uni-sync = { - enable = mkEnableOption "udev rules and software for Lian Li Uni Controllers"; - package = mkPackageOption pkgs "uni-sync" { }; + enable = lib.mkEnableOption "udev rules and software for Lian Li Uni Controllers"; + package = lib.mkPackageOption pkgs "uni-sync" { }; - devices = mkOption { + devices = lib.mkOption { default = [ ]; - example = literalExpression '' + example = lib.literalExpression '' [ { device_id = "VID:1111/PID:11111/SN:1111111111"; @@ -53,23 +52,23 @@ in ] ''; description = "List of controllers with their configurations."; - type = types.listOf ( - types.submodule { + type = lib.types.listOf ( + lib.types.submodule { options = { - device_id = mkOption { - type = types.str; + device_id = lib.mkOption { + type = lib.types.str; example = "VID:1111/PID:11111/SN:1111111111"; description = "Unique device ID displayed at each startup."; }; - sync_rgb = mkOption { - type = types.bool; + sync_rgb = lib.mkOption { + type = lib.types.bool; default = false; example = true; description = "Enable ARGB header sync."; }; - channels = mkOption { + channels = lib.mkOption { default = [ ]; - example = literalExpression '' + example = lib.literalExpression '' [ { mode = "PWM"; @@ -89,11 +88,11 @@ in ] ''; description = "List of channels connected to the controller."; - type = types.listOf ( - types.submodule { + type = lib.types.listOf ( + lib.types.submodule { options = { - mode = mkOption { - type = types.enum [ + mode = lib.mkOption { + type = lib.types.enum [ "Manual" "PWM" ]; @@ -101,8 +100,8 @@ in example = "PWM"; description = "\"PWM\" to enable PWM sync. \"Manual\" to set speed."; }; - speed = mkOption { - type = types.int; + speed = lib.mkOption { + type = lib.types.int; default = "50"; example = "100"; description = "Fan speed as percentage (clamped between 0 and 100)."; @@ -117,8 +116,8 @@ in }; }; - config = mkIf cfg.enable { - environment.etc."uni-sync/uni-sync.json".text = mkIf (cfg.devices != [ ]) ( + config = lib.mkIf cfg.enable { + environment.etc."uni-sync/uni-sync.json".text = lib.mkIf (cfg.devices != [ ]) ( builtins.toJSON { configs = cfg.devices; } ); diff --git a/nixos/modules/hardware/video/webcam/ipu6.nix b/nixos/modules/hardware/video/webcam/ipu6.nix index aab986251d75d..9ffff70b38fac 100644 --- a/nixos/modules/hardware/video/webcam/ipu6.nix +++ b/nixos/modules/hardware/video/webcam/ipu6.nix @@ -6,15 +6,6 @@ }: let - inherit (lib) - mkDefault - mkEnableOption - mkIf - mkOption - optional - types - ; - cfg = config.hardware.ipu6; in @@ -22,10 +13,10 @@ in options.hardware.ipu6 = { - enable = mkEnableOption "support for Intel IPU6/MIPI cameras"; + enable = lib.mkEnableOption "support for Intel IPU6/MIPI cameras"; - platform = mkOption { - type = types.enum [ + platform = lib.mkOption { + type = lib.types.enum [ "ipu6" "ipu6ep" "ipu6epmtl" @@ -40,7 +31,7 @@ in }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { # Module is upstream as of 6.10, # but still needs various out-of-tree i2c and the `intel-ipu6-psys` kernel driver @@ -56,20 +47,20 @@ in ''; services.v4l2-relayd.instances.ipu6 = { - enable = mkDefault true; + enable = lib.mkDefault true; - cardLabel = mkDefault "Intel MIPI Camera"; + cardLabel = lib.mkDefault "Intel MIPI Camera"; extraPackages = with pkgs.gst_all_1; [ ] - ++ optional (cfg.platform == "ipu6") icamerasrc-ipu6 - ++ optional (cfg.platform == "ipu6ep") icamerasrc-ipu6ep - ++ optional (cfg.platform == "ipu6epmtl") icamerasrc-ipu6epmtl; + ++ lib.optional (cfg.platform == "ipu6") icamerasrc-ipu6 + ++ lib.optional (cfg.platform == "ipu6ep") icamerasrc-ipu6ep + ++ lib.optional (cfg.platform == "ipu6epmtl") icamerasrc-ipu6epmtl; input = { pipeline = "icamerasrc"; - format = mkIf (cfg.platform != "ipu6") (mkDefault "NV12"); + format = lib.mkIf (cfg.platform != "ipu6") (lib.mkDefault "NV12"); }; }; }; diff --git a/nixos/modules/i18n/input-method/fcitx5.nix b/nixos/modules/i18n/input-method/fcitx5.nix index 5488b4fa89c68..906e9ed640f63 100644 --- a/nixos/modules/i18n/input-method/fcitx5.nix +++ b/nixos/modules/i18n/input-method/fcitx5.nix @@ -133,17 +133,17 @@ in ]; environment.etc = let - optionalFile = + lib.optionalFile = p: f: v: lib.optionalAttrs (v != { }) { "xdg/fcitx5/${p}".text = f v; }; in lib.attrsets.mergeAttrsList [ - (optionalFile "config" (lib.generators.toINI { }) cfg.settings.globalOptions) - (optionalFile "profile" (lib.generators.toINI { }) cfg.settings.inputMethod) + (lib.optionalFile "config" (lib.generators.toINI { }) cfg.settings.globalOptions) + (lib.optionalFile "profile" (lib.generators.toINI { }) cfg.settings.inputMethod) (lib.concatMapAttrs ( - name: value: optionalFile "conf/${name}.conf" (lib.generators.toINIWithGlobalSection { }) value + name: value: lib.optionalFile "conf/${name}.conf" (lib.generators.toINIWithGlobalSection { }) value ) cfg.settings.addons) ]; diff --git a/nixos/modules/image/images.nix b/nixos/modules/image/images.nix index 84e364818adc5..0cafe27f50c66 100644 --- a/nixos/modules/image/images.nix +++ b/nixos/modules/image/images.nix @@ -69,7 +69,7 @@ in options = { system.build = { images = lib.mkOption { - type = types.lazyAttrsOf types.raw; + type = lib.types.lazyAttrsOf types.raw; readOnly = true; description = '' Different target images generated for this NixOS configuration. @@ -77,7 +77,7 @@ in }; }; image.modules = lib.mkOption { - type = types.attrsOf (types.listOf types.deferredModule); + type = lib.types.attrsOf (types.listOf types.deferredModule); description = '' image-specific NixOS Modules used for `system.build.images`. ''; diff --git a/nixos/modules/image/repart.nix b/nixos/modules/image/repart.nix index 544779cd6e9b3..9e41b3c49285c 100644 --- a/nixos/modules/image/repart.nix +++ b/nixos/modules/image/repart.nix @@ -30,7 +30,7 @@ let type = with lib.types; attrsOf (submodule { options = { source = lib.mkOption { - type = types.path; + type = lib.types.path; description = "Path of the source file."; }; }; diff --git a/nixos/modules/installer/netboot/netboot-base.nix b/nixos/modules/installer/netboot/netboot-base.nix index 360ef56469962..7f2e935f65b6d 100644 --- a/nixos/modules/installer/netboot/netboot-base.nix +++ b/nixos/modules/installer/netboot/netboot-base.nix @@ -1,9 +1,7 @@ # This module contains the basic configuration for building netboot # images -{ lib, ... }: - -with lib; +{ ... }: { imports = [ diff --git a/nixos/modules/installer/netboot/netboot.nix b/nixos/modules/installer/netboot/netboot.nix index 856ecb3f94ad4..0f3a1f8c3a3f4 100644 --- a/nixos/modules/installer/netboot/netboot.nix +++ b/nixos/modules/installer/netboot/netboot.nix @@ -3,8 +3,6 @@ { config, lib, pkgs, modulesPath, ... }: -with lib; - { imports = [ ../../image/file-options.nix @@ -12,17 +10,17 @@ with lib; options = { - netboot.squashfsCompression = mkOption { + netboot.squashfsCompression = lib.mkOption { default = "zstd -Xcompression-level 19"; description = '' Compression settings to use for the squashfs nix store. ''; example = "zstd -Xcompression-level 6"; - type = types.str; + type = lib.types.str; }; - netboot.storeContents = mkOption { - example = literalExpression "[ pkgs.stdenv ]"; + netboot.storeContents = lib.mkOption { + example = lib.literalExpression "[ pkgs.stdenv ]"; description = '' This option lists additional derivations to be included in the Nix store in the generated netboot image. @@ -36,27 +34,27 @@ with lib; # here and it causes a cyclic dependency. boot.loader.grub.enable = false; - fileSystems."/" = mkImageMediaOverride + fileSystems."/" = lib.mkImageMediaOverride { fsType = "tmpfs"; options = [ "mode=0755" ]; }; # In stage 1, mount a tmpfs on top of /nix/store (the squashfs # image) to make this a live CD. - fileSystems."/nix/.ro-store" = mkImageMediaOverride + fileSystems."/nix/.ro-store" = lib.mkImageMediaOverride { fsType = "squashfs"; device = "../nix-store.squashfs"; options = [ "loop" ] ++ lib.optional (config.boot.kernelPackages.kernel.kernelAtLeast "6.2") "threads=multi"; neededForBoot = true; }; - fileSystems."/nix/.rw-store" = mkImageMediaOverride + fileSystems."/nix/.rw-store" = lib.mkImageMediaOverride { fsType = "tmpfs"; options = [ "mode=0755" ]; neededForBoot = true; }; - fileSystems."/nix/store" = mkImageMediaOverride + fileSystems."/nix/store" = lib.mkImageMediaOverride { overlay = { lowerdir = [ "/nix/.ro-store" ]; upperdir = "/nix/.rw-store/store"; diff --git a/nixos/modules/installer/sd-card/sd-image.nix b/nixos/modules/installer/sd-card/sd-image.nix index 617f10edddf6f..faa25c165751f 100644 --- a/nixos/modules/installer/sd-card/sd-image.nix +++ b/nixos/modules/installer/sd-card/sd-image.nix @@ -13,22 +13,20 @@ { config, lib, pkgs, ... }: -with lib; - let rootfsImage = pkgs.callPackage ../../../lib/make-ext4-fs.nix ({ inherit (config.sdImage) storePaths; compressImage = config.sdImage.compressImage; populateImageCommands = config.sdImage.populateRootCommands; volumeLabel = "NIXOS_SD"; - } // optionalAttrs (config.sdImage.rootPartitionUUID != null) { + } // lib.optionalAttrs (config.sdImage.rootPartitionUUID != null) { uuid = config.sdImage.rootPartitionUUID; }); in { imports = [ - (mkRemovedOptionModule [ "sdImage" "bootPartitionID" ] "The FAT partition for SD image now only holds the Raspberry Pi firmware files. Use firmwarePartitionID to configure that partition's ID.") - (mkRemovedOptionModule [ "sdImage" "bootSize" ] "The boot files for SD image have been moved to the main ext4 partition. The FAT partition now only holds the Raspberry Pi firmware files. Changing its size may not be required.") + (lib.mkRemovedOptionModule [ "sdImage" "bootPartitionID" ] "The FAT partition for SD image now only holds the Raspberry Pi firmware files. Use firmwarePartitionID to configure that partition's ID.") + (lib.mkRemovedOptionModule [ "sdImage" "bootSize" ] "The boot files for SD image have been moved to the main ext4 partition. The FAT partition now only holds the Raspberry Pi firmware files. Changing its size may not be required.") (lib.mkRenamedOptionModuleWith { sinceRelease = 2505; from = [ @@ -56,16 +54,16 @@ in ]; options.sdImage = { - storePaths = mkOption { - type = with types; listOf package; - example = literalExpression "[ pkgs.stdenv ]"; + storePaths = lib.mkOption { + type = with lib.types; listOf package; + example = lib.literalExpression "[ pkgs.stdenv ]"; description = '' Derivations to be included in the Nix store in the generated SD image. ''; }; - firmwarePartitionOffset = mkOption { - type = types.int; + firmwarePartitionOffset = lib.mkOption { + type = lib.types.int; default = 8; description = '' Gap in front of the /boot/firmware partition, in mebibytes (1024×1024 @@ -80,8 +78,8 @@ in ''; }; - firmwarePartitionID = mkOption { - type = types.str; + firmwarePartitionID = lib.mkOption { + type = lib.types.str; default = "0x2178694e"; description = '' Volume ID for the /boot/firmware partition on the SD card. This value @@ -89,16 +87,16 @@ in ''; }; - firmwarePartitionName = mkOption { - type = types.str; + firmwarePartitionName = lib.mkOption { + type = lib.types.str; default = "FIRMWARE"; description = '' Name of the filesystem which holds the boot firmware. ''; }; - rootPartitionUUID = mkOption { - type = types.nullOr types.str; + rootPartitionUUID = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; example = "14e19a7b-0ae0-484d-9d54-43bd6fdc20c7"; description = '' @@ -106,8 +104,8 @@ in ''; }; - firmwareSize = mkOption { - type = types.int; + firmwareSize = lib.mkOption { + type = lib.types.int; # As of 2019-08-18 the Raspberry pi firmware + u-boot takes ~18MiB default = 30; description = '' @@ -115,8 +113,8 @@ in ''; }; - populateFirmwareCommands = mkOption { - example = literalExpression "'' cp \${pkgs.myBootLoader}/u-boot.bin firmware/ ''"; + populateFirmwareCommands = lib.mkOption { + example = lib.literalExpression "'' cp \${pkgs.myBootLoader}/u-boot.bin firmware/ ''"; description = '' Shell commands to populate the ./firmware directory. All files in that directory are copied to the @@ -124,8 +122,8 @@ in ''; }; - populateRootCommands = mkOption { - example = literalExpression "''\${config.boot.loader.generic-extlinux-compatible.populateCmd} -c \${config.system.build.toplevel} -d ./files/boot''"; + populateRootCommands = lib.mkOption { + example = lib.literalExpression "''\${config.boot.loader.generic-extlinux-compatible.populateCmd} -c \${config.system.build.toplevel} -d ./files/boot''"; description = '' Shell commands to populate the ./files directory. All files in that directory are copied to the @@ -134,8 +132,8 @@ in ''; }; - postBuildCommands = mkOption { - example = literalExpression "'' dd if=\${pkgs.myBootLoader}/SPL of=$img bs=1024 seek=1 conv=notrunc ''"; + postBuildCommands = lib.mkOption { + example = lib.literalExpression "'' dd if=\${pkgs.myBootLoader}/SPL of=$img bs=1024 seek=1 conv=notrunc ''"; default = ""; description = '' Shell commands to run after the image is built. @@ -143,8 +141,8 @@ in ''; }; - compressImage = mkOption { - type = types.bool; + compressImage = lib.mkOption { + type = lib.types.bool; default = true; description = '' Whether the SD image should be compressed using @@ -152,16 +150,16 @@ in ''; }; - expandOnBoot = mkOption { - type = types.bool; + expandOnBoot = lib.mkOption { + type = lib.types.bool; default = true; description = '' Whether to configure the sd image to expand it's partition on boot. ''; }; - nixPathRegistrationFile = mkOption { - type = types.str; + nixPathRegistrationFile = lib.mkOption { + type = lib.types.str; default = "/nix-path-registration"; description = '' Location of the file containing the input for nix-store --load-db once the machine has booted. diff --git a/nixos/modules/misc/documentation.nix b/nixos/modules/misc/documentation.nix index b6ace630deccb..b6ce657eaf21c 100644 --- a/nixos/modules/misc/documentation.nix +++ b/nixos/modules/misc/documentation.nix @@ -1,54 +1,27 @@ { config, options, lib, pkgs, utils, modules, baseModules, extraModules, modulesPath, specialArgs, ... }: let - inherit (lib) - cleanSourceFilter - concatMapStringsSep - evalModules - filter - functionArgs - hasSuffix - isAttrs - isDerivation - isFunction - isPath - literalExpression - mapAttrs - mkIf - mkMerge - mkOption - mkRemovedOptionModule - mkRenamedOptionModule - optional - optionalAttrs - optionals - partition - removePrefix - types - warn - ; - cfg = config.documentation; allOpts = options; canCacheDocs = m: let f = import m; - instance = f (mapAttrs (n: _: abort "evaluating ${n} for `meta` failed") (functionArgs f)); + instance = f (lib.mapAttrs (n: _: abort "evaluating ${n} for `meta` failed") (lib.functionArgs f)); in cfg.nixos.options.splitBuild - && isPath m - && isFunction f + && lib.isPath m + && lib.isFunction f && instance ? options && instance.meta.buildDocsInSandbox or true; docModules = let - p = partition canCacheDocs (baseModules ++ cfg.nixos.extraModules); + p = lib.partition canCacheDocs (baseModules ++ cfg.nixos.extraModules); in { lazy = p.right; - eager = p.wrong ++ optionals cfg.nixos.includeAllModules (extraModules ++ modules); + eager = p.wrong ++ lib.optionals cfg.nixos.includeAllModules (extraModules ++ modules); }; manual = import ../../doc/manual rec { @@ -58,7 +31,7 @@ let extraSources = cfg.nixos.extraModuleSources; options = let - scrubbedEval = evalModules { + scrubbedEval = lib.evalModules { modules = [ { _module.check = false; } ] ++ docModules.eager; @@ -71,14 +44,14 @@ let inherit modulesPath utils; }; }; - scrubDerivations = namePrefix: pkgSet: mapAttrs + scrubDerivations = namePrefix: pkgSet: lib.mapAttrs (name: value: let wholeName = "${namePrefix}.${name}"; - guard = warn "Attempt to evaluate package ${wholeName} in option documentation; this is not supported and will eventually be an error. Use `mkPackageOption{,MD}` or `literalExpression` instead."; - in if isAttrs value then + guard = lib.warn "Attempt to evaluate package ${wholeName} in option documentation; this is not supported and will eventually be an error. Use `mkPackageOption{,MD}` or `literalExpression` instead."; + in if lib.isAttrs value then scrubDerivations wholeName value - // optionalAttrs (isDerivation value) { + // lib.optionalAttrs (lib.isDerivation value) { outPath = guard "\${${wholeName}}"; drvPath = guard value.drvPath; } @@ -92,9 +65,9 @@ let filter = builtins.filterSource (n: t: - cleanSourceFilter n t + lib.cleanSourceFilter n t && (t == "directory" -> baseNameOf n != "tests") - && (t == "file" -> hasSuffix ".nix" n) + && (t == "file" -> lib.hasSuffix ".nix" n) ); in pkgs.runCommand "lazy-options.json" { @@ -104,7 +77,7 @@ let NIX_ABORT_ON_WARN = warningsAreErrors; modules = "[ " - + concatMapStringsSep " " (p: ''"${removePrefix "${modulesPath}/" (toString p)}"'') docModules.lazy + + lib.concatMapStringsSep " " (p: ''"${lib.removePrefix "${modulesPath}/" (toString p)}"'') docModules.lazy + " ]"; passAsFile = [ "modules" ]; } '' @@ -186,10 +159,10 @@ in ./meta.nix ../config/system-path.nix ../system/etc/etc.nix - (mkRenamedOptionModule [ "programs" "info" "enable" ] [ "documentation" "info" "enable" ]) - (mkRenamedOptionModule [ "programs" "man" "enable" ] [ "documentation" "man" "enable" ]) - (mkRenamedOptionModule [ "services" "nixosManual" "enable" ] [ "documentation" "nixos" "enable" ]) - (mkRemovedOptionModule + (lib.mkRenamedOptionModule [ "programs" "info" "enable" ] [ "documentation" "info" "enable" ]) + (lib.mkRenamedOptionModule [ "programs" "man" "enable" ] [ "documentation" "man" "enable" ]) + (lib.mkRenamedOptionModule [ "services" "nixosManual" "enable" ] [ "documentation" "nixos" "enable" ]) + (lib.mkRemovedOptionModule [ "documentation" "nixos" "options" "allowDocBook" ] "DocBook option documentation is no longer supported") ]; @@ -198,8 +171,8 @@ in documentation = { - enable = mkOption { - type = types.bool; + enable = lib.mkOption { + type = lib.types.bool; default = true; description = '' Whether to install documentation of packages from @@ -210,8 +183,8 @@ in # which is at ../../../doc/multiple-output.chapter.md }; - man.enable = mkOption { - type = types.bool; + man.enable = lib.mkOption { + type = lib.types.bool; default = true; description = '' Whether to install manual pages. @@ -219,8 +192,8 @@ in ''; }; - man.generateCaches = mkOption { - type = types.bool; + man.generateCaches = lib.mkOption { + type = lib.types.bool; default = false; description = '' Whether to generate the manual page index caches. @@ -231,8 +204,8 @@ in ''; }; - info.enable = mkOption { - type = types.bool; + info.enable = lib.mkOption { + type = lib.types.bool; default = true; description = '' Whether to install info pages and the {command}`info` command. @@ -240,8 +213,8 @@ in ''; }; - doc.enable = mkOption { - type = types.bool; + doc.enable = lib.mkOption { + type = lib.types.bool; default = true; description = '' Whether to install documentation distributed in packages' `/share/doc`. @@ -250,8 +223,8 @@ in ''; }; - dev.enable = mkOption { - type = types.bool; + dev.enable = lib.mkOption { + type = lib.types.bool; default = false; description = '' Whether to install documentation targeted at developers. @@ -264,8 +237,8 @@ in ''; }; - nixos.enable = mkOption { - type = types.bool; + nixos.enable = lib.mkOption { + type = lib.types.bool; default = true; description = '' Whether to install NixOS's own documentation. @@ -278,16 +251,16 @@ in ''; }; - nixos.extraModules = mkOption { - type = types.listOf types.raw; + nixos.extraModules = lib.mkOption { + type = lib.types.listOf lib.types.raw; default = []; description = '' Modules for which to show options even when not imported. ''; }; - nixos.options.splitBuild = mkOption { - type = types.bool; + nixos.options.splitBuild = lib.mkOption { + type = lib.types.bool; default = true; description = '' Whether to split the option docs build into a cacheable and an uncacheable part. @@ -296,8 +269,8 @@ in ''; }; - nixos.options.warningsAreErrors = mkOption { - type = types.bool; + nixos.options.warningsAreErrors = lib.mkOption { + type = lib.types.bool; default = true; description = '' Treat warning emitted during the option documentation build (eg for missing option @@ -305,8 +278,8 @@ in ''; }; - nixos.includeAllModules = mkOption { - type = types.bool; + nixos.includeAllModules = lib.mkOption { + type = lib.types.bool; default = false; description = '' Whether the generated NixOS's documentation should include documentation for all @@ -316,14 +289,14 @@ in ''; }; - nixos.extraModuleSources = mkOption { - type = types.listOf (types.either types.path types.str); + nixos.extraModuleSources = lib.mkOption { + type = lib.types.listOf (lib.types.either lib.types.path lib.types.str); default = [ ]; description = '' Which extra NixOS module paths the generated NixOS's documentation should strip from options. ''; - example = literalExpression '' + example = lib.literalExpression '' # e.g. with options from modules in ''${pkgs.customModules}/nix: [ pkgs.customModules ] ''; @@ -333,7 +306,7 @@ in }; - config = mkIf cfg.enable (mkMerge [ + config = lib.mkIf cfg.enable (lib.mkMerge [ { assertions = [ { @@ -347,15 +320,15 @@ in # The actual implementation for this lives in man-db.nix or mandoc.nix, # depending on which backend is active. - (mkIf cfg.man.enable { + (lib.mkIf cfg.man.enable { environment.pathsToLink = [ "/share/man" ]; - environment.extraOutputsToInstall = [ "man" ] ++ optional cfg.dev.enable "devman"; + environment.extraOutputsToInstall = [ "man" ] ++ lib.optional cfg.dev.enable "devman"; }) - (mkIf cfg.info.enable { + (lib.mkIf cfg.info.enable { environment.systemPackages = [ pkgs.texinfoInteractive ]; environment.pathsToLink = [ "/share/info" ]; - environment.extraOutputsToInstall = [ "info" ] ++ optional cfg.dev.enable "devinfo"; + environment.extraOutputsToInstall = [ "info" ] ++ lib.optional cfg.dev.enable "devinfo"; environment.extraSetup = '' if [ -w $out/share/info ]; then shopt -s nullglob @@ -366,7 +339,7 @@ in ''; }) - (mkIf cfg.doc.enable { + (lib.mkIf cfg.doc.enable { environment.pathsToLink = [ "/share/doc" @@ -374,15 +347,15 @@ in "/share/gtk-doc" "/share/devhelp" ]; - environment.extraOutputsToInstall = [ "doc" ] ++ optional cfg.dev.enable "devdoc"; + environment.extraOutputsToInstall = [ "doc" ] ++ lib.optional cfg.dev.enable "devdoc"; }) - (mkIf cfg.nixos.enable { + (lib.mkIf cfg.nixos.enable { system.build.manual = manual; environment.systemPackages = [] - ++ optional cfg.man.enable manual.nixos-configuration-reference-manpage - ++ optionals cfg.doc.enable [ manual.manualHTML nixos-help ]; + ++ lib.optional cfg.man.enable manual.nixos-configuration-reference-manpage + ++ lib.optionals cfg.doc.enable [ manual.manualHTML nixos-help ]; }) ]); diff --git a/nixos/modules/misc/ids.nix b/nixos/modules/misc/ids.nix index fcdffc5209675..4fcfbd49b67f1 100644 --- a/nixos/modules/misc/ids.nix +++ b/nixos/modules/misc/ids.nix @@ -25,7 +25,7 @@ in description = '' The user IDs used in NixOS. ''; - type = types.attrsOf types.int; + type = lib.types.attrsOf types.int; }; ids.gids = lib.mkOption { @@ -33,7 +33,7 @@ in description = '' The group IDs used in NixOS. ''; - type = types.attrsOf types.int; + type = lib.types.attrsOf types.int; }; }; diff --git a/nixos/modules/misc/nixpkgs-flake.nix b/nixos/modules/misc/nixpkgs-flake.nix index 912f7a11fa367..1ec128909e978 100644 --- a/nixos/modules/misc/nixpkgs-flake.nix +++ b/nixos/modules/misc/nixpkgs-flake.nix @@ -28,7 +28,7 @@ in the store path of the nixpkgs flake used to build the system if using `nixpkgs.lib.nixosSystem`, and is otherwise null by default. - This can also be optionally set if the NixOS system is not built with a flake but still uses + This can also be lib.optionally set if the NixOS system is not built with a flake but still uses pinned sources: set this to the store path for the nixpkgs sources used to build the system, as may be obtained by `builtins.fetchTarball`, for example. diff --git a/nixos/modules/misc/nixpkgs/read-only.nix b/nixos/modules/misc/nixpkgs/read-only.nix index fa372d13e545c..f06cfacb2ac2f 100644 --- a/nixos/modules/misc/nixpkgs/read-only.nix +++ b/nixos/modules/misc/nixpkgs/read-only.nix @@ -13,8 +13,6 @@ let cfg = config.nixpkgs; - inherit (lib) mkOption types; - in { disabledModules = [ @@ -22,32 +20,32 @@ in ]; options = { nixpkgs = { - pkgs = mkOption { + pkgs = lib.mkOption { type = lib.types.pkgs; description = ''The pkgs module argument.''; }; - config = mkOption { + config = lib.mkOption { internal = true; - type = types.unique { message = "nixpkgs.config is set to read-only"; } types.anything; + type = lib.types.unique { message = "nixpkgs.config is set to read-only"; } lib.types.anything; description = '' The Nixpkgs `config` that `pkgs` was initialized with. ''; }; - overlays = mkOption { + overlays = lib.mkOption { internal = true; - type = types.unique { message = "nixpkgs.overlays is set to read-only"; } types.anything; + type = lib.types.unique { message = "nixpkgs.overlays is set to read-only"; } lib.types.anything; description = '' The Nixpkgs overlays that `pkgs` was initialized with. ''; }; - hostPlatform = mkOption { + hostPlatform = lib.mkOption { internal = true; readOnly = true; description = '' The platform of the machine that is running the NixOS configuration. ''; }; - buildPlatform = mkOption { + buildPlatform = lib.mkOption { internal = true; readOnly = true; description = '' diff --git a/nixos/modules/misc/version.nix b/nixos/modules/misc/version.nix index 6688ab9d1ca91..b8d63d6af41f3 100644 --- a/nixos/modules/misc/version.nix +++ b/nixos/modules/misc/version.nix @@ -10,24 +10,11 @@ let cfg = config.system.nixos; opt = options.system.nixos; - inherit (lib) - concatStringsSep - mapAttrsToList - toLower - optionalString - literalExpression - mkRenamedOptionModule - mkDefault - mkOption - trivial - types - ; - needsEscaping = s: null != builtins.match "[a-zA-Z0-9]+" s; escapeIfNecessary = s: if needsEscaping s then s else ''"${lib.escape [ "\$" "\"" "\\" "\`" ] s}"''; attrsToText = attrs: - concatStringsSep "\n" (mapAttrsToList (n: v: ''${n}=${escapeIfNecessary (toString v)}'') attrs) + lib.concatStringsSep "\n" (lib.mapAttrsToList (n: v: ''${n}=${escapeIfNecessary (toString v)}'') attrs) + "\n"; osReleaseContents = @@ -37,25 +24,25 @@ let { NAME = "${cfg.distroName}"; ID = "${cfg.distroId}"; - ID_LIKE = optionalString (!isNixos) "nixos"; + ID_LIKE = lib.optionalString (!isNixos) "nixos"; VENDOR_NAME = cfg.vendorName; VERSION = "${cfg.release} (${cfg.codeName})"; - VERSION_CODENAME = toLower cfg.codeName; + VERSION_CODENAME = lib.toLower cfg.codeName; VERSION_ID = cfg.release; BUILD_ID = cfg.version; PRETTY_NAME = "${cfg.distroName} ${cfg.release} (${cfg.codeName})"; CPE_NAME = "cpe:/o:${cfg.vendorId}:${cfg.distroId}:${cfg.release}"; LOGO = "nix-snowflake"; - HOME_URL = optionalString isNixos "https://nixos.org/"; - VENDOR_URL = optionalString isNixos "https://nixos.org/"; - DOCUMENTATION_URL = optionalString isNixos "https://nixos.org/learn.html"; - SUPPORT_URL = optionalString isNixos "https://nixos.org/community.html"; - BUG_REPORT_URL = optionalString isNixos "https://github.com/NixOS/nixpkgs/issues"; - ANSI_COLOR = optionalString isNixos "0;38;2;126;186;228"; - IMAGE_ID = optionalString (config.system.image.id != null) config.system.image.id; - IMAGE_VERSION = optionalString (config.system.image.version != null) config.system.image.version; - VARIANT = optionalString (cfg.variantName != null) cfg.variantName; - VARIANT_ID = optionalString (cfg.variant_id != null) cfg.variant_id; + HOME_URL = lib.optionalString isNixos "https://nixos.org/"; + VENDOR_URL = lib.optionalString isNixos "https://nixos.org/"; + DOCUMENTATION_URL = lib.optionalString isNixos "https://nixos.org/learn.html"; + SUPPORT_URL = lib.optionalString isNixos "https://nixos.org/community.html"; + BUG_REPORT_URL = lib.optionalString isNixos "https://github.com/NixOS/nixpkgs/issues"; + ANSI_COLOR = lib.optionalString isNixos "0;38;2;126;186;228"; + IMAGE_ID = lib.optionalString (config.system.image.id != null) config.system.image.id; + IMAGE_VERSION = lib.optionalString (config.system.image.version != null) config.system.image.version; + VARIANT = lib.optionalString (cfg.variantName != null) cfg.variantName; + VARIANT_ID = lib.optionalString (cfg.variant_id != null) cfg.variant_id; DEFAULT_HOSTNAME = config.system.nixos.distroId; } // cfg.extraOSReleaseArgs; @@ -69,13 +56,13 @@ in { imports = [ ./label.nix - (mkRenamedOptionModule [ "system" "nixosVersion" ] [ "system" "nixos" "version" ]) - (mkRenamedOptionModule [ "system" "nixosVersionSuffix" ] [ "system" "nixos" "versionSuffix" ]) - (mkRenamedOptionModule [ "system" "nixosRevision" ] [ "system" "nixos" "revision" ]) - (mkRenamedOptionModule [ "system" "nixosLabel" ] [ "system" "nixos" "label" ]) + (lib.mkRenamedOptionModule [ "system" "nixosVersion" ] [ "system" "nixos" "version" ]) + (lib.mkRenamedOptionModule [ "system" "nixosVersionSuffix" ] [ "system" "nixos" "versionSuffix" ]) + (lib.mkRenamedOptionModule [ "system" "nixosRevision" ] [ "system" "nixos" "revision" ]) + (lib.mkRenamedOptionModule [ "system" "nixosLabel" ] [ "system" "nixos" "label" ]) ]; - options.boot.initrd.osRelease = mkOption { + options.boot.initrd.osRelease = lib.mkOption { internal = true; readOnly = true; default = initrdRelease; @@ -83,85 +70,85 @@ in options.system = { nixos = { - version = mkOption { + version = lib.mkOption { internal = true; - type = types.str; + type = lib.types.str; description = "The full NixOS version (e.g. `16.03.1160.f2d4ee1`)."; }; - release = mkOption { + release = lib.mkOption { readOnly = true; - type = types.str; - default = trivial.release; + type = lib.types.str; + default = lib.trivial.release; description = "The NixOS release (e.g. `16.03`)."; }; - versionSuffix = mkOption { + versionSuffix = lib.mkOption { internal = true; - type = types.str; - default = trivial.versionSuffix; + type = lib.types.str; + default = lib.trivial.versionSuffix; description = "The NixOS version suffix (e.g. `1160.f2d4ee1`)."; }; - revision = mkOption { + revision = lib.mkOption { internal = true; - type = types.nullOr types.str; - default = trivial.revisionWithDefault null; + type = lib.types.nullOr lib.types.str; + default = lib.trivial.revisionWithDefault null; description = "The Git revision from which this NixOS configuration was built."; }; - codeName = mkOption { + codeName = lib.mkOption { readOnly = true; - type = types.str; - default = trivial.codeName; + type = lib.types.str; + default = lib.trivial.codeName; description = "The NixOS release code name (e.g. `Emu`)."; }; - distroId = mkOption { + distroId = lib.mkOption { internal = true; - type = types.str; + type = lib.types.str; default = "nixos"; description = "The id of the operating system"; }; - distroName = mkOption { + distroName = lib.mkOption { internal = true; - type = types.str; + type = lib.types.str; default = "NixOS"; description = "The name of the operating system"; }; - variant_id = mkOption { - type = types.nullOr (types.strMatching "^[a-z0-9._-]+$"); + variant_id = lib.mkOption { + type = lib.types.nullOr (lib.types.strMatching "^[a-z0-9._-]+$"); default = null; description = "A lower-case string identifying a specific variant or edition of the operating system"; example = "installer"; }; - variantName = mkOption { - type = types.nullOr types.str; + variantName = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; description = "A string identifying a specific variant or edition of the operating system suitable for presentation to the user"; example = "NixOS Installer Image"; }; - vendorId = mkOption { + vendorId = lib.mkOption { internal = true; - type = types.str; + type = lib.types.str; default = "nixos"; description = "The id of the operating system vendor"; }; - vendorName = mkOption { + vendorName = lib.mkOption { internal = true; - type = types.str; + type = lib.types.str; default = "NixOS"; description = "The name of the operating system vendor"; }; - extraOSReleaseArgs = mkOption { + extraOSReleaseArgs = lib.mkOption { internal = true; - type = types.attrsOf types.str; + type = lib.types.attrsOf lib.types.str; default = { }; description = "Additional attributes to be merged with the /etc/os-release generator."; example = { @@ -169,9 +156,9 @@ in }; }; - extraLSBReleaseArgs = mkOption { + extraLSBReleaseArgs = lib.mkOption { internal = true; - type = types.attrsOf types.str; + type = lib.types.attrsOf lib.types.str; default = { }; description = "Additional attributes to be merged with the /etc/lsb-release generator."; example = { @@ -183,7 +170,7 @@ in image = { id = lib.mkOption { - type = types.nullOr types.str; + type = lib.types.nullOr lib.types.str; default = null; description = '' Image identifier. @@ -197,7 +184,7 @@ in }; version = lib.mkOption { - type = types.nullOr types.str; + type = lib.types.nullOr lib.types.str; default = null; description = '' Image version. @@ -212,8 +199,8 @@ in }; - stateVersion = mkOption { - type = types.str; + stateVersion = lib.mkOption { + type = lib.types.str; # TODO Remove this and drop the default of the option so people are forced to set it. # Doing this also means fixing the comment in nixos/modules/testing/test-instrumentation.nix apply = @@ -222,7 +209,7 @@ in "system.stateVersion is not set, defaulting to ${v}. Read why this matters on https://nixos.org/manual/nixos/stable/options.html#opt-system.stateVersion." v; default = cfg.release; - defaultText = literalExpression "config.${opt.release}"; + defaultText = lib.literalExpression "config.${opt.release}"; description = '' This option defines the first version of NixOS you have installed on this particular machine, and is used to maintain compatibility with application data (e.g. databases) created on older NixOS versions. @@ -253,8 +240,8 @@ in ''; }; - configurationRevision = mkOption { - type = types.nullOr types.str; + configurationRevision = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; description = "The Git revision of the top-level flake from which this configuration was built."; }; @@ -266,7 +253,7 @@ in system.nixos = { # These defaults are set here rather than up there so that # changing them would not rebuild the manual - version = mkDefault (cfg.release + cfg.versionSuffix); + version = lib.mkDefault (cfg.release + cfg.versionSuffix); }; # Generate /etc/os-release. See @@ -278,7 +265,7 @@ in LSB_VERSION = "${cfg.release} (${cfg.codeName})"; DISTRIB_ID = "${cfg.distroId}"; DISTRIB_RELEASE = cfg.release; - DISTRIB_CODENAME = toLower cfg.codeName; + DISTRIB_CODENAME = lib.toLower cfg.codeName; DISTRIB_DESCRIPTION = "${cfg.distroName} ${cfg.release} (${cfg.codeName})"; } // cfg.extraLSBReleaseArgs diff --git a/nixos/modules/profiles/clone-config.nix b/nixos/modules/profiles/clone-config.nix index 2c6377e65c883..a3dd72fb351c7 100644 --- a/nixos/modules/profiles/clone-config.nix +++ b/nixos/modules/profiles/clone-config.nix @@ -6,8 +6,6 @@ ... }: -with lib; - let # Location of the repository on the harddrive @@ -19,20 +17,20 @@ let let s = toString path; in - removePrefix nixosPath s != s; + lib.removePrefix nixosPath s != s; # Copy modules given as extra configuration files. Unfortunately, we # cannot serialized attribute set given in the list of modules (that's why # you should use files). moduleFiles = # FIXME: use typeOf (Nix 1.6.1). - filter (x: !isAttrs x && !lib.isFunction x) modules; + lib.filter (x: !lib.isAttrs x && !lib.isFunction x) modules; # Partition module files because between NixOS and non-NixOS files. NixOS # files may change if the repository is updated. partitionedModuleFiles = let - p = partition isNixOSFile moduleFiles; + p = lib.partition isNixOSFile moduleFiles; in { nixos = p.right; @@ -43,7 +41,7 @@ let # device configuration could be rebuild. relocatedModuleFiles = let - relocateNixOS = path: ""; + relocateNixOS = path: ""; in { nixos = map relocateNixOS partitionedModuleFiles.nixos; @@ -72,7 +70,7 @@ in options = { - installer.cloneConfig = mkOption { + installer.cloneConfig = lib.mkOption { default = true; description = '' Try to clone the installation-device configuration by re-using it's @@ -80,7 +78,7 @@ in ''; }; - installer.cloneConfigIncludes = mkOption { + installer.cloneConfigIncludes = lib.mkOption { default = [ ]; example = [ "./nixos/modules/hardware/network/rt73.nix" ]; description = '' @@ -88,7 +86,7 @@ in ''; }; - installer.cloneConfigExtra = mkOption { + installer.cloneConfigExtra = lib.mkOption { default = ""; description = '' Extra text to include in the cloned configuration.nix included in this @@ -105,7 +103,7 @@ in # Provide a mount point for nixos-install. mkdir -p /mnt - ${optionalString config.installer.cloneConfig '' + ${lib.optionalString config.installer.cloneConfig '' # Provide a configuration for the CD/DVD itself, to allow users # to run nixos-rebuild to change the configuration of the # running system on the CD/DVD. diff --git a/nixos/modules/profiles/hardened.nix b/nixos/modules/profiles/hardened.nix index 62a9bb90e747c..0b128e7f81070 100644 --- a/nixos/modules/profiles/hardened.nix +++ b/nixos/modules/profiles/hardened.nix @@ -13,38 +13,36 @@ ... }: -with lib; - { meta = { maintainers = [ - maintainers.joachifm - maintainers.emily + lib.maintainers.joachifm + lib.maintainers.emily ]; }; - boot.kernelPackages = mkDefault pkgs.linuxPackages_hardened; + boot.kernelPackages = lib.mkDefault pkgs.linuxPackages_hardened; - nix.settings.allowed-users = mkDefault [ "@users" ]; + nix.settings.allowed-users = lib.mkDefault [ "@users" ]; - environment.memoryAllocator.provider = mkDefault "scudo"; - environment.variables.SCUDO_OPTIONS = mkDefault "ZeroContents=1"; + environment.memoryAllocator.provider = lib.mkDefault "scudo"; + environment.variables.SCUDO_OPTIONS = lib.mkDefault "ZeroContents=1"; - security.lockKernelModules = mkDefault true; + security.lockKernelModules = lib.mkDefault true; - security.protectKernelImage = mkDefault true; + security.protectKernelImage = lib.mkDefault true; - security.allowSimultaneousMultithreading = mkDefault false; + security.allowSimultaneousMultithreading = lib.mkDefault false; - security.forcePageTableIsolation = mkDefault true; + security.forcePageTableIsolation = lib.mkDefault true; # This is required by podman to run containers in rootless mode. - security.unprivilegedUsernsClone = mkDefault config.virtualisation.containers.enable; + security.unprivilegedUsernsClone = lib.mkDefault config.virtualisation.containers.enable; - security.virtualisation.flushL1DataCache = mkDefault "always"; + security.virtualisation.flushL1DataCache = lib.mkDefault "always"; - security.apparmor.enable = mkDefault true; - security.apparmor.killUnconfinedConfinables = mkDefault true; + security.apparmor.enable = lib.mkDefault true; + security.apparmor.killUnconfinedConfinables = lib.mkDefault true; boot.kernelParams = [ # Don't merge slabs @@ -91,35 +89,35 @@ with lib; ]; # Hide kptrs even for processes with CAP_SYSLOG - boot.kernel.sysctl."kernel.kptr_restrict" = mkOverride 500 2; + boot.kernel.sysctl."kernel.kptr_restrict" = lib.mkOverride 500 2; # Disable bpf() JIT (to eliminate spray attacks) - boot.kernel.sysctl."net.core.bpf_jit_enable" = mkDefault false; + boot.kernel.sysctl."net.core.bpf_jit_enable" = lib.mkDefault false; # Disable ftrace debugging - boot.kernel.sysctl."kernel.ftrace_enabled" = mkDefault false; + boot.kernel.sysctl."kernel.ftrace_enabled" = lib.mkDefault false; # Enable strict reverse path filtering (that is, do not attempt to route # packets that "obviously" do not belong to the iface's network; dropped # packets are logged as martians). - boot.kernel.sysctl."net.ipv4.conf.all.log_martians" = mkDefault true; - boot.kernel.sysctl."net.ipv4.conf.all.rp_filter" = mkDefault "1"; - boot.kernel.sysctl."net.ipv4.conf.default.log_martians" = mkDefault true; - boot.kernel.sysctl."net.ipv4.conf.default.rp_filter" = mkDefault "1"; + boot.kernel.sysctl."net.ipv4.conf.all.log_martians" = lib.mkDefault true; + boot.kernel.sysctl."net.ipv4.conf.all.rp_filter" = lib.mkDefault "1"; + boot.kernel.sysctl."net.ipv4.conf.default.log_martians" = lib.mkDefault true; + boot.kernel.sysctl."net.ipv4.conf.default.rp_filter" = lib.mkDefault "1"; # Ignore broadcast ICMP (mitigate SMURF) - boot.kernel.sysctl."net.ipv4.icmp_echo_ignore_broadcasts" = mkDefault true; + boot.kernel.sysctl."net.ipv4.icmp_echo_ignore_broadcasts" = lib.mkDefault true; # Ignore incoming ICMP redirects (note: default is needed to ensure that the # setting is applied to interfaces added after the sysctls are set) - boot.kernel.sysctl."net.ipv4.conf.all.accept_redirects" = mkDefault false; - boot.kernel.sysctl."net.ipv4.conf.all.secure_redirects" = mkDefault false; - boot.kernel.sysctl."net.ipv4.conf.default.accept_redirects" = mkDefault false; - boot.kernel.sysctl."net.ipv4.conf.default.secure_redirects" = mkDefault false; - boot.kernel.sysctl."net.ipv6.conf.all.accept_redirects" = mkDefault false; - boot.kernel.sysctl."net.ipv6.conf.default.accept_redirects" = mkDefault false; + boot.kernel.sysctl."net.ipv4.conf.all.accept_redirects" = lib.mkDefault false; + boot.kernel.sysctl."net.ipv4.conf.all.secure_redirects" = lib.mkDefault false; + boot.kernel.sysctl."net.ipv4.conf.default.accept_redirects" = lib.mkDefault false; + boot.kernel.sysctl."net.ipv4.conf.default.secure_redirects" = lib.mkDefault false; + boot.kernel.sysctl."net.ipv6.conf.all.accept_redirects" = lib.mkDefault false; + boot.kernel.sysctl."net.ipv6.conf.default.accept_redirects" = lib.mkDefault false; # Ignore outgoing ICMP redirects (this is ipv4 only) - boot.kernel.sysctl."net.ipv4.conf.all.send_redirects" = mkDefault false; - boot.kernel.sysctl."net.ipv4.conf.default.send_redirects" = mkDefault false; + boot.kernel.sysctl."net.ipv4.conf.all.send_redirects" = lib.mkDefault false; + boot.kernel.sysctl."net.ipv4.conf.default.send_redirects" = lib.mkDefault false; } diff --git a/nixos/modules/profiles/headless.nix b/nixos/modules/profiles/headless.nix index d6d754462c14f..26aba8df311de 100644 --- a/nixos/modules/profiles/headless.nix +++ b/nixos/modules/profiles/headless.nix @@ -3,8 +3,6 @@ { lib, ... }: -with lib; - { # Don't start a tty on the serial consoles. systemd.services."serial-getty@ttyS0".enable = lib.mkDefault false; diff --git a/nixos/modules/profiles/installation-device.nix b/nixos/modules/profiles/installation-device.nix index a4e5a4aac7905..42622bb3686ce 100644 --- a/nixos/modules/profiles/installation-device.nix +++ b/nixos/modules/profiles/installation-device.nix @@ -1,8 +1,6 @@ # Provide a basic configuration for installation devices like CDs. { config, pkgs, lib, ... }: -with lib; - { imports = [ # Enable devices which are usually scanned, because we don't know the @@ -23,10 +21,10 @@ with lib; system.nixos.variant_id = lib.mkDefault "installer"; # Enable in installer, even if the minimal profile disables it. - documentation.enable = mkImageMediaOverride true; + documentation.enable = lib.mkImageMediaOverride true; # Show the manual. - documentation.nixos.enable = mkImageMediaOverride true; + documentation.nixos.enable = lib.mkImageMediaOverride true; # Use less privileged nixos user users.users.nixos = { @@ -44,8 +42,8 @@ with lib; # Allow passwordless sudo from nixos user security.sudo = { - enable = mkDefault true; - wheelNeedsPassword = mkImageMediaOverride false; + enable = lib.mkDefault true; + wheelNeedsPassword = lib.mkImageMediaOverride false; }; # Automatically log in at the virtual consoles. @@ -62,7 +60,7 @@ with lib; If you need a wireless connection, type `sudo systemctl start wpa_supplicant` and configure a network using `wpa_cli`. See the NixOS manual for details. - '' + optionalString config.services.xserver.enable '' + '' + lib.optionalString config.services.xserver.enable '' Type `sudo systemctl start display-manager' to start the graphical user interface. @@ -74,14 +72,14 @@ with lib; # installation device for head-less systems i.e. arm boards by manually # mounting the storage in a different system. services.openssh = { - enable = mkDefault true; - settings.PermitRootLogin = mkDefault "yes"; + enable = lib.mkDefault true; + settings.PermitRootLogin = lib.mkDefault "yes"; }; # Enable wpa_supplicant, but don't start it by default. - networking.wireless.enable = mkDefault true; + networking.wireless.enable = lib.mkDefault true; networking.wireless.userControlled.enable = true; - systemd.services.wpa_supplicant.wantedBy = mkOverride 50 []; + systemd.services.wpa_supplicant.wantedBy = lib.mkOverride 50 []; # Tell the Nix evaluator to garbage collect more aggressively. # This is desirable in memory-constrained environments that don't @@ -114,7 +112,7 @@ with lib; # Show all debug messages from the kernel but don't log refused packets # because we have the firewall enabled. This makes installs from the # console less cumbersome if the machine has a public IP. - networking.firewall.logRefusedConnections = mkDefault false; + networking.firewall.logRefusedConnections = lib.mkDefault false; # Prevent installation media from evacuating persistent storage, as their # var directory is not persistent and it would thus result in deletion of diff --git a/nixos/modules/profiles/minimal.nix b/nixos/modules/profiles/minimal.nix index f4b0ea0668a67..e2abae3eb5740 100644 --- a/nixos/modules/profiles/minimal.nix +++ b/nixos/modules/profiles/minimal.nix @@ -10,37 +10,37 @@ let in { documentation = { - enable = mkDefault false; - doc.enable = mkDefault false; - info.enable = mkDefault false; - man.enable = mkDefault false; - nixos.enable = mkDefault false; + enable = lib.mkDefault false; + doc.enable = lib.mkDefault false; + info.enable = lib.mkDefault false; + man.enable = lib.mkDefault false; + nixos.enable = lib.mkDefault false; }; environment = { # Perl is a default package. - defaultPackages = mkDefault [ ]; - stub-ld.enable = mkDefault false; + defaultPackages = lib.mkDefault [ ]; + stub-ld.enable = lib.mkDefault false; }; programs = { # The lessopen package pulls in Perl. - less.lessopen = mkDefault null; - command-not-found.enable = mkDefault false; + less.lessopen = lib.mkDefault null; + command-not-found.enable = lib.mkDefault false; }; # This pulls in nixos-containers which depends on Perl. - boot.enableContainers = mkDefault false; + boot.enableContainers = lib.mkDefault false; services = { - logrotate.enable = mkDefault false; - udisks2.enable = mkDefault false; + logrotate.enable = lib.mkDefault false; + udisks2.enable = lib.mkDefault false; }; xdg = { - autostart.enable = mkDefault false; - icons.enable = mkDefault false; - mime.enable = mkDefault false; - sounds.enable = mkDefault false; + autostart.enable = lib.mkDefault false; + icons.enable = lib.mkDefault false; + mime.enable = lib.mkDefault false; + sounds.enable = lib.mkDefault false; }; } diff --git a/nixos/modules/profiles/nix-builder-vm.nix b/nixos/modules/profiles/nix-builder-vm.nix index fcaca974f302a..244be1a0f23fa 100644 --- a/nixos/modules/profiles/nix-builder-vm.nix +++ b/nixos/modules/profiles/nix-builder-vm.nix @@ -43,49 +43,49 @@ in } ]; - options.virtualisation.darwin-builder = with lib; { - diskSize = mkOption { + options.virtualisation.darwin-builder = { + diskSize = lib.mkOption { default = 20 * 1024; - type = types.int; + type = lib.types.int; example = 30720; description = "The maximum disk space allocated to the runner in MB"; }; - memorySize = mkOption { + memorySize = lib.mkOption { default = 3 * 1024; - type = types.int; + type = lib.types.int; example = 8192; description = "The runner's memory in MB"; }; - min-free = mkOption { + min-free = lib.mkOption { default = 1024 * 1024 * 1024; - type = types.int; + type = lib.types.int; example = 1073741824; description = '' The threshold (in bytes) of free disk space left at which to start garbage collection on the runner ''; }; - max-free = mkOption { + max-free = lib.mkOption { default = 3 * 1024 * 1024 * 1024; - type = types.int; + type = lib.types.int; example = 3221225472; description = '' The threshold (in bytes) of free disk space left at which to stop garbage collection on the runner ''; }; - workingDirectory = mkOption { + workingDirectory = lib.mkOption { default = "."; - type = types.str; + type = lib.types.str; example = "/var/lib/darwin-builder"; description = '' The working directory to use to run the script. When running as part of a flake will need to be set to a non read-only filesystem. ''; }; - hostPort = mkOption { + hostPort = lib.mkOption { default = 31022; - type = types.int; + type = lib.types.int; example = 22; description = '' The localhost host port to forward TCP to the guest port. diff --git a/nixos/modules/programs/bat.nix b/nixos/modules/programs/bat.nix index 5ccc87baf2c46..a8facb40c1461 100644 --- a/nixos/modules/programs/bat.nix +++ b/nixos/modules/programs/bat.nix @@ -6,20 +6,6 @@ }: let inherit (builtins) isList elem; - inherit (lib) - getExe - literalExpression - maintainers - mapAttrs' - mkEnableOption - mkIf - mkOption - mkPackageOption - nameValuePair - optionalString - types - ; - inherit (types) listOf package; cfg = config.programs.bat; @@ -34,20 +20,20 @@ let }: if (shell != "fish") then '' - eval "$(${getExe program} ${toString flags})" + eval "$(${lib.getExe program} ${toString flags})" '' else '' - ${getExe program} ${toString flags} | source + ${lib.getExe program} ${toString flags} | source ''; shellInit = shell: - optionalString (elem pkgs.bat-extras.batpipe cfg.extraPackages) (initScript { + lib.optionalString (elem pkgs.bat-extras.batpipe cfg.extraPackages) (initScript { program = pkgs.bat-extras.batpipe; inherit shell; }) - + optionalString (elem pkgs.bat-extras.batman cfg.extraPackages) (initScript { + + lib.optionalString (elem pkgs.bat-extras.batman cfg.extraPackages) (initScript { program = pkgs.bat-extras.batman; inherit shell; flags = [ "--export-env" ]; @@ -55,13 +41,13 @@ let in { options.programs.bat = { - enable = mkEnableOption "`bat`, a {manpage}`cat(1)` clone with wings"; + enable = lib.mkEnableOption "`bat`, a {manpage}`cat(1)` clone with wings"; - package = mkPackageOption pkgs "bat" { }; + package = lib.mkPackageOption pkgs "bat" { }; - extraPackages = mkOption { + extraPackages = lib.mkOption { default = [ ]; - example = literalExpression '' + example = lib.literalExpression '' with pkgs.bat-extras; [ batdiff batman @@ -71,10 +57,10 @@ in description = '' Extra `bat` scripts to be added to the system configuration. ''; - type = listOf package; + type = lib.types.listOf lib.types.package; }; - settings = mkOption { + settings = lib.mkOption { default = { }; example = { theme = "TwoDark"; @@ -93,13 +79,13 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { environment = { systemPackages = [ cfg.package ] ++ cfg.extraPackages; etc."bat/config".source = generate "bat-config" ( - mapAttrs' ( + lib.mapAttrs' ( name: value: - nameValuePair ("--" + name) ( + lib.nameValuePair ("--" + name) ( if (isList value) then map (str: "\"${str}\"") value else "\"${value}\"" ) ) cfg.settings @@ -107,16 +93,16 @@ in }; programs = { - bash = mkIf (!config.programs.fish.enable) { + bash = lib.mkIf (!config.programs.fish.enable) { interactiveShellInit = shellInit "bash"; }; - fish = mkIf config.programs.fish.enable { + fish = lib.mkIf config.programs.fish.enable { interactiveShellInit = shellInit "fish"; }; - zsh = mkIf (!config.programs.fish.enable && config.programs.zsh.enable) { + zsh = lib.mkIf (!config.programs.fish.enable && config.programs.zsh.enable) { interactiveShellInit = shellInit "zsh"; }; }; }; - meta.maintainers = with maintainers; [ sigmasquadron ]; + meta.maintainers = with lib.maintainers; [ sigmasquadron ]; } diff --git a/nixos/modules/programs/captive-browser.nix b/nixos/modules/programs/captive-browser.nix index 84eff22a4d346..fbc6899a9a9a8 100644 --- a/nixos/modules/programs/captive-browser.nix +++ b/nixos/modules/programs/captive-browser.nix @@ -8,24 +8,11 @@ let cfg = config.programs.captive-browser; - inherit (lib) - concatStringsSep - escapeShellArgs - optionalString - literalExpression - mkEnableOption - mkPackageOption - mkIf - mkOption - mkOptionDefault - types - ; - requiresSetcapWrapper = config.boot.kernelPackages.kernelOlder "5.7" && cfg.bindInterface; browserDefault = chromium: - concatStringsSep " " [ + lib.concatStringsSep " " [ ''env XDG_CONFIG_HOME="$PREV_CONFIG_HOME"'' ''${chromium}/bin/chromium'' ''--user-data-dir=''${XDG_DATA_HOME:-$HOME/.local/share}/chromium-captive'' @@ -52,7 +39,7 @@ let browser = """${cfg.browser}""" dhcp-dns = """${cfg.dhcp-dns}""" socks5-addr = """${cfg.socks5-addr}""" - ${optionalString cfg.bindInterface '' + ${lib.optionalString cfg.bindInterface '' bind-device = """${cfg.interface}""" ''} ''} @@ -64,20 +51,20 @@ in options = { programs.captive-browser = { - enable = mkEnableOption "captive browser, a dedicated Chrome instance to log into captive portals without messing with DNS settings"; + enable = lib.mkEnableOption "captive browser, a dedicated Chrome instance to log into captive portals without messing with DNS settings"; - package = mkPackageOption pkgs "captive-browser" { }; + package = lib.mkPackageOption pkgs "captive-browser" { }; - interface = mkOption { - type = types.str; + interface = lib.mkOption { + type = lib.types.str; description = "your public network interface (wlp3s0, wlan0, eth0, ...)"; }; # the options below are the same as in "captive-browser.toml" - browser = mkOption { - type = types.str; + browser = lib.mkOption { + type = lib.types.str; default = browserDefault pkgs.chromium; - defaultText = literalExpression (browserDefault "\${pkgs.chromium}"); + defaultText = lib.literalExpression (browserDefault "\${pkgs.chromium}"); description = '' The shell (/bin/sh) command executed once the proxy starts. When browser exits, the proxy exits. An extra env var PROXY is available. @@ -92,8 +79,8 @@ in ''; }; - dhcp-dns = mkOption { - type = types.str; + dhcp-dns = lib.mkOption { + type = lib.types.str; description = '' The shell (/bin/sh) command executed to obtain the DHCP DNS server address. The first match of an IPv4 regex is used. @@ -101,15 +88,15 @@ in ''; }; - socks5-addr = mkOption { - type = types.str; + socks5-addr = lib.mkOption { + type = lib.types.str; default = "localhost:1666"; description = "the listen address for the SOCKS5 proxy server"; }; - bindInterface = mkOption { + bindInterface = lib.mkOption { default = true; - type = types.bool; + type = lib.types.bool; description = '' Binds `captive-browser` to the network interface declared in `cfg.interface`. This can be used to avoid collisions @@ -121,7 +108,7 @@ in ###### implementation - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { environment.systemPackages = [ (pkgs.runCommand "captive-browser-desktop-item" { } '' install -Dm444 -t $out/share/applications ${desktopItem}/share/applications/*.desktop @@ -132,9 +119,9 @@ in programs.captive-browser.dhcp-dns = let iface = - prefixes: optionalString cfg.bindInterface (escapeShellArgs (prefixes ++ [ cfg.interface ])); + prefixes: lib.optionalString cfg.bindInterface (lib.escapeShellArgs (prefixes ++ [ cfg.interface ])); in - mkOptionDefault ( + lib.mkOptionDefault ( if config.networking.networkmanager.enable then "${pkgs.networkmanager}/bin/nmcli dev show ${iface [ ]} | ${pkgs.gnugrep}/bin/fgrep IP4.DNS" else if config.networking.dhcpcd.enable then @@ -156,7 +143,7 @@ in source = "${pkgs.busybox}/bin/udhcpc"; }; - security.wrappers.captive-browser = mkIf requiresSetcapWrapper { + security.wrappers.captive-browser = lib.mkIf requiresSetcapWrapper { owner = "root"; group = "root"; capabilities = "cap_net_raw+p"; diff --git a/nixos/modules/programs/dconf.nix b/nixos/modules/programs/dconf.nix index 4eaa61051e788..bc6068ca2d6cf 100644 --- a/nixos/modules/programs/dconf.nix +++ b/nixos/modules/programs/dconf.nix @@ -121,7 +121,7 @@ let type = attrs; default = { }; description = "An attrset used to generate dconf keyfile."; - example = literalExpression '' + example = lib.literalExpression '' with lib.gvariant; { "com/raggesilver/BlackBox" = { @@ -138,7 +138,7 @@ let A list of dconf keys to be lockdown. This doesn't take effect if `lockAll` is set. ''; - example = literalExpression '' + example = lib.literalExpression '' [ "/org/gnome/desktop/background/picture-uri" ] ''; }; diff --git a/nixos/modules/programs/gnupg.nix b/nixos/modules/programs/gnupg.nix index a6fbd081f44a7..7e12351fe8b96 100644 --- a/nixos/modules/programs/gnupg.nix +++ b/nixos/modules/programs/gnupg.nix @@ -6,15 +6,6 @@ }: let - inherit (lib) - mkRemovedOptionModule - mkOption - mkPackageOption - types - mkIf - optionalString - ; - cfg = config.programs.gnupg; agentSettingsFormat = pkgs.formats.keyValue { @@ -23,7 +14,7 @@ let in { imports = [ - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "programs" "gnupg" "agent" @@ -32,18 +23,18 @@ in ]; options.programs.gnupg = { - package = mkPackageOption pkgs "gnupg" { }; + package = lib.mkPackageOption pkgs "gnupg" { }; - agent.enable = mkOption { - type = types.bool; + agent.enable = lib.mkOption { + type = lib.types.bool; default = false; description = '' Enables GnuPG agent with socket-activation for every user session. ''; }; - agent.enableSSHSupport = mkOption { - type = types.bool; + agent.enableSSHSupport = lib.mkOption { + type = lib.types.bool; default = false; description = '' Enable SSH agent support in GnuPG agent. Also sets SSH_AUTH_SOCK @@ -52,24 +43,24 @@ in ''; }; - agent.enableExtraSocket = mkOption { - type = types.bool; + agent.enableExtraSocket = lib.mkOption { + type = lib.types.bool; default = false; description = '' Enable extra socket for GnuPG agent. ''; }; - agent.enableBrowserSocket = mkOption { - type = types.bool; + agent.enableBrowserSocket = lib.mkOption { + type = lib.types.bool; default = false; description = '' Enable browser socket for GnuPG agent. ''; }; - agent.pinentryPackage = mkOption { - type = types.nullOr types.package; + agent.pinentryPackage = lib.mkOption { + type = lib.types.nullOr lib.types.package; example = lib.literalMD "pkgs.pinentry-gnome3"; default = pkgs.pinentry-curses; defaultText = lib.literalMD "matching the configured desktop environment or `pkgs.pinentry-curses`"; @@ -82,7 +73,7 @@ in ''; }; - agent.settings = mkOption { + agent.settings = lib.mkOption { type = agentSettingsFormat.type; default = { }; example = { @@ -94,8 +85,8 @@ in ''; }; - dirmngr.enable = mkOption { - type = types.bool; + dirmngr.enable = lib.mkOption { + type = lib.types.bool; default = false; description = '' Enables GnuPG network certificate management daemon with socket-activation for every user session. @@ -103,8 +94,8 @@ in }; }; - config = mkIf cfg.agent.enable { - programs.gnupg.agent.settings = mkIf (cfg.agent.pinentryPackage != null) { + config = lib.mkIf cfg.agent.enable { + programs.gnupg.agent.settings = lib.mkIf (cfg.agent.pinentryPackage != null) { pinentry-program = lib.getExe cfg.agent.pinentryPackage; }; @@ -138,7 +129,7 @@ in wantedBy = [ "sockets.target" ]; }; - systemd.user.sockets.gpg-agent-ssh = mkIf cfg.agent.enableSSHSupport { + systemd.user.sockets.gpg-agent-ssh = lib.mkIf cfg.agent.enableSSHSupport { unitConfig = { Description = "GnuPG cryptographic agent (ssh-agent emulation)"; Documentation = "man:gpg-agent(1) man:ssh-add(1) man:ssh-agent(1) man:ssh(1)"; @@ -153,7 +144,7 @@ in wantedBy = [ "sockets.target" ]; }; - systemd.user.sockets.gpg-agent-extra = mkIf cfg.agent.enableExtraSocket { + systemd.user.sockets.gpg-agent-extra = lib.mkIf cfg.agent.enableExtraSocket { unitConfig = { Description = "GnuPG cryptographic agent and passphrase cache (restricted)"; Documentation = "man:gpg-agent(1)"; @@ -168,7 +159,7 @@ in wantedBy = [ "sockets.target" ]; }; - systemd.user.sockets.gpg-agent-browser = mkIf cfg.agent.enableBrowserSocket { + systemd.user.sockets.gpg-agent-browser = lib.mkIf cfg.agent.enableBrowserSocket { unitConfig = { Description = "GnuPG cryptographic agent and passphrase cache (access for web browsers)"; Documentation = "man:gpg-agent(1)"; @@ -183,7 +174,7 @@ in wantedBy = [ "sockets.target" ]; }; - systemd.user.services.dirmngr = mkIf cfg.dirmngr.enable { + systemd.user.services.dirmngr = lib.mkIf cfg.dirmngr.enable { unitConfig = { Description = "GnuPG network certificate management daemon"; Documentation = "man:dirmngr(8)"; @@ -195,7 +186,7 @@ in }; }; - systemd.user.sockets.dirmngr = mkIf cfg.dirmngr.enable { + systemd.user.sockets.dirmngr = lib.mkIf cfg.dirmngr.enable { unitConfig = { Description = "GnuPG network certificate management daemon"; Documentation = "man:dirmngr(8)"; @@ -208,7 +199,7 @@ in wantedBy = [ "sockets.target" ]; }; - services.dbus.packages = mkIf (lib.elem "gnome3" (cfg.agent.pinentryPackage.flavors or [ ])) [ + services.dbus.packages = lib.mkIf (lib.elem "gnome3" (cfg.agent.pinentryPackage.flavors or [ ])) [ pkgs.gcr ]; @@ -219,14 +210,14 @@ in export GPG_TTY=$(tty) ''; - programs.ssh.extraConfig = optionalString cfg.agent.enableSSHSupport '' + programs.ssh.extraConfig = lib.optionalString cfg.agent.enableSSHSupport '' # The SSH agent protocol doesn't have support for changing TTYs; however we # can simulate this with the `exec` feature of openssh (see ssh_config(5)) # that hooks a command to the shell currently running the ssh program. Match host * exec "${pkgs.runtimeShell} -c '${cfg.package}/bin/gpg-connect-agent --quiet updatestartuptty /bye >/dev/null 2>&1'" ''; - environment.extraInit = mkIf cfg.agent.enableSSHSupport '' + environment.extraInit = lib.mkIf cfg.agent.enableSSHSupport '' if [ -z "$SSH_AUTH_SOCK" ]; then export SSH_AUTH_SOCK=$(${cfg.package}/bin/gpgconf --list-dirs agent-ssh-socket) fi diff --git a/nixos/modules/programs/iay.nix b/nixos/modules/programs/iay.nix index adc8014fbfa29..c61d29e7728a7 100644 --- a/nixos/modules/programs/iay.nix +++ b/nixos/modules/programs/iay.nix @@ -7,31 +7,23 @@ let cfg = config.programs.iay; - inherit (lib) - mkEnableOption - mkIf - mkOption - mkPackageOption - optionalString - types - ; in { options.programs.iay = { - enable = mkEnableOption "iay, a minimalistic shell prompt"; - package = mkPackageOption pkgs "iay" { }; + enable = lib.mkEnableOption "iay, a minimalistic shell prompt"; + package = lib.mkPackageOption pkgs "iay" { }; - minimalPrompt = mkOption { - type = types.bool; + minimalPrompt = lib.mkOption { + type = lib.types.bool; default = false; description = "Use minimal one-liner prompt."; }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { programs.bash.promptInit = '' if [[ $TERM != "dumb" && (-z $INSIDE_EMACS || $INSIDE_EMACS == "vterm") ]]; then - PS1='$(iay ${optionalString cfg.minimalPrompt "-m"})' + PS1='$(iay ${lib.optionalString cfg.minimalPrompt "-m"})' fi ''; @@ -39,7 +31,7 @@ in if [[ $TERM != "dumb" && (-z $INSIDE_EMACS || $INSIDE_EMACS == "vterm") ]]; then autoload -Uz add-zsh-hook _iay_prompt() { - PROMPT="$(iay -z ${optionalString cfg.minimalPrompt "-m"})" + PROMPT="$(iay -z ${lib.optionalString cfg.minimalPrompt "-m"})" } add-zsh-hook precmd _iay_prompt fi diff --git a/nixos/modules/programs/nix-index.nix b/nixos/modules/programs/nix-index.nix index 21e9eb9e17656..161fbe234e196 100644 --- a/nixos/modules/programs/nix-index.nix +++ b/nixos/modules/programs/nix-index.nix @@ -8,20 +8,20 @@ let cfg = config.programs.nix-index; in { - options.programs.nix-index = with lib; { - enable = mkEnableOption "nix-index, a file database for nixpkgs"; + options.programs.nix-index = { + enable = lib.mkEnableOption "nix-index, a file database for nixpkgs"; - package = mkPackageOption pkgs "nix-index" { }; + package = lib.mkPackageOption pkgs "nix-index" { }; - enableBashIntegration = mkEnableOption "Bash integration" // { + enableBashIntegration = lib.mkEnableOption "Bash integration" // { default = true; }; - enableZshIntegration = mkEnableOption "Zsh integration" // { + enableZshIntegration = lib.mkEnableOption "Zsh integration" // { default = true; }; - enableFishIntegration = mkEnableOption "Fish integration" // { + enableFishIntegration = lib.mkEnableOption "Fish integration" // { default = true; }; }; diff --git a/nixos/modules/programs/nix-required-mounts.nix b/nixos/modules/programs/nix-required-mounts.nix index 5064d6aaf575d..4dde87d9a5644 100644 --- a/nixos/modules/programs/nix-required-mounts.nix +++ b/nixos/modules/programs/nix-required-mounts.nix @@ -10,14 +10,13 @@ let package = pkgs.nix-required-mounts; Mount = - with lib; - types.submodule { - options.host = mkOption { - type = types.str; + lib.types.submodule { + options.host = lib.mkOption { + type = lib.types.str; description = "Host path to mount"; }; - options.guest = mkOption { - type = types.str; + options.guest = lib.mkOption { + type = lib.types.str; description = "Location in the sandbox to mount the host path at"; }; }; @@ -76,7 +75,7 @@ in ''; allowedPatterns = with lib.types; - lib.mkOption rec { + lib.mkOption { type = attrsOf Pattern; description = "The hook config, describing which paths to mount for which system features"; default = { }; diff --git a/nixos/modules/programs/openvpn3.nix b/nixos/modules/programs/openvpn3.nix index 2ab5fbfc90839..d6f7e0f2b214e 100644 --- a/nixos/modules/programs/openvpn3.nix +++ b/nixos/modules/programs/openvpn3.nix @@ -9,37 +9,27 @@ let json = pkgs.formats.json { }; cfg = config.programs.openvpn3; - inherit (lib) - mkEnableOption - mkPackageOption - mkOption - literalExpression - max - options - lists - ; - inherit (lib.types) bool submodule ints; in { options.programs.openvpn3 = { - enable = mkEnableOption "the openvpn3 client"; - package = mkPackageOption pkgs "openvpn3" { }; - netcfg = mkOption { + enable = lib.mkEnableOption "the openvpn3 client"; + package = lib.mkPackageOption pkgs "openvpn3" { }; + netcfg = lib.mkOption { description = "Network configuration"; default = { }; - type = submodule { + type = lib.types.submodule { options = { - settings = mkOption { + settings = lib.mkOption { description = "Options stored in {file}`/etc/openvpn3/netcfg.json` configuration file"; default = { }; - type = submodule { + type = lib.types.submodule { freeformType = json.type; options = { - systemd_resolved = mkOption { - type = bool; + systemd_resolved = lib.mkOption { + type = lib.types.bool; description = "Whether to use systemd-resolved integration"; default = config.services.resolved.enable; - defaultText = literalExpression "config.services.resolved.enable"; + defaultText = lib.literalExpression "config.services.resolved.enable"; example = false; }; }; @@ -48,40 +38,40 @@ in }; }; }; - log-service = mkOption { + log-service = lib.mkOption { description = "Log service configuration"; default = { }; - type = submodule { + type = lib.types.submodule { options = { - settings = mkOption { + settings = lib.mkOption { description = "Options stored in {file}`/etc/openvpn3/log-service.json` configuration file"; default = { }; - type = submodule { + type = lib.types.submodule { freeformType = json.type; options = { - journald = mkOption { + journald = lib.mkOption { description = "Use systemd-journald"; - type = bool; + type = lib.types.bool; default = true; example = false; }; - log_dbus_details = mkOption { + log_dbus_details = lib.mkOption { description = "Add D-Bus details in log file/syslog"; - type = bool; + type = lib.types.bool; default = true; example = false; }; - log_level = mkOption { + log_level = lib.mkOption { description = "How verbose should the logging be"; - type = (ints.between 0 7) // { - merge = _loc: defs: lists.foldl max 0 (options.getValues defs); + type = (lib.types.ints.between 0 7) // { + merge = _loc: defs: lib.lists.foldl lib.max 0 (lib.options.getValues defs); }; default = 3; example = 6; }; - timestamp = mkOption { + timestamp = lib.mkOption { description = "Add timestamp log file"; - type = bool; + type = lib.types.bool; default = false; example = true; }; diff --git a/nixos/modules/programs/pay-respects.nix b/nixos/modules/programs/pay-respects.nix index 83822cdc2c7f7..5e1d5fc6c6d6c 100644 --- a/nixos/modules/programs/pay-respects.nix +++ b/nixos/modules/programs/pay-respects.nix @@ -5,37 +5,27 @@ ... }: let - inherit (lib) - getExe - maintainers - mkEnableOption - mkIf - mkOption - optionalString - types - ; - inherit (types) str; cfg = config.programs.pay-respects; initScript = shell: if (shell != "fish") then '' - eval $(${getExe pkgs.pay-respects} ${shell} --alias ${cfg.alias}) + eval $(${lib.getExe pkgs.pay-respects} ${shell} --alias ${cfg.alias}) '' else '' - ${getExe pkgs.pay-respects} ${shell} --alias ${cfg.alias} | source + ${lib.getExe pkgs.pay-respects} ${shell} --alias ${cfg.alias} | source ''; in { options = { programs.pay-respects = { - enable = mkEnableOption "pay-respects, an app which corrects your previous console command"; + enable = lib.mkEnableOption "pay-respects, an app which corrects your previous console command"; - alias = mkOption { + alias = lib.mkOption { default = "f"; - type = str; + type = lib.types.str; description = '' `pay-respects` needs an alias to be configured. The default value is `f`, but you can use anything else as well. @@ -44,14 +34,14 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { environment.systemPackages = [ pkgs.pay-respects ]; programs = { bash.interactiveShellInit = initScript "bash"; - fish.interactiveShellInit = optionalString config.programs.fish.enable (initScript "fish"); - zsh.interactiveShellInit = optionalString config.programs.zsh.enable (initScript "zsh"); + fish.interactiveShellInit = lib.optionalString config.programs.fish.enable (initScript "fish"); + zsh.interactiveShellInit = lib.optionalString config.programs.zsh.enable (initScript "zsh"); }; }; - meta.maintainers = with maintainers; [ sigmasquadron ]; + meta.maintainers = with lib.maintainers; [ sigmasquadron ]; } diff --git a/nixos/modules/programs/rust-motd.nix b/nixos/modules/programs/rust-motd.nix index ba080aa037e06..ef2530740011c 100644 --- a/nixos/modules/programs/rust-motd.nix +++ b/nixos/modules/programs/rust-motd.nix @@ -153,7 +153,7 @@ in security.pam.services.sshd.text = lib.mkIf cfg.enableMotdInSSHD ( lib.mkDefault ( lib.mkAfter '' - session optional ${pkgs.pam}/lib/security/pam_motd.so motd=/var/lib/rust-motd/motd + session lib.optional ${pkgs.pam}/lib/security/pam_motd.so motd=/var/lib/rust-motd/motd '' ) ); diff --git a/nixos/modules/programs/ryzen-monitor-ng.nix b/nixos/modules/programs/ryzen-monitor-ng.nix index 8d9e75928404e..4df63ebca4b5a 100644 --- a/nixos/modules/programs/ryzen-monitor-ng.nix +++ b/nixos/modules/programs/ryzen-monitor-ng.nix @@ -11,7 +11,7 @@ in { options = { programs.ryzen-monitor-ng = { - enable = mkEnableOption '' + enable = lib.mkEnableOption '' ryzen_monitor_ng, a userspace application for setting and getting Ryzen SMU (System Management Unit) parameters via the ryzen_smu kernel driver. Monitor power information of Ryzen processors via the PM table of the SMU. @@ -23,11 +23,11 @@ in WARNING: Damage cause by use of your AMD processor outside of official AMD specifications or outside of factory settings are not covered under any AMD product warranty and may not be covered by your board or system manufacturer's warranty ''; - package = mkPackageOption pkgs "ryzen-monitor-ng" { }; + package = lib.mkPackageOption pkgs "ryzen-monitor-ng" { }; }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { environment.systemPackages = [ cfg.package ]; hardware.cpu.amd.ryzen-smu.enable = true; }; diff --git a/nixos/modules/programs/skim.nix b/nixos/modules/programs/skim.nix index 67d7396d03441..d4a106ef873a1 100644 --- a/nixos/modules/programs/skim.nix +++ b/nixos/modules/programs/skim.nix @@ -5,43 +5,37 @@ ... }: let - inherit (lib) - mkEnableOption - mkPackageOption - optional - optionalString - ; cfg = config.programs.skim; in { options = { programs.skim = { - fuzzyCompletion = mkEnableOption "fuzzy completion with skim"; - keybindings = mkEnableOption "skim keybindings"; - package = mkPackageOption pkgs "skim" { }; + fuzzyCompletion = lib.mkEnableOption "fuzzy completion with skim"; + keybindings = lib.mkEnableOption "skim keybindings"; + package = lib.mkPackageOption pkgs "skim" { }; }; }; config = { - environment.systemPackages = optional (cfg.keybindings || cfg.fuzzyCompletion) cfg.package; + environment.systemPackages = lib.optional (cfg.keybindings || cfg.fuzzyCompletion) cfg.package; programs.bash.interactiveShellInit = - optionalString cfg.fuzzyCompletion '' + lib.optionalString cfg.fuzzyCompletion '' source ${cfg.package}/share/skim/completion.bash '' - + optionalString cfg.keybindings '' + + lib.optionalString cfg.keybindings '' source ${cfg.package}/share/skim/key-bindings.bash ''; programs.zsh.interactiveShellInit = - optionalString cfg.fuzzyCompletion '' + lib.optionalString cfg.fuzzyCompletion '' source ${cfg.package}/share/skim/completion.zsh '' - + optionalString cfg.keybindings '' + + lib.optionalString cfg.keybindings '' source ${cfg.package}/share/skim/key-bindings.zsh ''; - programs.fish.interactiveShellInit = optionalString cfg.keybindings '' + programs.fish.interactiveShellInit = lib.optionalString cfg.keybindings '' source ${cfg.package}/share/skim/key-bindings.fish && skim_key_bindings ''; }; diff --git a/nixos/modules/programs/tmux.nix b/nixos/modules/programs/tmux.nix index fe7a2789f71b8..14d85ec75c29c 100644 --- a/nixos/modules/programs/tmux.nix +++ b/nixos/modules/programs/tmux.nix @@ -6,13 +6,6 @@ }: let - inherit (lib) - mkOption - mkIf - types - optionalString - ; - cfg = config.programs.tmux; defaultKeyMode = "emacs"; @@ -28,9 +21,9 @@ let setw -g pane-base-index ${toString cfg.baseIndex} set -g history-limit ${toString cfg.historyLimit} - ${optionalString cfg.newSession "new-session"} + ${lib.optionalString cfg.newSession "new-session"} - ${optionalString cfg.reverseSplit '' + ${lib.optionalString cfg.reverseSplit '' bind v split-window -h bind s split-window -v ''} @@ -38,7 +31,7 @@ let set -g status-keys ${cfg.keyMode} set -g mode-keys ${cfg.keyMode} - ${optionalString (cfg.keyMode == "vi" && cfg.customPaneNavigationAndResize) '' + ${lib.optionalString (cfg.keyMode == "vi" && cfg.customPaneNavigationAndResize) '' bind h select-pane -L bind j select-pane -D bind k select-pane -U @@ -50,7 +43,7 @@ let bind -r L resize-pane -R ${toString cfg.resizeAmount} ''} - ${optionalString (cfg.shortcut != defaultShortcut) '' + ${lib.optionalString (cfg.shortcut != defaultShortcut) '' # rebind main key: C-${cfg.shortcut} unbind C-${defaultShortcut} set -g prefix C-${cfg.shortcut} @@ -80,147 +73,147 @@ in options = { programs.tmux = { - enable = mkOption { - type = types.bool; + enable = lib.mkOption { + type = lib.types.bool; default = false; description = "Whenever to configure {command}`tmux` system-wide."; relatedPackages = [ "tmux" ]; }; - aggressiveResize = mkOption { + aggressiveResize = lib.mkOption { default = false; - type = types.bool; + type = lib.types.bool; description = '' Resize the window to the size of the smallest session for which it is the current window. ''; }; - baseIndex = mkOption { + baseIndex = lib.mkOption { default = 0; example = 1; - type = types.int; + type = lib.types.int; description = "Base index for windows and panes."; }; - clock24 = mkOption { + clock24 = lib.mkOption { default = false; - type = types.bool; + type = lib.types.bool; description = "Use 24 hour clock."; }; - customPaneNavigationAndResize = mkOption { + customPaneNavigationAndResize = lib.mkOption { default = false; - type = types.bool; + type = lib.types.bool; description = "Override the hjkl and HJKL bindings for pane navigation and resizing in VI mode."; }; - escapeTime = mkOption { + escapeTime = lib.mkOption { default = 500; example = 0; - type = types.int; + type = lib.types.int; description = "Time in milliseconds for which tmux waits after an escape is input."; }; - extraConfigBeforePlugins = mkOption { + extraConfigBeforePlugins = lib.mkOption { default = ""; description = '' Additional contents of /etc/tmux.conf, to be run before sourcing plugins. ''; - type = types.lines; + type = lib.types.lines; }; - extraConfig = mkOption { + extraConfig = lib.mkOption { default = ""; description = '' Additional contents of /etc/tmux.conf, to be run after sourcing plugins. ''; - type = types.lines; + type = lib.types.lines; }; - historyLimit = mkOption { + historyLimit = lib.mkOption { default = 2000; example = 5000; - type = types.int; + type = lib.types.int; description = "Maximum number of lines held in window history."; }; - keyMode = mkOption { + keyMode = lib.mkOption { default = defaultKeyMode; example = "vi"; - type = types.enum [ + type = lib.types.enum [ "emacs" "vi" ]; description = "VI or Emacs style shortcuts."; }; - newSession = mkOption { + newSession = lib.mkOption { default = false; - type = types.bool; + type = lib.types.bool; description = "Automatically spawn a session if trying to attach and none are running."; }; - reverseSplit = mkOption { + reverseSplit = lib.mkOption { default = false; - type = types.bool; + type = lib.types.bool; description = "Reverse the window split shortcuts."; }; - resizeAmount = mkOption { + resizeAmount = lib.mkOption { default = defaultResize; example = 10; - type = types.int; + type = lib.types.int; description = "Number of lines/columns when resizing."; }; - shortcut = mkOption { + shortcut = lib.mkOption { default = defaultShortcut; example = "a"; - type = types.str; + type = lib.types.str; description = "Ctrl following by this key is used as the main shortcut."; }; - terminal = mkOption { + terminal = lib.mkOption { default = defaultTerminal; example = "screen-256color"; - type = types.str; + type = lib.types.str; description = '' Set the $TERM variable. Use tmux-direct if italics or 24bit true color support is needed. ''; }; - secureSocket = mkOption { + secureSocket = lib.mkOption { default = true; - type = types.bool; + type = lib.types.bool; description = '' Store tmux socket under /run, which is more secure than /tmp, but as a downside it doesn't survive user logout. ''; }; - plugins = mkOption { + plugins = lib.mkOption { default = [ ]; - type = types.listOf types.package; + type = lib.types.listOf lib.types.package; description = "List of plugins to install."; example = lib.literalExpression "[ pkgs.tmuxPlugins.nord ]"; }; - withUtempter = mkOption { + withUtempter = lib.mkOption { description = '' Whether to enable libutempter for tmux. This is required so that tmux can write to /var/run/utmp (which can be queried with `who` to display currently connected user sessions). Note, this will add a guid wrapper for the group utmp! ''; default = true; - type = types.bool; + type = lib.types.bool; }; }; }; ###### implementation - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { environment = { etc."tmux.conf".text = tmuxConf; @@ -230,7 +223,7 @@ in TMUX_TMPDIR = lib.optional cfg.secureSocket ''''${XDG_RUNTIME_DIR:-"/run/user/$(id -u)"}''; }; }; - security.wrappers = mkIf cfg.withUtempter { + security.wrappers = lib.mkIf cfg.withUtempter { utempter = { source = "${pkgs.libutempter}/lib/utempter/utempter"; owner = "root"; diff --git a/nixos/modules/programs/tsm-client.nix b/nixos/modules/programs/tsm-client.nix index abbcfa9055eb4..5a8ff3bf36894 100644 --- a/nixos/modules/programs/tsm-client.nix +++ b/nixos/modules/programs/tsm-client.nix @@ -10,73 +10,29 @@ let in let - - inherit (lib.attrsets) - attrNames - attrValues - mapAttrsToList - removeAttrs - ; - inherit (lib.lists) - all - allUnique - concatLists - concatMap - elem - isList - map - ; - inherit (lib.modules) mkDefault mkIf; - inherit (lib.options) mkEnableOption mkOption mkPackageOption; - inherit (lib.strings) - concatLines - match - optionalString - toLower - ; - inherit (lib.trivial) isInt; - inherit (lib.types) - addCheck - attrsOf - coercedTo - either - enum - int - lines - listOf - nonEmptyStr - nullOr - oneOf - path - port - singleLineStr - strMatching - submodule - ; - scalarType = # see the option's description below for the # handling/transformation of each possible type - oneOf [ - (enum [ + lib.types.oneOf [ + (lib.types.enum [ true null ]) - int - path - singleLineStr + lib.types.int + lib.types.path + lib.types.singleLineStr ]; # TSM rejects servername strings longer than 64 chars. - servernameType = strMatching "[^[:space:]]{1,64}"; + servernameType = lib.strMatching "[^[:space:]]{1,64}"; serverOptions = { name, config, ... }: { - freeformType = attrsOf (either scalarType (listOf scalarType)); + freeformType = lib.attrsOf (lib.either scalarType (lib.listOf scalarType)); # Client system-options file directives are explained here: # https://www.ibm.com/docs/en/storage-protect/8.1.25?topic=commands-processing-options - options.servername = mkOption { + options.servername = lib.mkOption { type = servernameType; default = name; example = "mainTsmServer"; @@ -85,29 +41,29 @@ let must not contain space or more than 64 chars. ''; }; - options.tcpserveraddress = mkOption { - type = nonEmptyStr; + options.tcpserveraddress = lib.mkOption { + type = lib.types.nonEmptyStr; example = "tsmserver.company.com"; description = '' Host/domain name or IP address of the IBM TSM server. ''; }; - options.tcpport = mkOption { - type = addCheck port (p: p <= 32767); + options.tcpport = lib.mkOption { + type = lib.types.addCheck lib.types.port (p: p <= 32767); default = 1500; # official default description = '' TCP port of the IBM TSM server. TSM does not support ports above 32767. ''; }; - options.nodename = mkOption { - type = nonEmptyStr; + options.nodename = lib.mkOption { + type = lib.types.nonEmptyStr; example = "MY-TSM-NODE"; description = '' Target node name on the IBM TSM server. ''; }; - options.genPasswd = mkEnableOption '' + options.genPasswd = lib.mkEnableOption '' automatic client password generation. This option does *not* cause a line in {file}`dsm.sys` by itself, but generates a @@ -119,15 +75,15 @@ let to renew the password (e.g. on first connection), a random password will be generated and stored ''; - options.passwordaccess = mkOption { - type = enum [ + options.passwordaccess = lib.mkOption { + type = lib.types.enum [ "generate" "prompt" ]; visible = false; }; - options.passworddir = mkOption { - type = nullOr path; + options.passworddir = lib.mkOption { + type = lib.types.nullOr lib.types.path; default = null; example = "/home/alice/tsm-password"; description = '' @@ -135,8 +91,8 @@ let node's password information. ''; }; - options.inclexcl = mkOption { - type = coercedTo lines (pkgs.writeText "inclexcl.dsm.sys") (nullOr path); + options.inclexcl = lib.mkOption { + type = lib.types.coercedTo lib.types.lines (pkgs.writeText "inclexcl.dsm.sys") (lib.types.nullOr lib.types.path); default = null; example = '' exclude.dir /nix/store @@ -148,39 +104,36 @@ let or an absolute path pointing to a file with such lines. ''; }; - config.commmethod = mkDefault "v6tcpip"; # uses v4 or v6, based on dns lookup result + config.commmethod = lib.mkDefault "v6tcpip"; # uses v4 or v6, based on dns lookup result config.passwordaccess = if config.genPasswd then "generate" else "prompt"; # XXX migration code for freeform settings, these can be removed in 2025: options.warnings = optionsGlobal.warnings; options.assertions = optionsGlobal.assertions; imports = - let - inherit (lib.modules) mkRemovedOptionModule mkRenamedOptionModule; - in [ - (mkRemovedOptionModule [ "extraConfig" ] + (lib.mkRemovedOptionModule [ "extraConfig" ] "Please just add options directly to the server attribute set, cf. the description of `programs.tsmClient.servers`." ) - (mkRemovedOptionModule [ "text" ] + (lib.mkRemovedOptionModule [ "text" ] "Please just add options directly to the server attribute set, cf. the description of `programs.tsmClient.servers`." ) - (mkRenamedOptionModule [ "name" ] [ "servername" ]) - (mkRenamedOptionModule [ "server" ] [ "tcpserveraddress" ]) - (mkRenamedOptionModule [ "port" ] [ "tcpport" ]) - (mkRenamedOptionModule [ "node" ] [ "nodename" ]) - (mkRenamedOptionModule [ "passwdDir" ] [ "passworddir" ]) - (mkRenamedOptionModule [ "includeExclude" ] [ "inclexcl" ]) + (lib.mkRenamedOptionModule [ "name" ] [ "servername" ]) + (lib.mkRenamedOptionModule [ "server" ] [ "tcpserveraddress" ]) + (lib.mkRenamedOptionModule [ "port" ] [ "tcpport" ]) + (lib.mkRenamedOptionModule [ "node" ] [ "nodename" ]) + (lib.mkRenamedOptionModule [ "passwdDir" ] [ "passworddir" ]) + (lib.mkRenamedOptionModule [ "includeExclude" ] [ "inclexcl" ]) ]; }; options.programs.tsmClient = { - enable = mkEnableOption '' + enable = lib.mkEnableOption '' IBM Storage Protect (Tivoli Storage Manager, TSM) client command line applications with a client system-options file "dsm.sys" ''; - servers = mkOption { - type = attrsOf (submodule serverOptions); + servers = lib.mkOption { + type = lib.types.attrsOf (lib.types.submodule serverOptions); default = { }; example.mainTsmServer = { tcpserveraddress = "tsmserver.company.com"; @@ -203,8 +156,8 @@ let each value, according to the rules above. ''; }; - defaultServername = mkOption { - type = nullOr servernameType; + defaultServername = lib.mkOption { + type = lib.types.nullOr servernameType; default = null; example = "mainTsmServer"; description = '' @@ -217,8 +170,8 @@ let `defaultserver` configuration line. ''; }; - dsmSysText = mkOption { - type = lines; + dsmSysText = lib.mkOption { + type = lib.types.lines; readOnly = true; description = '' This configuration key contains the effective text @@ -228,7 +181,7 @@ let TSM-depending packages used on the system. ''; }; - package = mkPackageOption pkgs "tsm-client" { + package = lib.mkPackageOption pkgs "tsm-client" { example = "tsm-client-withGui"; extraDescription = '' It will be used with `.override` @@ -236,7 +189,7 @@ let ''; }; wrappedPackage = - mkPackageOption pkgs "tsm-client" { + lib.mkPackageOption pkgs "tsm-client" { default = null; extraDescription = '' This option is to provide the effective derivation, @@ -252,12 +205,12 @@ let }; cfg = config.programs.tsmClient; - servernames = map (s: s.servername) (attrValues cfg.servers); + servernames = map (s: s.servername) (lib.attrValues cfg.servers); assertions = [ { - assertion = allUnique (map toLower servernames); + assertion = lib.allUnique (map lib.toLower servernames); message = '' TSM server names (option `programs.tsmClient.servers`) @@ -266,7 +219,7 @@ let ''; } { - assertion = (cfg.defaultServername != null) -> (elem cfg.defaultServername servernames); + assertion = (cfg.defaultServername != null) -> (lib.elem cfg.defaultServername servernames); message = '' TSM default server name `programs.tsmClient.defaultServername="${cfg.defaultServername}"` @@ -275,16 +228,16 @@ let ''; } ] - ++ (mapAttrsToList (name: serverCfg: { - assertion = all (key: null != match "[^[:space:]]+" key) (attrNames serverCfg); + ++ (lib.mapAttrsToList (name: serverCfg: { + assertion = lib.all (key: null != lib.match "[^[:space:]]+" key) (lib.attrNames serverCfg); message = '' TSM server setting names in `programs.tsmClient.servers.${name}.*` contain spaces, but that's not allowed. ''; }) cfg.servers) - ++ (mapAttrsToList (name: serverCfg: { - assertion = allUnique (map toLower (attrNames serverCfg)); + ++ (lib.mapAttrsToList (name: serverCfg: { + assertion = lib.allUnique (map lib.toLower (lib.attrNames serverCfg)); message = '' TSM server setting names in `programs.tsmClient.servers.${name}.*` @@ -307,8 +260,8 @@ let # Turn a key-value pair from the server options attrset # into zero (value==null), one (scalar value) or # more (value is list) configuration stanza lines. - if isList value then - concatMap (makeDsmSysLines key) value + if lib.isList value then + lib.concatMap (makeDsmSysLines key) value # recurse into list else if value == null then [ ] @@ -320,12 +273,12 @@ let if value == true then "" # just output key if value is `true` - else if isInt value then + else if lib.isInt value then " ${builtins.toString value}" - else if path.check value then + else if lib.path.check value then " \"${value}\"" # enclose path in ".." - else if singleLineStr.check value then + else if lib.singleLineStr.check value then " ${value}" else throw "assertion failed: cannot convert type" # should never happen @@ -355,7 +308,7 @@ let in '' servername ${servername} - ${concatLines (concatLists (mapAttrsToList makeDsmSysLines attrs))} + ${lib.concatLines (lib.concatLists (lib.mapAttrsToList makeDsmSysLines attrs))} ''; dsmSysText = '' @@ -364,16 +317,16 @@ let **** Do not edit! **** This file is generated by NixOS configuration. - ${optionalString (cfg.defaultServername != null) "defaultserver ${cfg.defaultServername}"} + ${lib.optionalString (cfg.defaultServername != null) "defaultserver ${cfg.defaultServername}"} - ${concatLines (map makeDsmSysStanza (attrValues cfg.servers))} + ${lib.concatLines (map makeDsmSysStanza (lib.attrValues cfg.servers))} ''; # XXX migration code for freeform settings, this can be removed in 2025: enrichMigrationInfos = what: how: - concatLists ( - mapAttrsToList ( + lib.concatLists ( + lib.mapAttrsToList ( name: serverCfg: map (how (text: "In `programs.tsmClient.servers.${name}`: ${text}")) serverCfg."${what}" ) cfg.servers @@ -385,7 +338,7 @@ in inherit options; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { inherit assertions; programs.tsmClient.dsmSysText = dsmSysText; programs.tsmClient.wrappedPackage = cfg.package.override rec { diff --git a/nixos/modules/programs/wayland/lib.nix b/nixos/modules/programs/wayland/lib.nix index bc639dc6d0e0c..dcd3639551709 100644 --- a/nixos/modules/programs/wayland/lib.nix +++ b/nixos/modules/programs/wayland/lib.nix @@ -4,10 +4,9 @@ genFinalPackage = pkg: args: let - expectedArgs = with lib; lib.naturalSort (lib.attrNames args); + expectedArgs = lib.naturalSort (lib.attrNames args); existingArgs = - with lib; - naturalSort (intersectLists expectedArgs (attrNames (functionArgs pkg.override))); + lib.naturalSort (lib.intersectLists expectedArgs (lib.attrNames (lib.functionArgs pkg.override))); in if existingArgs != expectedArgs then pkg else pkg.override args; } diff --git a/nixos/modules/programs/xwayland.nix b/nixos/modules/programs/xwayland.nix index 6d00d6fe27edd..d018fc07b930e 100644 --- a/nixos/modules/programs/xwayland.nix +++ b/nixos/modules/programs/xwayland.nix @@ -19,7 +19,7 @@ in type = lib.types.str; default = lib.optionalString config.fonts.fontDir.enable "/run/current-system/sw/share/X11/fonts"; defaultText = lib.literalExpression '' - optionalString config.fonts.fontDir.enable "/run/current-system/sw/share/X11/fonts" + lib.optionalString config.fonts.fontDir.enable "/run/current-system/sw/share/X11/fonts" ''; description = '' Default font path. Setting this option causes Xwayland to be rebuilt. diff --git a/nixos/modules/programs/yubikey-touch-detector.nix b/nixos/modules/programs/yubikey-touch-detector.nix index 2986c13443279..82c76f343210c 100644 --- a/nixos/modules/programs/yubikey-touch-detector.nix +++ b/nixos/modules/programs/yubikey-touch-detector.nix @@ -17,7 +17,7 @@ in libnotify = lib.mkOption { # This used to be true previously and using libnotify would be a sane default. default = true; - type = types.bool; + type = lib.types.bool; description = '' If set to true, yubikey-touch-detctor will send notifications using libnotify ''; @@ -25,7 +25,7 @@ in unixSocket = lib.mkOption { default = true; - type = types.bool; + type = lib.types.bool; description = '' If set to true, yubikey-touch-detector will send notifications to a unix socket ''; @@ -33,7 +33,7 @@ in verbose = lib.mkOption { default = false; - type = types.bool; + type = lib.types.bool; description = '' Enables verbose logging ''; diff --git a/nixos/modules/rename.nix b/nixos/modules/rename.nix index d175a6954c6e3..5600d4d5a997b 100644 --- a/nixos/modules/rename.nix +++ b/nixos/modules/rename.nix @@ -21,278 +21,278 @@ in (mkAliasOptionModuleMD [ "environment" "checkConfigurationOptions" ] [ "_module" "check" ]) # Completely removed modules - (mkRemovedOptionModule [ "boot" "loader" "raspberryPi" ] + (lib.mkRemovedOptionModule [ "boot" "loader" "raspberryPi" ] "The raspberryPi boot loader has been removed. See https://github.com/NixOS/nixpkgs/pull/241534 for what to use instead." ) - (mkRemovedOptionModule [ "environment" "blcr" "enable" ] "The BLCR module has been removed") - (mkRemovedOptionModule [ "environment" "noXlibs" ] '' + (lib.mkRemovedOptionModule [ "environment" "blcr" "enable" ] "The BLCR module has been removed") + (lib.mkRemovedOptionModule [ "environment" "noXlibs" ] '' The environment.noXlibs option was removed, as it often caused surprising breakages for new users. If you need its functionality, you can apply similar overlays in your own config. '') - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "fonts" "fontconfig" "penultimate" ] "The corresponding package has removed from nixpkgs.") - (mkRemovedOptionModule [ "hardware" "brightnessctl" ] '' + (lib.mkRemovedOptionModule [ "hardware" "brightnessctl" ] '' The brightnessctl module was removed because newer versions of brightnessctl don't require the udev rules anymore (they can use the systemd-logind API). Instead of using the module you can now simply add the brightnessctl package to environment.systemPackages. '') - (mkRemovedOptionModule [ "hardware" "gkraken" "enable" ] '' + (lib.mkRemovedOptionModule [ "hardware" "gkraken" "enable" ] '' gkraken was deprecated by coolercontrol and thus removed from nixpkgs. Consider using programs.coolercontrol instead. '') - (mkRemovedOptionModule [ "hardware" "u2f" ] '' + (lib.mkRemovedOptionModule [ "hardware" "u2f" ] '' The U2F modules module was removed, as all it did was adding the udev rules from libu2f-host to the system. Udev gained native support to handle FIDO security tokens, so this isn't necessary anymore. '') - (mkRemovedOptionModule [ "hardware" "xow" ] '' + (lib.mkRemovedOptionModule [ "hardware" "xow" ] '' The xow package was removed from nixpkgs. Upstream has deprecated the project and users are urged to switch to xone. '') - (mkRemovedOptionModule [ "networking" "vpnc" ] "Use environment.etc.\"vpnc/service.conf\" instead.") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "networking" "vpnc" ] "Use environment.etc.\"vpnc/service.conf\" instead.") + (lib.mkRemovedOptionModule [ "networking" "wicd" ] "The corresponding package was removed from nixpkgs.") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "programs" "gnome-documents" ] "The corresponding package was removed from nixpkgs.") - (mkRemovedOptionModule [ "programs" "pantheon-tweaks" ] '' + (lib.mkRemovedOptionModule [ "programs" "pantheon-tweaks" ] '' pantheon-tweaks is no longer a switchboard plugin but an independent app, adding the package to environment.systemPackages is sufficient. '') - (mkRemovedOptionModule [ "programs" "tilp2" ] "The corresponding package was removed from nixpkgs.") - (mkRemovedOptionModule [ "programs" "way-cooler" ] ( + (lib.mkRemovedOptionModule [ "programs" "tilp2" ] "The corresponding package was removed from nixpkgs.") + (lib.mkRemovedOptionModule [ "programs" "way-cooler" ] ( "way-cooler is abandoned by its author: " + "https://way-cooler.org/blog/2020/01/09/way-cooler-post-mortem.html" )) - (mkRemovedOptionModule [ "security" "hideProcessInformation" ] '' + (lib.mkRemovedOptionModule [ "security" "hideProcessInformation" ] '' The hidepid module was removed, since the underlying machinery is broken when using cgroups-v2. '') - (mkRemovedOptionModule [ "services" "antennas" ] + (lib.mkRemovedOptionModule [ "services" "antennas" ] "The antennas package and the corresponding module have been removed as they only work with tvheadend, which nobody was willing to maintain and was stuck on an unmaintained version that required FFmpeg 4; please see https://github.com/NixOS/nixpkgs/pull/332259 if you are interested in maintaining a newer version." ) - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "anbox" ] "The corresponding package was removed from nixpkgs as it is not maintained upstream anymore.") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "ankisyncd" ] "`services.ankisyncd` has been replaced by `services.anki-sync-server`.") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "baget" "enable" ] "The baget module was removed due to the upstream package being unmaintained.") - (mkRemovedOptionModule [ "services" "beegfs" ] "The BeeGFS module has been removed") - (mkRemovedOptionModule [ "services" "beegfsEnable" ] "The BeeGFS module has been removed") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "beegfs" ] "The BeeGFS module has been removed") + (lib.mkRemovedOptionModule [ "services" "beegfsEnable" ] "The BeeGFS module has been removed") + (lib.mkRemovedOptionModule [ "services" "cgmanager" "enable" ] "cgmanager was deprecated by lxc and therefore removed from nixpkgs.") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "chronos" ] "The corresponding package was removed from nixpkgs.") - (mkRemovedOptionModule [ "services" "confluence" ] + (lib.mkRemovedOptionModule [ "services" "confluence" ] "Atlassian software has been removed, as support for the Atlassian Server products ended in February 2024 and there was insufficient interest in maintaining the Atlassian Data Center replacements" ) - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "couchpotato" ] "The corresponding package was removed from nixpkgs.") - (mkRemovedOptionModule [ "services" "crowd" ] + (lib.mkRemovedOptionModule [ "services" "crowd" ] "Atlassian software has been removed, as support for the Atlassian Server products ended in February 2024 and there was insufficient interest in maintaining the Atlassian Data Center replacements" ) - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "dd-agent" ] "dd-agent was removed from nixpkgs in favor of the newer datadog-agent.") - (mkRemovedOptionModule [ "services" "dnscrypt-proxy" ] "Use services.dnscrypt-proxy2 instead") - (mkRemovedOptionModule [ "services" "dnscrypt-wrapper" ] '' + (lib.mkRemovedOptionModule [ "services" "dnscrypt-proxy" ] "Use services.dnscrypt-proxy2 instead") + (lib.mkRemovedOptionModule [ "services" "dnscrypt-wrapper" ] '' The dnscrypt-wrapper module was removed since the project has been effectively unmaintained since 2018; moreover the NixOS module had to rely on an abandoned version of dnscrypt-proxy v1 for the rotation of keys. To wrap a resolver with DNSCrypt you can instead use dnsdist. See options `services.dnsdist.dnscrypt.*` '') - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "exhibitor" ] "The corresponding package was removed from nixpkgs.") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "firefox" "syncserver" ] "The corresponding package was removed from nixpkgs.") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "flashpolicyd" ] "The flashpolicyd module has been removed. Adobe Flash Player is deprecated.") - (mkRemovedOptionModule [ "services" "fourStore" ] "The fourStore module has been removed") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "fourStore" ] "The fourStore module has been removed") + (lib.mkRemovedOptionModule [ "services" "fourStoreEndpoint" ] "The fourStoreEndpoint module has been removed") - (mkRemovedOptionModule [ "services" "fprot" ] "The corresponding package was removed from nixpkgs.") - (mkRemovedOptionModule [ "services" "frab" ] "The frab module has been removed") - (mkRemovedOptionModule [ "services" "homeassistant-satellite" ] + (lib.mkRemovedOptionModule [ "services" "fprot" ] "The corresponding package was removed from nixpkgs.") + (lib.mkRemovedOptionModule [ "services" "frab" ] "The frab module has been removed") + (lib.mkRemovedOptionModule [ "services" "homeassistant-satellite" ] "The `services.homeassistant-satellite` module has been replaced by `services.wyoming-satellite`." ) - (mkRemovedOptionModule [ "services" "hydron" ] + (lib.mkRemovedOptionModule [ "services" "hydron" ] "The `services.hydron` module has been removed as the project has been archived upstream since 2022 and is affected by a severe remote code execution vulnerability." ) - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "ihatemoney" ] "The ihatemoney module has been removed for lack of downstream maintainer") - (mkRemovedOptionModule [ "services" "jira" ] + (lib.mkRemovedOptionModule [ "services" "jira" ] "Atlassian software has been removed, as support for the Atlassian Server products ended in February 2024 and there was insufficient interest in maintaining the Atlassian Data Center replacements" ) - (mkRemovedOptionModule [ "services" "kippo" ] "The corresponding package was removed from nixpkgs.") - (mkRemovedOptionModule [ "services" "lshd" ] + (lib.mkRemovedOptionModule [ "services" "kippo" ] "The corresponding package was removed from nixpkgs.") + (lib.mkRemovedOptionModule [ "services" "lshd" ] "The corresponding package was removed from nixpkgs as it had no maintainer in Nixpkgs and hasn't seen an upstream release in over a decades." ) - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "mailpile" ] "The corresponding package was removed from nixpkgs.") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "marathon" ] "The corresponding package was removed from nixpkgs.") - (mkRemovedOptionModule [ "services" "mathics" ] "The Mathics module has been removed") - (mkRemovedOptionModule [ "services" "matrix-sliding-sync" ] + (lib.mkRemovedOptionModule [ "services" "mathics" ] "The Mathics module has been removed") + (lib.mkRemovedOptionModule [ "services" "matrix-sliding-sync" ] "The matrix-sliding-sync package has been removed, since matrix-synapse incorporated its functionality. Remove `services.sliding-sync` from your NixOS Configuration, and the `.well-known` record for `org.matrix.msc3575.proxy` from your webserver" ) - (mkRemovedOptionModule [ "services" "meguca" ] "Use meguca has been removed from nixpkgs") - (mkRemovedOptionModule [ "services" "mesos" ] "The corresponding package was removed from nixpkgs.") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "meguca" ] "Use meguca has been removed from nixpkgs") + (lib.mkRemovedOptionModule [ "services" "mesos" ] "The corresponding package was removed from nixpkgs.") + (lib.mkRemovedOptionModule [ "services" "mxisd" ] "The mxisd module has been removed as both mxisd and ma1sd got removed.") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "moinmoin" ] "The corresponding package was removed from nixpkgs.") - (mkRemovedOptionModule [ "services" "mwlib" ] "The corresponding package was removed from nixpkgs.") - (mkRemovedOptionModule [ "services" "pantheon" "files" ] '' + (lib.mkRemovedOptionModule [ "services" "mwlib" ] "The corresponding package was removed from nixpkgs.") + (lib.mkRemovedOptionModule [ "services" "pantheon" "files" ] '' This module was removed, please add pkgs.pantheon.elementary-files to environment.systemPackages directly. '') - (mkRemovedOptionModule [ "services" "prey" ] '' + (lib.mkRemovedOptionModule [ "services" "prey" ] '' prey-bash-client is deprecated upstream '') - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "quagga" ] "the corresponding package has been removed from nixpkgs") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "railcar" ] "the corresponding package has been removed from nixpkgs") - (mkRemovedOptionModule [ "services" "replay-sorcery" ] + (lib.mkRemovedOptionModule [ "services" "replay-sorcery" ] "the corresponding package has been removed from nixpkgs as it is unmaintained upstream. Consider using `gpu-screen-recorder` or `obs-studio` instead." ) - (mkRemovedOptionModule [ "services" "seeks" ] "") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "seeks" ] "") + (lib.mkRemovedOptionModule [ "services" "shout" ] "shout was removed because it was deprecated upstream in favor of thelounge.") - (mkRemovedOptionModule [ "services" "ssmtp" ] '' + (lib.mkRemovedOptionModule [ "services" "ssmtp" ] '' The ssmtp package and the corresponding module have been removed due to the program being unmaintained. The options `programs.msmtp.*` can be used instead. '') - (mkRemovedOptionModule [ "services" "tvheadend" ] + (lib.mkRemovedOptionModule [ "services" "tvheadend" ] "The tvheadend package and the corresponding module have been removed as nobody was willing to maintain them and they were stuck on an unmaintained version that required FFmpeg 4; please see https://github.com/NixOS/nixpkgs/pull/332259 if you are interested in maintaining a newer version." ) - (mkRemovedOptionModule [ "services" "unifi-video" ] + (lib.mkRemovedOptionModule [ "services" "unifi-video" ] "The unifi-video package and the corresponding module have been removed as the software has been unsupported since 2021 and requires a MongoDB version that has reached end of life." ) - (mkRemovedOptionModule [ "services" "venus" ] "The corresponding package was removed from nixpkgs.") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "venus" ] "The corresponding package was removed from nixpkgs.") + (lib.mkRemovedOptionModule [ "services" "wakeonlan" ] "This module was removed in favor of enabling it with networking.interfaces..wakeOnLan") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "winstone" ] "The corresponding package was removed from nixpkgs.") - (mkRemovedOptionModule [ "services" "xserver" "displayManager" "auto" ] '' + (lib.mkRemovedOptionModule [ "services" "xserver" "displayManager" "auto" ] '' The services.xserver.displayManager.auto module has been removed because it was only intended for use in internal NixOS tests, and gave the false impression of it being a special display manager when it's actually LightDM. Please use the services.displayManager.autoLogin options instead, or any other display manager in NixOS as they all support auto-login. '') - (mkRemovedOptionModule [ "services" "xserver" "multitouch" ] '' + (lib.mkRemovedOptionModule [ "services" "xserver" "multitouch" ] '' services.xserver.multitouch (which uses xf86_input_mtrack) has been removed as the underlying package isn't being maintained. Working alternatives are libinput and synaptics. '') - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "xmr-stak" ] "The corresponding package was removed from nixpkgs.") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "virtualisation" "rkt" ] "The rkt module has been removed, it was archived by upstream") - (mkRemovedOptionModule [ "services" "racoon" ] '' + (lib.mkRemovedOptionModule [ "services" "racoon" ] '' The racoon module has been removed, because the software project was abandoned upstream. '') - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "shellinabox" ] "The corresponding package was removed from nixpkgs.") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "gogoclient" ] "The corresponding package was removed from nixpkgs.") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "virtuoso" ] "The corresponding package was removed from nixpkgs.") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "openfire" ] "The corresponding package was removed from nixpkgs.") - (mkRemovedOptionModule [ "services" "riak" ] "The corresponding package was removed from nixpkgs.") - (mkRemovedOptionModule [ "services" "rtsp-simple-server" ] + (lib.mkRemovedOptionModule [ "services" "riak" ] "The corresponding package was removed from nixpkgs.") + (lib.mkRemovedOptionModule [ "services" "rtsp-simple-server" ] "Package has been completely rebranded by upstream as mediamtx, and thus the service and the package were renamed in NixOS as well." ) - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "prayer" ] "The corresponding package was removed from nixpkgs.") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "restya-board" ] "The corresponding package was removed from nixpkgs.") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "i18n" "inputMethod" "fcitx" ] "The fcitx module has been removed. Please use fcitx5 instead") - (mkRemovedOptionModule [ "services" "dhcpd4" ] '' + (lib.mkRemovedOptionModule [ "services" "dhcpd4" ] '' The dhcpd4 module has been removed because ISC DHCP reached its end of life. See https://www.isc.org/blogs/isc-dhcp-eol/ for details. Please switch to a different implementation like kea or dnsmasq. '') - (mkRemovedOptionModule [ "services" "dhcpd6" ] '' + (lib.mkRemovedOptionModule [ "services" "dhcpd6" ] '' The dhcpd6 module has been removed because ISC DHCP reached its end of life. See https://www.isc.org/blogs/isc-dhcp-eol/ for details. Please switch to a different implementation like kea or dnsmasq. '') - (mkRemovedOptionModule [ "services" "tedicross" ] '' + (lib.mkRemovedOptionModule [ "services" "tedicross" ] '' The corresponding package was broken and removed from nixpkgs. '') diff --git a/nixos/modules/security/acme/default.nix b/nixos/modules/security/acme/default.nix index 4cdce9eec9cb3..fdd1ff1f8b0af 100644 --- a/nixos/modules/security/acme/default.nix +++ b/nixos/modules/security/acme/default.nix @@ -627,7 +627,7 @@ let inherit (defaultAndText "environmentFile" null) default defaultText; description = '' Path to an EnvironmentFile for the cert's service containing any required and - optional environment variables for your selected dnsProvider. + lib.optional environment variables for your selected dnsProvider. To find out what values you need to set, consult the documentation at for the corresponding dnsProvider. ''; diff --git a/nixos/modules/security/apparmor.nix b/nixos/modules/security/apparmor.nix index a4c2f9e29fc34..3588fd5d07445 100644 --- a/nixos/modules/security/apparmor.nix +++ b/nixos/modules/security/apparmor.nix @@ -56,12 +56,12 @@ in description = '' AppArmor policies. ''; - type = types.attrsOf ( + type = lib.types.attrsOf ( types.submodule { options = { state = lib.mkOption { description = "How strictly this policy should be enforced"; - type = types.enum [ + type = lib.types.enum [ "disable" "complain" "enforce" @@ -73,12 +73,12 @@ in profile = lib.mkOption { description = "The profile file contents. Incompatible with path."; - type = types.lines; + type = lib.types.lines; }; path = lib.mkOption { description = "A path of a profile file to include. Incompatible with profile."; - type = types.nullOr types.path; + type = lib.types.nullOr lib.types.path; default = null; }; }; @@ -87,7 +87,7 @@ in default = { }; }; includes = lib.mkOption { - type = types.attrsOf types.lines; + type = lib.types.attrsOf types.lines; default = { }; description = '' List of paths to be added to AppArmor's searched paths @@ -96,7 +96,7 @@ in apply = lib.mapAttrs pkgs.writeText; }; packages = lib.mkOption { - type = types.listOf types.package; + type = lib.types.listOf lib.types.package; default = [ ]; description = "List of packages to be added to AppArmor's include path"; }; diff --git a/nixos/modules/security/dhparams.nix b/nixos/modules/security/dhparams.nix index 36bb8398f5423..d4c914a76eb72 100644 --- a/nixos/modules/security/dhparams.nix +++ b/nixos/modules/security/dhparams.nix @@ -7,11 +7,10 @@ }: let - inherit (lib) literalExpression mkOption types; cfg = config.security.dhparams; opt = options.security.dhparams; - bitType = types.addCheck types.int (b: b >= 16) // { + bitType = lib.types.addCheck lib.types.int (b: b >= 16) // { name = "bits"; description = "integer of at least 16 bits"; }; @@ -19,18 +18,18 @@ let paramsSubmodule = { name, config, ... }: { - options.bits = mkOption { + options.bits = lib.mkOption { type = bitType; default = cfg.defaultBitSize; - defaultText = literalExpression "config.${opt.defaultBitSize}"; + defaultText = lib.literalExpression "config.${opt.defaultBitSize}"; description = '' The bit size for the prime that is used during a Diffie-Hellman key exchange. ''; }; - options.path = mkOption { - type = types.path; + options.path = lib.mkOption { + type = lib.types.path; readOnly = true; description = '' The resulting path of the generated Diffie-Hellman parameters @@ -53,17 +52,17 @@ in { options = { security.dhparams = { - enable = mkOption { - type = types.bool; + enable = lib.mkOption { + type = lib.types.bool; default = false; description = '' Whether to generate new DH params and clean up old DH params. ''; }; - params = mkOption { + params = lib.mkOption { type = - with types; + with lib.types; let coerce = bits: { inherit bits; }; in @@ -102,8 +101,8 @@ in ''; }; - stateful = mkOption { - type = types.bool; + stateful = lib.mkOption { + type = lib.types.bool; default = true; description = '' Whether generation of Diffie-Hellman parameters should be stateful or @@ -120,7 +119,7 @@ in ''; }; - defaultBitSize = mkOption { + defaultBitSize = lib.mkOption { type = bitType; default = 2048; description = '' @@ -130,8 +129,8 @@ in ''; }; - path = mkOption { - type = types.str; + path = lib.mkOption { + type = lib.types.str; default = "/var/lib/dhparams"; description = '' Path to the directory in which Diffie-Hellman parameters will be diff --git a/nixos/modules/security/doas.nix b/nixos/modules/security/doas.nix index 659499a242581..2dd589f572ba2 100644 --- a/nixos/modules/security/doas.nix +++ b/nixos/modules/security/doas.nix @@ -122,7 +122,7 @@ in options = { noPass = lib.mkOption { - type = with types; bool; + type = with lib.types; bool; default = false; description = '' If `true`, the user is not required to enter a @@ -131,7 +131,7 @@ in }; noLog = lib.mkOption { - type = with types; bool; + type = with lib.types; bool; default = false; description = '' If `true`, successful executions will not be logged @@ -141,7 +141,7 @@ in }; persist = lib.mkOption { - type = with types; bool; + type = with lib.types; bool; default = false; description = '' If `true`, do not ask for a password again for some @@ -150,7 +150,7 @@ in }; keepEnv = lib.mkOption { - type = with types; bool; + type = with lib.types; bool; default = false; description = '' If `true`, environment variables other than those @@ -161,7 +161,7 @@ in }; setEnv = lib.mkOption { - type = with types; listOf str; + type = with lib.types; listOf str; default = [ ]; description = '' Keep or set the specified variables. Variables may also be @@ -180,19 +180,19 @@ in }; users = lib.mkOption { - type = with types; listOf (either str int); + type = with lib.types; listOf (either str int); default = [ ]; description = "The usernames / UIDs this rule should apply for."; }; groups = lib.mkOption { - type = with types; listOf (either str int); + type = with lib.types; listOf (either str int); default = [ ]; description = "The groups / GIDs this rule should apply for."; }; runAs = lib.mkOption { - type = with types; nullOr str; + type = with lib.types; nullOr str; default = null; description = '' Which user or group the specified command is allowed to run as. @@ -206,7 +206,7 @@ in }; cmd = lib.mkOption { - type = with types; nullOr str; + type = with lib.types; nullOr str; default = null; description = '' The command the user is allowed to run. When set to @@ -219,7 +219,7 @@ in }; args = lib.mkOption { - type = with types; nullOr (listOf str); + type = with lib.types; nullOr (listOf str); default = null; description = '' Arguments that must be provided to the command. When set to diff --git a/nixos/modules/security/ipa.nix b/nixos/modules/security/ipa.nix index e746ca75724a1..40def99aee53f 100644 --- a/nixos/modules/security/ipa.nix +++ b/nixos/modules/security/ipa.nix @@ -4,7 +4,7 @@ pkgs, ... }: -with lib; let +let cfg = config.security.ipa; pyBool = x: if x @@ -31,17 +31,17 @@ with lib; let in { options = { security.ipa = { - enable = mkEnableOption "FreeIPA domain integration"; + enable = lib.mkEnableOption "FreeIPA domain integration"; - certificate = mkOption { - type = types.package; + certificate = lib.mkOption { + type = lib.types.package; description = '' IPA server CA certificate. Use `nix-prefetch-url http://$server/ipa/config/ca.crt` to obtain the file and the hash. ''; - example = literalExpression '' + example = lib.literalExpression '' pkgs.fetchurl { url = http://ipa.example.com/ipa/config/ca.crt; sha256 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; @@ -49,84 +49,84 @@ in { ''; }; - domain = mkOption { - type = types.str; + domain = lib.mkOption { + type = lib.types.str; example = "example.com"; description = "Domain of the IPA server."; }; - realm = mkOption { - type = types.str; + realm = lib.mkOption { + type = lib.types.str; example = "EXAMPLE.COM"; description = "Kerberos realm."; }; - server = mkOption { - type = types.str; + server = lib.mkOption { + type = lib.types.str; example = "ipa.example.com"; description = "IPA Server hostname."; }; - basedn = mkOption { - type = types.str; + basedn = lib.mkOption { + type = lib.types.str; example = "dc=example,dc=com"; description = "Base DN to use when performing LDAP operations."; }; - offlinePasswords = mkOption { - type = types.bool; + offlinePasswords = lib.mkOption { + type = lib.types.bool; default = true; description = "Whether to store offline passwords when the server is down."; }; - cacheCredentials = mkOption { - type = types.bool; + cacheCredentials = lib.mkOption { + type = lib.types.bool; default = true; description = "Whether to cache credentials."; }; - ipaHostname = mkOption { - type = types.str; + ipaHostname = lib.mkOption { + type = lib.types.str; example = "myworkstation.example.com"; default = if config.networking.domain != null then config.networking.fqdn else "${config.networking.hostName}.${cfg.domain}"; - defaultText = literalExpression '' + defaultText = lib.literalExpression '' if config.networking.domain != null then config.networking.fqdn else "''${networking.hostName}.''${security.ipa.domain}" ''; description = "Fully-qualified hostname used to identify this host in the IPA domain."; }; - ifpAllowedUids = mkOption { - type = types.listOf types.str; + ifpAllowedUids = lib.mkOption { + type = lib.types.listOf lib.types.str; default = ["root"]; description = "A list of users allowed to access the ifp dbus interface."; }; dyndns = { - enable = mkOption { - type = types.bool; + enable = lib.mkOption { + type = lib.types.bool; default = true; description = "Whether to enable FreeIPA automatic hostname updates."; }; - interface = mkOption { - type = types.str; + interface = lib.mkOption { + type = lib.types.str; example = "eth0"; default = "*"; description = "Network interface to perform hostname updates through."; }; }; - chromiumSupport = mkOption { - type = types.bool; + chromiumSupport = lib.mkOption { + type = lib.types.bool; default = true; description = "Whether to whitelist the FreeIPA domain in Chromium."; }; }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { assertions = [ { assertion = !config.security.krb5.enable; @@ -187,7 +187,7 @@ in { "openldap/ldap.conf".source = ldapConf; }; - environment.etc."chromium/policies/managed/freeipa.json" = mkIf cfg.chromiumSupport { + environment.etc."chromium/policies/managed/freeipa.json" = lib.mkIf cfg.chromiumSupport { text = '' { "AuthServerWhitelist": "*.${cfg.domain}" } ''; @@ -234,7 +234,7 @@ in { cache_credentials = ${pyBool cfg.cacheCredentials} krb5_store_password_if_offline = ${pyBool cfg.offlinePasswords} - ${optionalString ((toLower cfg.domain) != (toLower cfg.realm)) + ${lib.optionalString ((lib.toLower cfg.domain) != (lib.toLower cfg.realm)) "krb5_realm = ${cfg.realm}"} dyndns_update = ${pyBool cfg.dyndns.enable} @@ -264,13 +264,13 @@ in { [ifp] user_attributes = +mail, +telephoneNumber, +givenname, +sn, +lock - allowed_uids = ${concatStringsSep ", " cfg.ifpAllowedUids} + allowed_uids = ${lib.concatStringsSep ", " cfg.ifpAllowedUids} ''; - services.ntp.servers = singleton cfg.server; + services.ntp.servers = lib.singleton cfg.server; services.sssd.enable = true; services.ntp.enable = true; - security.pki.certificateFiles = singleton cfg.certificate; + security.pki.certificateFiles = lib.singleton cfg.certificate; }; } diff --git a/nixos/modules/security/isolate.nix b/nixos/modules/security/isolate.nix index 74274d04c6b83..9c8d6b743e9a9 100644 --- a/nixos/modules/security/isolate.nix +++ b/nixos/modules/security/isolate.nix @@ -6,15 +6,6 @@ }: let - inherit (lib) - mkEnableOption - mkPackageOption - mkOption - types - mkIf - maintainers - ; - cfg = config.security.isolate; configFile = pkgs.writeText "isolate-config.cf" '' box_root=${cfg.boxRoot} @@ -44,14 +35,14 @@ let in { options.security.isolate = { - enable = mkEnableOption '' + enable = lib.mkEnableOption '' Sandbox for securely executing untrusted programs ''; - package = mkPackageOption pkgs "isolate-unwrapped" { }; + package = lib.mkPackageOption pkgs "isolate-unwrapped" { }; - boxRoot = mkOption { - type = types.path; + boxRoot = lib.mkOption { + type = lib.types.path; default = "/var/lib/isolate/boxes"; description = '' All sandboxes are created under this directory. @@ -60,16 +51,16 @@ in ''; }; - lockRoot = mkOption { - type = types.path; + lockRoot = lib.mkOption { + type = lib.types.path; default = "/run/isolate/locks"; description = '' Directory where lock files are created. ''; }; - cgRoot = mkOption { - type = types.str; + cgRoot = lib.mkOption { + type = lib.types.str; default = "auto:/run/isolate/cgroup"; description = '' Control group which subgroups are placed under. @@ -78,24 +69,24 @@ in ''; }; - firstUid = mkOption { - type = types.numbers.between 1000 65533; + firstUid = lib.mkOption { + type = lib.types.numbers.between 1000 65533; default = 60000; description = '' Start of block of UIDs reserved for sandboxes. ''; }; - firstGid = mkOption { - type = types.numbers.between 1000 65533; + firstGid = lib.mkOption { + type = lib.types.numbers.between 1000 65533; default = 60000; description = '' Start of block of GIDs reserved for sandboxes. ''; }; - numBoxes = mkOption { - type = types.numbers.between 1000 65533; + numBoxes = lib.mkOption { + type = lib.types.numbers.between 1000 65533; default = 1000; description = '' Number of UIDs and GIDs to reserve, starting from @@ -103,16 +94,16 @@ in ''; }; - restrictedInit = mkOption { - type = types.bool; + restrictedInit = lib.mkOption { + type = lib.types.bool; default = false; description = '' If true, only root can create sandboxes. ''; }; - extraConfig = mkOption { - type = types.str; + extraConfig = lib.mkOption { + type = lib.types.str; default = ""; description = '' Extra configuration to append to the configuration file. @@ -120,7 +111,7 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { environment.systemPackages = [ isolate ]; @@ -140,6 +131,6 @@ in description = "Isolate Sandbox Slice"; }; - meta.maintainers = with maintainers; [ virchau13 ]; + meta.maintainers = with lib.maintainers; [ virchau13 ]; }; } diff --git a/nixos/modules/security/krb5/default.nix b/nixos/modules/security/krb5/default.nix index fa7895f4a0a95..706acde4af3ca 100644 --- a/nixos/modules/security/krb5/default.nix +++ b/nixos/modules/security/krb5/default.nix @@ -5,15 +5,9 @@ ... }: let - inherit (lib) - mkIf - mkOption - mkPackageOption - mkRemovedOptionModule - ; inherit (lib.types) bool; - mkRemovedOptionModule' = name: reason: mkRemovedOptionModule [ "krb5" name ] reason; + mkRemovedOptionModule' = name: reason: lib.mkRemovedOptionModule [ "krb5" name ] reason; mkRemovedOptionModuleCfg = name: mkRemovedOptionModule' name '' @@ -26,32 +20,32 @@ let in { imports = [ - (mkRemovedOptionModuleCfg "libdefaults") - (mkRemovedOptionModuleCfg "realms") - (mkRemovedOptionModuleCfg "domain_realm") - (mkRemovedOptionModuleCfg "capaths") - (mkRemovedOptionModuleCfg "appdefaults") - (mkRemovedOptionModuleCfg "plugins") - (mkRemovedOptionModuleCfg "config") - (mkRemovedOptionModuleCfg "extraConfig") - (mkRemovedOptionModule' "kerberos" '' + (lib.mkRemovedOptionModuleCfg "libdefaults") + (lib.mkRemovedOptionModuleCfg "realms") + (lib.mkRemovedOptionModuleCfg "domain_realm") + (lib.mkRemovedOptionModuleCfg "capaths") + (lib.mkRemovedOptionModuleCfg "appdefaults") + (lib.mkRemovedOptionModuleCfg "plugins") + (lib.mkRemovedOptionModuleCfg "config") + (lib.mkRemovedOptionModuleCfg "extraConfig") + (lib.mkRemovedOptionModule' "kerberos" '' The option `krb5.kerberos' has been moved to `security.krb5.package'. '') ]; options = { security.krb5 = { - enable = mkOption { + enable = lib.mkOption { default = false; description = "Enable and configure Kerberos utilities"; type = bool; }; - package = mkPackageOption pkgs "krb5" { + package = lib.mkPackageOption pkgs "krb5" { example = "heimdal"; }; - settings = mkOption { + settings = lib.mkOption { default = { }; type = format.type; description = '' @@ -91,7 +85,7 @@ in }; config = { - assertions = mkIf (cfg.enable || config.services.kerberos_server.enable) [ + assertions = lib.mkIf (cfg.enable || config.services.kerberos_server.enable) [ ( let implementation = cfg.package.passthru.implementation or ""; @@ -113,7 +107,7 @@ in ) ]; - environment = mkIf cfg.enable { + environment = lib.mkIf cfg.enable { systemPackages = [ cfg.package ]; etc."krb5.conf".source = format.generate "krb5.conf" cfg.settings; }; diff --git a/nixos/modules/security/krb5/krb5-conf-format.nix b/nixos/modules/security/krb5/krb5-conf-format.nix index 274e1024209da..1af432f097e58 100644 --- a/nixos/modules/security/krb5/krb5-conf-format.nix +++ b/nixos/modules/security/krb5/krb5-conf-format.nix @@ -4,89 +4,61 @@ # - https://web.mit.edu/kerberos/krb5-1.12/doc/admin/conf_files/krb5_conf.html # - https://manpages.debian.org/unstable/heimdal-docs/krb5.conf.5heimdal.en.html -let - inherit (lib) - boolToString - concatMapStringsSep - concatStringsSep - filter - isAttrs - isBool - isList - mapAttrsToList - mkOption - singleton - splitString - ; - inherit (lib.types) - attrsOf - bool - coercedTo - either - enum - int - listOf - oneOf - path - str - submodule - ; -in { enableKdcACLEntries ? false, }: rec { sectionType = let - relation = oneOf [ - (listOf (attrsOf value)) - (attrsOf value) + relation = lib.types.oneOf [ + (lib.types.listOf (lib.types.attrsOf value)) + (lib.types.attrsOf value) value ]; - value = either (listOf atom) atom; - atom = oneOf [ - int - str - bool + value = lib.types.either (lib.types.listOf atom) atom; + atom = lib.types.oneOf [ + lib.types.int + lib.types.str + lib.types.bool ]; in - attrsOf relation; + lib.types.attrsOf relation; type = let - aclEntry = submodule { + aclEntry = lib.types.submodule { options = { - principal = mkOption { - type = str; + principal = lib.mkOption { + type = lib.types.str; description = "Which principal the rule applies to"; }; - access = mkOption { - type = either (listOf (enum [ + access = lib.mkOption { + type = lib.types.either (lib.types.listOf (lib.types.enum [ "add" "cpw" "delete" "get" "list" "modify" - ])) (enum [ "all" ]); + ])) (lib.types.enum [ "all" ]); default = "all"; description = "The changes the principal is allowed to make."; }; - target = mkOption { - type = str; + target = lib.mkOption { + type = lib.types.str; default = "*"; description = "The principals that 'access' applies to."; }; }; }; - realm = submodule ( + realm = lib.types.submodule ( { name, ... }: { freeformType = sectionType; options = { - acl = mkOption { - type = listOf aclEntry; + acl = lib.mkOption { + type = lib.types.listOf aclEntry; default = [ { principal = "*/admin"; @@ -105,36 +77,36 @@ rec { } ); in - submodule { - freeformType = attrsOf sectionType; + lib.types.submodule { + freeformType = lib.types.attrsOf sectionType; options = { - include = mkOption { + include = lib.mkOption { default = [ ]; description = '' Files to include in the Kerberos configuration. ''; - type = coercedTo path singleton (listOf path); + type = lib.types.coercedTo lib.types.path lib.types.singleton (lib.types.listOf lib.types.path); }; - includedir = mkOption { + includedir = lib.mkOption { default = [ ]; description = '' Directories containing files to include in the Kerberos configuration. ''; - type = coercedTo path singleton (listOf path); + type = lib.types.coercedTo lib.types.path lib.types.singleton (lib.types.listOf lib.types.path); }; - module = mkOption { + module = lib.mkOption { default = [ ]; description = '' Modules to obtain Kerberos configuration from. ''; - type = coercedTo path singleton (listOf path); + type = lib.types.coercedTo lib.types.path lib.types.singleton (lib.types.listOf lib.types.path); }; } // (lib.optionalAttrs enableKdcACLEntries { - realms = mkOption { - type = attrsOf realm; + realms = lib.mkOption { + type = lib.types.attrsOf realm; description = '' The realm(s) to serve keys for. ''; @@ -144,7 +116,7 @@ rec { generate = let - indent = str: concatMapStringsSep "\n" (line: " " + line) (splitString "\n" str); + indent = str: lib.concatMapStringsSep "\n" (line: " " + line) (lib.splitString "\n" str); formatToplevel = args@{ @@ -160,40 +132,40 @@ rec { "module" ]; in - concatStringsSep "\n" ( - filter (x: x != "") [ - (concatStringsSep "\n" (mapAttrsToList formatSection sections)) - (concatMapStringsSep "\n" (m: "module ${m}") module) - (concatMapStringsSep "\n" (i: "include ${i}") include) - (concatMapStringsSep "\n" (i: "includedir ${i}") includedir) + lib.concatStringsSep "\n" ( + lib.filter (x: x != "") [ + (lib.concatStringsSep "\n" (lib.mapAttrsToList formatSection sections)) + (lib.concatMapStringsSep "\n" (m: "module ${m}") module) + (lib.concatMapStringsSep "\n" (i: "include ${i}") include) + (lib.concatMapStringsSep "\n" (i: "includedir ${i}") includedir) ] ); formatSection = name: section: '' [${name}] - ${indent (concatStringsSep "\n" (mapAttrsToList formatRelation section))} + ${indent (lib.concatStringsSep "\n" (lib.mapAttrsToList formatRelation section))} ''; formatRelation = name: relation: - if isAttrs relation then + if lib.isAttrs relation then '' ${name} = { - ${indent (concatStringsSep "\n" (mapAttrsToList formatValue relation))} + ${indent (lib.concatStringsSep "\n" (lib.mapAttrsToList formatValue relation))} }'' - else if isList relation then - concatMapStringsSep "\n" (formatRelation name) relation + else if lib.isList relation then + lib.concatMapStringsSep "\n" (formatRelation name) relation else formatValue name relation; formatValue = name: value: - if isList value then concatMapStringsSep "\n" (formatAtom name) value else formatAtom name value; + if lib.isList value then lib.concatMapStringsSep "\n" (formatAtom name) value else formatAtom name value; formatAtom = name: atom: let - v = if isBool atom then boolToString atom else toString atom; + v = if lib.isBool atom then lib.boolToString atom else toString atom; in "${name} = ${v}"; in diff --git a/nixos/modules/security/pam.nix b/nixos/modules/security/pam.nix index 280ef183068b6..c05a52afced2a 100644 --- a/nixos/modules/security/pam.nix +++ b/nixos/modules/security/pam.nix @@ -909,23 +909,23 @@ let "${domain} ${type} ${item} ${toString value}\n") limits); - limitsType = with lib.types; listOf (submodule ({ ... }: { + limitsType = lib.types.listOf (lib.types.submodule ({ ... }: { options = { domain = lib.mkOption { description = "Username, groupname, or wildcard this limit applies to"; example = "@wheel"; - type = str; + type = lib.types.str; }; type = lib.mkOption { description = "Type of this limit"; - type = enum [ "-" "hard" "soft" ]; + type = lib.types.enum [ "-" "hard" "soft" ]; default = "-"; }; item = lib.mkOption { description = "Item this limit applies to"; - type = enum [ + type = lib.types.enum [ "core" "data" "fsize" @@ -949,7 +949,7 @@ let value = lib.mkOption { description = "Value of this limit"; - type = oneOf [ str int ]; + type = lib.types.oneOf [ lib.types.str lib.types.int ]; }; }; })); @@ -963,7 +963,7 @@ let value.source = pkgs.writeText "${name}.pam" service.text; }; - optionalSudoConfigForSSHAgentAuth = lib.optionalString + lib.optionalSudoConfigForSSHAgentAuth = lib.optionalString (config.security.pam.sshAgentAuth.enable || config.security.pam.rssh.enable) '' # Keep SSH_AUTH_SOCK so that pam_ssh_agent_auth.so and libpam_rssh.so can do their magic. Defaults env_keep+=SSH_AUTH_SOCK @@ -1661,9 +1661,9 @@ in lib.concatMapStrings (name: "r ${config.environment.etc."pam.d/${name}".source},\n") (lib.attrNames config.security.pam.services) + - (with lib; pipe config.security.pam.services [ + (lib.pipe config.security.pam.services [ lib.attrValues - (catAttrs "rules") + (lib.catAttrs "rules") (lib.concatMap lib.attrValues) (lib.concatMap lib.attrValues) (lib.filter (rule: rule.enable)) @@ -1675,10 +1675,10 @@ in )) lib.unique (map (module: "mr ${module},")) - concatLines + lib.concatLines ]); - security.sudo.extraConfig = optionalSudoConfigForSSHAgentAuth; - security.sudo-rs.extraConfig = optionalSudoConfigForSSHAgentAuth; + security.sudo.extraConfig = lib.optionalSudoConfigForSSHAgentAuth; + security.sudo-rs.extraConfig = lib.optionalSudoConfigForSSHAgentAuth; }; } diff --git a/nixos/modules/security/rtkit.nix b/nixos/modules/security/rtkit.nix index 99826c6e8891e..0eefcf3863447 100644 --- a/nixos/modules/security/rtkit.nix +++ b/nixos/modules/security/rtkit.nix @@ -3,8 +3,6 @@ { config, lib, pkgs, utils, ... }: -with lib; - let cfg = config.security.rtkit; package = pkgs.rtkit; @@ -13,8 +11,8 @@ in { options = { - security.rtkit.enable = mkOption { - type = types.bool; + security.rtkit.enable = lib.mkOption { + type = lib.types.bool; default = false; description = '' Whether to enable the RealtimeKit system service, which hands @@ -24,8 +22,8 @@ in { ''; }; - security.rtkit.args = mkOption { - type = types.listOf types.str; + security.rtkit.args = lib.mkOption { + type = lib.types.listOf lib.types.str; default = []; description = '' Command-line options for `rtkit-daemon`. @@ -39,7 +37,7 @@ in { }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { security.polkit.enable = true; diff --git a/nixos/modules/security/sudo.nix b/nixos/modules/security/sudo.nix index f68d31c5a577b..22c6db212921f 100644 --- a/nixos/modules/security/sudo.nix +++ b/nixos/modules/security/sudo.nix @@ -116,7 +116,7 @@ in listOf (submodule { options = { users = lib.mkOption { - type = with types; listOf (either str int); + type = with lib.types; listOf (either str int); description = '' The usernames / UIDs this rule should apply for. ''; @@ -124,7 +124,7 @@ in }; groups = lib.mkOption { - type = with types; listOf (either str int); + type = with lib.types; listOf (either str int); description = '' The groups / GIDs this rule should apply for. ''; @@ -132,7 +132,7 @@ in }; host = lib.mkOption { - type = types.str; + type = lib.types.str; default = "ALL"; description = '' For what host this rule should apply. @@ -140,7 +140,7 @@ in }; runAs = lib.mkOption { - type = with types; str; + type = with lib.types; str; default = "ALL:ALL"; description = '' Under which user/group the specified command is allowed to run. @@ -156,13 +156,13 @@ in The commands for which the rule should apply. ''; type = - with types; + with lib.types; listOf ( either str (submodule { options = { command = lib.mkOption { - type = with types; str; + type = with lib.types; str; description = '' A command being either just a path to a binary to allow any arguments, the full command with arguments pre-set or with `""` used as the argument, @@ -172,7 +172,7 @@ in options = lib.mkOption { type = - with types; + with lib.types; listOf (enum [ "NOPASSWD" "PASSWD" diff --git a/nixos/modules/security/systemd-confinement.nix b/nixos/modules/security/systemd-confinement.nix index c3c0a1a4975d6..812ac13ffb56f 100644 --- a/nixos/modules/security/systemd-confinement.nix +++ b/nixos/modules/security/systemd-confinement.nix @@ -13,12 +13,12 @@ let in { options.systemd.services = lib.mkOption { - type = types.attrsOf ( + type = lib.types.attrsOf ( types.submodule ( { name, config, ... }: { options.confinement.enable = lib.mkOption { - type = types.bool; + type = lib.types.bool; default = false; description = '' If set, all the required runtime store paths for this service are @@ -28,7 +28,7 @@ in }; options.confinement.fullUnit = lib.mkOption { - type = types.bool; + type = lib.types.bool; default = false; description = '' Whether to include the full closure of the systemd unit file into the @@ -45,7 +45,7 @@ in }; options.confinement.packages = lib.mkOption { - type = types.listOf (types.either types.str types.package); + type = lib.types.listOf (types.either types.str types.package); default = [ ]; description = let @@ -76,7 +76,7 @@ in }; options.confinement.binSh = lib.mkOption { - type = types.nullOr types.path; + type = lib.types.nullOr lib.types.path; default = toplevelConfig.environment.binsh; defaultText = lib.literalExpression "config.environment.binsh"; example = lib.literalExpression ''"''${pkgs.dash}/bin/dash"''; @@ -91,7 +91,7 @@ in }; options.confinement.mode = lib.mkOption { - type = types.enum [ + type = lib.types.enum [ "full-apivfs" "chroot-only" ]; diff --git a/nixos/modules/services/accessibility/orca.nix b/nixos/modules/services/accessibility/orca.nix index 4487afba103c5..84a4fd2d955ac 100644 --- a/nixos/modules/services/accessibility/orca.nix +++ b/nixos/modules/services/accessibility/orca.nix @@ -14,11 +14,11 @@ let in { options.services.orca = { - enable = mkEnableOption "Orca screen reader"; - package = mkPackageOption pkgs "orca" { }; + enable = lib.mkEnableOption "Orca screen reader"; + package = lib.mkPackageOption pkgs "orca" { }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { environment.systemPackages = [ cfg.package ]; services.speechd.enable = true; }; diff --git a/nixos/modules/services/accessibility/speechd.nix b/nixos/modules/services/accessibility/speechd.nix index 165be86346ccb..da6be5689ff40 100644 --- a/nixos/modules/services/accessibility/speechd.nix +++ b/nixos/modules/services/accessibility/speechd.nix @@ -17,13 +17,13 @@ in options.services.speechd = { # FIXME: figure out how to deprecate this EXTREMELY CAREFULLY # default guessed conservatively in ../misc/graphical-desktop.nix - enable = mkEnableOption "speech-dispatcher speech synthesizer daemon"; - package = mkPackageOption pkgs "speechd" { }; + enable = lib.mkEnableOption "speech-dispatcher speech synthesizer daemon"; + package = lib.mkPackageOption pkgs "speechd" { }; }; # FIXME: speechd 0.12 (or whatever the next version is) # will support socket activation, so switch to that once it's out. - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { environment = { systemPackages = [ cfg.package ]; sessionVariables.SPEECHD_CMD = getExe cfg.package; diff --git a/nixos/modules/services/admin/docuum.nix b/nixos/modules/services/admin/docuum.nix index a2516cf9eb94e..02127b4ca3d03 100644 --- a/nixos/modules/services/admin/docuum.nix +++ b/nixos/modules/services/admin/docuum.nix @@ -8,50 +8,41 @@ let cfg = config.services.docuum; - inherit (lib) - mkIf - mkEnableOption - mkOption - getExe - types - optionals - concatMap - ; in { options.services.docuum = { - enable = mkEnableOption "docuum daemon"; + enable = lib.mkEnableOption "docuum daemon"; - threshold = mkOption { + threshold = lib.mkOption { description = "Threshold for deletion in bytes, like `10 GB`, `10 GiB`, `10GB` or percentage-based thresholds like `50%`"; - type = types.str; + type = lib.types.str; default = "10 GB"; example = "50%"; }; - minAge = mkOption { + minAge = lib.mkOption { description = "Sets the minimum age of images to be considered for deletion."; - type = types.nullOr types.str; + type = lib.types.nullOr lib.types.str; default = null; example = "1d"; }; - keep = mkOption { + keep = lib.mkOption { description = "Prevents deletion of images for which repository:tag matches the specified regex."; - type = types.listOf types.str; + type = lib.types.listOf lib.types.str; default = [ ]; example = [ "^my-image" ]; }; - deletionChunkSize = mkOption { + deletionChunkSize = lib.mkOption { description = "Removes specified quantity of images at a time."; - type = types.int; + type = lib.types.int; default = 1; example = 10; }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { assertions = [ { assertion = config.virtualisation.docker.enable; @@ -72,17 +63,17 @@ in SupplementaryGroups = [ "docker" ]; ExecStart = utils.escapeSystemdExecArgs ( [ - (getExe pkgs.docuum) + (lib.getExe pkgs.docuum) "--threshold" cfg.threshold "--deletion-chunk-size" cfg.deletionChunkSize ] - ++ (concatMap (keep: [ + ++ (lib.concatMap (keep: [ "--keep" keep ]) cfg.keep) - ++ (optionals (cfg.minAge != null) [ + ++ (lib.optionals (cfg.minAge != null) [ "--min-age" cfg.minAge ]) diff --git a/nixos/modules/services/admin/meshcentral.nix b/nixos/modules/services/admin/meshcentral.nix index 6d8be447645d8..c6932b123c6a1 100644 --- a/nixos/modules/services/admin/meshcentral.nix +++ b/nixos/modules/services/admin/meshcentral.nix @@ -9,12 +9,11 @@ let configFormat = pkgs.formats.json { }; configFile = configFormat.generate "meshcentral-config.json" cfg.settings; in -with lib; { - options.services.meshcentral = with types; { - enable = mkEnableOption "MeshCentral computer management server"; - package = mkPackageOption pkgs "meshcentral" { }; - settings = mkOption { + options.services.meshcentral = { + enable = lib.mkEnableOption "MeshCentral computer management server"; + package = lib.mkPackageOption pkgs "meshcentral" { }; + settings = lib.mkOption { description = '' Settings for MeshCentral. Refer to upstream documentation for details: @@ -23,7 +22,7 @@ with lib; - [complex sample configuration](https://github.com/Ylianst/MeshCentral/blob/master/sample-config-advanced.json) - [Old homepage with documentation link](https://www.meshcommander.com/meshcentral2) ''; - type = types.submodule { + type = lib.types.submodule { freeformType = configFormat.type; }; example = { @@ -37,7 +36,7 @@ with lib; }; }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { services.meshcentral.settings.settings.autoBackup.backupPath = lib.mkDefault "/var/lib/meshcentral/backups"; systemd.services.meshcentral = { diff --git a/nixos/modules/services/admin/pgadmin.nix b/nixos/modules/services/admin/pgadmin.nix index 79cc14b828ec5..69b73744d4e58 100644 --- a/nixos/modules/services/admin/pgadmin.nix +++ b/nixos/modules/services/admin/pgadmin.nix @@ -180,7 +180,7 @@ in wantedBy = [ "multi-user.target" ]; after = [ "network.target" ]; requires = [ "network.target" ]; - # we're adding this optionally so just in case there's any race it'll be caught + # we're adding this lib.optionally so just in case there's any race it'll be caught # in case postgres doesn't start, pgadmin will just start normally wants = [ "postgresql.service" ]; diff --git a/nixos/modules/services/audio/botamusique.nix b/nixos/modules/services/audio/botamusique.nix index 0ee641dd0df05..3cfc5f4599c95 100644 --- a/nixos/modules/services/audio/botamusique.nix +++ b/nixos/modules/services/audio/botamusique.nix @@ -25,26 +25,26 @@ in freeformType = format.type; options = { server.host = lib.mkOption { - type = types.str; + type = lib.types.str; default = "localhost"; example = "mumble.example.com"; description = "Hostname of the mumble server to connect to."; }; server.port = lib.mkOption { - type = types.port; + type = lib.types.port; default = 64738; description = "Port of the mumble server to connect to."; }; bot.username = lib.mkOption { - type = types.str; + type = lib.types.str; default = "botamusique"; description = "Name the bot should appear with."; }; bot.comment = lib.mkOption { - type = types.str; + type = lib.types.str; default = "Hi, I'm here to play radio, local music or youtube/soundcloud music. Have fun!"; description = "Comment displayed for the bot."; }; diff --git a/nixos/modules/services/audio/music-assistant.nix b/nixos/modules/services/audio/music-assistant.nix index aaabe5c3ac4c3..775aabb59ccdf 100644 --- a/nixos/modules/services/audio/music-assistant.nix +++ b/nixos/modules/services/audio/music-assistant.nix @@ -7,20 +7,6 @@ }: let - inherit (lib) - mkIf - mkEnableOption - mkOption - mkPackageOption - types - ; - - inherit (types) - listOf - enum - str - ; - cfg = config.services.music-assistant; finalPackage = cfg.package.override { @@ -32,12 +18,12 @@ in meta.buildDocsInSandbox = false; options.services.music-assistant = { - enable = mkEnableOption "Music Assistant"; + enable = lib.mkEnableOption "Music Assistant"; - package = mkPackageOption pkgs "music-assistant" { }; + package = lib.mkPackageOption pkgs "music-assistant" { }; - extraOptions = mkOption { - type = listOf str; + extraOptions = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ "--config" "/var/lib/music-assistant" @@ -51,8 +37,8 @@ in ''; }; - providers = mkOption { - type = listOf (enum cfg.package.providerNames); + providers = lib.mkOption { + type = lib.types.listOf (lib.types.enum cfg.package.providerNames); default = [ ]; example = [ "opensubsonic" @@ -64,7 +50,7 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { systemd.services.music-assistant = { description = "Music Assistant"; documentation = [ "https://music-assistant.io" ]; diff --git a/nixos/modules/services/audio/mympd.nix b/nixos/modules/services/audio/mympd.nix index d6507133366da..4170ac5dc0be5 100644 --- a/nixos/modules/services/audio/mympd.nix +++ b/nixos/modules/services/audio/mympd.nix @@ -37,12 +37,11 @@ in settings = lib.mkOption { type = lib.types.submodule { freeformType = - with lib.types; - attrsOf ( - nullOr (oneOf [ - str - bool - int + lib.types.attrsOf ( + lib.types.nullOr (lib.types.oneOf [ + lib.types.str + lib.types.bool + lib.types.int ]) ); options = { @@ -85,17 +84,17 @@ in # upstream service config: https://github.com/jcorporation/myMPD/blob/master/contrib/initscripts/mympd.service.in after = [ "mpd.service" ]; wantedBy = [ "multi-user.target" ]; - preStart = with lib; '' + preStart = '' config_dir="/var/lib/mympd/config" mkdir -p "$config_dir" - ${pipe cfg.settings [ - (mapAttrsToList ( + ${lib.pipe cfg.settings [ + (lib.mapAttrsToList ( name: value: '' - echo -n "${if isBool value then boolToString value else toString value}" > "$config_dir/${name}" + echo -n "${if lib.isBool value then lib.boolToString value else toString value}" > "$config_dir/${name}" '' )) - (concatStringsSep "\n") + (lib.concatStringsSep "\n") ]} ''; unitConfig = { diff --git a/nixos/modules/services/audio/navidrome.nix b/nixos/modules/services/audio/navidrome.nix index e69bfef484386..4ff7def07ba65 100644 --- a/nixos/modules/services/audio/navidrome.nix +++ b/nixos/modules/services/audio/navidrome.nix @@ -6,18 +6,6 @@ }: let - inherit (lib) - mkEnableOption - mkPackageOption - mkOption - maintainers - ; - inherit (lib.types) - bool - port - str - submodule - ; cfg = config.services.navidrome; settingsFormat = pkgs.formats.json { }; in @@ -25,31 +13,31 @@ in options = { services.navidrome = { - enable = mkEnableOption "Navidrome music server"; + enable = lib.mkEnableOption "Navidrome music server"; - package = mkPackageOption pkgs "navidrome" { }; + package = lib.mkPackageOption pkgs "navidrome" { }; - settings = mkOption { - type = submodule { + settings = lib.mkOption { + type = lib.types.submodule { freeformType = settingsFormat.type; options = { - Address = mkOption { + Address = lib.mkOption { default = "127.0.0.1"; description = "Address to run Navidrome on."; - type = str; + type = lib.types.str; }; - Port = mkOption { + Port = lib.mkOption { default = 4533; description = "Port to run Navidrome on."; - type = port; + type = lib.types.port; }; - EnableInsightsCollector = mkOption { + EnableInsightsCollector = lib.mkOption { default = false; description = "Enable anonymous usage data collection, see for details."; - type = bool; + type = lib.types.bool; }; }; }; @@ -60,20 +48,20 @@ in description = "Configuration for Navidrome, see for supported values."; }; - user = mkOption { - type = str; + user = lib.mkOption { + type = lib.types.str; default = "navidrome"; description = "User under which Navidrome runs."; }; - group = mkOption { - type = str; + group = lib.mkOption { + type = lib.types.str; default = "navidrome"; description = "Group under which Navidrome runs."; }; - openFirewall = mkOption { - type = bool; + openFirewall = lib.mkOption { + type = lib.types.bool; default = false; description = "Whether to open the TCP port in the firewall"; }; @@ -82,10 +70,9 @@ in config = let - inherit (lib) mkIf optional getExe; WorkingDirectory = "/var/lib/navidrome"; in - mkIf cfg.enable { + lib.mkIf cfg.enable { systemd = { tmpfiles.settings.navidromeDirs = { "${cfg.settings.DataFolder or WorkingDirectory}"."d" = { @@ -103,7 +90,7 @@ in wantedBy = [ "multi-user.target" ]; serviceConfig = { ExecStart = '' - ${getExe cfg.package} --configfile ${settingsFormat.generate "navidrome.json" cfg.settings} + ${lib.getExe cfg.package} --configfile ${settingsFormat.generate "navidrome.json" cfg.settings} ''; User = cfg.user; Group = cfg.group; @@ -113,8 +100,8 @@ in RootDirectory = "/run/navidrome"; ReadWritePaths = ""; BindPaths = - optional (cfg.settings ? DataFolder) cfg.settings.DataFolder - ++ optional (cfg.settings ? CacheFolder) cfg.settings.CacheFolder; + lib.optional (cfg.settings ? DataFolder) cfg.settings.DataFolder + ++ lib.optional (cfg.settings ? CacheFolder) cfg.settings.CacheFolder; BindReadOnlyPaths = [ # navidrome uses online services to download additional album metadata / covers @@ -124,7 +111,7 @@ in builtins.storeDir "/etc" ] - ++ optional (cfg.settings ? MusicFolder) cfg.settings.MusicFolder + ++ lib.optional (cfg.settings ? MusicFolder) cfg.settings.MusicFolder ++ lib.optionals config.services.resolved.enable [ "/run/systemd/resolve/stub-resolv.conf" "/run/systemd/resolve/resolv.conf" @@ -158,16 +145,16 @@ in }; }; - users.users = mkIf (cfg.user == "navidrome") { + users.users = lib.mkIf (cfg.user == "navidrome") { navidrome = { inherit (cfg) group; isSystemUser = true; }; }; - users.groups = mkIf (cfg.group == "navidrome") { navidrome = { }; }; + users.groups = lib.mkIf (cfg.group == "navidrome") { navidrome = { }; }; - networking.firewall.allowedTCPPorts = mkIf cfg.openFirewall [ cfg.settings.Port ]; + networking.firewall.allowedTCPPorts = lib.mkIf cfg.openFirewall [ cfg.settings.Port ]; }; - meta.maintainers = with maintainers; [ fsnkty ]; + meta.maintainers = with lib.maintainers; [ fsnkty ]; } diff --git a/nixos/modules/services/audio/snapserver.nix b/nixos/modules/services/audio/snapserver.nix index 86ba7ec7183d8..911f4c7572acc 100644 --- a/nixos/modules/services/audio/snapserver.nix +++ b/nixos/modules/services/audio/snapserver.nix @@ -46,17 +46,17 @@ let + lib.concatStrings (lib.mapAttrsToList toQueryString opt.query) + "\""; - optionalNull = val: ret: lib.optional (val != null) ret; + lib.optionalNull = val: ret: lib.optional (val != null) ret; optionString = lib.concatStringsSep " " ( lib.mapAttrsToList streamToOption cfg.streams # global options ++ [ "--stream.bind_to_address=${cfg.listenAddress}" ] ++ [ "--stream.port=${toString cfg.port}" ] - ++ optionalNull cfg.sampleFormat "--stream.sampleformat=${cfg.sampleFormat}" - ++ optionalNull cfg.codec "--stream.codec=${cfg.codec}" - ++ optionalNull cfg.streamBuffer "--stream.stream_buffer=${toString cfg.streamBuffer}" - ++ optionalNull cfg.buffer "--stream.buffer=${toString cfg.buffer}" + ++ lib.optionalNull cfg.sampleFormat "--stream.sampleformat=${cfg.sampleFormat}" + ++ lib.optionalNull cfg.codec "--stream.codec=${cfg.codec}" + ++ lib.optionalNull cfg.streamBuffer "--stream.stream_buffer=${toString cfg.streamBuffer}" + ++ lib.optionalNull cfg.buffer "--stream.buffer=${toString cfg.buffer}" ++ lib.optional cfg.sendToMuted "--stream.send_to_muted" # tcp json rpc ++ [ "--tcp.enabled=${toString cfg.tcp.enable}" ] diff --git a/nixos/modules/services/audio/squeezelite.nix b/nixos/modules/services/audio/squeezelite.nix index 525285d00ca50..b40c7d9cf5d11 100644 --- a/nixos/modules/services/audio/squeezelite.nix +++ b/nixos/modules/services/audio/squeezelite.nix @@ -6,14 +6,6 @@ }: let - inherit (lib) - mkEnableOption - mkIf - mkOption - optionalString - types - ; - dataDir = "/var/lib/squeezelite"; cfg = config.services.squeezelite; pkg = if cfg.pulseAudio then pkgs.squeezelite-pulse else pkgs.squeezelite; @@ -25,13 +17,13 @@ in ###### interface options.services.squeezelite = { - enable = mkEnableOption "Squeezelite, a software Squeezebox emulator"; + enable = lib.mkEnableOption "Squeezelite, a software Squeezebox emulator"; - pulseAudio = mkEnableOption "pulseaudio support"; + pulseAudio = lib.mkEnableOption "pulseaudio support"; - extraArguments = mkOption { + extraArguments = lib.mkOption { default = ""; - type = types.str; + type = lib.types.str; description = '' Additional command line arguments to pass to Squeezelite. ''; @@ -40,7 +32,7 @@ in ###### implementation - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { systemd.services.squeezelite = { wantedBy = [ "multi-user.target" ]; after = [ diff --git a/nixos/modules/services/audio/tts.nix b/nixos/modules/services/audio/tts.nix index 554256e6d2464..685538bc81d7f 100644 --- a/nixos/modules/services/audio/tts.nix +++ b/nixos/modules/services/audio/tts.nix @@ -11,33 +11,25 @@ in { options.services.tts = - let - inherit (lib) - literalExpression - mkOption - mkEnableOption - types - ; - in { - servers = mkOption { - type = types.attrsOf ( - types.submodule ( + servers = lib.mkOption { + type = lib.types.attrsOf ( + lib.types.submodule ( { ... }: { options = { - enable = mkEnableOption "Coqui TTS server"; + enable = lib.mkEnableOption "Coqui TTS server"; - port = mkOption { - type = types.port; + port = lib.mkOption { + type = lib.types.port; example = 5000; description = '' Port to bind the TTS server to. ''; }; - model = mkOption { - type = types.nullOr types.str; + model = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = "tts_models/en/ljspeech/tacotron2-DDC"; example = null; description = '' @@ -49,8 +41,8 @@ in ''; }; - useCuda = mkOption { - type = types.bool; + useCuda = lib.mkOption { + type = lib.types.bool; default = false; example = true; description = '' @@ -58,8 +50,8 @@ in ''; }; - extraArgs = mkOption { - type = types.listOf types.str; + extraArgs = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; description = '' Extra arguments to pass to the server commandline. @@ -70,7 +62,7 @@ in ) ); default = { }; - example = literalExpression '' + example = lib.literalExpression '' { english = { port = 5300; @@ -93,20 +85,10 @@ in }; config = - let - inherit (lib) - mkIf - mapAttrs' - nameValuePair - optionalString - concatMapStringsSep - escapeShellArgs - ; - in - mkIf (cfg.servers != { }) { - systemd.services = mapAttrs' ( + lib.mkIf (cfg.servers != { }) { + systemd.services = lib.mapAttrs' ( server: options: - nameValuePair "tts-${server}" { + lib.nameValuePair "tts-${server}" { description = "Coqui TTS server instance ${server}"; after = [ "network-online.target" @@ -124,9 +106,9 @@ in StateDirectory = "tts"; ExecStart = "${pkgs.tts}/bin/tts-server --port ${toString options.port} " - + optionalString (options.model != null) "--model_name ${options.model} " - + optionalString (options.useCuda) "--use_cuda " - + (escapeShellArgs options.extraArgs); + + lib.optionalString (options.model != null) "--model_name ${options.model} " + + lib.optionalString (options.useCuda) "--use_cuda " + + (lib.escapeShellArgs options.extraArgs); CapabilityBoundingSet = ""; DeviceAllow = if options.useCuda then diff --git a/nixos/modules/services/backup/automysqlbackup.nix b/nixos/modules/services/backup/automysqlbackup.nix index 83518f994aebc..c9ec69b8250a1 100644 --- a/nixos/modules/services/backup/automysqlbackup.nix +++ b/nixos/modules/services/backup/automysqlbackup.nix @@ -7,25 +7,6 @@ let - inherit (lib) - concatMapStringsSep - concatStringsSep - isInt - isList - literalExpression - ; - inherit (lib) - mapAttrs - mapAttrsToList - mkDefault - mkEnableOption - mkIf - mkOption - mkRenamedOptionModule - optional - types - ; - cfg = config.services.automysqlbackup; pkg = pkgs.automysqlbackup; user = "automysqlbackup"; @@ -33,9 +14,9 @@ let toStr = val: - if isList val then - "( ${concatMapStringsSep " " (val: "'${val}'") val} )" - else if isInt val then + if lib.isList val then + "( ${lib.concatMapStringsSep " " (val: "'${val}'") val} )" + else if lib.isInt val then toString val else if true == val then "'yes'" @@ -48,13 +29,13 @@ let #version=${pkg.version} # DONT'T REMOVE THE PREVIOUS VERSION LINE! # - ${concatStringsSep "\n" (mapAttrsToList (name: value: "CONFIG_${name}=${toStr value}") cfg.config)} + ${lib.concatStringsSep "\n" (lib.mapAttrsToList (name: value: "CONFIG_${name}=${toStr value}") cfg.config)} ''; in { imports = [ - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "automysqlbackup" "config" ] [ "services" "automysqlbackup" "settings" ] ) @@ -64,19 +45,19 @@ in options = { services.automysqlbackup = { - enable = mkEnableOption "AutoMySQLBackup"; + enable = lib.mkEnableOption "AutoMySQLBackup"; - calendar = mkOption { - type = types.str; + calendar = lib.mkOption { + type = lib.types.str; default = "01:15:00"; description = '' Configured when to run the backup service systemd unit (DayOfWeek Year-Month-Day Hour:Minute:Second). ''; }; - settings = mkOption { + settings = lib.mkOption { type = - with types; + with lib.types; attrsOf (oneOf [ str int @@ -89,7 +70,7 @@ in {file}`''${pkgs.automysqlbackup}/etc/automysqlbackup.conf` for details on supported values. ''; - example = literalExpression '' + example = lib.literalExpression '' { db_names = [ "nextcloud" "matomo" ]; table_exclude = [ "nextcloud.oc_users" "nextcloud.oc_whats_new" ]; @@ -103,7 +84,7 @@ in }; # implementation - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { assertions = [ { @@ -112,7 +93,7 @@ in } ]; - services.automysqlbackup.config = mapAttrs (name: mkDefault) { + services.automysqlbackup.config = lib.mapAttrs (name: lib.mkDefault) { mysql_dump_username = user; mysql_dump_host = "localhost"; mysql_dump_socket = "/run/mysqld/mysqld.sock"; @@ -156,7 +137,7 @@ in ]; services.mysql.ensureUsers = - optional (config.services.mysql.enable && cfg.config.mysql_dump_host == "localhost") + lib.optional (config.services.mysql.enable && cfg.config.mysql_dump_host == "localhost") { name = user; ensurePermissions = { diff --git a/nixos/modules/services/backup/bacula.nix b/nixos/modules/services/backup/bacula.nix index a35350646c9be..1f63017d28eeb 100644 --- a/nixos/modules/services/backup/bacula.nix +++ b/nixos/modules/services/backup/bacula.nix @@ -9,32 +9,22 @@ # TODO: support sqlite3 (it's deprecate?) and mysql let - inherit (lib) - concatStringsSep - literalExpression - mapAttrsToList - mkIf - mkOption - optional - optionalString - types - ; libDir = "/var/lib/bacula"; yes_no = bool: if bool then "yes" else "no"; tls_conf = tls_cfg: - optionalString tls_cfg.enable ( - concatStringsSep "\n" ( + lib.optionalString tls_cfg.enable ( + lib.concatStringsSep "\n" ( [ "TLS Enable = yes;" ] - ++ optional (tls_cfg.require != null) "TLS Require = ${yes_no tls_cfg.require};" - ++ optional (tls_cfg.certificate != null) ''TLS Certificate = "${tls_cfg.certificate}";'' + ++ lib.optional (tls_cfg.require != null) "TLS Require = ${yes_no tls_cfg.require};" + ++ lib.optional (tls_cfg.certificate != null) ''TLS Certificate = "${tls_cfg.certificate}";'' ++ [ ''TLS Key = "${tls_cfg.key}";'' ] - ++ optional (tls_cfg.verifyPeer != null) "TLS Verify Peer = ${yes_no tls_cfg.verifyPeer};" - ++ optional ( + ++ lib.optional (tls_cfg.verifyPeer != null) "TLS Verify Peer = ${yes_no tls_cfg.verifyPeer};" + ++ lib.optional ( tls_cfg.allowedCN != [ ] - ) "TLS Allowed CN = ${concatStringsSep " " (tls_cfg.allowedCN)};" - ++ optional ( + ) "TLS Allowed CN = ${lib.concatStringsSep " " (tls_cfg.allowedCN)};" + ++ lib.optional ( tls_cfg.caCertificateFile != null ) ''TLS CA Certificate File = "${tls_cfg.caCertificateFile}";'' ) @@ -51,8 +41,8 @@ let ${tls_conf fd_cfg.tls} } - ${concatStringsSep "\n" ( - mapAttrsToList (name: value: '' + ${lib.concatStringsSep "\n" ( + lib.mapAttrsToList (name: value: '' Director { Name = "${name}"; Password = ${value.password}; @@ -80,11 +70,11 @@ let ${tls_conf sd_cfg.tls} } - ${concatStringsSep "\n" ( - mapAttrsToList (name: value: '' + ${lib.concatStringsSep "\n" ( + lib.mapAttrsToList (name: value: '' Autochanger { Name = "${name}"; - Device = ${concatStringsSep ", " (map (a: "\"${a}\"") value.devices)}; + Device = ${lib.concatStringsSep ", " (map (a: "\"${a}\"") value.devices)}; Changer Device = ${value.changerDevice}; Changer Command = ${value.changerCommand}; ${value.extraAutochangerConfig} @@ -92,8 +82,8 @@ let '') sd_cfg.autochanger )} - ${concatStringsSep "\n" ( - mapAttrsToList (name: value: '' + ${lib.concatStringsSep "\n" ( + lib.mapAttrsToList (name: value: '' Device { Name = "${name}"; Archive Device = ${value.archiveDevice}; @@ -103,8 +93,8 @@ let '') sd_cfg.device )} - ${concatStringsSep "\n" ( - mapAttrsToList (name: value: '' + ${lib.concatStringsSep "\n" ( + lib.mapAttrsToList (name: value: '' Director { Name = "${name}"; Password = ${value.password}; @@ -160,16 +150,16 @@ let { ... }: { options = { - enable = mkOption { - type = types.bool; + enable = lib.mkOption { + type = lib.types.bool; default = false; description = '' Specifies if TLS should be enabled. If this set to `false` TLS will be completely disabled, even if ${tlsLink "tls.require" submodulePath} is true. ''; }; - require = mkOption { - type = types.nullOr types.bool; + require = lib.mkOption { + type = lib.types.nullOr lib.types.bool; default = null; description = '' Require TLS or TLS-PSK encryption. @@ -181,8 +171,8 @@ let component will refuse any connection request that does not use TLS. ''; }; - certificate = mkOption { - type = types.nullOr types.path; + certificate = lib.mkOption { + type = lib.types.nullOr lib.types.path; default = null; description = '' The full path to the PEM encoded TLS certificate. @@ -193,15 +183,15 @@ let `false` in the corresponding server context. ''; }; - key = mkOption { - type = types.path; + key = lib.mkOption { + type = lib.types.path; description = '' The path of a PEM encoded TLS private key. It must correspond to the TLS certificate. ''; }; - verifyPeer = mkOption { - type = types.nullOr types.bool; + verifyPeer = lib.mkOption { + type = lib.types.nullOr lib.types.bool; default = null; description = '' Verify peer certificate. @@ -216,8 +206,8 @@ let Standard from Bacula is `true`. ''; }; - allowedCN = mkOption { - type = types.listOf types.str; + allowedCN = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; description = '' Common name attribute of allowed peer certificates. @@ -227,8 +217,8 @@ let CN list will not be checked if ${tlsLink "tls.verifyPeer" submodulePath} is false. ''; }; - caCertificateFile = mkOption { - type = types.nullOr types.path; + caCertificateFile = lib.mkOption { + type = lib.types.nullOr lib.types.path; default = null; description = '' The path specifying a PEM encoded TLS CA certificate(s). @@ -245,8 +235,8 @@ let { ... }: { options = { - password = mkOption { - type = types.str; + password = lib.mkOption { + type = lib.types.str; # TODO: required? description = '' Specifies the password that must be supplied for the default Bacula @@ -265,8 +255,8 @@ let ''; }; - monitor = mkOption { - type = types.enum [ + monitor = lib.mkOption { + type = lib.types.enum [ "no" "yes" ]; @@ -284,8 +274,8 @@ let ''; }; - tls = mkOption { - type = types.submodule (tlsOptions "${submodulePath}.director."); + tls = lib.mkOption { + type = lib.types.submodule (tlsOptions "${submodulePath}.director."); description = '' TLS Options for the Director in this Configuration. ''; @@ -297,8 +287,8 @@ let { ... }: { options = { - changerDevice = mkOption { - type = types.str; + changerDevice = lib.mkOption { + type = lib.types.str; description = '' The specified name-string must be the generic SCSI device name of the autochanger that corresponds to the normal read/write Archive Device @@ -310,14 +300,14 @@ let `/dev/sg0` for the Changer Device name. Depending on your exact configuration, and the number of autochangers or the type of autochanger, what you specify here can vary. This directive - is optional. See the Using AutochangersAutochangersChapter chapter of + is lib.optional. See the Using AutochangersAutochangersChapter chapter of this manual for more details of using this and the following autochanger directives. ''; }; - changerCommand = mkOption { - type = types.str; + changerCommand = lib.mkOption { + type = lib.types.str; description = '' The name-string specifies an external program to be called that will automatically change volumes as required by Bacula. Normally, this @@ -339,14 +329,14 @@ let default = "/etc/bacula/mtx-changer %c %o %S %a %d"; }; - devices = mkOption { + devices = lib.mkOption { description = ""; - type = types.listOf types.str; + type = lib.types.listOf lib.types.str; }; - extraAutochangerConfig = mkOption { + extraAutochangerConfig = lib.mkOption { default = ""; - type = types.lines; + type = lib.types.lines; description = '' Extra configuration to be passed in Autochanger directive. ''; @@ -361,9 +351,9 @@ let { ... }: { options = { - archiveDevice = mkOption { + archiveDevice = lib.mkOption { # TODO: required? - type = types.str; + type = lib.types.str; description = '' The specified name-string gives the system file name of the storage device managed by this storage daemon. This will usually be the @@ -378,9 +368,9 @@ let ''; }; - mediaType = mkOption { + mediaType = lib.mkOption { # TODO: required? - type = types.str; + type = lib.types.str; description = '' The specified name-string names the type of media supported by this device, for example, `DLT7000`. Media type names are @@ -416,9 +406,9 @@ let ''; }; - extraDeviceConfig = mkOption { + extraDeviceConfig = lib.mkOption { default = ""; - type = types.lines; + type = lib.types.lines; description = '' Extra configuration to be passed in Device directive. ''; @@ -438,18 +428,18 @@ in { options = { services.bacula-fd = { - enable = mkOption { - type = types.bool; + enable = lib.mkOption { + type = lib.types.bool; default = false; description = '' Whether to enable the Bacula File Daemon. ''; }; - name = mkOption { + name = lib.mkOption { default = "${config.networking.hostName}-fd"; - defaultText = literalExpression ''"''${config.networking.hostName}-fd"''; - type = types.str; + defaultText = lib.literalExpression ''"''${config.networking.hostName}-fd"''; + type = lib.types.str; description = '' The client name that must be used by the Director when connecting. Generally, it is a good idea to use a name related to the machine so @@ -458,9 +448,9 @@ in ''; }; - port = mkOption { + port = lib.mkOption { default = 9102; - type = types.port; + type = lib.types.port; description = '' This specifies the port number on which the Client listens for Director connections. It must agree with the FDPort specified in @@ -468,16 +458,16 @@ in ''; }; - director = mkOption { + director = lib.mkOption { default = { }; description = '' This option defines director resources in Bacula File Daemon. ''; - type = types.attrsOf (types.submodule (directorOptions "services.bacula-fd")); + type = lib.types.attrsOf (lib.types.submodule (directorOptions "services.bacula-fd")); }; - tls = mkOption { - type = types.submodule (tlsOptions "services.bacula-fd"); + tls = lib.mkOption { + type = lib.types.submodule (tlsOptions "services.bacula-fd"); default = { }; description = '' TLS Options for the File Daemon. @@ -485,9 +475,9 @@ in ''; }; - extraClientConfig = mkOption { + extraClientConfig = lib.mkOption { default = ""; - type = types.lines; + type = lib.types.lines; description = '' Extra configuration to be passed in Client directive. ''; @@ -497,9 +487,9 @@ in ''; }; - extraMessagesConfig = mkOption { + extraMessagesConfig = lib.mkOption { default = ""; - type = types.lines; + type = lib.types.lines; description = '' Extra configuration to be passed in Messages directive. ''; @@ -510,59 +500,59 @@ in }; services.bacula-sd = { - enable = mkOption { - type = types.bool; + enable = lib.mkOption { + type = lib.types.bool; default = false; description = '' Whether to enable Bacula Storage Daemon. ''; }; - name = mkOption { + name = lib.mkOption { default = "${config.networking.hostName}-sd"; - defaultText = literalExpression ''"''${config.networking.hostName}-sd"''; - type = types.str; + defaultText = lib.literalExpression ''"''${config.networking.hostName}-sd"''; + type = lib.types.str; description = '' Specifies the Name of the Storage daemon. ''; }; - port = mkOption { + port = lib.mkOption { default = 9103; - type = types.port; + type = lib.types.port; description = '' Specifies port number on which the Storage daemon listens for Director connections. ''; }; - director = mkOption { + director = lib.mkOption { default = { }; description = '' This option defines Director resources in Bacula Storage Daemon. ''; - type = types.attrsOf (types.submodule (directorOptions "services.bacula-sd")); + type = lib.types.attrsOf (lib.types.submodule (directorOptions "services.bacula-sd")); }; - device = mkOption { + device = lib.mkOption { default = { }; description = '' This option defines Device resources in Bacula Storage Daemon. ''; - type = types.attrsOf (types.submodule deviceOptions); + type = lib.types.attrsOf (lib.types.submodule deviceOptions); }; - autochanger = mkOption { + autochanger = lib.mkOption { default = { }; description = '' This option defines Autochanger resources in Bacula Storage Daemon. ''; - type = types.attrsOf (types.submodule autochangerOptions); + type = lib.types.attrsOf (lib.types.submodule autochangerOptions); }; - extraStorageConfig = mkOption { + extraStorageConfig = lib.mkOption { default = ""; - type = types.lines; + type = lib.types.lines; description = '' Extra configuration to be passed in Storage directive. ''; @@ -572,9 +562,9 @@ in ''; }; - extraMessagesConfig = mkOption { + extraMessagesConfig = lib.mkOption { default = ""; - type = types.lines; + type = lib.types.lines; description = '' Extra configuration to be passed in Messages directive. ''; @@ -582,8 +572,8 @@ in console = all ''; }; - tls = mkOption { - type = types.submodule (tlsOptions "services.bacula-sd"); + tls = lib.mkOption { + type = lib.types.submodule (tlsOptions "services.bacula-sd"); default = { }; description = '' TLS Options for the Storage Daemon. @@ -594,27 +584,27 @@ in }; services.bacula-dir = { - enable = mkOption { - type = types.bool; + enable = lib.mkOption { + type = lib.types.bool; default = false; description = '' Whether to enable Bacula Director Daemon. ''; }; - name = mkOption { + name = lib.mkOption { default = "${config.networking.hostName}-dir"; - defaultText = literalExpression ''"''${config.networking.hostName}-dir"''; - type = types.str; + defaultText = lib.literalExpression ''"''${config.networking.hostName}-dir"''; + type = lib.types.str; description = '' The director name used by the system administrator. This directive is required. ''; }; - port = mkOption { + port = lib.mkOption { default = 9101; - type = types.port; + type = lib.types.port; description = '' Specify the port (a positive integer) on which the Director daemon will listen for Bacula Console connections. This same port number @@ -625,17 +615,17 @@ in ''; }; - password = mkOption { + password = lib.mkOption { # TODO: required? - type = types.str; + type = lib.types.str; description = '' Specifies the password that must be supplied for a Director. ''; }; - extraMessagesConfig = mkOption { + extraMessagesConfig = lib.mkOption { default = ""; - type = types.lines; + type = lib.types.lines; description = '' Extra configuration to be passed in Messages directive. ''; @@ -644,9 +634,9 @@ in ''; }; - extraDirectorConfig = mkOption { + extraDirectorConfig = lib.mkOption { default = ""; - type = types.lines; + type = lib.types.lines; description = '' Extra configuration to be passed in Director directive. ''; @@ -656,9 +646,9 @@ in ''; }; - extraConfig = mkOption { + extraConfig = lib.mkOption { default = ""; - type = types.lines; + type = lib.types.lines; description = '' Extra configuration for Bacula Director Daemon. ''; @@ -667,8 +657,8 @@ in ''; }; - tls = mkOption { - type = types.submodule (tlsOptions "services.bacula-dir"); + tls = lib.mkOption { + type = lib.types.submodule (tlsOptions "services.bacula-dir"); default = { }; description = '' TLS Options for the Director. @@ -678,7 +668,7 @@ in }; }; - config = mkIf (fd_cfg.enable || sd_cfg.enable || dir_cfg.enable) { + config = lib.mkIf (fd_cfg.enable || sd_cfg.enable || dir_cfg.enable) { systemd.slices.system-bacula = { description = "Bacula Backup System Slice"; documentation = [ @@ -687,7 +677,7 @@ in ]; }; - systemd.services.bacula-fd = mkIf fd_cfg.enable { + systemd.services.bacula-fd = lib.mkIf fd_cfg.enable { after = [ "network.target" ]; description = "Bacula File Daemon"; wantedBy = [ "multi-user.target" ]; @@ -701,7 +691,7 @@ in }; }; - systemd.services.bacula-sd = mkIf sd_cfg.enable { + systemd.services.bacula-sd = lib.mkIf sd_cfg.enable { after = [ "network.target" ]; description = "Bacula Storage Daemon"; wantedBy = [ "multi-user.target" ]; @@ -717,7 +707,7 @@ in services.postgresql.enable = lib.mkIf dir_cfg.enable true; - systemd.services.bacula-dir = mkIf dir_cfg.enable { + systemd.services.bacula-dir = lib.mkIf dir_cfg.enable { after = [ "network.target" "postgresql.service" diff --git a/nixos/modules/services/backup/borgbackup.nix b/nixos/modules/services/backup/borgbackup.nix index c1594ff2086a2..04852d024ef3e 100644 --- a/nixos/modules/services/backup/borgbackup.nix +++ b/nixos/modules/services/backup/borgbackup.nix @@ -153,10 +153,10 @@ let }: pkgs.runCommand "${name}-wrapper" { nativeBuildInputs = [ pkgs.makeWrapper ]; - } (with lib; '' + } '' makeWrapper "${original}" "$out/bin/${name}" \ ${lib.concatStringsSep " \\\n " (lib.mapAttrsToList (name: value: ''--set ${name} "${value}"'') set)} - ''); + ''; mkBorgWrapper = name: cfg: mkWrapperDrv { original = lib.getExe config.services.borgbackup.package; @@ -444,9 +444,9 @@ in { }; compression = lib.mkOption { - # "auto" is optional, + # "auto" is lib.optional, # compression mode must be given, - # compression level is optional + # compression level is lib.optional type = lib.types.strMatching "none|(auto,)?(lz4|zstd|zlib|lzma)(,[[:digit:]]{1,2})?"; description = '' Compression method to use. Refer to diff --git a/nixos/modules/services/backup/borgmatic.nix b/nixos/modules/services/backup/borgmatic.nix index c05fe208acb30..fbb92426d6edf 100644 --- a/nixos/modules/services/backup/borgmatic.nix +++ b/nixos/modules/services/backup/borgmatic.nix @@ -50,7 +50,7 @@ let default = [ ]; description = '' A required list of local or remote repositories with paths and - optional labels (which can be used with the --repository flag to + lib.optional labels (which can be used with the --repository flag to select a repository). Tildes are expanded. Multiple repositories are backed up to in sequence. Borg placeholders can be used. See the output of "borg help placeholders" for details. See ssh_command for diff --git a/nixos/modules/services/backup/btrbk.nix b/nixos/modules/services/backup/btrbk.nix index 03cf7d08fa5ae..41e40e30e998e 100644 --- a/nixos/modules/services/backup/btrbk.nix +++ b/nixos/modules/services/backup/btrbk.nix @@ -5,26 +5,6 @@ ... }: let - inherit (lib) - concatLists - concatMap - concatMapStringsSep - concatStringsSep - filterAttrs - flatten - getAttr - isAttrs - literalExpression - mapAttrs' - mapAttrsToList - mkIf - mkOption - optional - optionalString - sortOn - types - ; - # The priority of an option or section. # The configurations format are order-sensitive. Pairs are added as children of # the last sections if possible, otherwise, they start a new section. @@ -35,7 +15,7 @@ let # 4. Etc. prioOf = { name, value }: - if !isAttrs value then + if !lib.isAttrs value then 0 # Leaf options. else { @@ -45,23 +25,23 @@ let } .${name} or (throw "Unknow section '${name}'"); - genConfig' = set: concatStringsSep "\n" (genConfig set); + genConfig' = set: lib.concatStringsSep "\n" (genConfig set); genConfig = set: let - pairs = mapAttrsToList (name: value: { inherit name value; }) set; - sortedPairs = sortOn prioOf pairs; + pairs = lib.mapAttrsToList (name: value: { inherit name value; }) set; + sortedPairs = lib.sortOn prioOf pairs; in - concatMap genPair sortedPairs; + lib.concatMap genPair sortedPairs; genSection = sec: secName: value: [ "${sec} ${secName}" ] ++ map (x: " " + x) (genConfig value); genPair = { name, value }: - if !isAttrs value then + if !lib.isAttrs value then [ "${name} ${value}" ] else - concatLists (mapAttrsToList (genSection name) value); + lib.concatLists (lib.mapAttrsToList (genSection name) value); sudoRule = { users = [ "btrbk" ]; @@ -144,7 +124,7 @@ in options = { services.btrbk = { - extraPackages = mkOption { + extraPackages = lib.mkOption { description = '' Extra packages for btrbk, like compression utilities for `stream_compress`. @@ -153,40 +133,39 @@ in depending on configured compression method in `services.btrbk.instances..settings` option. ''; - type = types.listOf types.package; + type = lib.types.listOf lib.types.package; default = [ ]; - example = literalExpression "[ pkgs.xz ]"; + example = lib.literalExpression "[ pkgs.xz ]"; }; - niceness = mkOption { + niceness = lib.mkOption { description = "Niceness for local instances of btrbk. Also applies to remote ones connecting via ssh when positive."; - type = types.ints.between (-20) 19; + type = lib.types.ints.between (-20) 19; default = 10; }; - ioSchedulingClass = mkOption { + ioSchedulingClass = lib.mkOption { description = "IO scheduling class for btrbk (see ionice(1) for a quick description). Applies to local instances, and remote ones connecting by ssh if set to idle."; - type = types.enum [ + type = lib.types.enum [ "idle" "best-effort" "realtime" ]; default = "best-effort"; }; - instances = mkOption { + instances = lib.mkOption { description = "Set of btrbk instances. The instance named `btrbk` is the default one."; type = - with types; - attrsOf (submodule { + lib.types.attrsOf (lib.types.submodule { options = { - onCalendar = mkOption { - type = types.nullOr types.str; + onCalendar = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = "daily"; description = '' How often this btrbk instance is started. See systemd.time(7) for more information about the format. Setting it to null disables the timer, thus this instance can only be started manually. ''; }; - snapshotOnly = mkOption { - type = types.bool; + snapshotOnly = lib.mkOption { + type = lib.types.bool; default = false; description = '' Whether to run in snapshot only mode. This skips backup creation and deletion steps. @@ -196,22 +175,22 @@ in See also `snapshot` subcommand in {manpage}`btrbk(1)`. ''; }; - settings = mkOption { - type = types.submodule { + settings = lib.mkOption { + type = lib.types.submodule { freeformType = let - t = types.attrsOf ( - types.either types.str (t // { description = "instances of this type recursively"; }) + t = lib.types.types.attrsOf ( + lib.types.types.either lib.types.types.str (t // { description = "instances of this type recursively"; }) ); in t; options = { - stream_compress = mkOption { + stream_compress = lib.mkOption { description = '' Compress the btrfs send stream before transferring it from/to remote locations using a compression command. ''; - type = types.enum [ + type = lib.types.enum [ "gzip" "pigz" "bzip2" @@ -249,18 +228,17 @@ in }); default = { }; }; - sshAccess = mkOption { + sshAccess = lib.mkOption { description = "SSH keys that should be able to make or push snapshots on this system remotely with btrbk"; type = - with types; - listOf (submodule { + lib.types.listOf (lib.types.submodule { options = { - key = mkOption { - type = str; + key = lib.mkOption { + type = lib.types.str; description = "SSH public key allowed to login as user `btrbk` to run remote backups."; }; - roles = mkOption { - type = listOf (enum [ + roles = lib.mkOption { + type = lib.types.listOf (lib.types.enum [ "info" "source" "target" @@ -283,14 +261,14 @@ in }; }; - config = mkIf (sshEnabled || serviceEnabled) { + config = lib.mkIf (sshEnabled || serviceEnabled) { environment.systemPackages = [ pkgs.btrbk ] ++ cfg.extraPackages; - security.sudo.extraRules = mkIf (sudo_doas == "sudo") [ sudoRule ]; - security.sudo-rs.extraRules = mkIf (sudo_doas == "sudo") [ sudoRule ]; + security.sudo.extraRules = lib.mkIf (sudo_doas == "sudo") [ sudoRule ]; + security.sudo-rs.extraRules = lib.mkIf (sudo_doas == "sudo") [ sudoRule ]; - security.doas = mkIf (sudo_doas == "doas") { + security.doas = lib.mkIf (sudo_doas == "doas") { extraRules = let doasCmdNoPass = cmd: { @@ -324,7 +302,7 @@ in openssh.authorizedKeys.keys = map ( v: let - options = concatMapStringsSep " " (x: "--" + x) v.roles; + options = lib.concatMapStringsSep " " (x: "--" + x) v.roles; ioniceClass = { "idle" = 3; @@ -335,7 +313,7 @@ in sudo_doas_flag = "--${sudo_doas}"; in ''command="${pkgs.util-linux}/bin/ionice -t -c ${toString ioniceClass} ${ - optionalString (cfg.niceness >= 1) "${pkgs.coreutils}/bin/nice -n ${toString cfg.niceness}" + lib.optionalString (cfg.niceness >= 1) "${pkgs.coreutils}/bin/nice -n ${toString cfg.niceness}" } ${pkgs.btrbk}/share/btrbk/scripts/ssh_filter_btrbk.sh ${sudo_doas_flag} ${options}" ${v.key}'' ) cfg.sshAccess; }; @@ -345,11 +323,11 @@ in "d /var/lib/btrbk/.ssh 0700 btrbk btrbk" "f /var/lib/btrbk/.ssh/config 0700 btrbk btrbk - StrictHostKeyChecking=accept-new" ]; - environment.etc = mapAttrs' (name: instance: { + environment.etc = lib.mapAttrs' (name: instance: { name = "btrbk/${name}.conf"; value.source = mkConfigFile name instance.settings; }) cfg.instances; - systemd.services = mapAttrs' (name: instance: { + systemd.services = lib.mapAttrs' (name: instance: { name = "btrbk-${name}"; value = { description = "Takes BTRFS snapshots and maintains retention policies."; @@ -357,8 +335,8 @@ in path = [ "/run/wrappers" ] ++ cfg.extraPackages - ++ optional (instance.settings.stream_compress != "no") ( - getAttr instance.settings.stream_compress streamCompressMap + ++ lib.optional (instance.settings.stream_compress != "no") ( + lib.getAttr instance.settings.stream_compress streamCompressMap ); serviceConfig = { User = "btrbk"; @@ -374,7 +352,7 @@ in }; }) cfg.instances; - systemd.timers = mapAttrs' (name: instance: { + systemd.timers = lib.mapAttrs' (name: instance: { name = "btrbk-${name}"; value = { description = "Timer to take BTRFS snapshots and maintain retention policies."; @@ -385,7 +363,7 @@ in Persistent = true; }; }; - }) (filterAttrs (name: instance: instance.onCalendar != null) cfg.instances); + }) (lib.filterAttrs (name: instance: instance.onCalendar != null) cfg.instances); }; } diff --git a/nixos/modules/services/backup/mysql-backup.nix b/nixos/modules/services/backup/mysql-backup.nix index b30579103699e..a4ede69627bea 100644 --- a/nixos/modules/services/backup/mysql-backup.nix +++ b/nixos/modules/services/backup/mysql-backup.nix @@ -106,7 +106,6 @@ in { name = cfg.user; ensurePermissions = - with lib; let privs = "SELECT, SHOW VIEW, TRIGGER, LOCK TABLES"; grant = db: lib.nameValuePair "${db}.*" privs; diff --git a/nixos/modules/services/backup/tsm.nix b/nixos/modules/services/backup/tsm.nix index 697f798b7fcfa..e4d1ac1bbdbf9 100644 --- a/nixos/modules/services/backup/tsm.nix +++ b/nixos/modules/services/backup/tsm.nix @@ -2,21 +2,15 @@ let - inherit (lib.attrsets) hasAttr; - inherit (lib.meta) getExe'; - inherit (lib.modules) mkDefault mkIf; - inherit (lib.options) mkEnableOption mkOption; - inherit (lib.types) nonEmptyStr nullOr; - options.services.tsmBackup = { - enable = mkEnableOption '' + enable = lib.mkEnableOption '' automatic backups with the IBM Storage Protect (Tivoli Storage Manager, TSM) client. This also enables {option}`programs.tsmClient.enable` ''; - command = mkOption { - type = nonEmptyStr; + command = lib.mkOption { + type = lib.types.nonEmptyStr; default = "backup"; example = "incr"; description = '' @@ -24,8 +18,8 @@ let `dsmc` executable to start the backup. ''; }; - servername = mkOption { - type = nonEmptyStr; + servername = lib.mkOption { + type = lib.types.nonEmptyStr; example = "mainTsmServer"; description = '' Create a systemd system service @@ -41,8 +35,8 @@ let `dsmc`. ''; }; - autoTime = mkOption { - type = nullOr nonEmptyStr; + autoTime = lib.mkOption { + type = lib.types.nullOr lib.types.nonEmptyStr; default = null; example = "12:00"; description = '' @@ -61,7 +55,7 @@ let assertions = [ { - assertion = hasAttr cfg.servername cfgPrg.servers; + assertion = lib.types.hasAttr cfg.servername cfgPrg.servers; message = "TSM service servername not found in list of servers"; } { @@ -76,10 +70,10 @@ in inherit options; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { inherit assertions; programs.tsmClient.enable = true; - programs.tsmClient.servers.${cfg.servername}.passworddir = mkDefault "/var/lib/tsm-backup/password"; + programs.tsmClient.servers.${cfg.servername}.passworddir = lib.mkDefault "/var/lib/tsm-backup/password"; systemd.services.tsm-backup = { description = "IBM Storage Protect (Tivoli Storage Manager) Backup"; # DSM_LOG needs a trailing slash to have it treated as a directory. @@ -93,7 +87,7 @@ in SuccessExitStatus = "4 8"; # The `-se` option must come after the command. # The `-optfile` option suppresses a `dsm.opt`-not-found warning. - ExecStart = "${getExe' cfgPrg.wrappedPackage "dsmc"} ${cfg.command} -se='${cfg.servername}' -optfile=/dev/null"; + ExecStart = "${lib.types.getExe' cfgPrg.wrappedPackage "dsmc"} ${cfg.command} -se='${cfg.servername}' -optfile=/dev/null"; LogsDirectory = "tsm-backup"; StateDirectory = "tsm-backup"; StateDirectoryMode = "0750"; @@ -115,7 +109,7 @@ in RestrictNamespaces = true; RestrictSUIDSGID = true; }; - startAt = mkIf (cfg.autoTime != null) cfg.autoTime; + startAt = lib.mkIf (cfg.autoTime != null) cfg.autoTime; }; }; diff --git a/nixos/modules/services/cluster/druid/default.nix b/nixos/modules/services/cluster/druid/default.nix index d22a3f2236787..262eab1124f34 100644 --- a/nixos/modules/services/cluster/druid/default.nix +++ b/nixos/modules/services/cluster/druid/default.nix @@ -6,25 +6,12 @@ }: let cfg = config.services.druid; - inherit (lib) - concatStrings - concatStringsSep - mapAttrsToList - concatMap - attrByPath - mkIf - mkMerge - mkEnableOption - mkOption - types - mkPackageOption - ; druidServiceOption = serviceName: { - enable = mkEnableOption serviceName; + enable = lib.mkEnableOption serviceName; - restartIfChanged = mkOption { - type = types.bool; + restartIfChanged = lib.mkOption { + type = lib.types.bool; description = '' Automatically restart the service on config change. This can be set to false to defer restarts on clusters running critical applications. @@ -34,9 +21,9 @@ let default = false; }; - config = mkOption { + config = lib.mkOption { default = { }; - type = types.attrsOf types.anything; + type = lib.types.attrsOf lib.types.anything; description = '' (key=value) Configuration to be written to runtime.properties of the druid ${serviceName} @@ -47,23 +34,23 @@ let }; }; - jdk = mkPackageOption pkgs "JDK" { default = [ "jdk17_headless" ]; }; + jdk = lib.mkPackageOption pkgs "JDK" { default = [ "jdk17_headless" ]; }; - jvmArgs = mkOption { - type = types.str; + jvmArgs = lib.mkOption { + type = lib.types.str; default = ""; description = "Arguments to pass to the JVM"; }; - openFirewall = mkOption { - type = types.bool; + openFirewall = lib.mkOption { + type = lib.types.bool; default = false; description = "Open firewall ports for ${serviceName}."; }; - internalConfig = mkOption { + internalConfig = lib.mkOption { default = { }; - type = types.attrsOf types.anything; + type = lib.types.attrsOf lib.types.anything; internal = true; description = "Internal Option to add to runtime.properties for ${serviceName}."; }; @@ -77,7 +64,7 @@ let tmpDirs ? [ ], extraConfig ? { }, }: - (mkIf serviceOptions.enable (mkMerge [ + (lib.mkIf serviceOptions.enable (lib.mkMerge [ { systemd = { services."druid-${name}" = { @@ -99,16 +86,16 @@ let cfgFile = fileName: properties: pkgs.writeTextDir fileName ( - concatStringsSep "\n" (mapAttrsToList (n: v: "${n}=${toString v}") properties) + lib.concatStringsSep "\n" (lib.mapAttrsToList (n: v: "${n}=${toString v}") properties) ); commonConfigFile = cfgFile "common.runtime.properties" cfg.commonConfig; configFile = cfgFile "runtime.properties" (serviceOptions.config // serviceOptions.internalConfig); - extraClassPath = concatStrings (map (path: ":" + path) cfg.extraClassPaths); + extraClassPath = lib.concatStrings (map (path: ":" + path) cfg.extraClassPaths); - extraConfDir = concatStrings (map (dir: ":" + dir + "/*") cfg.extraConfDirs); + extraConfDir = lib.concatStrings (map (dir: ":" + dir + "/*") cfg.extraConfDirs); in '' run-java -Dlog4j.configurationFile=file:${cfg.log4j} \ @@ -126,9 +113,9 @@ let }; }; - tmpfiles.rules = concatMap (x: [ "d ${x} 0755 druid druid" ]) (cfg.commonTmpDirs ++ tmpDirs); + tmpfiles.rules = lib.concatMap (x: [ "d ${x} 0755 druid druid" ]) (cfg.commonTmpDirs ++ tmpDirs); }; - networking.firewall.allowedTCPPorts = mkIf (attrByPath [ + networking.firewall.allowedTCPPorts = lib.mkIf (lib.attrByPath [ "openFirewall" ] false serviceOptions) allowedTCPPorts; @@ -146,12 +133,12 @@ let in { options.services.druid = { - package = mkPackageOption pkgs "apache-druid" { default = [ "druid" ]; }; + package = lib.mkPackageOption pkgs "apache-druid" { default = [ "druid" ]; }; - commonConfig = mkOption { + commonConfig = lib.mkOption { default = { }; - type = types.attrsOf types.anything; + type = lib.types.attrsOf lib.types.anything; description = "(key=value) Configuration to be written to common.runtime.properties"; @@ -163,26 +150,26 @@ in }; }; - commonTmpDirs = mkOption { + commonTmpDirs = lib.mkOption { default = [ "/var/log/druid/requests" ]; - type = types.listOf types.str; + type = lib.types.listOf lib.types.str; description = "Common List of directories used by druid processes"; }; - log4j = mkOption { - type = types.path; + log4j = lib.mkOption { + type = lib.types.path; description = "Log4j Configuration for the druid process"; }; - extraClassPaths = mkOption { + extraClassPaths = lib.mkOption { default = [ ]; - type = types.listOf types.str; + type = lib.types.listOf lib.types.str; description = "Extra classpath to include in the jvm"; }; - extraConfDirs = mkOption { + extraConfDirs = lib.mkOption { default = [ ]; - type = types.listOf types.path; + type = lib.types.listOf lib.types.path; description = "Extra Conf Dirs to include in the jvm"; }; @@ -193,29 +180,28 @@ in broker = druidServiceOption "Druid Broker"; historical = (druidServiceOption "Druid Historical") // { - segmentLocations = mkOption { + segmentLocations = lib.mkOption { default = null; description = "Locations where the historical will store its data."; type = - with types; - nullOr ( - listOf (submodule { + lib.types.nullOr ( + lib.types.listOf (lib.types.submodule { options = { - path = mkOption { - type = path; + path = lib.mkOption { + type = lib.types.path; description = "the path to store the segments"; }; - maxSize = mkOption { - type = str; + maxSize = lib.mkOption { + type = lib.types.str; description = "Max size the druid historical can occupy"; }; - freeSpacePercent = mkOption { - type = float; + freeSpacePercent = lib.mkOption { + type = lib.types.float; default = 1.0; description = "Druid Historical will fail to write if it exceeds this value"; }; @@ -229,33 +215,33 @@ in middleManager = druidServiceOption "Druid middleManager"; router = druidServiceOption "Druid Router"; }; - config = mkMerge [ + config = lib.mkMerge [ (druidServiceConfig rec { name = "overlord"; - allowedTCPPorts = [ (attrByPath [ "druid.plaintextPort" ] 8090 cfg."${name}".config) ]; + allowedTCPPorts = [ (lib.attrByPath [ "druid.plaintextPort" ] 8090 cfg."${name}".config) ]; }) (druidServiceConfig rec { name = "coordinator"; - allowedTCPPorts = [ (attrByPath [ "druid.plaintextPort" ] 8081 cfg."${name}".config) ]; + allowedTCPPorts = [ (lib.attrByPath [ "druid.plaintextPort" ] 8081 cfg."${name}".config) ]; }) (druidServiceConfig rec { name = "broker"; - tmpDirs = [ (attrByPath [ "druid.lookup.snapshotWorkingDir" ] "" cfg."${name}".config) ]; + tmpDirs = [ (lib.attrByPath [ "druid.lookup.snapshotWorkingDir" ] "" cfg."${name}".config) ]; - allowedTCPPorts = [ (attrByPath [ "druid.plaintextPort" ] 8082 cfg."${name}".config) ]; + allowedTCPPorts = [ (lib.attrByPath [ "druid.plaintextPort" ] 8082 cfg."${name}".config) ]; }) (druidServiceConfig rec { name = "historical"; tmpDirs = [ - (attrByPath [ "druid.lookup.snapshotWorkingDir" ] "" cfg."${name}".config) + (lib.attrByPath [ "druid.lookup.snapshotWorkingDir" ] "" cfg."${name}".config) ] ++ (map (x: x.path) cfg."${name}".segmentLocations); - allowedTCPPorts = [ (attrByPath [ "druid.plaintextPort" ] 8083 cfg."${name}".config) ]; + allowedTCPPorts = [ (lib.attrByPath [ "druid.plaintextPort" ] 8083 cfg."${name}".config) ]; extraConfig.services.druid.historical.internalConfig."druid.segmentCache.locations" = builtins.toJSON cfg.historical.segmentLocations; @@ -266,22 +252,22 @@ in tmpDirs = [ "/var/log/druid/indexer" - ] ++ [ (attrByPath [ "druid.indexer.task.baseTaskDir" ] "" cfg."${name}".config) ]; + ] ++ [ (lib.attrByPath [ "druid.indexer.task.baseTaskDir" ] "" cfg."${name}".config) ]; - allowedTCPPorts = [ (attrByPath [ "druid.plaintextPort" ] 8091 cfg."${name}".config) ]; + allowedTCPPorts = [ (lib.attrByPath [ "druid.plaintextPort" ] 8091 cfg."${name}".config) ]; extraConfig = { services.druid.middleManager.internalConfig = { "druid.indexer.runner.javaCommand" = "${cfg.middleManager.jdk}/bin/java"; "druid.indexer.runner.javaOpts" = - (attrByPath [ "druid.indexer.runner.javaOpts" ] "" cfg.middleManager.config) + (lib.attrByPath [ "druid.indexer.runner.javaOpts" ] "" cfg.middleManager.config) + " -Dlog4j.configurationFile=file:${cfg.log4j}"; }; - networking.firewall.allowedTCPPortRanges = mkIf cfg.middleManager.openFirewall [ + networking.firewall.allowedTCPPortRanges = lib.mkIf cfg.middleManager.openFirewall [ { - from = attrByPath [ "druid.indexer.runner.startPort" ] 8100 cfg.middleManager.config; - to = attrByPath [ "druid.indexer.runner.endPort" ] 65535 cfg.middleManager.config; + from = lib.attrByPath [ "druid.indexer.runner.startPort" ] 8100 cfg.middleManager.config; + to = lib.attrByPath [ "druid.indexer.runner.endPort" ] 65535 cfg.middleManager.config; } ]; }; @@ -290,7 +276,7 @@ in (druidServiceConfig rec { name = "router"; - allowedTCPPorts = [ (attrByPath [ "druid.plaintextPort" ] 8888 cfg."${name}".config) ]; + allowedTCPPorts = [ (lib.attrByPath [ "druid.plaintextPort" ] 8888 cfg."${name}".config) ]; }) ]; diff --git a/nixos/modules/services/cluster/hadoop/hbase.nix b/nixos/modules/services/cluster/hadoop/hbase.nix index 1d63530406c28..d1b3eff9fae48 100644 --- a/nixos/modules/services/cluster/hadoop/hbase.nix +++ b/nixos/modules/services/cluster/hadoop/hbase.nix @@ -215,7 +215,7 @@ in environment.systemPackages = lib.mkIf cfg.gatewayRole.enableHbaseCli [ cfg.hbase.package ]; services.hadoop.hbaseSiteInternal = with cfg.hbase; { - "hbase.zookeeper.quorum" = mkIfNotNull zookeeperQuorum; + "hbase.zookeeper.quorum" = lib.mkIfNotNull zookeeperQuorum; }; users.users.hbase = { diff --git a/nixos/modules/services/cluster/hadoop/yarn.nix b/nixos/modules/services/cluster/hadoop/yarn.nix index b21a4ca5c277f..91c9a422a3f27 100644 --- a/nixos/modules/services/cluster/hadoop/yarn.nix +++ b/nixos/modules/services/cluster/hadoop/yarn.nix @@ -190,7 +190,7 @@ in with cfg.yarn.nodemanager; lib.mkMerge [ ({ - "yarn.nodemanager.local-dirs" = lib.mkIf (localDir != null) (concatStringsSep "," localDir); + "yarn.nodemanager.local-dirs" = lib.mkIf (localDir != null) (lib.concatStringsSep "," localDir); "yarn.scheduler.maximum-allocation-vcores" = resource.maximumAllocationVCores; "yarn.scheduler.maximum-allocation-mb" = resource.maximumAllocationMB; "yarn.nodemanager.resource.cpu-vcores" = resource.cpuVCores; diff --git a/nixos/modules/services/cluster/kubernetes/apiserver.nix b/nixos/modules/services/cluster/kubernetes/apiserver.nix index e05bcb37e819f..d89d517e86955 100644 --- a/nixos/modules/services/cluster/kubernetes/apiserver.nix +++ b/nixos/modules/services/cluster/kubernetes/apiserver.nix @@ -120,26 +120,26 @@ in servers = lib.mkOption { description = "List of etcd servers."; default = ["http://127.0.0.1:2379"]; - type = types.listOf types.str; + type = lib.types.listOf lib.types.str; }; keyFile = lib.mkOption { description = "Etcd key file."; default = null; - type = types.nullOr types.path; + type = lib.types.nullOr lib.types.path; }; certFile = lib.mkOption { description = "Etcd cert file."; default = null; - type = types.nullOr types.path; + type = lib.types.nullOr lib.types.path; }; caFile = lib.mkOption { description = "Etcd ca file."; default = top.caFile; defaultText = lib.literalExpression "config.${otop.caFile}"; - type = types.nullOr types.path; + type = lib.types.nullOr lib.types.path; }; }; diff --git a/nixos/modules/services/cluster/kubernetes/default.nix b/nixos/modules/services/cluster/kubernetes/default.nix index 86e5e072aa061..cfda7a4444498 100644 --- a/nixos/modules/services/cluster/kubernetes/default.nix +++ b/nixos/modules/services/cluster/kubernetes/default.nix @@ -169,7 +169,7 @@ in apiserverAddress = lib.mkOption { description = '' Clusterwide accessible address for the kubernetes apiserver, - including protocol and optional port. + including protocol and lib.optional port. ''; example = "https://kubernetes-apiserver.example.com:6443"; type = lib.types.str; diff --git a/nixos/modules/services/cluster/kubernetes/kubelet.nix b/nixos/modules/services/cluster/kubernetes/kubelet.nix index aa759e20f49fc..129084e74b83d 100644 --- a/nixos/modules/services/cluster/kubernetes/kubelet.nix +++ b/nixos/modules/services/cluster/kubernetes/kubelet.nix @@ -6,8 +6,6 @@ ... }: -with lib; - let top = config.services.kubernetes; otop = options.services.kubernetes; @@ -21,7 +19,7 @@ let else (pkgs.buildEnv { name = "kubernetes-cni-config"; - paths = imap ( + paths = lib.imap ( i: entry: pkgs.writeTextDir "${toString (10 + i)}-${entry.type}.conf" (builtins.toJSON entry) ) cfg.cni.config; }); @@ -86,17 +84,17 @@ let { name, ... }: { options = { - key = mkOption { + key = lib.mkOption { description = "Key of taint."; default = name; defaultText = literalMD "Name of this submodule."; type = str; }; - value = mkOption { + value = lib.mkOption { description = "Value of taint."; type = str; }; - effect = mkOption { + effect = lib.mkOption { description = "Effect of taint."; example = "NoSchedule"; type = enum [ @@ -108,60 +106,60 @@ let }; }; - taints = concatMapStringsSep "," (v: "${v.key}=${v.value}:${v.effect}") ( - mapAttrsToList (n: v: v) cfg.taints + taints = lib.concatMapStringsSep "," (v: "${v.key}=${v.value}:${v.effect}") ( + lib.mapAttrsToList (n: v: v) cfg.taints ); in { imports = [ - (mkRemovedOptionModule [ "services" "kubernetes" "kubelet" "applyManifests" ] "") - (mkRemovedOptionModule [ "services" "kubernetes" "kubelet" "cadvisorPort" ] "") - (mkRemovedOptionModule [ "services" "kubernetes" "kubelet" "allowPrivileged" ] "") - (mkRemovedOptionModule [ "services" "kubernetes" "kubelet" "networkPlugin" ] "") - (mkRemovedOptionModule [ "services" "kubernetes" "kubelet" "containerRuntime" ] "") + (lib.mkRemovedOptionModule [ "services" "kubernetes" "kubelet" "applyManifests" ] "") + (lib.mkRemovedOptionModule [ "services" "kubernetes" "kubelet" "cadvisorPort" ] "") + (lib.mkRemovedOptionModule [ "services" "kubernetes" "kubelet" "allowPrivileged" ] "") + (lib.mkRemovedOptionModule [ "services" "kubernetes" "kubelet" "networkPlugin" ] "") + (lib.mkRemovedOptionModule [ "services" "kubernetes" "kubelet" "containerRuntime" ] "") ]; ###### interface options.services.kubernetes.kubelet = with lib.types; { - address = mkOption { + address = lib.mkOption { description = "Kubernetes kubelet info server listening address."; default = "0.0.0.0"; type = str; }; - clusterDns = mkOption { + clusterDns = lib.mkOption { description = "Use alternative DNS."; default = [ "10.1.0.1" ]; type = listOf str; }; - clusterDomain = mkOption { + clusterDomain = lib.mkOption { description = "Use alternative domain."; default = config.services.kubernetes.addons.dns.clusterDomain; - defaultText = literalExpression "config.${options.services.kubernetes.addons.dns.clusterDomain}"; + defaultText = lib.literalExpression "config.${options.services.kubernetes.addons.dns.clusterDomain}"; type = str; }; - clientCaFile = mkOption { + clientCaFile = lib.mkOption { description = "Kubernetes apiserver CA file for client authentication."; default = top.caFile; - defaultText = literalExpression "config.${otop.caFile}"; + defaultText = lib.literalExpression "config.${otop.caFile}"; type = nullOr path; }; cni = { - packages = mkOption { + packages = lib.mkOption { description = "List of network plugin packages to install."; type = listOf package; default = [ ]; }; - config = mkOption { + config = lib.mkOption { description = "Kubernetes CNI configuration."; type = listOf attrs; default = [ ]; - example = literalExpression '' + example = lib.literalExpression '' [{ "cniVersion": "0.3.1", "name": "mynet", @@ -183,28 +181,28 @@ in ''; }; - configDir = mkOption { + configDir = lib.mkOption { description = "Path to Kubernetes CNI configuration directory."; type = nullOr path; default = null; }; }; - containerRuntimeEndpoint = mkOption { + containerRuntimeEndpoint = lib.mkOption { description = "Endpoint at which to find the container runtime api interface/socket"; type = str; default = "unix:///run/containerd/containerd.sock"; }; - enable = mkEnableOption "Kubernetes kubelet"; + enable = lib.mkEnableOption "Kubernetes kubelet"; - extraOpts = mkOption { + extraOpts = lib.mkOption { description = "Kubernetes kubelet extra command line options."; default = ""; type = separatedString " "; }; - extraConfig = mkOption { + extraConfig = lib.mkOption { description = '' Kubernetes kubelet extra configuration file entries. @@ -215,90 +213,90 @@ in type = attrsOf ((pkgs.formats.json { }).type); }; - featureGates = mkOption { + featureGates = lib.mkOption { description = "Attribute set of feature gate"; default = top.featureGates; - defaultText = literalExpression "config.${otop.featureGates}"; + defaultText = lib.literalExpression "config.${otop.featureGates}"; type = attrsOf bool; }; healthz = { - bind = mkOption { + bind = lib.mkOption { description = "Kubernetes kubelet healthz listening address."; default = "127.0.0.1"; type = str; }; - port = mkOption { + port = lib.mkOption { description = "Kubernetes kubelet healthz port."; default = 10248; type = port; }; }; - hostname = mkOption { + hostname = lib.mkOption { description = "Kubernetes kubelet hostname override."; - defaultText = literalExpression "config.networking.fqdnOrHostName"; + defaultText = lib.literalExpression "config.networking.fqdnOrHostName"; type = str; }; kubeconfig = top.lib.mkKubeConfigOptions "Kubelet"; - manifests = mkOption { + manifests = lib.mkOption { description = "List of manifests to bootstrap with kubelet (only pods can be created as manifest entry)"; type = attrsOf attrs; default = { }; }; - nodeIp = mkOption { + nodeIp = lib.mkOption { description = "IP address of the node. If set, kubelet will use this IP address for the node."; default = null; type = nullOr str; }; - registerNode = mkOption { + registerNode = lib.mkOption { description = "Whether to auto register kubelet with API server."; default = true; type = bool; }; - port = mkOption { + port = lib.mkOption { description = "Kubernetes kubelet info server listening port."; default = 10250; type = port; }; - seedDockerImages = mkOption { + seedDockerImages = lib.mkOption { description = "List of docker images to preload on system"; default = [ ]; type = listOf package; }; - taints = mkOption { + taints = lib.mkOption { description = "Node taints (https://kubernetes.io/docs/concepts/configuration/assign-pod-node/)."; default = { }; type = attrsOf (submodule [ taintOptions ]); }; - tlsCertFile = mkOption { + tlsCertFile = lib.mkOption { description = "File containing x509 Certificate for HTTPS."; default = null; type = nullOr path; }; - tlsKeyFile = mkOption { + tlsKeyFile = lib.mkOption { description = "File containing x509 private key matching tlsCertFile."; default = null; type = nullOr path; }; - unschedulable = mkOption { + unschedulable = lib.mkOption { description = "Whether to set node taint to unschedulable=true as it is the case of node that has only master role."; default = false; type = bool; }; - verbosity = mkOption { + verbosity = lib.mkOption { description = '' Optional glog verbosity level for logging statements. See @@ -310,8 +308,8 @@ in }; ###### implementation - config = mkMerge [ - (mkIf cfg.enable { + config = lib.mkMerge [ + (lib.mkIf cfg.enable { environment.etc."cni/net.d".source = cniConfig; @@ -346,7 +344,7 @@ in ++ lib.optional config.boot.zfs.enabled config.boot.zfs.package ++ top.path; preStart = '' - ${concatMapStrings (img: '' + ${lib.concatMapStrings (img: '' echo "Seeding container image: ${img}" ${ if (lib.hasSuffix "gz" img) then @@ -357,7 +355,7 @@ in '') cfg.seedDockerImages} rm /opt/cni/bin/* || true - ${concatMapStrings (package: '' + ${lib.concatMapStrings (package: '' echo "Linking cni package: ${package}" ln -fs ${package}/bin/* /opt/cni/bin '') cfg.cni.packages} @@ -373,12 +371,12 @@ in --config=${kubeletConfig} \ --hostname-override=${cfg.hostname} \ --kubeconfig=${kubeconfig} \ - ${optionalString (cfg.nodeIp != null) "--node-ip=${cfg.nodeIp}"} \ + ${lib.optionalString (cfg.nodeIp != null) "--node-ip=${cfg.nodeIp}"} \ --pod-infra-container-image=pause \ - ${optionalString (cfg.manifests != { }) "--pod-manifest-path=/etc/${manifestPath}"} \ - ${optionalString (taints != "") "--register-with-taints=${taints}"} \ + ${lib.optionalString (cfg.manifests != { }) "--pod-manifest-path=/etc/${manifestPath}"} \ + ${lib.optionalString (taints != "") "--register-with-taints=${taints}"} \ --root-dir=${top.dataDir} \ - ${optionalString (cfg.verbosity != null) "--v=${toString cfg.verbosity}"} \ + ${lib.optionalString (cfg.verbosity != null) "--v=${toString cfg.verbosity}"} \ ${cfg.extraOpts} ''; WorkingDirectory = top.dataDir; @@ -399,7 +397,7 @@ in "overlay" ]; - services.kubernetes.kubelet.hostname = mkDefault (lib.toLower config.networking.fqdnOrHostName); + services.kubernetes.kubelet.hostname = lib.mkDefault (lib.toLower config.networking.fqdnOrHostName); services.kubernetes.pki.certs = with top.lib; { kubelet = mkCert { @@ -418,20 +416,20 @@ in }; }; - services.kubernetes.kubelet.kubeconfig.server = mkDefault top.apiserverAddress; + services.kubernetes.kubelet.kubeconfig.server = lib.mkDefault top.apiserverAddress; }) - (mkIf (cfg.enable && cfg.manifests != { }) { - environment.etc = mapAttrs' ( + (lib.mkIf (cfg.enable && cfg.manifests != { }) { + environment.etc = lib.mapAttrs' ( name: manifest: - nameValuePair "${manifestPath}/${name}.json" { + lib.nameValuePair "${manifestPath}/${name}.json" { text = builtins.toJSON manifest; mode = "0755"; } ) cfg.manifests; }) - (mkIf (cfg.unschedulable && cfg.enable) { + (lib.mkIf (cfg.unschedulable && cfg.enable) { services.kubernetes.kubelet.taints.unschedulable = { value = "true"; effect = "NoSchedule"; diff --git a/nixos/modules/services/cluster/kubernetes/pki.nix b/nixos/modules/services/cluster/kubernetes/pki.nix index e4f8cf44e7033..63b534482ffa1 100644 --- a/nixos/modules/services/cluster/kubernetes/pki.nix +++ b/nixos/modules/services/cluster/kubernetes/pki.nix @@ -5,8 +5,6 @@ ... }: -with lib; - let top = config.services.kubernetes; cfg = top.pki; @@ -17,7 +15,7 @@ let algo = "rsa"; size = 2048; }; - names = singleton cfg.caSpec; + names = lib.singleton cfg.caSpec; } ); @@ -51,15 +49,15 @@ in ###### interface options.services.kubernetes.pki = with lib.types; { - enable = mkEnableOption "easyCert issuer service"; + enable = lib.mkEnableOption "easyCert issuer service"; - certs = mkOption { + certs = lib.mkOption { description = "List of certificate specs to feed to cert generator."; default = { }; type = attrs; }; - genCfsslCACert = mkOption { + genCfsslCACert = lib.mkOption { description = '' Whether to automatically generate cfssl CA certificate and key, if they don't exist. @@ -68,7 +66,7 @@ in type = bool; }; - genCfsslAPICerts = mkOption { + genCfsslAPICerts = lib.mkOption { description = '' Whether to automatically generate cfssl API webserver TLS cert and key, if they don't exist. @@ -77,7 +75,7 @@ in type = bool; }; - cfsslAPIExtraSANs = mkOption { + cfsslAPIExtraSANs = lib.mkOption { description = '' Extra x509 Subject Alternative Names to be added to the cfssl API webserver TLS cert. ''; @@ -86,7 +84,7 @@ in type = listOf str; }; - genCfsslAPIToken = mkOption { + genCfsslAPIToken = lib.mkOption { description = '' Whether to automatically generate cfssl API-token secret, if they doesn't exist. @@ -95,24 +93,24 @@ in type = bool; }; - pkiTrustOnBootstrap = mkOption { + pkiTrustOnBootstrap = lib.mkOption { description = "Whether to always trust remote cfssl server upon initial PKI bootstrap."; default = true; type = bool; }; - caCertPathPrefix = mkOption { + caCertPathPrefix = lib.mkOption { description = '' Path-prefrix for the CA-certificate to be used for cfssl signing. Suffixes ".pem" and "-key.pem" will be automatically appended for the public and private keys respectively. ''; default = "${config.services.cfssl.dataDir}/ca"; - defaultText = literalExpression ''"''${config.services.cfssl.dataDir}/ca"''; + defaultText = lib.literalExpression ''"''${config.services.cfssl.dataDir}/ca"''; type = str; }; - caSpec = mkOption { + caSpec = lib.mkOption { description = "Certificate specification for the auto-generated CAcert."; default = { CN = "kubernetes-cluster-ca"; @@ -123,7 +121,7 @@ in type = attrs; }; - etcClusterAdminKubeconfig = mkOption { + etcClusterAdminKubeconfig = lib.mkOption { description = '' Symlink a kubeconfig with cluster-admin privileges to environment path (/etc/\). @@ -135,7 +133,7 @@ in }; ###### implementation - config = mkIf cfg.enable ( + config = lib.mkIf cfg.enable ( let cfsslCertPathPrefix = "${config.services.cfssl.dataDir}/cfssl"; cfsslCert = "${cfsslCertPathPrefix}.pem"; @@ -143,7 +141,7 @@ in in { - services.cfssl = mkIf (top.apiserver.enable) { + services.cfssl = lib.mkIf (top.apiserver.enable) { enable = true; address = "0.0.0.0"; tlsCert = cfsslCert; @@ -203,7 +201,7 @@ in description = "Kubernetes certmgr bootstrapper"; wantedBy = [ "certmgr.service" ]; after = [ "cfssl.target" ]; - script = concatStringsSep "\n" [ + script = lib.concatStringsSep "\n" [ '' set -e @@ -219,7 +217,7 @@ in install -m 600 /dev/null "${certmgrAPITokenPath}" fi '' - (optionalString (cfg.pkiTrustOnBootstrap) '' + (lib.optionalString (cfg.pkiTrustOnBootstrap) '' if [ ! -f "${top.caFile}" ] || [ $(cat "${top.caFile}" | wc -c) -lt 1 ]; then ${pkgs.curl}/bin/curl --fail-early -f -kd '{}' ${remote}/api/v1/cfssl/info | \ ${pkgs.cfssl}/bin/cfssljson -stdout >${top.caFile} @@ -261,7 +259,7 @@ in }; }; in - mapAttrs mkSpec cfg.certs; + lib.mapAttrs mkSpec cfg.certs; }; #TODO: Get rid of kube-addon-manager in the future for the following reasons @@ -269,7 +267,7 @@ in # - it assumes that it is clusterAdmin or can gain clusterAdmin rights through serviceAccount # - it is designed to be used with k8s system components only # - it would be better with a more Nix-oriented way of managing addons - systemd.services.kube-addon-manager = mkIf top.addonManager.enable (mkMerge [ + systemd.services.kube-addon-manager = lib.mkIf top.addonManager.enable (lib.mkMerge [ { environment.KUBECONFIG = with cfg.certs.addonManager; @@ -280,7 +278,7 @@ in }; } - (optionalAttrs (top.addonManager.bootstrapAddons != { }) { + (lib.optionalAttrs (top.addonManager.bootstrapAddons != { }) { serviceConfig.PermissionsStartOnly = true; preStart = with pkgs; @@ -291,16 +289,16 @@ in in '' export KUBECONFIG=${clusterAdminKubeconfig} - ${top.package}/bin/kubectl apply -f ${concatStringsSep " \\\n -f " files} + ${top.package}/bin/kubectl apply -f ${lib.concatStringsSep " \\\n -f " files} ''; }) ]); - environment.etc.${cfg.etcClusterAdminKubeconfig}.source = mkIf ( + environment.etc.${cfg.etcClusterAdminKubeconfig}.source = lib.mkIf ( cfg.etcClusterAdminKubeconfig != null ) clusterAdminKubeconfig; - environment.systemPackages = mkIf (top.kubelet.enable || top.proxy.enable) [ + environment.systemPackages = lib.mkIf (top.kubelet.enable || top.proxy.enable) [ (pkgs.writeScriptBin "nixos-kubernetes-node-join" '' set -e exec 1>&2 @@ -331,19 +329,19 @@ in echo "Waiting for certs to appear..." >&1 - ${optionalString top.kubelet.enable '' + ${lib.optionalString top.kubelet.enable '' while [ ! -f ${cfg.certs.kubelet.cert} ]; do sleep 1; done echo "Restarting kubelet..." >&1 systemctl restart kubelet ''} - ${optionalString top.proxy.enable '' + ${lib.optionalString top.proxy.enable '' while [ ! -f ${cfg.certs.kubeProxyClient.cert} ]; do sleep 1; done echo "Restarting kube-proxy..." >&1 systemctl restart kube-proxy ''} - ${optionalString top.flannel.enable '' + ${lib.optionalString top.flannel.enable '' while [ ! -f ${cfg.certs.flannelClient.cert} ]; do sleep 1; done echo "Restarting flannel..." >&1 systemctl restart flannel @@ -361,11 +359,11 @@ in advertiseClientUrls = [ "https://etcd.local:2379" ]; initialCluster = [ "${top.masterAddress}=https://etcd.local:2380" ]; initialAdvertisePeerUrls = [ "https://etcd.local:2380" ]; - certFile = mkDefault cert; - keyFile = mkDefault key; - trustedCaFile = mkDefault caCert; + certFile = lib.mkDefault cert; + keyFile = lib.mkDefault key; + trustedCaFile = lib.mkDefault caCert; }; - networking.extraHosts = mkIf (config.services.etcd.enable) '' + networking.extraHosts = lib.mkIf (config.services.etcd.enable) '' 127.0.0.1 etcd.${top.addons.dns.clusterDomain} etcd.local ''; @@ -379,54 +377,54 @@ in services.kubernetes = { - apiserver = mkIf top.apiserver.enable ( + apiserver = lib.mkIf top.apiserver.enable ( with cfg.certs.apiServer; { etcd = with cfg.certs.apiserverEtcdClient; { servers = [ "https://etcd.local:2379" ]; - certFile = mkDefault cert; - keyFile = mkDefault key; - caFile = mkDefault caCert; + certFile = lib.mkDefault cert; + keyFile = lib.mkDefault key; + caFile = lib.mkDefault caCert; }; - clientCaFile = mkDefault caCert; - tlsCertFile = mkDefault cert; - tlsKeyFile = mkDefault key; - serviceAccountKeyFile = mkDefault cfg.certs.serviceAccount.cert; - serviceAccountSigningKeyFile = mkDefault cfg.certs.serviceAccount.key; - kubeletClientCaFile = mkDefault caCert; - kubeletClientCertFile = mkDefault cfg.certs.apiserverKubeletClient.cert; - kubeletClientKeyFile = mkDefault cfg.certs.apiserverKubeletClient.key; - proxyClientCertFile = mkDefault cfg.certs.apiserverProxyClient.cert; - proxyClientKeyFile = mkDefault cfg.certs.apiserverProxyClient.key; + clientCaFile = lib.mkDefault caCert; + tlsCertFile = lib.mkDefault cert; + tlsKeyFile = lib.mkDefault key; + serviceAccountKeyFile = lib.mkDefault cfg.certs.serviceAccount.cert; + serviceAccountSigningKeyFile = lib.mkDefault cfg.certs.serviceAccount.key; + kubeletClientCaFile = lib.mkDefault caCert; + kubeletClientCertFile = lib.mkDefault cfg.certs.apiserverKubeletClient.cert; + kubeletClientKeyFile = lib.mkDefault cfg.certs.apiserverKubeletClient.key; + proxyClientCertFile = lib.mkDefault cfg.certs.apiserverProxyClient.cert; + proxyClientKeyFile = lib.mkDefault cfg.certs.apiserverProxyClient.key; } ); - controllerManager = mkIf top.controllerManager.enable { - serviceAccountKeyFile = mkDefault cfg.certs.serviceAccount.key; + controllerManager = lib.mkIf top.controllerManager.enable { + serviceAccountKeyFile = lib.mkDefault cfg.certs.serviceAccount.key; rootCaFile = cfg.certs.controllerManagerClient.caCert; kubeconfig = with cfg.certs.controllerManagerClient; { - certFile = mkDefault cert; - keyFile = mkDefault key; + certFile = lib.mkDefault cert; + keyFile = lib.mkDefault key; }; }; - scheduler = mkIf top.scheduler.enable { + scheduler = lib.mkIf top.scheduler.enable { kubeconfig = with cfg.certs.schedulerClient; { - certFile = mkDefault cert; - keyFile = mkDefault key; + certFile = lib.mkDefault cert; + keyFile = lib.mkDefault key; }; }; - kubelet = mkIf top.kubelet.enable { - clientCaFile = mkDefault cfg.certs.kubelet.caCert; - tlsCertFile = mkDefault cfg.certs.kubelet.cert; - tlsKeyFile = mkDefault cfg.certs.kubelet.key; + kubelet = lib.mkIf top.kubelet.enable { + clientCaFile = lib.mkDefault cfg.certs.kubelet.caCert; + tlsCertFile = lib.mkDefault cfg.certs.kubelet.cert; + tlsKeyFile = lib.mkDefault cfg.certs.kubelet.key; kubeconfig = with cfg.certs.kubeletClient; { - certFile = mkDefault cert; - keyFile = mkDefault key; + certFile = lib.mkDefault cert; + keyFile = lib.mkDefault key; }; }; - proxy = mkIf top.proxy.enable { + proxy = lib.mkIf top.proxy.enable { kubeconfig = with cfg.certs.kubeProxyClient; { - certFile = mkDefault cert; - keyFile = mkDefault key; + certFile = lib.mkDefault cert; + keyFile = lib.mkDefault key; }; }; }; diff --git a/nixos/modules/services/cluster/kubernetes/proxy.nix b/nixos/modules/services/cluster/kubernetes/proxy.nix index 2e3fdc87b4396..49afa16a9080f 100644 --- a/nixos/modules/services/cluster/kubernetes/proxy.nix +++ b/nixos/modules/services/cluster/kubernetes/proxy.nix @@ -1,7 +1,5 @@ { config, lib, options, pkgs, ... }: -with lib; - let top = config.services.kubernetes; otop = options.services.kubernetes; @@ -9,43 +7,43 @@ let in { imports = [ - (mkRenamedOptionModule [ "services" "kubernetes" "proxy" "address" ] ["services" "kubernetes" "proxy" "bindAddress"]) + (lib.mkRenamedOptionModule [ "services" "kubernetes" "proxy" "address" ] ["services" "kubernetes" "proxy" "bindAddress"]) ]; ###### interface options.services.kubernetes.proxy = with lib.types; { - bindAddress = mkOption { + bindAddress = lib.mkOption { description = "Kubernetes proxy listening address."; default = "0.0.0.0"; type = str; }; - enable = mkEnableOption "Kubernetes proxy"; + enable = lib.mkEnableOption "Kubernetes proxy"; - extraOpts = mkOption { + extraOpts = lib.mkOption { description = "Kubernetes proxy extra command line options."; default = ""; type = separatedString " "; }; - featureGates = mkOption { + featureGates = lib.mkOption { description = "Attribute set of feature gates."; default = top.featureGates; - defaultText = literalExpression "config.${otop.featureGates}"; + defaultText = lib.literalExpression "config.${otop.featureGates}"; type = attrsOf bool; }; - hostname = mkOption { + hostname = lib.mkOption { description = "Kubernetes proxy hostname override."; default = config.networking.hostName; - defaultText = literalExpression "config.networking.hostName"; + defaultText = lib.literalExpression "config.networking.hostName"; type = str; }; kubeconfig = top.lib.mkKubeConfigOptions "Kubernetes proxy"; - verbosity = mkOption { + verbosity = lib.mkOption { description = '' Optional glog verbosity level for logging statements. See @@ -57,7 +55,7 @@ in }; ###### implementation - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { systemd.services.kube-proxy = { description = "Kubernetes Proxy Service"; wantedBy = [ "kubernetes.target" ]; @@ -67,13 +65,13 @@ in Slice = "kubernetes.slice"; ExecStart = ''${top.package}/bin/kube-proxy \ --bind-address=${cfg.bindAddress} \ - ${optionalString (top.clusterCidr!=null) + ${lib.optionalString (top.clusterCidr!=null) "--cluster-cidr=${top.clusterCidr}"} \ - ${optionalString (cfg.featureGates != {}) - "--feature-gates=${concatStringsSep "," (builtins.attrValues (mapAttrs (n: v: "${n}=${trivial.boolToString v}") cfg.featureGates))}"} \ + ${lib.optionalString (cfg.featureGates != {}) + "--feature-gates=${lib.concatStringsSep "," (builtins.attrValues (lib.mapAttrs (n: v: "${n}=${lib.trivial.boolToString v}") cfg.featureGates))}"} \ --hostname-override=${cfg.hostname} \ --kubeconfig=${top.lib.mkKubeConfig "kube-proxy" cfg.kubeconfig} \ - ${optionalString (cfg.verbosity != null) "--v=${toString cfg.verbosity}"} \ + ${lib.optionalString (cfg.verbosity != null) "--v=${toString cfg.verbosity}"} \ ${cfg.extraOpts} ''; WorkingDirectory = top.dataDir; @@ -95,7 +93,7 @@ in }; }; - services.kubernetes.proxy.kubeconfig.server = mkDefault top.apiserverAddress; + services.kubernetes.proxy.kubeconfig.server = lib.mkDefault top.apiserverAddress; }; meta.buildDocsInSandbox = false; diff --git a/nixos/modules/services/cluster/rke2/default.nix b/nixos/modules/services/cluster/rke2/default.nix index 1c7ef3af1c8ae..a1dc1a6d20016 100644 --- a/nixos/modules/services/cluster/rke2/default.nix +++ b/nixos/modules/services/cluster/rke2/default.nix @@ -26,7 +26,7 @@ in If it's a server: - By default it also runs workloads as an agent. - - any optionals is allowed. + - any lib.optionals is allowed. If it's an agent: diff --git a/nixos/modules/services/continuous-integration/gitea-actions-runner.nix b/nixos/modules/services/continuous-integration/gitea-actions-runner.nix index b4bb4d6879200..c1131171378f3 100644 --- a/nixos/modules/services/continuous-integration/gitea-actions-runner.nix +++ b/nixos/modules/services/continuous-integration/gitea-actions-runner.nix @@ -7,25 +7,6 @@ }: let - inherit (lib) - any - attrValues - concatStringsSep - escapeShellArg - hasInfix - hasSuffix - optionalAttrs - optionals - literalExpression - mapAttrs' - mkEnableOption - mkOption - mkPackageOption - mkIf - nameValuePair - types - ; - inherit (utils) escapeSystemdPath ; @@ -38,10 +19,10 @@ let # Empty label strings result in the upstream defined defaultLabels, which require docker # https://gitea.com/gitea/act_runner/src/tag/v0.1.5/internal/app/cmd/register.go#L93-L98 hasDockerScheme = - instance: instance.labels == [ ] || any (label: hasInfix ":docker:" label) instance.labels; - wantsContainerRuntime = any hasDockerScheme (attrValues cfg.instances); + instance: instance.labels == [ ] || lib.any (label: lib.hasInfix ":docker:" label) instance.labels; + wantsContainerRuntime = lib.any hasDockerScheme (lib.attrValues cfg.instances); - hasHostScheme = instance: any (label: hasSuffix ":host" label) instance.labels; + hasHostScheme = instance: lib.any (label: lib.hasSuffix ":host" label) instance.labels; # provide shorthands for whether container runtimes are enabled hasDocker = config.virtualisation.docker.enable; @@ -57,44 +38,44 @@ in hexa ]; - options.services.gitea-actions-runner = with types; { - package = mkPackageOption pkgs "gitea-actions-runner" { }; + options.services.gitea-actions-runner = { + package = lib.mkPackageOption pkgs "gitea-actions-runner" { }; - instances = mkOption { + instances = lib.mkOption { default = { }; description = '' Gitea Actions Runner instances. ''; - type = attrsOf (submodule { + type = lib.types.attrsOf (lib.types.submodule { options = { - enable = mkEnableOption "Gitea Actions Runner instance"; + enable = lib.mkEnableOption "Gitea Actions Runner instance"; - name = mkOption { - type = str; - example = literalExpression "config.networking.hostName"; + name = lib.mkOption { + type = lib.types.str; + example = lib.literalExpression "config.networking.hostName"; description = '' The name identifying the runner instance towards the Gitea/Forgejo instance. ''; }; - url = mkOption { - type = str; + url = lib.mkOption { + type = lib.types.str; example = "https://forge.example.com"; description = '' Base URL of your Gitea/Forgejo instance. ''; }; - token = mkOption { - type = nullOr str; + token = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; description = '' Plain token to register at the configured Gitea/Forgejo instance. ''; }; - tokenFile = mkOption { - type = nullOr (either str path); + tokenFile = lib.mkOption { + type = lib.types.nullOr (lib.types.either lib.types.str lib.types.path); default = null; description = '' Path to an environment file, containing the `TOKEN` environment @@ -103,9 +84,9 @@ in ''; }; - labels = mkOption { - type = listOf str; - example = literalExpression '' + labels = lib.mkOption { + type = lib.types.listOf lib.types.str; + example = lib.literalExpression '' [ # provide a debian base with nodejs for actions "debian-latest:docker://node:18-bullseye" @@ -123,21 +104,21 @@ in that follows the filesystem hierarchy standard. ''; }; - settings = mkOption { + settings = lib.mkOption { description = '' Configuration for `act_runner daemon`. See https://gitea.com/gitea/act_runner/src/branch/main/internal/pkg/config/config.example.yaml for an example configuration ''; - type = types.submodule { + type = lib.types.submodule { freeformType = settingsFormat.type; }; default = { }; }; - hostPackages = mkOption { - type = listOf package; + hostPackages = lib.mkOption { + type = lib.types.listOf lib.types.package; default = with pkgs; [ bash coreutils @@ -148,7 +129,7 @@ in nodejs wget ]; - defaultText = literalExpression '' + defaultText = lib.literalExpression '' with pkgs; [ bash coreutils @@ -170,10 +151,10 @@ in }; }; - config = mkIf (cfg.instances != { }) { + config = lib.mkIf (cfg.instances != { }) { assertions = [ { - assertion = any tokenXorTokenFile (attrValues cfg.instances); + assertion = lib.any tokenXorTokenFile (lib.attrValues cfg.instances); message = "Instances of gitea-actions-runner can have `token` or `tokenFile`, not both."; } { @@ -193,7 +174,7 @@ in wantsPodman = wantsContainerRuntime && config.virtualisation.podman.enable; configFile = settingsFormat.generate "config.yaml" instance.settings; in - nameValuePair "gitea-runner-${escapeSystemdPath name}" { + lib.nameValuePair "gitea-runner-${escapeSystemdPath name}" { inherit (instance) enable; description = "Gitea Actions Runner"; wants = [ "network-online.target" ]; @@ -201,20 +182,20 @@ in [ "network-online.target" ] - ++ optionals (wantsDocker) [ + ++ lib.optionals (wantsDocker) [ "docker.service" ] - ++ optionals (wantsPodman) [ + ++ lib.optionals (wantsPodman) [ "podman.service" ]; wantedBy = [ "multi-user.target" ]; environment = - optionalAttrs (instance.token != null) { + lib.optionalAttrs (instance.token != null) { TOKEN = "${instance.token}"; } - // optionalAttrs (wantsPodman) { + // lib.optionalAttrs (wantsPodman) { DOCKER_HOST = "unix:///run/podman/podman.sock"; } // { @@ -245,7 +226,7 @@ in # force reregistration on changed labels export LABELS_FILE="$INSTANCE_DIR/.labels" - export LABELS_WANTED="$(echo ${escapeShellArg (concatStringsSep "\n" instance.labels)} | sort)" + export LABELS_WANTED="$(echo ${lib.escapeShellArg (lib.concatStringsSep "\n" instance.labels)} | sort)" export LABELS_CURRENT="$(cat $LABELS_FILE 2>/dev/null || echo 0)" if [ ! -e "$INSTANCE_DIR/.runner" ] || [ "$LABELS_WANTED" != "$LABELS_CURRENT" ]; then @@ -254,10 +235,10 @@ in # perform the registration ${cfg.package}/bin/act_runner register --no-interactive \ - --instance ${escapeShellArg instance.url} \ + --instance ${lib.escapeShellArg instance.url} \ --token "$TOKEN" \ - --name ${escapeShellArg instance.name} \ - --labels ${escapeShellArg (concatStringsSep "," instance.labels)} \ + --name ${lib.escapeShellArg instance.name} \ + --labels ${lib.escapeShellArg (lib.concatStringsSep "," instance.labels)} \ --config ${configFile} # and write back the configured labels @@ -268,18 +249,18 @@ in ]; ExecStart = "${cfg.package}/bin/act_runner daemon --config ${configFile}"; SupplementaryGroups = - optionals (wantsDocker) [ + lib.optionals (wantsDocker) [ "docker" ] - ++ optionals (wantsPodman) [ + ++ lib.optionals (wantsPodman) [ "podman" ]; } - // optionalAttrs (instance.tokenFile != null) { + // lib.optionalAttrs (instance.tokenFile != null) { EnvironmentFile = instance.tokenFile; }; }; in - mapAttrs' mkRunnerService cfg.instances; + lib.mapAttrs' mkRunnerService cfg.instances; }; } diff --git a/nixos/modules/services/continuous-integration/gitlab-runner.nix b/nixos/modules/services/continuous-integration/gitlab-runner.nix index 895ba66e7ea0c..00efb2498ccf2 100644 --- a/nixos/modules/services/continuous-integration/gitlab-runner.nix +++ b/nixos/modules/services/continuous-integration/gitlab-runner.nix @@ -6,43 +6,6 @@ }: let - inherit (builtins) - hashString - map - substring - toJSON - toString - unsafeDiscardStringContext - ; - - inherit (lib) - any - assertMsg - attrValues - concatStringsSep - escapeShellArg - filterAttrs - hasPrefix - isStorePath - literalExpression - mapAttrs' - mapAttrsToList - mkDefault - mkEnableOption - mkIf - mkOption - mkPackageOption - mkRemovedOptionModule - mkRenamedOptionModule - nameValuePair - optional - optionalAttrs - optionals - teams - toShellVar - types - ; - cfg = config.services.gitlab-runner; hasDocker = config.virtualisation.docker.enable; hasPodman = config.virtualisation.podman.enable && config.virtualisation.podman.dockerSocket.enable; @@ -55,15 +18,15 @@ let genRunnerName = name: service: let - hash = substring 0 12 (hashString "md5" (unsafeDiscardStringContext (toJSON service))); + hash = lib.substring 0 12 (lib.hashString "md5" (lib.unsafeDiscardStringContext (lib.toJSON service))); in if service ? description && service.description != null then "${hash} ${service.description}" else "${name}_${config.networking.hostName}_${hash}"; - hashedServices = mapAttrs' ( - name: service: nameValuePair (genRunnerName name service) service + hashedServices = lib.mapAttrs' ( + name: service: lib.nameValuePair (genRunnerName name service) service ) cfg.services; configPath = ''"$HOME"/.gitlab-runner/config.toml''; configureScript = pkgs.writeShellApplication { @@ -97,14 +60,14 @@ let # update global options remarshal --if toml --of json --stringify ${configPath} \ | jq -cM 'with_entries(select([.key] | inside(["runners"])))' \ - | jq -scM '.[0] + .[1]' - <(echo ${escapeShellArg (toJSON cfg.settings)}) \ + | jq -scM '.[0] + .[1]' - <(echo ${lib.escapeShellArg (lib.toJSON cfg.settings)}) \ | remarshal --if json --of toml \ | sponge ${configPath} # remove no longer existing services gitlab-runner verify --delete - ${toShellVar "NEEDED_SERVICES" (lib.mapAttrs (name: value: 1) hashedServices)} + ${lib.toShellVar "NEEDED_SERVICES" (lib.mapAttrs (name: value: 1) hashedServices)} declare -A REGISTERED_SERVICES @@ -133,13 +96,13 @@ let done # register new services - ${concatStringsSep "\n" ( - mapAttrsToList (name: service: '' + ${lib.concatStringsSep "\n" ( + lib.mapAttrsToList (name: service: '' # TODO so here we should mention NEW_SERVICES if [ -v 'NEW_SERVICES["${name}"]' ] ; then bash -c ${ - escapeShellArg ( - concatStringsSep " \\\n " ( + lib.escapeShellArg ( + lib.concatStringsSep " \\\n " ( [ "set -a && source ${ if service.registrationConfigFile != null then @@ -154,44 +117,44 @@ let "--limit ${toString service.limit}" "--request-concurrency ${toString service.requestConcurrency}" ] - ++ optional ( + ++ lib.optional ( service.authenticationTokenConfigFile == null ) "--maximum-timeout ${toString service.maximumTimeout}" ++ service.registrationFlags - ++ optional (service.buildsDir != null) "--builds-dir ${service.buildsDir}" - ++ optional (service.cloneUrl != null) "--clone-url ${service.cloneUrl}" - ++ optional ( + ++ lib.optional (service.buildsDir != null) "--builds-dir ${service.buildsDir}" + ++ lib.optional (service.cloneUrl != null) "--clone-url ${service.cloneUrl}" + ++ lib.optional ( service.preGetSourcesScript != null ) "--pre-get-sources-script ${service.preGetSourcesScript}" - ++ optional ( + ++ lib.optional ( service.postGetSourcesScript != null ) "--post-get-sources-script ${service.postGetSourcesScript}" - ++ optional (service.preBuildScript != null) "--pre-build-script ${service.preBuildScript}" - ++ optional (service.postBuildScript != null) "--post-build-script ${service.postBuildScript}" - ++ optional ( + ++ lib.optional (service.preBuildScript != null) "--pre-build-script ${service.preBuildScript}" + ++ lib.optional (service.postBuildScript != null) "--post-build-script ${service.postBuildScript}" + ++ lib.optional ( service.authenticationTokenConfigFile == null && service.tagList != [ ] - ) "--tag-list ${concatStringsSep "," service.tagList}" - ++ optional (service.authenticationTokenConfigFile == null && service.runUntagged) "--run-untagged" - ++ optional ( + ) "--tag-list ${lib.concatStringsSep "," service.tagList}" + ++ lib.optional (service.authenticationTokenConfigFile == null && service.runUntagged) "--run-untagged" + ++ lib.optional ( service.authenticationTokenConfigFile == null && service.protected ) "--access-level ref_protected" - ++ optional service.debugTraceDisabled "--debug-trace-disabled" - ++ map (e: "--env ${escapeShellArg e}") ( - mapAttrsToList (name: value: "${name}=${value}") service.environmentVariables + ++ lib.optional service.debugTraceDisabled "--debug-trace-disabled" + ++ map (e: "--env ${lib.escapeShellArg e}") ( + lib.mapAttrsToList (name: value: "${name}=${value}") service.environmentVariables ) - ++ optionals (hasPrefix "docker" service.executor) ( + ++ lib.optionals (lib.hasPrefix "docker" service.executor) ( assert ( - assertMsg ( + lib.assertMsg ( service.dockerImage != null ) "dockerImage option is required for ${service.executor} executor (${name})" ); [ "--docker-image ${service.dockerImage}" ] - ++ optional service.dockerDisableCache "--docker-disable-cache" - ++ optional service.dockerPrivileged "--docker-privileged" - ++ map (v: "--docker-volumes ${escapeShellArg v}") service.dockerVolumes - ++ map (v: "--docker-extra-hosts ${escapeShellArg v}") service.dockerExtraHosts - ++ map (v: "--docker-allowed-images ${escapeShellArg v}") service.dockerAllowedImages - ++ map (v: "--docker-allowed-services ${escapeShellArg v}") service.dockerAllowedServices + ++ lib.optional service.dockerDisableCache "--docker-disable-cache" + ++ lib.optional service.dockerPrivileged "--docker-privileged" + ++ map (v: "--docker-volumes ${lib.escapeShellArg v}") service.dockerVolumes + ++ map (v: "--docker-extra-hosts ${lib.escapeShellArg v}") service.dockerExtraHosts + ++ map (v: "--docker-allowed-images ${lib.escapeShellArg v}") service.dockerAllowedImages + ++ map (v: "--docker-allowed-services ${lib.escapeShellArg v}") service.dockerAllowedServices ) ) ) @@ -222,9 +185,9 @@ let in { options.services.gitlab-runner = { - enable = mkEnableOption "Gitlab Runner"; - configFile = mkOption { - type = types.nullOr types.path; + enable = lib.mkEnableOption "Gitlab Runner"; + configFile = lib.mkOption { + type = lib.types.nullOr lib.types.path; default = null; description = '' Configuration file for gitlab-runner. @@ -238,8 +201,8 @@ in for settings not covered by this module. ''; }; - settings = mkOption { - type = types.submodule { + settings = lib.mkOption { + type = lib.types.submodule { freeformType = (pkgs.formats.json { }).type; }; default = { }; @@ -249,8 +212,8 @@ in for supported values. ''; }; - gracefulTermination = mkOption { - type = types.bool; + gracefulTermination = lib.mkOption { + type = lib.types.bool; default = false; description = '' Finish all remaining jobs before stopping. @@ -258,28 +221,28 @@ in for jobs to finish, which will lead to failed builds. ''; }; - gracefulTimeout = mkOption { - type = types.str; + gracefulTimeout = lib.mkOption { + type = lib.types.str; default = "infinity"; example = "5min 20s"; description = '' Time to wait until a graceful shutdown is turned into a forceful one. ''; }; - package = mkPackageOption pkgs "gitlab-runner" { + package = lib.mkPackageOption pkgs "gitlab-runner" { example = "gitlab-runner_1_11"; }; - extraPackages = mkOption { - type = types.listOf types.package; + extraPackages = lib.mkOption { + type = lib.types.listOf lib.types.package; default = [ ]; description = '' Extra packages to add to PATH for the gitlab-runner process. ''; }; - services = mkOption { + services = lib.mkOption { description = "GitLab Runner services."; default = { }; - example = literalExpression '' + example = lib.literalExpression '' { # runner for building in docker via host's nix-daemon # nix store will be readable in runner, might be insecure @@ -313,7 +276,7 @@ in . ''${pkgs.nix}/etc/profile.d/nix.sh - ''${pkgs.nix}/bin/nix-env -i ''${concatStringsSep " " (with pkgs; [ nix cacert git openssh ])} + ''${pkgs.nix}/bin/nix-env -i ''${lib.concatStringsSep " " (with pkgs; [ nix cacert git openssh ])} ''${pkgs.nix}/bin/nix-channel --add https://nixos.org/channels/nixpkgs-unstable ''${pkgs.nix}/bin/nix-channel --update nixpkgs @@ -362,11 +325,11 @@ in }; } ''; - type = types.attrsOf ( - types.submodule { + type = lib.types.attrsOf ( + lib.types.submodule { options = { - authenticationTokenConfigFile = mkOption { - type = with types; nullOr path; + authenticationTokenConfigFile = lib.mkOption { + type = with lib.types; nullOr path; default = null; description = '' Absolute path to a file containing environment variables used for @@ -389,8 +352,8 @@ in [GitLab documentation]: https://docs.gitlab.com/17.0/ee/ci/runners/new_creation_workflow.html#estimated-time-frame-for-planned-changes ''; }; - registrationConfigFile = mkOption { - type = with types; nullOr path; + registrationConfigFile = lib.mkOption { + type = with lib.types; nullOr path; default = null; description = '' Absolute path to a file with environment variables @@ -420,8 +383,8 @@ in [runner authentication tokens]: https://docs.gitlab.com/17.0/ee/ci/runners/new_creation_workflow.html#the-new-runner-registration-workflow ''; }; - registrationFlags = mkOption { - type = types.listOf types.str; + registrationFlags = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; example = [ "--docker-helper-image my/gitlab-runner-helper" ]; description = '' @@ -431,8 +394,8 @@ in for a list of supported flags. ''; }; - environmentVariables = mkOption { - type = types.attrsOf types.str; + environmentVariables = lib.mkOption { + type = lib.types.attrsOf lib.types.str; default = { }; example = { NAME = "value"; @@ -443,23 +406,23 @@ in with `RUNNER_ENV` variable set. ''; }; - description = mkOption { - type = types.nullOr types.str; + description = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; description = '' Name/description of the runner. ''; }; - executor = mkOption { - type = types.str; + executor = lib.mkOption { + type = lib.types.str; default = "docker"; description = '' Select executor, eg. shell, docker, etc. See [runner documentation](https://docs.gitlab.com/runner/executors/README.html) for more information. ''; }; - buildsDir = mkOption { - type = types.nullOr types.path; + buildsDir = lib.mkOption { + type = lib.types.nullOr lib.types.path; default = null; example = "/var/lib/gitlab-runner/builds"; description = '' @@ -467,23 +430,23 @@ in in context of selected executor (Locally, Docker, SSH). ''; }; - cloneUrl = mkOption { - type = types.nullOr types.str; + cloneUrl = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; example = "http://gitlab.example.local"; description = '' Overwrite the URL for the GitLab instance. Used if the Runner can’t connect to GitLab on the URL GitLab exposes itself. ''; }; - dockerImage = mkOption { - type = types.nullOr types.str; + dockerImage = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; description = '' Docker image to be used. ''; }; - dockerVolumes = mkOption { - type = types.listOf types.str; + dockerVolumes = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; example = [ "/var/run/docker.sock:/var/run/docker.sock" ]; description = '' @@ -491,30 +454,30 @@ in if it doesn't exist prior to mounting. ''; }; - dockerDisableCache = mkOption { - type = types.bool; + dockerDisableCache = lib.mkOption { + type = lib.types.bool; default = false; description = '' Disable all container caching. ''; }; - dockerPrivileged = mkOption { - type = types.bool; + dockerPrivileged = lib.mkOption { + type = lib.types.bool; default = false; description = '' Give extended privileges to container. ''; }; - dockerExtraHosts = mkOption { - type = types.listOf types.str; + dockerExtraHosts = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; example = [ "other-host:127.0.0.1" ]; description = '' Add a custom host-to-IP mapping. ''; }; - dockerAllowedImages = mkOption { - type = types.listOf types.str; + dockerAllowedImages = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; example = [ "ruby:*" @@ -526,8 +489,8 @@ in Whitelist allowed images. ''; }; - dockerAllowedServices = mkOption { - type = types.listOf types.str; + dockerAllowedServices = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; example = [ "postgres:9" @@ -538,38 +501,38 @@ in Whitelist allowed services. ''; }; - preGetSourcesScript = mkOption { - type = types.nullOr (types.either types.str types.path); + preGetSourcesScript = lib.mkOption { + type = lib.types.nullOr (lib.types.either lib.types.str lib.types.path); default = null; description = '' Runner-specific command script executed before code is pulled. ''; }; - postGetSourcesScript = mkOption { - type = types.nullOr (types.either types.str types.path); + postGetSourcesScript = lib.mkOption { + type = lib.types.nullOr (lib.types.either lib.types.str lib.types.path); default = null; description = '' Runner-specific command script executed after code is pulled. ''; }; - preBuildScript = mkOption { - type = types.nullOr (types.either types.str types.path); + preBuildScript = lib.mkOption { + type = lib.types.nullOr (lib.types.either lib.types.str lib.types.path); default = null; description = '' Runner-specific command script executed after code is pulled, just before build executes. ''; }; - postBuildScript = mkOption { - type = types.nullOr (types.either types.str types.path); + postBuildScript = lib.mkOption { + type = lib.types.nullOr (lib.types.either lib.types.str lib.types.path); default = null; description = '' Runner-specific command script executed after code is pulled and just after build executes. ''; }; - tagList = mkOption { - type = types.listOf types.str; + tagList = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; description = '' Tag list. @@ -578,8 +541,8 @@ in authentication tokens and will be ignored. ''; }; - runUntagged = mkOption { - type = types.bool; + runUntagged = lib.mkOption { + type = lib.types.bool; default = false; description = '' Register to run untagged builds; defaults to @@ -589,23 +552,23 @@ in authentication tokens and will be ignored. ''; }; - limit = mkOption { - type = types.int; + limit = lib.mkOption { + type = lib.types.int; default = 0; description = '' Limit how many jobs can be handled concurrently by this service. 0 (default) simply means don't limit. ''; }; - requestConcurrency = mkOption { - type = types.int; + requestConcurrency = lib.mkOption { + type = lib.types.int; default = 0; description = '' Limit number of concurrent requests for new jobs from GitLab. ''; }; - maximumTimeout = mkOption { - type = types.int; + maximumTimeout = lib.mkOption { + type = lib.types.int; default = 0; description = '' What is the maximum timeout (in seconds) that will be set for @@ -615,8 +578,8 @@ in authentication tokens and will be ignored. ''; }; - protected = mkOption { - type = types.bool; + protected = lib.mkOption { + type = lib.types.bool; default = false; description = '' When set to true Runner will only run on pipelines @@ -626,8 +589,8 @@ in authentication tokens and will be ignored. ''; }; - debugTraceDisabled = mkOption { - type = types.bool; + debugTraceDisabled = lib.mkOption { + type = lib.types.bool; default = false; description = '' When set to true Runner will disable the possibility of @@ -639,8 +602,8 @@ in ); }; clear-docker-cache = { - enable = mkOption { - type = types.bool; + enable = lib.mkOption { + type = lib.types.bool; default = false; description = '' Whether to periodically prune gitlab runner's Docker resources. If @@ -649,8 +612,8 @@ in ''; }; - flags = mkOption { - type = types.listOf types.str; + flags = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; example = [ "prune" ]; description = '' @@ -658,9 +621,9 @@ in ''; }; - dates = mkOption { + dates = lib.mkOption { default = "weekly"; - type = types.str; + type = lib.types.str; description = '' Specification (in the format described by {manpage}`systemd.time(7)`) of the time at @@ -668,90 +631,90 @@ in ''; }; - package = mkOption { + package = lib.mkOption { default = config.virtualisation.docker.package; - defaultText = literalExpression "config.virtualisation.docker.package"; - example = literalExpression "pkgs.docker"; + defaultText = lib.literalExpression "config.virtualisation.docker.package"; + example = lib.literalExpression "pkgs.docker"; description = "Docker package to use for clearing up docker cache."; }; }; }; - config = mkIf cfg.enable { - assertions = mapAttrsToList (name: serviceConfig: { + config = lib.mkIf cfg.enable { + assertions = lib.mapAttrsToList (name: serviceConfig: { assertion = serviceConfig.registrationConfigFile == null || serviceConfig.authenticationTokenConfigFile == null; message = "`services.gitlab-runner.${name}.registrationConfigFile` and `services.gitlab-runner.services.${name}.authenticationTokenConfigFile` are mutually exclusive."; }) cfg.services; warnings = - mapAttrsToList ( + lib.mapAttrsToList ( name: serviceConfig: "services.gitlab-runner.services.${name}.`registrationConfigFile` points to a file in Nix Store. You should use quoted absolute path to prevent this." - ) (filterAttrs (name: serviceConfig: isStorePath serviceConfig.registrationConfigFile) cfg.services) + ) (lib.filterAttrs (name: serviceConfig: lib.isStorePath serviceConfig.registrationConfigFile) cfg.services) ++ - mapAttrsToList + lib.mapAttrsToList ( name: serviceConfig: "services.gitlab-runner.services.${name}.`authenticationTokenConfigFile` points to a file in Nix Store. You should use quoted absolute path to prevent this." ) ( - filterAttrs ( - name: serviceConfig: isStorePath serviceConfig.authenticationTokenConfigFile + lib.filterAttrs ( + name: serviceConfig: lib.isStorePath serviceConfig.authenticationTokenConfigFile ) cfg.services ) ++ - mapAttrsToList + lib.mapAttrsToList (name: serviceConfig: '' Runner registration tokens have been deprecated and disabled by default in GitLab >= 17.0. Consider migrating to runner authentication tokens by setting `services.gitlab-runner.services.${name}.authenticationTokenConfigFile`. https://docs.gitlab.com/17.0/ee/ci/runners/new_creation_workflow.html'') ( - filterAttrs (name: serviceConfig: serviceConfig.authenticationTokenConfigFile == null) cfg.services + lib.filterAttrs (name: serviceConfig: serviceConfig.authenticationTokenConfigFile == null) cfg.services ) ++ - mapAttrsToList + lib.mapAttrsToList ( name: serviceConfig: ''`services.gitlab-runner.services.${name}.protected` with runner authentication tokens has no effect and will be ignored. Please remove it from your configuration.'' ) ( - filterAttrs ( + lib.filterAttrs ( name: serviceConfig: serviceConfig.authenticationTokenConfigFile != null && serviceConfig.protected == true ) cfg.services ) ++ - mapAttrsToList + lib.mapAttrsToList ( name: serviceConfig: ''`services.gitlab-runner.services.${name}.runUntagged` with runner authentication tokens has no effect and will be ignored. Please remove it from your configuration.'' ) ( - filterAttrs ( + lib.filterAttrs ( name: serviceConfig: serviceConfig.authenticationTokenConfigFile != null && serviceConfig.runUntagged == true ) cfg.services ) ++ - mapAttrsToList + lib.mapAttrsToList ( name: v: ''`services.gitlab-runner.services.${name}.maximumTimeout` with runner authentication tokens has no effect and will be ignored. Please remove it from your configuration.'' ) ( - filterAttrs ( + lib.filterAttrs ( name: serviceConfig: serviceConfig.authenticationTokenConfigFile != null && serviceConfig.maximumTimeout != 0 ) cfg.services ) ++ - mapAttrsToList + lib.mapAttrsToList ( name: v: ''`services.gitlab-runner.services.${name}.tagList` with runner authentication tokens has no effect and will be ignored. Please remove it from your configuration.'' ) ( - filterAttrs ( + lib.filterAttrs ( serviceName: serviceConfig: serviceConfig.authenticationTokenConfigFile != null && serviceConfig.tagList != [ ] ) cfg.services @@ -762,9 +725,9 @@ in description = "Gitlab Runner"; documentation = [ "https://docs.gitlab.com/runner/" ]; after = - [ "network.target" ] ++ optional hasDocker "docker.service" ++ optional hasPodman "podman.service"; + [ "network.target" ] ++ lib.optional hasDocker "docker.service" ++ lib.optional hasPodman "podman.service"; - requires = optional hasDocker "docker.service" ++ optional hasPodman "podman.service"; + requires = lib.optional hasDocker "docker.service" ++ lib.optional hasPodman "podman.service"; wantedBy = [ "multi-user.target" ]; environment = config.networking.proxy.envVars // { HOME = "/var/lib/gitlab-runner"; @@ -791,12 +754,12 @@ in # Make sure to restart service or changes won't apply. DynamicUser = true; StateDirectory = "gitlab-runner"; - SupplementaryGroups = optional hasDocker "docker" ++ optional hasPodman "podman"; + SupplementaryGroups = lib.optional hasDocker "docker" ++ lib.optional hasPodman "podman"; ExecStartPre = "!${configureScript}/bin/gitlab-runner-configure"; ExecStart = "${startScript}/bin/gitlab-runner-start"; ExecReload = "!${configureScript}/bin/gitlab-runner-configure"; } - // optionalAttrs cfg.gracefulTermination { + // lib.optionalAttrs cfg.gracefulTermination { TimeoutStopSec = "${cfg.gracefulTimeout}"; KillSignal = "SIGQUIT"; KillMode = "process"; @@ -804,7 +767,7 @@ in }; # Enable periodic clear-docker-cache script systemd.services.gitlab-runner-clear-docker-cache = - mkIf (cfg.clear-docker-cache.enable && (any (s: s.executor == "docker") (attrValues cfg.services))) + lib.mkIf (cfg.clear-docker-cache.enable && (lib.any (s: s.executor == "docker") (lib.attrValues cfg.services))) { description = "Prune gitlab-runner docker resources"; restartIfChanged = false; @@ -824,56 +787,56 @@ in startAt = cfg.clear-docker-cache.dates; }; # Enable docker if `docker` executor is used in any service - virtualisation.docker.enable = mkIf (any (s: s.executor == "docker") (attrValues cfg.services)) ( - mkDefault true + virtualisation.docker.enable = lib.mkIf (lib.any (s: s.executor == "docker") (lib.attrValues cfg.services)) ( + lib.mkDefault true ); }; imports = [ - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "gitlab-runner" "packages" ] [ "services" "gitlab-runner" "extraPackages" ] ) - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "gitlab-runner" "configOptions" ] "Use services.gitlab-runner.services option instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "gitlab-runner" "workDir" ] "You should move contents of workDir (if any) to /var/lib/gitlab-runner") - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "gitlab-runner" "checkInterval" ] [ "services" "gitlab-runner" "settings" "check_interval" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "gitlab-runner" "concurrent" ] [ "services" "gitlab-runner" "settings" "concurrent" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "gitlab-runner" "sentryDSN" ] [ "services" "gitlab-runner" "settings" "sentry_dsn" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "gitlab-runner" "prometheusListenAddress" ] [ "services" "gitlab-runner" "settings" "listen_address" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "gitlab-runner" "sessionServer" "listenAddress" ] [ "services" "gitlab-runner" "settings" "session_server" "listen_address" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "gitlab-runner" "sessionServer" "advertiseAddress" ] [ "services" "gitlab-runner" "settings" "session_server" "advertise_address" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "gitlab-runner" "sessionServer" "sessionTimeout" ] [ "services" "gitlab-runner" "settings" "session_server" "session_timeout" ] ) ]; - meta.maintainers = teams.gitlab.members; + meta.maintainers = lib.teams.gitlab.members; } diff --git a/nixos/modules/services/continuous-integration/gocd-server/default.nix b/nixos/modules/services/continuous-integration/gocd-server/default.nix index 0997cb394cbe4..70cc101fd21b3 100644 --- a/nixos/modules/services/continuous-integration/gocd-server/default.nix +++ b/nixos/modules/services/continuous-integration/gocd-server/default.nix @@ -6,8 +6,6 @@ ... }: -with lib; - let cfg = config.services.gocd-server; opt = options.services.gocd-server; @@ -15,27 +13,27 @@ in { options = { services.gocd-server = { - enable = mkEnableOption "gocd-server"; + enable = lib.mkEnableOption "gocd-server"; - user = mkOption { + user = lib.mkOption { default = "gocd-server"; - type = types.str; + type = lib.types.str; description = '' User the Go.CD server should execute under. ''; }; - group = mkOption { + group = lib.mkOption { default = "gocd-server"; - type = types.str; + type = lib.types.str; description = '' If the default user "gocd-server" is configured then this is the primary group of that user. ''; }; - extraGroups = mkOption { + extraGroups = lib.mkOption { default = [ ]; - type = types.listOf types.str; + type = lib.types.listOf lib.types.str; example = [ "wheel" "docker" @@ -45,40 +43,40 @@ in ''; }; - listenAddress = mkOption { + listenAddress = lib.mkOption { default = "0.0.0.0"; example = "localhost"; - type = types.str; + type = lib.types.str; description = '' Specifies the bind address on which the Go.CD server HTTP interface listens. ''; }; - port = mkOption { + port = lib.mkOption { default = 8153; - type = types.port; + type = lib.types.port; description = '' Specifies port number on which the Go.CD server HTTP interface listens. ''; }; - sslPort = mkOption { + sslPort = lib.mkOption { default = 8154; - type = types.int; + type = lib.types.int; description = '' Specifies port number on which the Go.CD server HTTPS interface listens. ''; }; - workDir = mkOption { + workDir = lib.mkOption { default = "/var/lib/go-server"; - type = types.str; + type = lib.types.str; description = '' Specifies the working directory in which the Go.CD server java archive resides. ''; }; - packages = mkOption { + packages = lib.mkOption { default = [ pkgs.stdenv pkgs.jre @@ -86,31 +84,31 @@ in config.programs.ssh.package pkgs.nix ]; - defaultText = literalExpression "[ pkgs.stdenv pkgs.jre pkgs.git config.programs.ssh.package pkgs.nix ]"; - type = types.listOf types.package; + defaultText = lib.literalExpression "[ pkgs.stdenv pkgs.jre pkgs.git config.programs.ssh.package pkgs.nix ]"; + type = lib.types.listOf lib.types.package; description = '' Packages to add to PATH for the Go.CD server's process. ''; }; - initialJavaHeapSize = mkOption { + initialJavaHeapSize = lib.mkOption { default = "512m"; - type = types.str; + type = lib.types.str; description = '' Specifies the initial java heap memory size for the Go.CD server's java process. ''; }; - maxJavaHeapMemory = mkOption { + maxJavaHeapMemory = lib.mkOption { default = "1024m"; - type = types.str; + type = lib.types.str; description = '' Specifies the java maximum heap memory size for the Go.CD server's java process. ''; }; - startupOptions = mkOption { - type = types.listOf types.str; + startupOptions = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ "-Xms${cfg.initialJavaHeapSize}" "-Xmx${cfg.maxJavaHeapMemory}" @@ -125,7 +123,7 @@ in "--add-opens=java.base/java.lang=ALL-UNNAMED" "--add-opens=java.base/java.util=ALL-UNNAMED" ]; - defaultText = literalExpression '' + defaultText = lib.literalExpression '' [ "-Xms''${config.${opt.initialJavaHeapSize}}" "-Xmx''${config.${opt.maxJavaHeapMemory}}" @@ -148,9 +146,9 @@ in ''; }; - extraOptions = mkOption { + extraOptions = lib.mkOption { default = [ ]; - type = types.listOf types.str; + type = lib.types.listOf lib.types.str; example = [ "-X debug" "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005" @@ -167,9 +165,9 @@ in ''; }; - environment = mkOption { + environment = lib.mkOption { default = { }; - type = with types; attrsOf str; + type = with lib.types; attrsOf str; description = '' Additional environment variables to be passed to the gocd-server process. As a base environment, gocd-server receives NIX_PATH from @@ -180,12 +178,12 @@ in }; }; - config = mkIf cfg.enable { - users.groups = optionalAttrs (cfg.group == "gocd-server") { + config = lib.mkIf cfg.enable { + users.groups = lib.optionalAttrs (cfg.group == "gocd-server") { gocd-server.gid = config.ids.gids.gocd-server; }; - users.users = optionalAttrs (cfg.user == "gocd-server") { + users.users = lib.optionalAttrs (cfg.user == "gocd-server") { gocd-server = { description = "gocd-server user"; createHome = true; @@ -218,8 +216,8 @@ in script = '' ${pkgs.git}/bin/git config --global --add http.sslCAinfo /etc/ssl/certs/ca-certificates.crt - ${pkgs.jre}/bin/java -server ${concatStringsSep " " cfg.startupOptions} \ - ${concatStringsSep " " cfg.extraOptions} \ + ${pkgs.jre}/bin/java -server ${lib.concatStringsSep " " cfg.startupOptions} \ + ${lib.concatStringsSep " " cfg.extraOptions} \ -jar ${pkgs.gocd-server}/go-server/lib/go.jar ''; diff --git a/nixos/modules/services/continuous-integration/hercules-ci-agent/common.nix b/nixos/modules/services/continuous-integration/hercules-ci-agent/common.nix index 136ed5102e1a8..8a19db7203599 100644 --- a/nixos/modules/services/continuous-integration/hercules-ci-agent/common.nix +++ b/nixos/modules/services/continuous-integration/hercules-ci-agent/common.nix @@ -12,16 +12,6 @@ ... }: let - inherit (lib) - filterAttrs - literalExpression - mkIf - mkOption - mkRemovedOptionModule - mkRenamedOptionModule - types - mkPackageOption - ; cfg = config.services.hercules-ci-agent; @@ -30,26 +20,26 @@ let in { imports = [ - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "hercules-ci-agent" "extraOptions" ] [ "services" "hercules-ci-agent" "settings" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "hercules-ci-agent" "baseDirectory" ] [ "services" "hercules-ci-agent" "settings" "baseDirectory" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "hercules-ci-agent" "concurrentTasks" ] [ "services" "hercules-ci-agent" "settings" "concurrentTasks" ] ) - (mkRemovedOptionModule [ "services" "hercules-ci-agent" "patchNix" ] + (lib.mkRemovedOptionModule [ "services" "hercules-ci-agent" "patchNix" ] "Nix versions packaged in this version of Nixpkgs don't need a patched nix-daemon to work correctly in Hercules CI Agent clusters." ) ]; options.services.hercules-ci-agent = { - enable = mkOption { - type = types.bool; + enable = lib.mkOption { + type = lib.types.bool; default = false; description = '' Enable to run Hercules CI Agent as a system service. @@ -60,8 +50,8 @@ in Support is available at [help@hercules-ci.com](mailto:help@hercules-ci.com). ''; }; - package = mkPackageOption pkgs "hercules-ci-agent" { }; - settings = mkOption { + package = lib.mkPackageOption pkgs "hercules-ci-agent" { }; + settings = lib.mkOption { description = '' These settings are written to the `agent.toml` file. @@ -69,7 +59,7 @@ in For the exhaustive list of settings, see . ''; - type = types.submoduleWith { modules = [ settingsModule ]; }; + type = lib.types.submoduleWith { modules = [ settingsModule ]; }; }; /* @@ -78,8 +68,8 @@ in These are written as options instead of let binding to allow sharing with default.nix on both NixOS and nix-darwin. */ - tomlFile = mkOption { - type = types.path; + tomlFile = lib.mkOption { + type = lib.types.path; internal = true; defaultText = lib.literalMD "generated `hercules-ci-agent.toml`"; description = '' @@ -88,7 +78,7 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { # Make sure that nix.extraOptions does not override trusted-users assertions = [ { diff --git a/nixos/modules/services/continuous-integration/hercules-ci-agent/default.nix b/nixos/modules/services/continuous-integration/hercules-ci-agent/default.nix index 20c5deb02e8ec..2f23e4524c17e 100644 --- a/nixos/modules/services/continuous-integration/hercules-ci-agent/default.nix +++ b/nixos/modules/services/continuous-integration/hercules-ci-agent/default.nix @@ -28,7 +28,7 @@ in ) ]; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { systemd.services.hercules-ci-agent = { wantedBy = [ "multi-user.target" ]; after = [ "network-online.target" ]; @@ -94,12 +94,12 @@ in mkIfNotNull = x: mkIf (x != null) x; in { - nixos.configurationRevision = mkIfNotNull config.system.configurationRevision; + nixos.configurationRevision = lib.mkIfNotNull config.system.configurationRevision; nixos.release = config.system.nixos.release; - nixos.label = mkIfNotNull config.system.nixos.label; + nixos.label = lib.mkIfNotNull config.system.nixos.label; nixos.codeName = config.system.nixos.codeName; nixos.tags = config.system.nixos.tags; - nixos.systemName = mkIfNotNull config.system.name; + nixos.systemName = lib.mkIfNotNull config.system.name; }; }; }; diff --git a/nixos/modules/services/continuous-integration/hercules-ci-agent/settings.nix b/nixos/modules/services/continuous-integration/hercules-ci-agent/settings.nix index a2e2f5d13d68e..67d396af60965 100644 --- a/nixos/modules/services/continuous-integration/hercules-ci-agent/settings.nix +++ b/nixos/modules/services/continuous-integration/hercules-ci-agent/settings.nix @@ -1,11 +1,6 @@ # Not a module { pkgs, lib }: let - inherit (lib) - types - literalExpression - mkOption - ; format = pkgs.formats.toml { }; @@ -19,24 +14,24 @@ let { freeformType = format.type; options = { - apiBaseUrl = mkOption { + apiBaseUrl = lib.mkOption { description = '' API base URL that the agent will connect to. When using Hercules CI Enterprise, set this to the URL where your Hercules CI server is reachable. ''; - type = types.str; + type = lib.types.str; default = "https://hercules-ci.com"; }; - baseDirectory = mkOption { - type = types.path; + baseDirectory = lib.mkOption { + type = lib.types.path; default = "/var/lib/hercules-ci-agent"; description = '' State directory (secrets, work directory, etc) for agent ''; }; - concurrentTasks = mkOption { + concurrentTasks = lib.mkOption { description = '' Number of tasks to perform simultaneously. @@ -54,13 +49,13 @@ let because each split of resources causes inefficiencies; particularly with regards to build latency because of extra downloads. ''; - type = types.either types.ints.positive (types.enum [ "auto" ]); + type = lib.types.either lib.types.ints.positive (lib.types.enum [ "auto" ]); default = "auto"; defaultText = lib.literalMD '' `"auto"`, meaning equal to the number of CPU cores. ''; }; - labels = mkOption { + labels = lib.mkOption { description = '' A key-value map of user data. @@ -71,7 +66,7 @@ let involving arrays of non-primitive types may not be representable currently. ''; type = format.type; - defaultText = literalExpression '' + defaultText = lib.literalExpression '' { agent.source = "..."; # One of "nixpkgs", "flake", "override" lib.version = "..."; @@ -79,25 +74,25 @@ let } ''; }; - workDirectory = mkOption { + workDirectory = lib.mkOption { description = '' The directory in which temporary subdirectories are created for task state. This includes sources for Nix evaluation. ''; - type = types.path; + type = lib.types.path; default = config.baseDirectory + "/work"; - defaultText = literalExpression ''baseDirectory + "/work"''; + defaultText = lib.literalExpression ''baseDirectory + "/work"''; }; - staticSecretsDirectory = mkOption { + staticSecretsDirectory = lib.mkOption { description = '' This is the default directory to look for statically configured secrets like `cluster-join-token.key`. See also `clusterJoinTokenPath` and `binaryCachesPath` for fine-grained configuration. ''; - type = types.path; + type = lib.types.path; default = config.baseDirectory + "/secrets"; - defaultText = literalExpression ''baseDirectory + "/secrets"''; + defaultText = lib.literalExpression ''baseDirectory + "/secrets"''; }; - clusterJoinTokenPath = mkOption { + clusterJoinTokenPath = lib.mkOption { description = '' Location of the cluster-join-token.key file. @@ -110,11 +105,11 @@ let The contents of the file are used for authentication between the agent and the API. ''; - type = types.path; + type = lib.types.path; default = config.staticSecretsDirectory + "/cluster-join-token.key"; - defaultText = literalExpression ''staticSecretsDirectory + "/cluster-join-token.key"''; + defaultText = lib.literalExpression ''staticSecretsDirectory + "/cluster-join-token.key"''; }; - binaryCachesPath = mkOption { + binaryCachesPath = lib.mkOption { description = '' Path to a JSON file containing binary cache secret keys. @@ -124,11 +119,11 @@ let The format is described on . ''; - type = types.path; + type = lib.types.path; default = config.staticSecretsDirectory + "/binary-caches.json"; - defaultText = literalExpression ''staticSecretsDirectory + "/binary-caches.json"''; + defaultText = lib.literalExpression ''staticSecretsDirectory + "/binary-caches.json"''; }; - secretsJsonPath = mkOption { + secretsJsonPath = lib.mkOption { description = '' Path to a JSON file containing secrets for effects. @@ -138,9 +133,9 @@ let The format is described on . ''; - type = types.path; + type = lib.types.path; default = config.staticSecretsDirectory + "/secrets.json"; - defaultText = literalExpression ''staticSecretsDirectory + "/secrets.json"''; + defaultText = lib.literalExpression ''staticSecretsDirectory + "/secrets.json"''; }; }; config = { diff --git a/nixos/modules/services/continuous-integration/jenkins/slave.nix b/nixos/modules/services/continuous-integration/jenkins/slave.nix index aa374834743a8..5f06aa4f95e95 100644 --- a/nixos/modules/services/continuous-integration/jenkins/slave.nix +++ b/nixos/modules/services/continuous-integration/jenkins/slave.nix @@ -6,7 +6,6 @@ }: let - inherit (lib) mkIf mkOption types; cfg = config.services.jenkinsSlave; masterCfg = config.services.jenkins; in @@ -18,8 +17,8 @@ in # enable ssh slaves. # * Optionally configure the node as a jenkins ad-hoc slave. This would imply configuration # properties for the master node. - enable = mkOption { - type = types.bool; + enable = lib.mkOption { + type = lib.types.bool; default = false; description = '' If true the system will be configured to work as a jenkins slave. @@ -28,26 +27,26 @@ in ''; }; - user = mkOption { + user = lib.mkOption { default = "jenkins"; - type = types.str; + type = lib.types.str; description = '' User the jenkins slave agent should execute under. ''; }; - group = mkOption { + group = lib.mkOption { default = "jenkins"; - type = types.str; + type = lib.types.str; description = '' If the default slave agent user "jenkins" is configured then this is the primary group of that user. ''; }; - home = mkOption { + home = lib.mkOption { default = "/var/lib/jenkins"; - type = types.path; + type = lib.types.path; description = '' The path to use as JENKINS_HOME. If the default user "jenkins" is configured then this is the home of the "jenkins" user. @@ -58,7 +57,7 @@ in }; }; - config = mkIf (cfg.enable && !masterCfg.enable) { + config = lib.mkIf (cfg.enable && !masterCfg.enable) { users.groups = lib.optionalAttrs (cfg.group == "jenkins") { jenkins.gid = config.ids.gids.jenkins; }; diff --git a/nixos/modules/services/databases/cassandra.nix b/nixos/modules/services/databases/cassandra.nix index 0130564778e68..3cdc3214584d5 100644 --- a/nixos/modules/services/databases/cassandra.nix +++ b/nixos/modules/services/databases/cassandra.nix @@ -6,31 +6,16 @@ }: let - inherit (lib) - concatStringsSep - flip - literalMD - literalExpression - optionalAttrs - optionals - recursiveUpdate - mkEnableOption - mkPackageOption - mkIf - mkOption - types - versionAtLeast - ; cfg = config.services.cassandra; - atLeast3 = versionAtLeast cfg.package.version "3"; - atLeast3_11 = versionAtLeast cfg.package.version "3.11"; - atLeast4 = versionAtLeast cfg.package.version "4"; + atLeast3 = lib.versionAtLeast cfg.package.version "3"; + atLeast3_11 = lib.versionAtLeast cfg.package.version "3.11"; + atLeast4 = lib.versionAtLeast cfg.package.version "4"; defaultUser = "cassandra"; - cassandraConfig = flip recursiveUpdate cfg.extraConfig ( + cassandraConfig = lib.flip lib.recursiveUpdate cfg.extraConfig ( { commitlog_sync = "batch"; commitlog_sync_batch_window_in_ms = 2; @@ -42,15 +27,15 @@ let commitlog_directory = "${cfg.homeDir}/commitlog"; saved_caches_directory = "${cfg.homeDir}/saved_caches"; } - // optionalAttrs (cfg.seedAddresses != [ ]) { + // lib.optionalAttrs (cfg.seedAddresses != [ ]) { seed_provider = [ { class_name = "org.apache.cassandra.locator.SimpleSeedProvider"; - parameters = [ { seeds = concatStringsSep "," cfg.seedAddresses; } ]; + parameters = [ { seeds = lib.concatStringsSep "," cfg.seedAddresses; } ]; } ]; } - // optionalAttrs atLeast3 { + // lib.optionalAttrs atLeast3 { hints_directory = "${cfg.homeDir}/hints"; } ); @@ -109,14 +94,14 @@ let fullJvmOptions = cfg.jvmOpts - ++ optionals (cfg.jmxRoles != [ ]) [ + ++ lib.optionals (cfg.jmxRoles != [ ]) [ "-Dcom.sun.management.jmxremote.authenticate=true" "-Dcom.sun.management.jmxremote.password.file=${cfg.jmxRolesFile}" ] - ++ optionals cfg.remoteJmx [ + ++ lib.optionals cfg.remoteJmx [ "-Djava.rmi.server.hostname=${cfg.rpcAddress}" ] - ++ optionals atLeast4 [ + ++ lib.optionals atLeast4 [ # Historically, we don't use a log dir, whereas the upstream scripts do # expect this. We override those by providing our own -Xlog:gc flag. "-Xlog:gc=warning,heap*=warning,age*=warning,safepoint=warning,promotion*=warning" @@ -134,12 +119,12 @@ in { options.services.cassandra = { - enable = mkEnableOption '' + enable = lib.mkEnableOption '' Apache Cassandra – Scalable and highly available database ''; - clusterName = mkOption { - type = types.str; + clusterName = lib.mkOption { + type = lib.types.str; default = "Test Cluster"; description = '' The name of the cluster. @@ -148,40 +133,40 @@ in ''; }; - user = mkOption { - type = types.str; + user = lib.mkOption { + type = lib.types.str; default = defaultUser; description = "Run Apache Cassandra under this user."; }; - group = mkOption { - type = types.str; + group = lib.mkOption { + type = lib.types.str; default = defaultUser; description = "Run Apache Cassandra under this group."; }; - homeDir = mkOption { - type = types.path; + homeDir = lib.mkOption { + type = lib.types.path; default = "/var/lib/cassandra"; description = '' Home directory for Apache Cassandra. ''; }; - package = mkPackageOption pkgs "cassandra" { + package = lib.mkPackageOption pkgs "cassandra" { example = "cassandra_3_11"; }; - jvmOpts = mkOption { - type = types.listOf types.str; + jvmOpts = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; description = '' Populate the `JVM_OPT` environment variable. ''; }; - listenAddress = mkOption { - type = types.nullOr types.str; + listenAddress = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = "127.0.0.1"; example = null; description = '' @@ -201,8 +186,8 @@ in ''; }; - listenInterface = mkOption { - type = types.nullOr types.str; + listenInterface = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; example = "eth1"; description = '' @@ -212,8 +197,8 @@ in ''; }; - rpcAddress = mkOption { - type = types.nullOr types.str; + rpcAddress = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = "127.0.0.1"; example = null; description = '' @@ -234,8 +219,8 @@ in ''; }; - rpcInterface = mkOption { - type = types.nullOr types.str; + rpcInterface = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; example = "eth1"; description = '' @@ -244,8 +229,8 @@ in ''; }; - logbackConfig = mkOption { - type = types.lines; + logbackConfig = lib.mkOption { + type = lib.types.lines; default = '' @@ -266,8 +251,8 @@ in ''; }; - seedAddresses = mkOption { - type = types.listOf types.str; + seedAddresses = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ "127.0.0.1" ]; description = '' The addresses of hosts designated as contact points in the cluster. A @@ -277,8 +262,8 @@ in ''; }; - allowClients = mkOption { - type = types.bool; + allowClients = lib.mkOption { + type = lib.types.bool; default = true; description = '' Enables or disables the native transport server (CQL binary protocol). @@ -290,8 +275,8 @@ in ''; }; - extraConfig = mkOption { - type = types.attrs; + extraConfig = lib.mkOption { + type = lib.types.attrs; default = { }; example = { commitlog_sync_batch_window_in_ms = 3; @@ -301,17 +286,17 @@ in ''; }; - extraEnvSh = mkOption { - type = types.lines; + extraEnvSh = lib.mkOption { + type = lib.types.lines; default = ""; - example = literalExpression ''"CLASSPATH=$CLASSPATH:''${extraJar}"''; + example = lib.literalExpression ''"CLASSPATH=$CLASSPATH:''${extraJar}"''; description = '' Extra shell lines to be appended onto {file}`cassandra-env.sh`. ''; }; - fullRepairInterval = mkOption { - type = types.nullOr types.str; + fullRepairInterval = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = "3w"; example = null; description = '' @@ -324,8 +309,8 @@ in ''; }; - fullRepairOptions = mkOption { - type = types.listOf types.str; + fullRepairOptions = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; example = [ "--partitioner-range" ]; description = '' @@ -333,8 +318,8 @@ in ''; }; - incrementalRepairInterval = mkOption { - type = types.nullOr types.str; + incrementalRepairInterval = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = "3d"; example = null; description = '' @@ -347,8 +332,8 @@ in ''; }; - incrementalRepairOptions = mkOption { - type = types.listOf types.str; + incrementalRepairOptions = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; example = [ "--partitioner-range" ]; description = '' @@ -356,8 +341,8 @@ in ''; }; - maxHeapSize = mkOption { - type = types.nullOr types.str; + maxHeapSize = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; example = "4G"; description = '' @@ -377,8 +362,8 @@ in ''; }; - heapNewSize = mkOption { - type = types.nullOr types.str; + heapNewSize = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; example = "800M"; description = '' @@ -401,8 +386,8 @@ in ''; }; - mallocArenaMax = mkOption { - type = types.nullOr types.int; + mallocArenaMax = lib.mkOption { + type = lib.types.nullOr lib.types.int; default = null; example = 4; description = '' @@ -410,8 +395,8 @@ in ''; }; - remoteJmx = mkOption { - type = types.bool; + remoteJmx = lib.mkOption { + type = lib.types.bool; default = false; description = '' Cassandra ships with JMX accessible *only* from localhost. @@ -422,8 +407,8 @@ in ''; }; - jmxPort = mkOption { - type = types.int; + jmxPort = lib.mkOption { + type = lib.types.int; default = 7199; description = '' Specifies the default port over which Cassandra will be available for @@ -433,7 +418,7 @@ in ''; }; - jmxRoles = mkOption { + jmxRoles = lib.mkOption { default = [ ]; description = '' Roles that are allowed to access the JMX (e.g. {command}`nodetool`) @@ -444,15 +429,15 @@ in Doesn't work in versions older than 3.11 because they don't like that it's world readable. ''; - type = types.listOf ( - types.submodule { + type = lib.types.listOf ( + lib.types.submodule { options = { - username = mkOption { - type = types.str; + username = lib.mkOption { + type = lib.types.str; description = "Username for JMX"; }; - password = mkOption { - type = types.str; + password = lib.mkOption { + type = lib.types.str; description = "Password for JMX"; }; }; @@ -460,10 +445,10 @@ in ); }; - jmxRolesFile = mkOption { - type = types.nullOr types.path; + jmxRolesFile = lib.mkOption { + type = lib.types.nullOr lib.types.path; default = if atLeast3_11 then pkgs.writeText "jmx-roles-file" defaultJmxRolesFile else null; - defaultText = literalMD ''generated configuration file if version is at least 3.11, otherwise `null`''; + defaultText = lib.literalMD ''generated configuration file if version is at least 3.11, otherwise `null`''; example = "/var/lib/cassandra/jmx.password"; description = '' Specify your own jmx roles file. @@ -474,7 +459,7 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { assertions = [ { assertion = (cfg.listenAddress == null) != (cfg.listenInterface == null); @@ -497,7 +482,7 @@ in ''; } ]; - users = mkIf (cfg.user == defaultUser) { + users = lib.mkIf (cfg.user == defaultUser) { users.${defaultUser} = { group = cfg.group; home = cfg.homeDir; @@ -536,7 +521,7 @@ in serviceConfig = { User = cfg.user; Group = cfg.group; - ExecStart = concatStringsSep " " ( + ExecStart = lib.concatStringsSep " " ( [ "${cfg.package}/bin/nodetool" "repair" @@ -547,7 +532,7 @@ in }; }; - systemd.timers.cassandra-full-repair = mkIf (cfg.fullRepairInterval != null) { + systemd.timers.cassandra-full-repair = lib.mkIf (cfg.fullRepairInterval != null) { description = "Schedule full repairs on Cassandra"; wantedBy = [ "timers.target" ]; timerConfig = { @@ -565,7 +550,7 @@ in serviceConfig = { User = cfg.user; Group = cfg.group; - ExecStart = concatStringsSep " " ( + ExecStart = lib.concatStringsSep " " ( [ "${cfg.package}/bin/nodetool" "repair" @@ -575,7 +560,7 @@ in }; }; - systemd.timers.cassandra-incremental-repair = mkIf (cfg.incrementalRepairInterval != null) { + systemd.timers.cassandra-incremental-repair = lib.mkIf (cfg.incrementalRepairInterval != null) { description = "Schedule incremental repairs on Cassandra"; wantedBy = [ "timers.target" ]; timerConfig = { diff --git a/nixos/modules/services/databases/chromadb.nix b/nixos/modules/services/databases/chromadb.nix index d8d60078cf455..404bd160dabf8 100644 --- a/nixos/modules/services/databases/chromadb.nix +++ b/nixos/modules/services/databases/chromadb.nix @@ -7,13 +7,6 @@ let cfg = config.services.chromadb; - inherit (lib) - mkEnableOption - mkOption - mkIf - types - literalExpression - ; in { @@ -21,48 +14,48 @@ in options = { services.chromadb = { - enable = mkEnableOption "ChromaDB, an open-source AI application database."; + enable = lib.mkEnableOption "ChromaDB, an open-source AI application database."; - package = mkOption { - type = types.package; - example = literalExpression "pkgs.python3Packages.chromadb"; + package = lib.mkOption { + type = lib.types.package; + example = lib.literalExpression "pkgs.python3Packages.chromadb"; default = pkgs.python3Packages.chromadb; defaultText = "pkgs.python3Packages.chromadb"; description = "ChromaDB package to use."; }; - host = mkOption { - type = types.str; + host = lib.mkOption { + type = lib.types.str; default = "127.0.0.1"; description = '' Defines the IP address by which ChromaDB will be accessible. ''; }; - port = mkOption { - type = types.port; + port = lib.mkOption { + type = lib.types.port; default = 8000; description = '' Defined the port number to listen. ''; }; - logFile = mkOption { - type = types.path; + logFile = lib.mkOption { + type = lib.types.path; default = "/var/log/chromadb/chromadb.log"; description = '' Specifies the location of file for logging output. ''; }; - dbpath = mkOption { - type = types.str; + dbpath = lib.mkOption { + type = lib.types.str; default = "/var/lib/chromadb"; description = "Location where ChromaDB stores its files"; }; - openFirewall = mkOption { - type = types.bool; + openFirewall = lib.mkOption { + type = lib.types.bool; default = false; description = '' Whether to automatically open the specified TCP port in the firewall. @@ -71,7 +64,7 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { systemd.services.chromadb = { description = "ChromaDB"; after = [ "network.target" ]; diff --git a/nixos/modules/services/databases/influxdb2.nix b/nixos/modules/services/databases/influxdb2.nix index 3dea70f6b8485..039e675bc8826 100644 --- a/nixos/modules/services/databases/influxdb2.nix +++ b/nixos/modules/services/databases/influxdb2.nix @@ -6,32 +6,6 @@ }: let - inherit (lib) - any - attrNames - attrValues - count - escapeShellArg - filterAttrs - flatten - flip - getExe - hasAttr - hasInfix - listToAttrs - literalExpression - mapAttrsToList - mkEnableOption - mkPackageOption - mkIf - mkOption - nameValuePair - optional - subtractLists - types - unique - ; - format = pkgs.formats.json { }; cfg = config.services.influxdb2; configFile = format.generate "config.json" cfg.settings; @@ -62,8 +36,8 @@ let ]; # Determines whether at least one active api token is defined - anyAuthDefined = flip any (attrValues cfg.provision.organizations) ( - o: o.present && flip any (attrValues o.auths) (a: a.present && a.tokenFile != null) + anyAuthDefined = lib.flip lib.any (lib.attrValues cfg.provision.organizations) ( + o: o.present && lib.flip lib.any (lib.attrValues o.auths) (a: a.present && a.tokenFile != null) ); provisionState = pkgs.writeText "provision_state.json" ( @@ -73,9 +47,9 @@ let ); influxHost = "http://${ - escapeShellArg ( + lib.escapeShellArg ( if - !hasAttr "http-bind-address" cfg.settings || hasInfix "0.0.0.0" cfg.settings.http-bind-address + !lib.hasAttr "http-bind-address" cfg.settings || lib.hasInfix "0.0.0.0" cfg.settings.http-bind-address then "localhost:8086" else @@ -112,9 +86,9 @@ let if test -e "$STATE_DIRECTORY/.first_startup"; then influx setup \ --configs-path /dev/null \ - --org ${escapeShellArg cfg.provision.initialSetup.organization} \ - --bucket ${escapeShellArg cfg.provision.initialSetup.bucket} \ - --username ${escapeShellArg cfg.provision.initialSetup.username} \ + --org ${lib.escapeShellArg cfg.provision.initialSetup.organization} \ + --bucket ${lib.escapeShellArg cfg.provision.initialSetup.bucket} \ + --username ${lib.escapeShellArg cfg.provision.initialSetup.username} \ --password "$(< "$CREDENTIALS_DIRECTORY/admin-password")" \ --token "$(< "$CREDENTIALS_DIRECTORY/admin-token")" \ --retention ${toString cfg.provision.initialSetup.retention}s \ @@ -123,7 +97,7 @@ let rm -f "$STATE_DIRECTORY/.first_startup" fi - provision_result=$(${getExe pkgs.influxdb2-provision} ${provisionState} "$INFLUX_HOST" "$(< "$CREDENTIALS_DIRECTORY/admin-token")") + provision_result=$(${lib.getExe pkgs.influxdb2-provision} ${provisionState} "$INFLUX_HOST" "$(< "$CREDENTIALS_DIRECTORY/admin-token")") if [[ "$(jq '[.auths[] | select(.action == "created")] | length' <<< "$provision_result")" -gt 0 ]]; then echo "Created at least one new token, queueing service restart so we can manipulate secrets" touch "$STATE_DIRECTORY/.needs_restart" @@ -138,50 +112,50 @@ let fi ''; - organizationSubmodule = types.submodule ( + organizationSubmodule = lib.types.submodule ( organizationSubmod: let org = organizationSubmod.config._module.args.name; in { options = { - present = mkOption { + present = lib.mkOption { description = "Whether to ensure that this organization is present or absent."; - type = types.bool; + type = lib.types.bool; default = true; }; - description = mkOption { + description = lib.mkOption { description = "Optional description for the organization."; default = null; - type = types.nullOr types.str; + type = lib.types.nullOr lib.types.str; }; - buckets = mkOption { + buckets = lib.mkOption { description = "Buckets to provision in this organization."; default = { }; - type = types.attrsOf ( - types.submodule ( + type = lib.types.attrsOf ( + lib.types.submodule ( bucketSubmod: let bucket = bucketSubmod.config._module.args.name; in { options = { - present = mkOption { + present = lib.mkOption { description = "Whether to ensure that this bucket is present or absent."; - type = types.bool; + type = lib.types.bool; default = true; }; - description = mkOption { + description = lib.mkOption { description = "Optional description for the bucket."; default = null; - type = types.nullOr types.str; + type = lib.types.nullOr lib.types.str; }; - retention = mkOption { - type = types.ints.unsigned; + retention = lib.mkOption { + type = lib.types.ints.unsigned; default = 0; description = "The duration in seconds for which the bucket will retain data (0 is infinite)."; }; @@ -191,32 +165,32 @@ let ); }; - auths = mkOption { + auths = lib.mkOption { description = "API tokens to provision for the user in this organization."; default = { }; - type = types.attrsOf ( - types.submodule ( + type = lib.types.attrsOf ( + lib.types.submodule ( authSubmod: let auth = authSubmod.config._module.args.name; in { options = { - id = mkOption { + id = lib.mkOption { description = "A unique identifier for this authentication token. Since influx doesn't store names for tokens, this will be hashed and appended to the description to identify the token."; readOnly = true; default = builtins.substring 0 32 (builtins.hashString "sha256" "${org}:${auth}"); defaultText = ""; - type = types.str; + type = lib.types.str; }; - present = mkOption { + present = lib.mkOption { description = "Whether to ensure that this user is present or absent."; - type = types.bool; + type = lib.types.bool; default = true; }; - description = mkOption { + description = lib.mkOption { description = '' Optional description for the API token. Note that the actual token will always be created with a descriptionregardless @@ -224,28 +198,28 @@ let to later identify the token to track whether it has already been created. ''; default = null; - type = types.nullOr types.str; + type = lib.types.nullOr lib.types.str; }; - tokenFile = mkOption { - type = types.nullOr types.path; + tokenFile = lib.mkOption { + type = lib.types.nullOr lib.types.path; default = null; description = "The token value. If not given, influx will automatically generate one."; }; - operator = mkOption { + operator = lib.mkOption { description = "Grants all permissions in all organizations."; default = false; - type = types.bool; + type = lib.types.bool; }; - allAccess = mkOption { + allAccess = lib.mkOption { description = "Grants all permissions in the associated organization."; default = false; - type = types.bool; + type = lib.types.bool; }; - readPermissions = mkOption { + readPermissions = lib.mkOption { description = '' The read permissions to include for this token. Access is usually granted only for resources in the associated organization. @@ -261,10 +235,10 @@ let more granular access permissions. ''; default = [ ]; - type = types.listOf (types.enum validPermissions); + type = lib.types.listOf (lib.types.enum validPermissions); }; - writePermissions = mkOption { + writePermissions = lib.mkOption { description = '' The read permissions to include for this token. Access is usually granted only for resources in the associated organization. @@ -280,19 +254,19 @@ let more granular access permissions. ''; default = [ ]; - type = types.listOf (types.enum validPermissions); + type = lib.types.listOf (lib.types.enum validPermissions); }; - readBuckets = mkOption { + readBuckets = lib.mkOption { description = "The organization's buckets which should be allowed to be read"; default = [ ]; - type = types.listOf types.str; + type = lib.types.listOf lib.types.str; }; - writeBuckets = mkOption { + writeBuckets = lib.mkOption { description = "The organization's buckets which should be allowed to be written"; default = [ ]; - type = types.listOf types.str; + type = lib.types.listOf lib.types.str; }; }; } @@ -306,58 +280,58 @@ in { options = { services.influxdb2 = { - enable = mkEnableOption "the influxdb2 server"; + enable = lib.mkEnableOption "the influxdb2 server"; - package = mkPackageOption pkgs "influxdb2" { }; + package = lib.mkPackageOption pkgs "influxdb2" { }; - settings = mkOption { + settings = lib.mkOption { default = { }; description = ''configuration options for influxdb2, see for details.''; type = format.type; }; provision = { - enable = mkEnableOption "initial database setup and provisioning"; + enable = lib.mkEnableOption "initial database setup and provisioning"; initialSetup = { - organization = mkOption { - type = types.str; + organization = lib.mkOption { + type = lib.types.str; example = "main"; description = "Primary organization name"; }; - bucket = mkOption { - type = types.str; + bucket = lib.mkOption { + type = lib.types.str; example = "example"; description = "Primary bucket name"; }; - username = mkOption { - type = types.str; + username = lib.mkOption { + type = lib.types.str; default = "admin"; description = "Primary username"; }; - retention = mkOption { - type = types.ints.unsigned; + retention = lib.mkOption { + type = lib.types.ints.unsigned; default = 0; description = "The duration in seconds for which the bucket will retain data (0 is infinite)."; }; - passwordFile = mkOption { - type = types.path; + passwordFile = lib.mkOption { + type = lib.types.path; description = "Password for primary user. Don't use a file from the nix store!"; }; - tokenFile = mkOption { - type = types.path; + tokenFile = lib.mkOption { + type = lib.types.path; description = "API Token to set for the admin user. Don't use a file from the nix store!"; }; }; - organizations = mkOption { + organizations = lib.mkOption { description = "Organizations to provision."; - example = literalExpression '' + example = lib.literalExpression '' { myorg = { description = "My organization"; @@ -373,20 +347,20 @@ in } ''; default = { }; - type = types.attrsOf organizationSubmodule; + type = lib.types.attrsOf organizationSubmodule; }; - users = mkOption { + users = lib.mkOption { description = "Users to provision."; default = { }; - example = literalExpression '' + example = lib.literalExpression '' { # admin = {}; /* The initialSetup.username will automatically be added. */ myuser.passwordFile = "/run/secrets/myuser_password"; } ''; - type = types.attrsOf ( - types.submodule ( + type = lib.types.attrsOf ( + lib.types.submodule ( userSubmod: let user = userSubmod.config._module.args.name; @@ -394,16 +368,16 @@ in in { options = { - present = mkOption { + present = lib.mkOption { description = "Whether to ensure that this user is present or absent."; - type = types.bool; + type = lib.types.bool; default = true; }; - passwordFile = mkOption { + passwordFile = lib.mkOption { description = "Password for the user. If unset, the user will not be able to log in until a password is set by an operator! Don't use a file from the nix store!"; default = null; - type = types.nullOr types.path; + type = lib.types.nullOr lib.types.path; }; }; } @@ -414,22 +388,22 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { assertions = [ { - assertion = !(hasAttr "bolt-path" cfg.settings) && !(hasAttr "engine-path" cfg.settings); + assertion = !(lib.hasAttr "bolt-path" cfg.settings) && !(lib.hasAttr "engine-path" cfg.settings); message = "services.influxdb2.config: bolt-path and engine-path should not be set as they are managed by systemd"; } ] - ++ flatten ( - flip mapAttrsToList cfg.provision.organizations ( + ++ lib.flatten ( + lib.flip lib.mapAttrsToList cfg.provision.organizations ( orgName: org: - flip mapAttrsToList org.auths ( + lib.flip lib.mapAttrsToList org.auths ( authName: auth: [ { assertion = - 1 == count (x: x) [ + 1 == lib.count (x: x) [ auth.operator auth.allAccess ( @@ -443,7 +417,7 @@ in } ( let - unknownBuckets = subtractLists (attrNames org.buckets) auth.readBuckets; + unknownBuckets = lib.subtractLists (lib.attrNames org.buckets) auth.readBuckets; in { assertion = unknownBuckets == [ ]; @@ -452,7 +426,7 @@ in ) ( let - unknownBuckets = subtractLists (attrNames org.buckets) auth.writeBuckets; + unknownBuckets = lib.subtractLists (lib.attrNames org.buckets) auth.writeBuckets; in { assertion = unknownBuckets == [ ]; @@ -464,7 +438,7 @@ in ) ); - services.influxdb2.provision = mkIf cfg.provision.enable { + services.influxdb2.provision = lib.mkIf cfg.provision.enable { organizations.${cfg.provision.initialSetup.organization} = { buckets.${cfg.provision.initialSetup.bucket} = { inherit (cfg.provision.initialSetup) retention; @@ -495,7 +469,7 @@ in LimitNOFILE = 65536; KillMode = "control-group"; Restart = "on-failure"; - LoadCredential = mkIf cfg.provision.enable [ + LoadCredential = lib.mkIf cfg.provision.enable [ "admin-password:${cfg.provision.initialSetup.passwordFile}" "admin-token:${cfg.provision.initialSetup.tokenFile}" ]; @@ -508,7 +482,7 @@ in [ provisioningScript ] ++ # Only the restarter runs with elevated privileges - optional anyAuthDefined "+${restarterScript}" + lib.optional anyAuthDefined "+${restarterScript}" )); }; @@ -521,28 +495,28 @@ in # Also extract any token secret mappings and apply them if this isn't the first start. preStart = let - tokenPaths = listToAttrs ( - flatten + tokenPaths = lib.listToAttrs ( + lib.flatten # For all organizations ( - flip mapAttrsToList cfg.provision.organizations + lib.flip lib.mapAttrsToList cfg.provision.organizations # For each contained token that has a token file ( _: org: - flip mapAttrsToList (filterAttrs (_: x: x.tokenFile != null) org.auths) + lib.flip lib.mapAttrsToList (lib.filterAttrs (_: x: x.tokenFile != null) org.auths) # Collect id -> tokenFile for the mapping - (_: auth: nameValuePair auth.id auth.tokenFile) + (_: auth: lib.nameValuePair auth.id auth.tokenFile) ) ) ); tokenMappings = pkgs.writeText "token_mappings.json" (builtins.toJSON tokenPaths); in - mkIf cfg.provision.enable '' + lib.mkIf cfg.provision.enable '' if ! test -e "$STATE_DIRECTORY/influxd.bolt"; then touch "$STATE_DIRECTORY/.first_startup" else # Manipulate provisioned api tokens if necessary - ${getExe pkgs.influxdb2-token-manipulator} "$STATE_DIRECTORY/influxd.bolt" ${tokenMappings} + ${lib.getExe pkgs.influxdb2-token-manipulator} "$STATE_DIRECTORY/influxd.bolt" ${tokenMappings} fi ''; }; diff --git a/nixos/modules/services/databases/lldap.nix b/nixos/modules/services/databases/lldap.nix index a9fbe8f7e11a9..51e408f5b2341 100644 --- a/nixos/modules/services/databases/lldap.nix +++ b/nixos/modules/services/databases/lldap.nix @@ -11,13 +11,13 @@ let format = pkgs.formats.toml { }; in { - options.services.lldap = with lib; { - enable = mkEnableOption "lldap, a lightweight authentication server that provides an opinionated, simplified LDAP interface for authentication"; + options.services.lldap = { + enable = lib.mkEnableOption "lldap, a lightweight authentication server that provides an opinionated, simplified LDAP interface for authentication"; - package = mkPackageOption pkgs "lldap" { }; + package = lib.mkPackageOption pkgs "lldap" { }; - environment = mkOption { - type = with types; attrsOf str; + environment = lib.mkOption { + type = with lib.types; attrsOf str; default = { }; example = { LLDAP_JWT_SECRET_FILE = "/run/lldap/jwt_secret"; @@ -29,15 +29,15 @@ in ''; }; - environmentFile = mkOption { - type = types.nullOr types.path; + environmentFile = lib.mkOption { + type = lib.types.nullOr lib.types.path; default = null; description = '' Environment file as defined in {manpage}`systemd.exec(5)` passed to the service. ''; }; - settings = mkOption { + settings = lib.mkOption { description = '' Free-form settings written directly to the `lldap_config.toml` file. Refer to for supported values. @@ -45,59 +45,59 @@ in default = { }; - type = types.submodule { + type = lib.types.submodule { freeformType = format.type; options = { - ldap_host = mkOption { - type = types.str; + ldap_host = lib.mkOption { + type = lib.types.str; description = "The host address that the LDAP server will be bound to."; default = "::"; }; - ldap_port = mkOption { - type = types.port; + ldap_port = lib.mkOption { + type = lib.types.port; description = "The port on which to have the LDAP server."; default = 3890; }; - http_host = mkOption { - type = types.str; + http_host = lib.mkOption { + type = lib.types.str; description = "The host address that the HTTP server will be bound to."; default = "::"; }; - http_port = mkOption { - type = types.port; + http_port = lib.mkOption { + type = lib.types.port; description = "The port on which to have the HTTP server, for user login and administration."; default = 17170; }; - http_url = mkOption { - type = types.str; + http_url = lib.mkOption { + type = lib.types.str; description = "The public URL of the server, for password reset links."; default = "http://localhost"; }; - ldap_base_dn = mkOption { - type = types.str; + ldap_base_dn = lib.mkOption { + type = lib.types.str; description = "Base DN for LDAP."; example = "dc=example,dc=com"; }; - ldap_user_dn = mkOption { - type = types.str; + ldap_user_dn = lib.mkOption { + type = lib.types.str; description = "Admin username"; default = "admin"; }; - ldap_user_email = mkOption { - type = types.str; + ldap_user_email = lib.mkOption { + type = lib.types.str; description = "Admin email."; default = "admin@example.com"; }; - database_url = mkOption { - type = types.str; + database_url = lib.mkOption { + type = lib.types.str; description = "Database URL."; default = "sqlite://./users.db?mode=rwc"; example = "postgres://postgres-user:password@postgres-server/my-database"; diff --git a/nixos/modules/services/databases/mysql.nix b/nixos/modules/services/databases/mysql.nix index 412fe4836cd3d..875308555cbeb 100644 --- a/nixos/modules/services/databases/mysql.nix +++ b/nixos/modules/services/databases/mysql.nix @@ -158,7 +158,7 @@ in default = []; description = '' List of database names and their initial schemas that should be used to create databases on the first startup - of MySQL. The schema attribute is optional: If not specified, an empty database is created. + of MySQL. The schema attribute is lib.optional: If not specified, an empty database is created. ''; example = lib.literalExpression '' [ diff --git a/nixos/modules/services/databases/postgresql.nix b/nixos/modules/services/databases/postgresql.nix index 59fef3824d857..409e7d1f8cfce 100644 --- a/nixos/modules/services/databases/postgresql.nix +++ b/nixos/modules/services/databases/postgresql.nix @@ -6,36 +6,6 @@ }: let - inherit (lib) - any - attrValues - concatMapStrings - concatStringsSep - const - elem - escapeShellArgs - filterAttrs - getName - isString - literalExpression - mapAttrs - mapAttrsToList - mkAfter - mkBefore - mkDefault - mkEnableOption - mkIf - mkMerge - mkOption - mkPackageOption - mkRemovedOptionModule - mkRenamedOptionModule - optionalString - types - versionAtLeast - warn - ; - cfg = config.services.postgresql; # ensure that @@ -54,15 +24,15 @@ let "yes" else if false == value then "no" - else if isString value then + else if lib.isString value then "'${lib.replaceStrings [ "'" ] [ "''" ] value}'" else builtins.toString value; # The main PostgreSQL configuration file. configFile = pkgs.writeTextDir "postgresql.conf" ( - concatStringsSep "\n" ( - mapAttrsToList (n: v: "${n} = ${toStr v}") (filterAttrs (const (x: x != null)) cfg.settings) + lib.concatStringsSep "\n" ( + lib.mapAttrsToList (n: v: "${n} = ${toStr v}") (lib.filterAttrs (lib.const (x: x != null)) cfg.settings) ) ); @@ -71,29 +41,29 @@ let touch $out ''; - groupAccessAvailable = versionAtLeast cfg.finalPackage.version "11.0"; + groupAccessAvailable = lib.versionAtLeast cfg.finalPackage.version "11.0"; - extensionNames = map getName postgresql.installedExtensions; - extensionInstalled = extension: elem extension extensionNames; + extensionNames = map lib.getName postgresql.installedExtensions; + extensionInstalled = extension: lib.elem extension extensionNames; in { imports = [ - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "postgresql" "extraConfig" ] "Use services.postgresql.settings instead.") - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "postgresql" "logLinePrefix" ] [ "services" "postgresql" "settings" "log_line_prefix" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "postgresql" "port" ] [ "services" "postgresql" "settings" "port" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "postgresql" "extraPlugins" ] [ "services" "postgresql" "extensions" ] ) @@ -105,16 +75,16 @@ in services.postgresql = { - enable = mkEnableOption "PostgreSQL Server"; + enable = lib.mkEnableOption "PostgreSQL Server"; - enableJIT = mkEnableOption "JIT support"; + enableJIT = lib.mkEnableOption "JIT support"; - package = mkPackageOption pkgs "postgresql" { + package = lib.mkPackageOption pkgs "postgresql" { example = "postgresql_15"; }; - finalPackage = mkOption { - type = types.package; + finalPackage = lib.mkOption { + type = lib.types.package; readOnly = true; default = postgresql; defaultText = "with config.services.postgresql; package.withPackages extensions"; @@ -124,15 +94,15 @@ in ''; }; - checkConfig = mkOption { - type = types.bool; + checkConfig = lib.mkOption { + type = lib.types.bool; default = true; description = "Check the syntax of the configuration file at compile time"; }; - dataDir = mkOption { - type = types.path; - defaultText = literalExpression ''"/var/lib/postgresql/''${config.services.postgresql.package.psqlSchema}"''; + dataDir = lib.mkOption { + type = lib.types.path; + defaultText = lib.literalExpression ''"/var/lib/postgresql/''${config.services.postgresql.package.psqlSchema}"''; example = "/var/lib/postgresql/15"; description = '' The data directory for PostgreSQL. If left as the default value @@ -142,8 +112,8 @@ in ''; }; - authentication = mkOption { - type = types.lines; + authentication = lib.mkOption { + type = lib.types.lines; default = ""; description = '' Defines how users authenticate themselves to the server. See the @@ -158,8 +128,8 @@ in ''; }; - identMap = mkOption { - type = types.lines; + identMap = lib.mkOption { + type = lib.types.lines; default = ""; example = '' map-name-0 system-username-0 database-username-0 @@ -172,8 +142,8 @@ in ''; }; - initdbArgs = mkOption { - type = with types; listOf str; + initdbArgs = lib.mkOption { + type = with lib.types; listOf str; default = [ ]; example = [ "--data-checksums" @@ -185,10 +155,10 @@ in ''; }; - initialScript = mkOption { - type = types.nullOr types.path; + initialScript = lib.mkOption { + type = lib.types.nullOr lib.types.path; default = null; - example = literalExpression '' + example = lib.literalExpression '' pkgs.writeText "init-sql-script" ''' alter user postgres with password 'myPassword'; ''';''; @@ -198,8 +168,8 @@ in ''; }; - ensureDatabases = mkOption { - type = types.listOf types.str; + ensureDatabases = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; description = '' Ensures that the specified databases exist. @@ -213,19 +183,19 @@ in ]; }; - ensureUsers = mkOption { - type = types.listOf ( - types.submodule { + ensureUsers = lib.mkOption { + type = lib.types.listOf ( + lib.types.submodule { options = { - name = mkOption { - type = types.str; + name = lib.mkOption { + type = lib.types.str; description = '' Name of the user to ensure. ''; }; - ensureDBOwnership = mkOption { - type = types.bool; + ensureDBOwnership = lib.mkOption { + type = lib.types.bool; default = false; description = '' Grants the user ownership to a database with the same name. @@ -234,14 +204,14 @@ in ''; }; - ensureClauses = mkOption { + ensureClauses = lib.mkOption { description = '' An attrset of clauses to grant to the user. Under the hood this uses the [ALTER USER syntax](https://www.postgresql.org/docs/current/sql-alteruser.html) for each attrName where the attrValue is true in the attrSet: `ALTER USER user.name WITH attrName` ''; - example = literalExpression '' + example = lib.literalExpression '' { superuser = true; createrole = true; @@ -252,7 +222,7 @@ in defaultText = lib.literalMD '' The default, `null`, means that the user created will have the default permissions assigned by PostgreSQL. Subsequent server starts will not set or unset the clause, so imperative changes are preserved. ''; - type = types.submodule { + type = lib.types.submodule { options = let defaultText = lib.literalMD '' @@ -260,8 +230,8 @@ in ''; in { - superuser = mkOption { - type = types.nullOr types.bool; + superuser = lib.mkOption { + type = lib.types.nullOr lib.types.bool; description = '' Grants the user, created by the ensureUser attr, superuser permissions. From the postgres docs: @@ -277,8 +247,8 @@ in default = null; inherit defaultText; }; - createrole = mkOption { - type = types.nullOr types.bool; + createrole = lib.mkOption { + type = lib.types.nullOr lib.types.bool; description = '' Grants the user, created by the ensureUser attr, createrole permissions. From the postgres docs: @@ -296,8 +266,8 @@ in default = null; inherit defaultText; }; - createdb = mkOption { - type = types.nullOr types.bool; + createdb = lib.mkOption { + type = lib.types.nullOr lib.types.bool; description = '' Grants the user, created by the ensureUser attr, createdb permissions. From the postgres docs: @@ -311,8 +281,8 @@ in default = null; inherit defaultText; }; - "inherit" = mkOption { - type = types.nullOr types.bool; + "inherit" = lib.mkOption { + type = lib.types.nullOr lib.types.bool; description = '' Grants the user created inherit permissions. From the postgres docs: @@ -326,8 +296,8 @@ in default = null; inherit defaultText; }; - login = mkOption { - type = types.nullOr types.bool; + login = lib.mkOption { + type = lib.types.nullOr lib.types.bool; description = '' Grants the user, created by the ensureUser attr, login permissions. From the postgres docs: @@ -348,8 +318,8 @@ in default = null; inherit defaultText; }; - replication = mkOption { - type = types.nullOr types.bool; + replication = lib.mkOption { + type = lib.types.nullOr lib.types.bool; description = '' Grants the user, created by the ensureUser attr, replication permissions. From the postgres docs: @@ -364,8 +334,8 @@ in default = null; inherit defaultText; }; - bypassrls = mkOption { - type = types.nullOr types.bool; + bypassrls = lib.mkOption { + type = lib.types.nullOr lib.types.bool; description = '' Grants the user, created by the ensureUser attr, replication permissions. From the postgres docs: @@ -395,7 +365,7 @@ in once granted with `ensureDBOwnership = true;`. This means that this must be cleaned up manually when changing after changing the config in here. ''; - example = literalExpression '' + example = lib.literalExpression '' [ { name = "nextcloud"; @@ -408,8 +378,8 @@ in ''; }; - enableTCPIP = mkOption { - type = types.bool; + enableTCPIP = lib.mkOption { + type = lib.types.bool; default = false; description = '' Whether PostgreSQL should listen on all network interfaces. @@ -418,18 +388,18 @@ in ''; }; - extensions = mkOption { - type = with types; coercedTo (listOf path) (path: _ignorePg: path) (functionTo (listOf path)); + extensions = lib.mkOption { + type = with lib.types; coercedTo (listOf path) (path: _ignorePg: path) (functionTo (listOf path)); default = _: [ ]; - example = literalExpression "ps: with ps; [ postgis pg_repack ]"; + example = lib.literalExpression "ps: with ps; [ postgis pg_repack ]"; description = '' List of PostgreSQL extensions to install. ''; }; - settings = mkOption { + settings = lib.mkOption { type = - with types; + with lib.types; submodule { freeformType = attrsOf (oneOf [ bool @@ -438,17 +408,17 @@ in str ]); options = { - shared_preload_libraries = mkOption { - type = nullOr (coercedTo (listOf str) (concatStringsSep ", ") str); + shared_preload_libraries = lib.mkOption { + type = nullOr (coercedTo (listOf str) (lib.concatStringsSep ", ") str); default = null; - example = literalExpression ''[ "auto_explain" "anon" ]''; + example = lib.literalExpression ''[ "auto_explain" "anon" ]''; description = '' List of libraries to be preloaded. ''; }; - log_line_prefix = mkOption { - type = types.str; + log_line_prefix = lib.mkOption { + type = lib.types.str; default = "[%p] "; example = "%m [%p] "; description = '' @@ -458,8 +428,8 @@ in ''; }; - port = mkOption { - type = types.port; + port = lib.mkOption { + type = lib.types.port; default = 5432; description = '' The port on which PostgreSQL listens. @@ -478,7 +448,7 @@ in escaped with two single quotes as described by the upstream documentation linked above. ::: ''; - example = literalExpression '' + example = lib.literalExpression '' { log_connections = true; log_statement = "all"; @@ -489,16 +459,16 @@ in ''; }; - recoveryConfig = mkOption { - type = types.nullOr types.lines; + recoveryConfig = lib.mkOption { + type = lib.types.nullOr lib.types.lines; default = null; description = '' Contents of the {file}`recovery.conf` file. ''; }; - superUser = mkOption { - type = types.str; + superUser = lib.mkOption { + type = lib.types.str; default = "postgres"; internal = true; readOnly = true; @@ -513,12 +483,12 @@ in ###### implementation - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { assertions = map ( { name, ensureDBOwnership, ... }: { - assertion = ensureDBOwnership -> elem name cfg.ensureDatabases; + assertion = ensureDBOwnership -> lib.elem name cfg.ensureDatabases; message = '' For each database user defined with `services.postgresql.ensureUsers` and `ensureDBOwnership = true;`, a database with the same name must be defined @@ -534,7 +504,7 @@ in ident_file = "${pkgs.writeText "pg_ident.conf" cfg.identMap}"; log_destination = "stderr"; listen_addresses = if cfg.enableTCPIP then "*" else "localhost"; - jit = mkDefault (if cfg.enableJIT then "on" else "off"); + jit = lib.mkDefault (if cfg.enableJIT then "on" else "off"); }; services.postgresql.package = @@ -542,7 +512,7 @@ in mkThrow = ver: throw "postgresql_${ver} was removed, please upgrade your postgresql version."; mkWarn = ver: - warn '' + lib.warn '' The postgresql package is not pinned and selected automatically by `system.stateVersion`. Right now this is `pkgs.postgresql_${ver}`, the oldest postgresql version available and thus the next that will be @@ -551,17 +521,17 @@ in See also https://endoflife.date/postgresql ''; base = - if versionAtLeast config.system.stateVersion "24.11" then + if lib.versionAtLeast config.system.stateVersion "24.11" then pkgs.postgresql_16 - else if versionAtLeast config.system.stateVersion "23.11" then + else if lib.versionAtLeast config.system.stateVersion "23.11" then pkgs.postgresql_15 - else if versionAtLeast config.system.stateVersion "22.05" then + else if lib.versionAtLeast config.system.stateVersion "22.05" then pkgs.postgresql_14 - else if versionAtLeast config.system.stateVersion "21.11" then + else if lib.versionAtLeast config.system.stateVersion "21.11" then mkWarn "13" pkgs.postgresql_13 - else if versionAtLeast config.system.stateVersion "20.03" then + else if lib.versionAtLeast config.system.stateVersion "20.03" then mkThrow "11" - else if versionAtLeast config.system.stateVersion "17.09" then + else if lib.versionAtLeast config.system.stateVersion "17.09" then mkThrow "9_6" else mkThrow "9_5"; @@ -569,13 +539,13 @@ in # Note: when changing the default, make it conditional on # ‘system.stateVersion’ to maintain compatibility with existing # systems! - mkDefault (if cfg.enableJIT then base.withJIT else base); + lib.mkDefault (if cfg.enableJIT then base.withJIT else base); - services.postgresql.dataDir = mkDefault "/var/lib/postgresql/${cfg.package.psqlSchema}"; + services.postgresql.dataDir = lib.mkDefault "/var/lib/postgresql/${cfg.package.psqlSchema}"; - services.postgresql.authentication = mkMerge [ - (mkBefore "# Generated file; do not edit!") - (mkAfter '' + services.postgresql.authentication = lib.mkMerge [ + (lib.mkBefore "# Generated file; do not edit!") + (lib.mkAfter '' # default value of services.postgresql.authentication local all all peer host all all 127.0.0.1/32 md5 @@ -620,14 +590,14 @@ in rm -f ${cfg.dataDir}/*.conf # Initialise the database. - initdb -U ${cfg.superUser} ${escapeShellArgs cfg.initdbArgs} + initdb -U ${cfg.superUser} ${lib.escapeShellArgs cfg.initdbArgs} # See postStart! touch "${cfg.dataDir}/.first_startup" fi ln -sfn "${configFile}/postgresql.conf" "${cfg.dataDir}/postgresql.conf" - ${optionalString (cfg.recoveryConfig != null) '' + ${lib.optionalString (cfg.recoveryConfig != null) '' ln -sfn "${pkgs.writeText "recovery.conf" cfg.recoveryConfig}" \ "${cfg.dataDir}/recovery.conf" ''} @@ -644,28 +614,28 @@ in done if test -e "${cfg.dataDir}/.first_startup"; then - ${optionalString (cfg.initialScript != null) '' + ${lib.optionalString (cfg.initialScript != null) '' $PSQL -f "${cfg.initialScript}" -d postgres ''} rm -f "${cfg.dataDir}/.first_startup" fi '' - + optionalString (cfg.ensureDatabases != [ ]) '' - ${concatMapStrings (database: '' + + lib.optionalString (cfg.ensureDatabases != [ ]) '' + ${lib.concatMapStrings (database: '' $PSQL -tAc "SELECT 1 FROM pg_database WHERE datname = '${database}'" | grep -q 1 || $PSQL -tAc 'CREATE DATABASE "${database}"' '') cfg.ensureDatabases} '' + '' - ${concatMapStrings ( + ${lib.concatMapStrings ( user: let - dbOwnershipStmt = optionalString user.ensureDBOwnership ''$PSQL -tAc 'ALTER DATABASE "${user.name}" OWNER TO "${user.name}";' ''; + dbOwnershipStmt = lib.optionalString user.ensureDBOwnership ''$PSQL -tAc 'ALTER DATABASE "${user.name}" OWNER TO "${user.name}";' ''; - filteredClauses = filterAttrs (name: value: value != null) user.ensureClauses; + filteredClauses = lib.filterAttrs (name: value: value != null) user.ensureClauses; - clauseSqlStatements = attrValues (mapAttrs (n: v: if v then n else "no${n}") filteredClauses); + clauseSqlStatements = lib.attrValues (lib.mapAttrs (n: v: if v then n else "no${n}") filteredClauses); - userClauses = ''$PSQL -tAc 'ALTER ROLE "${user.name}" ${concatStringsSep " " clauseSqlStatements}' ''; + userClauses = ''$PSQL -tAc 'ALTER ROLE "${user.name}" ${lib.concatStringsSep " " clauseSqlStatements}' ''; in '' $PSQL -tAc "SELECT 1 FROM pg_roles WHERE rolname='${user.name}'" | grep -q 1 || $PSQL -tAc 'CREATE USER "${user.name}"' @@ -676,13 +646,13 @@ in ) cfg.ensureUsers} ''; - serviceConfig = mkMerge [ + serviceConfig = lib.mkMerge [ { ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID"; User = "postgres"; Group = "postgres"; RuntimeDirectory = "postgresql"; - Type = if versionAtLeast cfg.package.version "9.6" then "notify" else "simple"; + Type = if lib.versionAtLeast cfg.package.version "9.6" then "notify" else "simple"; # Shut down Postgres using SIGINT ("Fast Shutdown mode"). See # https://www.postgresql.org/docs/current/server-shutdown.html @@ -702,7 +672,7 @@ in ProtectHome = true; ProtectSystem = "strict"; MemoryDenyWriteExecute = lib.mkDefault ( - cfg.settings.jit == "off" && (!any extensionInstalled [ "plv8" ]) + cfg.settings.jit == "off" && (!lib.any extensionInstalled [ "plv8" ]) ); NoNewPrivileges = true; LockPersonality = true; @@ -730,13 +700,13 @@ in SystemCallFilter = [ "@system-service" "~@privileged @resources" - ] ++ lib.optionals (any extensionInstalled [ "plv8" ]) [ "@pkey" ]; + ] ++ lib.optionals (lib.any extensionInstalled [ "plv8" ]) [ "@pkey" ]; UMask = if groupAccessAvailable then "0027" else "0077"; } - (mkIf (cfg.dataDir != "/var/lib/postgresql") { + (lib.mkIf (cfg.dataDir != "/var/lib/postgresql") { ReadWritePaths = [ cfg.dataDir ]; }) - (mkIf (cfg.dataDir == "/var/lib/postgresql/${cfg.package.psqlSchema}") { + (lib.mkIf (cfg.dataDir == "/var/lib/postgresql/${cfg.package.psqlSchema}") { StateDirectory = "postgresql postgresql/${cfg.package.psqlSchema}"; StateDirectoryMode = if groupAccessAvailable then "0750" else "0700"; }) diff --git a/nixos/modules/services/databases/redis.nix b/nixos/modules/services/databases/redis.nix index 31532646f8edc..7835a2509c0a2 100644 --- a/nixos/modules/services/databases/redis.nix +++ b/nixos/modules/services/databases/redis.nix @@ -64,7 +64,7 @@ in { enable = lib.mkEnableOption "Redis server"; user = lib.mkOption { - type = types.str; + type = lib.types.str; default = redisName name; defaultText = lib.literalExpression '' if name == "" then "redis" else "redis-''${name}" @@ -80,7 +80,7 @@ in { }; group = lib.mkOption { - type = types.str; + type = lib.types.str; default = config.user; defaultText = lib.literalExpression "config.user"; description = '' @@ -94,7 +94,7 @@ in { }; port = lib.mkOption { - type = types.port; + type = lib.types.port; default = if name == "" then 6379 else 0; defaultText = lib.literalExpression ''if name == "" then 6379 else 0''; description = '' @@ -104,7 +104,7 @@ in { }; openFirewall = lib.mkOption { - type = types.bool; + type = lib.types.bool; default = false; description = '' Whether to open ports in the firewall for the server. @@ -112,14 +112,14 @@ in { }; extraParams = lib.mkOption { - type = with types; listOf str; + type = with lib.types; listOf str; default = []; description = "Extra parameters to append to redis-server invocation"; example = [ "--sentinel" ]; }; bind = lib.mkOption { - type = with types; nullOr str; + type = with lib.types; nullOr str; default = "127.0.0.1"; description = '' The IP interface to bind to. @@ -129,7 +129,7 @@ in { }; unixSocket = lib.mkOption { - type = with types; nullOr path; + type = with lib.types; nullOr path; default = "/run/${redisName name}/redis.sock"; defaultText = lib.literalExpression '' if name == "" then "/run/redis/redis.sock" else "/run/redis-''${name}/redis.sock" @@ -138,46 +138,46 @@ in { }; unixSocketPerm = lib.mkOption { - type = types.int; + type = lib.types.int; default = 660; description = "Change permissions for the socket"; example = 600; }; logLevel = lib.mkOption { - type = types.str; + type = lib.types.str; default = "notice"; # debug, verbose, notice, warning example = "debug"; description = "Specify the server verbosity level, options: debug, verbose, notice, warning."; }; logfile = lib.mkOption { - type = types.str; + type = lib.types.str; default = "/dev/null"; description = "Specify the log file name. Also 'stdout' can be used to force Redis to log on the standard output."; example = "/var/log/redis.log"; }; syslog = lib.mkOption { - type = types.bool; + type = lib.types.bool; default = true; description = "Enable logging to the system logger."; }; databases = lib.mkOption { - type = types.int; + type = lib.types.int; default = 16; description = "Set the number of databases."; }; maxclients = lib.mkOption { - type = types.int; + type = lib.types.int; default = 10000; description = "Set the max number of connected clients at the same time."; }; save = lib.mkOption { - type = with types; listOf (listOf int); + type = with lib.types; listOf (listOf int); default = [ [900 1] [300 10] [60 10000] ]; description = '' The schedule in which data is persisted to disk, represented as a list of lists where the first element represent the amount of seconds and the second the number of changes. @@ -187,7 +187,7 @@ in { }; slaveOf = lib.mkOption { - type = with types; nullOr (submodule ({ ... }: { + type = with lib.types; nullOr (submodule ({ ... }: { options = { ip = lib.mkOption { type = str; @@ -209,7 +209,7 @@ in { }; masterAuth = lib.mkOption { - type = with types; nullOr str; + type = with lib.types; nullOr str; default = null; description = ''If the master is password protected (using the requirePass configuration) it is possible to tell the slave to authenticate before starting the replication synchronization @@ -218,7 +218,7 @@ in { }; requirePass = lib.mkOption { - type = with types; nullOr str; + type = with lib.types; nullOr str; default = null; description = '' Password for database (STORED PLAIN TEXT, WORLD-READABLE IN NIX STORE). @@ -228,40 +228,40 @@ in { }; requirePassFile = lib.mkOption { - type = with types; nullOr path; + type = with lib.types; nullOr path; default = null; description = "File with password for the database."; example = "/run/keys/redis-password"; }; appendOnly = lib.mkOption { - type = types.bool; + type = lib.types.bool; default = false; description = "By default data is only periodically persisted to disk, enable this option to use an append-only file for improved persistence."; }; appendFsync = lib.mkOption { - type = types.str; + type = lib.types.str; default = "everysec"; # no, always, everysec description = "How often to fsync the append-only log, options: no, always, everysec."; }; slowLogLogSlowerThan = lib.mkOption { - type = types.int; + type = lib.types.int; default = 10000; description = "Log queries whose execution take longer than X in milliseconds."; example = 1000; }; slowLogMaxLen = lib.mkOption { - type = types.int; + type = lib.types.int; default = 128; description = "Maximum number of items to keep in slow log."; }; settings = lib.mkOption { # TODO: this should be converted to freeformType - type = with types; attrsOf (oneOf [ bool int str (listOf str) ]); + type = with lib.types; attrsOf (oneOf [ bool int str (listOf str) ]); default = {}; description = '' Redis configuration. Refer to diff --git a/nixos/modules/services/databases/tigerbeetle.nix b/nixos/modules/services/databases/tigerbeetle.nix index 514652a6c8d14..54b67490906d1 100644 --- a/nixos/modules/services/databases/tigerbeetle.nix +++ b/nixos/modules/services/databases/tigerbeetle.nix @@ -15,13 +15,13 @@ in }; options = { - services.tigerbeetle = with lib; { - enable = mkEnableOption "TigerBeetle server"; + services.tigerbeetle = { + enable = lib.mkEnableOption "TigerBeetle server"; - package = mkPackageOption pkgs "tigerbeetle" { }; + package = lib.mkPackageOption pkgs "tigerbeetle" { }; - clusterId = mkOption { - type = types.either types.ints.unsigned (types.strMatching "[0-9]+"); + clusterId = lib.mkOption { + type = lib.types.either lib.types.ints.unsigned (lib.types.strMatching "[0-9]+"); default = 0; description = '' The 128-bit cluster ID used to create the replica data file (if needed). @@ -30,24 +30,24 @@ in ''; }; - replicaIndex = mkOption { - type = types.ints.unsigned; + replicaIndex = lib.mkOption { + type = lib.types.ints.unsigned; default = 0; description = '' The index (starting at 0) of the replica in the cluster. ''; }; - replicaCount = mkOption { - type = types.ints.unsigned; + replicaCount = lib.mkOption { + type = lib.types.ints.unsigned; default = 1; description = '' The number of replicas participating in replication of the cluster. ''; }; - cacheGridSize = mkOption { - type = types.strMatching "[0-9]+(K|M|G)iB"; + cacheGridSize = lib.mkOption { + type = lib.types.strMatching "[0-9]+(K|M|G)iB"; default = "1GiB"; description = '' The grid cache size. @@ -56,8 +56,8 @@ in ''; }; - addresses = mkOption { - type = types.listOf types.nonEmptyStr; + addresses = lib.mkOption { + type = lib.types.listOf lib.types.nonEmptyStr; default = [ "3001" ]; description = '' The addresses of all replicas in the cluster. diff --git a/nixos/modules/services/databases/victoriametrics.nix b/nixos/modules/services/databases/victoriametrics.nix index e22b85371c3a1..de37371a7fc18 100644 --- a/nixos/modules/services/databases/victoriametrics.nix +++ b/nixos/modules/services/databases/victoriametrics.nix @@ -4,7 +4,6 @@ lib, ... }: -with lib; let cfg = config.services.victoriametrics; settingsFormat = pkgs.formats.yaml { }; @@ -40,18 +39,18 @@ in VictoriaMetrics is a fast, cost-effective and scalable monitoring solution and time series database. ''; }; - package = mkPackageOption pkgs "victoriametrics" { }; + package = lib.mkPackageOption pkgs "victoriametrics" { }; - listenAddress = mkOption { + listenAddress = lib.mkOption { default = ":8428"; - type = types.str; + type = lib.types.str; description = '' TCP address to listen for incoming http requests. ''; }; - stateDir = mkOption { - type = types.str; + stateDir = lib.mkOption { + type = lib.types.str; default = "victoriametrics"; description = '' Directory below `/var/lib` to store VictoriaMetrics metrics data. @@ -59,14 +58,14 @@ in ''; }; - retentionPeriod = mkOption { - type = types.nullOr types.str; + retentionPeriod = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; example = "15d"; description = '' How long to retain samples in storage. The minimum retentionPeriod is 24h or 1d. See also -retentionFilter - The following optional suffixes are supported: s (second), h (hour), d (day), w (week), y (year). + The following lib.optional suffixes are supported: s (second), h (hour), d (day), w (week), y (year). If suffix isn't set, then the duration is counted in months (default 1) ''; }; @@ -74,7 +73,7 @@ in prometheusConfig = lib.mkOption { type = lib.types.submodule { freeformType = settingsFormat.type; }; default = { }; - example = literalExpression '' + example = lib.literalExpression '' { scrape_configs = [ { @@ -111,10 +110,10 @@ in ''; }; - extraOptions = mkOption { - type = types.listOf types.str; + extraOptions = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; - example = literalExpression '' + example = lib.literalExpression '' [ "-httpAuth.username=username" "-httpAuth.password=file:///abs/path/to/file" diff --git a/nixos/modules/services/desktop-managers/plasma6.nix b/nixos/modules/services/desktop-managers/plasma6.nix index f6be4413fc7d2..63205d74cc724 100644 --- a/nixos/modules/services/desktop-managers/plasma6.nix +++ b/nixos/modules/services/desktop-managers/plasma6.nix @@ -9,14 +9,6 @@ let cfg = config.services.desktopManager.plasma6; inherit (pkgs) kdePackages; - inherit (lib) - literalExpression - mkDefault - mkIf - mkOption - mkPackageOption - types - ; activationScript = '' # will be rebuilt automatically @@ -26,29 +18,29 @@ in { options = { services.desktopManager.plasma6 = { - enable = mkOption { - type = types.bool; + enable = lib.mkOption { + type = lib.types.bool; default = false; description = "Enable the Plasma 6 (KDE 6) desktop environment."; }; - enableQt5Integration = mkOption { - type = types.bool; + enableQt5Integration = lib.mkOption { + type = lib.types.bool; default = true; description = "Enable Qt 5 integration (theming, etc). Disable for a pure Qt 6 system."; }; - notoPackage = mkPackageOption pkgs "Noto fonts - used for UI by default" { + notoPackage = lib.mkPackageOption pkgs "Noto fonts - used for UI by default" { default = [ "noto-fonts" ]; example = "noto-fonts-lgc-plus"; }; }; - environment.plasma6.excludePackages = mkOption { + environment.plasma6.excludePackages = lib.mkOption { description = "List of default packages to exclude from the configuration"; - type = types.listOf types.package; + type = lib.types.listOf lib.types.package; default = [ ]; - example = literalExpression "[ pkgs.kdePackages.elisa ]"; + example = lib.literalExpression "[ pkgs.kdePackages.elisa ]"; }; }; @@ -67,7 +59,7 @@ in ) ]; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { assertions = [ { assertion = cfg.enable -> !config.services.xserver.desktopManager.plasma5.enable; @@ -93,7 +85,7 @@ in kguiaddons # provides geo URL handlers kiconthemes # provides Qt plugins kimageformats # provides Qt plugins - qtimageformats # provides optional image formats such as .webp and .avif + qtimageformats # provides lib.optional image formats such as .webp and .avif kio # provides helper service + a bunch of other stuff kio-admin # managing files as admin kio-extras # stuff for MTP, AFC, etc @@ -154,7 +146,7 @@ in systemsettings kcmutils ]; - optionalPackages = + lib.optionalPackages = [ plasma-browser-integration konsole @@ -180,7 +172,7 @@ in ]; in requiredPackages - ++ utils.removePackagesByName optionalPackages config.environment.plasma6.excludePackages + ++ utils.removePackagesByName lib.optionalPackages config.environment.plasma6.excludePackages ++ lib.optionals config.services.desktopManager.plasma6.enableQt5Integration [ breeze.qt5 plasma-integration.qt5 @@ -254,20 +246,20 @@ in serif = [ "Noto Serif" ]; }; - programs.gnupg.agent.pinentryPackage = mkDefault pkgs.pinentry-qt; - programs.kde-pim.enable = mkDefault true; - programs.ssh.askPassword = mkDefault "${kdePackages.ksshaskpass.out}/bin/ksshaskpass"; + programs.gnupg.agent.pinentryPackage = lib.mkDefault pkgs.pinentry-qt; + programs.kde-pim.enable = lib.mkDefault true; + programs.ssh.askPassword = lib.mkDefault "${kdePackages.ksshaskpass.out}/bin/ksshaskpass"; # Enable helpful DBus services. services.accounts-daemon.enable = true; # when changing an account picture the accounts-daemon reads a temporary file containing the image which systemsettings5 may place under /tmp systemd.services.accounts-daemon.serviceConfig.PrivateTmp = false; - services.power-profiles-daemon.enable = mkDefault true; - services.system-config-printer.enable = mkIf config.services.printing.enable (mkDefault true); + services.power-profiles-daemon.enable = lib.mkDefault true; + services.system-config-printer.enable = lib.mkIf config.services.printing.enable (lib.mkDefault true); services.udisks2.enable = true; services.upower.enable = config.powerManagement.enable; - services.libinput.enable = mkDefault true; + services.libinput.enable = lib.mkDefault true; # Extra UDEV rules used by Solid services.udev.packages = [ @@ -281,7 +273,7 @@ in systemd.services."drkonqi-coredump-processor@".wantedBy = [ "systemd-coredump@.service" ]; xdg.icons.enable = true; - xdg.icons.fallbackCursorThemes = mkDefault [ "breeze_cursors" ]; + xdg.icons.fallbackCursorThemes = lib.mkDefault [ "breeze_cursors" ]; xdg.portal.enable = true; xdg.portal.extraPortals = [ @@ -289,20 +281,20 @@ in kdePackages.xdg-desktop-portal-kde pkgs.xdg-desktop-portal-gtk ]; - xdg.portal.configPackages = mkDefault [ kdePackages.plasma-workspace ]; - services.pipewire.enable = mkDefault true; + xdg.portal.configPackages = lib.mkDefault [ kdePackages.plasma-workspace ]; + services.pipewire.enable = lib.mkDefault true; # Enable screen reader by default - services.orca.enable = mkDefault true; + services.orca.enable = lib.mkDefault true; services.displayManager = { sessionPackages = [ kdePackages.plasma-workspace ]; - defaultSession = mkDefault "plasma"; + defaultSession = lib.mkDefault "plasma"; }; services.displayManager.sddm = { package = kdePackages.sddm; - theme = mkDefault "breeze"; - wayland = mkDefault { + theme = lib.mkDefault "breeze"; + wayland = lib.mkDefault { enable = true; compositor = "kwin"; }; diff --git a/nixos/modules/services/desktops/bamf.nix b/nixos/modules/services/desktops/bamf.nix index d9c46e94d9e04..59abadadc46c5 100644 --- a/nixos/modules/services/desktops/bamf.nix +++ b/nixos/modules/services/desktops/bamf.nix @@ -1,8 +1,8 @@ # Bamf { config, lib, pkgs, ... }: { - meta = with lib; { - maintainers = with lib.maintainers; [ ] ++ lib.teams.pantheon.members; + meta = { + maintainers = [ ] ++ lib.teams.pantheon.members; }; ###### interface diff --git a/nixos/modules/services/desktops/geoclue2.nix b/nixos/modules/services/desktops/geoclue2.nix index 16d1cb17ca066..84a3014ae8988 100644 --- a/nixos/modules/services/desktops/geoclue2.nix +++ b/nixos/modules/services/desktops/geoclue2.nix @@ -296,7 +296,7 @@ in ); }; - meta = with lib; { - maintainers = with maintainers; [ ] ++ teams.pantheon.members; + meta = { + maintainers = with lib.maintainers; [ ] ++ lib.teams.pantheon.members; }; } diff --git a/nixos/modules/services/desktops/gnome/gnome-browser-connector.nix b/nixos/modules/services/desktops/gnome/gnome-browser-connector.nix index 335ebc9a144d3..af72588ee411e 100644 --- a/nixos/modules/services/desktops/gnome/gnome-browser-connector.nix +++ b/nixos/modules/services/desktops/gnome/gnome-browser-connector.nix @@ -16,17 +16,17 @@ in { meta = { - maintainers = teams.gnome.members; + maintainers = lib.teams.gnome.members; }; options = { - services.gnome.gnome-browser-connector.enable = mkEnableOption '' + services.gnome.gnome-browser-connector.enable = lib.mkEnableOption '' native host connector for the GNOME Shell browser extension, a DBus service allowing to install GNOME Shell extensions from a web browser ''; }; - config = mkIf config.services.gnome.gnome-browser-connector.enable { + config = lib.mkIf config.services.gnome.gnome-browser-connector.enable { environment.etc = { "chromium/native-messaging-hosts/org.gnome.browser_connector.json".source = "${pkgs.gnome-browser-connector}/etc/chromium/native-messaging-hosts/org.gnome.browser_connector.json"; diff --git a/nixos/modules/services/desktops/neard.nix b/nixos/modules/services/desktops/neard.nix index 56a7578c24349..1f36ec1435455 100644 --- a/nixos/modules/services/desktops/neard.nix +++ b/nixos/modules/services/desktops/neard.nix @@ -6,27 +6,21 @@ }: let - inherit (lib) - mkEnableOption - mkIf - mkOption - types - ; cfg = config.services.neard; format = pkgs.formats.ini { }; configFile = format.generate "neard.conf" cfg.settings; in { options.services.neard = { - enable = mkEnableOption "neard, an NFC daemon"; + enable = lib.mkEnableOption "neard, an NFC daemon"; - settings = mkOption { - type = types.submodule { + settings = lib.mkOption { + type = lib.types.submodule { freeformType = format.type; options = { General = { - ConstantPoll = mkOption { - type = types.bool; + ConstantPoll = lib.mkOption { + type = lib.types.bool; default = false; description = '' Enable constant polling. Constant polling will automatically trigger a new @@ -34,16 +28,16 @@ in ''; }; - DefaultPowered = mkOption { - type = types.bool; + DefaultPowered = lib.mkOption { + type = lib.types.bool; default = true; description = '' Automatically turn an adapter on when being discovered. ''; }; - ResetOnError = mkOption { - type = types.bool; + ResetOnError = lib.mkOption { + type = lib.types.bool; default = true; description = '' Power cycle the adapter when getting a driver error from the kernel. @@ -61,7 +55,7 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { environment.etc."neard/main.conf".source = configFile; environment.systemPackages = [ pkgs.neard ]; diff --git a/nixos/modules/services/desktops/pipewire/pipewire.nix b/nixos/modules/services/desktops/pipewire/pipewire.nix index 91ac32e79c35b..4c037df4e7c41 100644 --- a/nixos/modules/services/desktops/pipewire/pipewire.nix +++ b/nixos/modules/services/desktops/pipewire/pipewire.nix @@ -7,41 +7,17 @@ }: let - inherit (builtins) attrNames concatMap length; - inherit (lib) maintainers teams; - inherit (lib.attrsets) - attrByPath - attrsToList - concatMapAttrs - filterAttrs - ; - inherit (lib.lists) flatten optional optionals; - inherit (lib.modules) mkIf mkRemovedOptionModule; - inherit (lib.options) - literalExpression - mkEnableOption - mkOption - mkPackageOption - ; - inherit (lib.strings) concatMapStringsSep hasPrefix optionalString; - inherit (lib.types) - attrsOf - bool - listOf - package - ; - json = pkgs.formats.json { }; mapToFiles = location: config: - concatMapAttrs (name: value: { + lib.concatMapAttrs (name: value: { "share/pipewire/${location}.conf.d/${name}.conf" = json.generate "${name}" value; }) config; extraConfigPkgFromFiles = locations: filesSet: pkgs.runCommand "pipewire-extra-config" { } '' - mkdir -p ${concatMapStringsSep " " (l: "$out/share/pipewire/${l}.conf.d") locations} - ${concatMapStringsSep ";" ({ name, value }: "ln -s ${value} $out/${name}") (attrsToList filesSet)} + mkdir -p ${lib.concatMapStringsSep " " (l: "$out/share/pipewire/${l}.conf.d") locations} + ${lib.concatMapStringsSep ";" ({ name, value }: "ln -s ${value} $out/${name}") (lib.attrsToList filesSet)} ''; cfg = config.services.pipewire; enable32BitAlsaPlugins = @@ -73,12 +49,12 @@ let paths = configPackages ++ [ extraConfigPkg ] - ++ optionals cfg.wireplumber.enable cfg.wireplumber.configPackages; + ++ lib.optionals cfg.wireplumber.enable cfg.wireplumber.configPackages; pathsToLink = [ "/share/pipewire" ]; }; - requiredLv2Packages = flatten ( - concatMap (p: attrByPath [ "passthru" "requiredLv2Packages" ] [ ] p) configPackages + requiredLv2Packages = lib.flatten ( + lib.concatMap (p: lib.attrByPath [ "passthru" "requiredLv2Packages" ] [ ] p) configPackages ); lv2Plugins = pkgs.buildEnv { @@ -88,44 +64,44 @@ let }; in { - meta.maintainers = teams.freedesktop.members ++ [ maintainers.k900 ]; + meta.maintainers = lib.teams.freedesktop.members ++ [ lib.maintainers.k900 ]; ###### interface options = { services.pipewire = { - enable = mkEnableOption "PipeWire service"; + enable = lib.mkEnableOption "PipeWire service"; - package = mkPackageOption pkgs "pipewire" { }; + package = lib.mkPackageOption pkgs "pipewire" { }; - socketActivation = mkOption { + socketActivation = lib.mkOption { default = true; - type = bool; + type = lib.types.bool; description = '' Automatically run PipeWire when connections are made to the PipeWire socket. ''; }; audio = { - enable = mkOption { - type = bool; + enable = lib.mkOption { + type = lib.types.bool; # this is for backwards compatibility default = cfg.alsa.enable || cfg.jack.enable || cfg.pulse.enable; - defaultText = literalExpression "config.services.pipewire.alsa.enable || config.services.pipewire.jack.enable || config.services.pipewire.pulse.enable"; + defaultText = lib.literalExpression "config.services.pipewire.alsa.enable || config.services.pipewire.jack.enable || config.services.pipewire.pulse.enable"; description = "Whether to use PipeWire as the primary sound server"; }; }; alsa = { - enable = mkEnableOption "ALSA support"; - support32Bit = mkEnableOption "32-bit ALSA support on 64-bit systems"; + enable = lib.mkEnableOption "ALSA support"; + support32Bit = lib.mkEnableOption "32-bit ALSA support on 64-bit systems"; }; jack = { - enable = mkEnableOption "JACK audio emulation"; + enable = lib.mkEnableOption "JACK audio emulation"; }; - raopOpenFirewall = mkOption { - type = bool; + raopOpenFirewall = lib.mkOption { + type = lib.types.bool; default = false; description = '' Opens UDP/6001-6002, required by RAOP/Airplay for timing and control data. @@ -133,11 +109,11 @@ in }; pulse = { - enable = mkEnableOption "PulseAudio server emulation"; + enable = lib.mkEnableOption "PulseAudio server emulation"; }; - systemWide = mkOption { - type = bool; + systemWide = lib.mkOption { + type = lib.types.bool; default = false; description = '' If true, a system-wide PipeWire service and socket is enabled @@ -152,8 +128,8 @@ in }; extraConfig = { - pipewire = mkOption { - type = attrsOf json.type; + pipewire = lib.mkOption { + type = lib.types.attrsOf json.type; default = { }; example = { "10-clock-rate" = { @@ -185,8 +161,8 @@ in [wiki-network]: https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/Network ''; }; - client = mkOption { - type = attrsOf json.type; + client = lib.mkOption { + type = lib.types.attrsOf json.type; default = { }; example = { "10-no-resample" = { @@ -205,8 +181,8 @@ in [wiki]: https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/Config-client ''; }; - client-rt = mkOption { - type = attrsOf json.type; + client-rt = lib.mkOption { + type = lib.types.attrsOf json.type; default = { }; example = { "10-alsa-linear-volume" = { @@ -226,8 +202,8 @@ in [wiki-alsa]: https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/Config-ALSA ''; }; - jack = mkOption { - type = attrsOf json.type; + jack = lib.mkOption { + type = lib.types.attrsOf json.type; default = { }; example = { "20-hide-midi" = { @@ -246,8 +222,8 @@ in [wiki]: https://gitlab.freedesktop.org/pipewire/pipewire/-/wikis/Config-JACK ''; }; - pipewire-pulse = mkOption { - type = attrsOf json.type; + pipewire-pulse = lib.mkOption { + type = lib.types.attrsOf json.type; default = { }; example = { "15-force-s16-info" = { @@ -279,10 +255,10 @@ in }; }; - configPackages = mkOption { - type = listOf package; + configPackages = lib.mkOption { + type = lib.types.listOf lib.types.package; default = [ ]; - example = literalExpression '' + example = lib.literalExpression '' [ (pkgs.writeTextDir "share/pipewire/pipewire.conf.d/10-loopback.conf" ''' context.modules = [ @@ -314,10 +290,10 @@ in ''; }; - extraLv2Packages = mkOption { - type = listOf package; + extraLv2Packages = lib.mkOption { + type = lib.types.listOf lib.types.package; default = [ ]; - example = literalExpression "[ pkgs.lsp-plugins ]"; + example = lib.literalExpression "[ pkgs.lsp-plugins ]"; description = '' List of packages that provide LV2 plugins in `lib/lv2` that should be made available to PipeWire for [filter chains][wiki-filter-chain]. @@ -333,18 +309,18 @@ in }; imports = [ - (mkRemovedOptionModule [ "services" "pipewire" "config" ] '' + (lib.mkRemovedOptionModule [ "services" "pipewire" "config" ] '' Overriding default PipeWire configuration through NixOS options never worked correctly and is no longer supported. Please create drop-in configuration files via `services.pipewire.extraConfig` instead. '') - (mkRemovedOptionModule [ "services" "pipewire" "media-session" ] '' + (lib.mkRemovedOptionModule [ "services" "pipewire" "media-session" ] '' pipewire-media-session is no longer supported upstream and has been removed. Please switch to `services.pipewire.wireplumber` instead. '') ]; ###### implementation - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { assertions = [ { assertion = cfg.audio.enable -> !config.services.pulseaudio.enable; @@ -361,16 +337,16 @@ in } { assertion = - length ( - attrNames ( - filterAttrs (name: value: hasPrefix "pipewire/" name || name == "pipewire") config.environment.etc + lib.length ( + lib.attrNames ( + lib.filterAttrs (name: value: lib.hasPrefix "pipewire/" name || name == "pipewire") config.environment.etc ) ) == 1; message = "Using `environment.etc.\"pipewire<...>\"` directly is no longer supported. Use `services.pipewire.extraConfig` or `services.pipewire.configPackages` instead."; } ]; - environment.systemPackages = [ cfg.package ] ++ optional cfg.jack.enable jack-libs; + environment.systemPackages = [ cfg.package ] ++ lib.optional cfg.jack.enable jack-libs; systemd.packages = [ cfg.package ]; @@ -386,8 +362,8 @@ in systemd.user.sockets.pipewire.enable = !cfg.systemWide; systemd.user.services.pipewire.enable = !cfg.systemWide; - systemd.services.pipewire.environment.LV2_PATH = mkIf cfg.systemWide "${lv2Plugins}/lib/lv2"; - systemd.user.services.pipewire.environment.LV2_PATH = mkIf ( + systemd.services.pipewire.environment.LV2_PATH = lib.mkIf cfg.systemWide "${lv2Plugins}/lib/lv2"; + systemd.user.services.pipewire.environment.LV2_PATH = lib.mkIf ( !cfg.systemWide ) "${lv2Plugins}/lib/lv2"; @@ -395,40 +371,40 @@ in systemd.user.services.pipewire-pulse.enable = cfg.pulse.enable; systemd.user.sockets.pipewire-pulse.enable = cfg.pulse.enable; - systemd.sockets.pipewire.wantedBy = mkIf cfg.socketActivation [ "sockets.target" ]; - systemd.user.sockets.pipewire.wantedBy = mkIf cfg.socketActivation [ "sockets.target" ]; - systemd.user.sockets.pipewire-pulse.wantedBy = mkIf cfg.socketActivation [ "sockets.target" ]; + systemd.sockets.pipewire.wantedBy = lib.mkIf cfg.socketActivation [ "sockets.target" ]; + systemd.user.sockets.pipewire.wantedBy = lib.mkIf cfg.socketActivation [ "sockets.target" ]; + systemd.user.sockets.pipewire-pulse.wantedBy = lib.mkIf cfg.socketActivation [ "sockets.target" ]; services.udev.packages = [ cfg.package ]; # If any paths are updated here they must also be updated in the package test. environment.etc = { - "alsa/conf.d/49-pipewire-modules.conf" = mkIf cfg.alsa.enable { + "alsa/conf.d/49-pipewire-modules.conf" = lib.mkIf cfg.alsa.enable { text = '' pcm_type.pipewire { libs.native = ${cfg.package}/lib/alsa-lib/libasound_module_pcm_pipewire.so ; - ${optionalString enable32BitAlsaPlugins "libs.32Bit = ${pkgs.pkgsi686Linux.pipewire}/lib/alsa-lib/libasound_module_pcm_pipewire.so ;"} + ${lib.optionalString enable32BitAlsaPlugins "libs.32Bit = ${pkgs.pkgsi686Linux.pipewire}/lib/alsa-lib/libasound_module_pcm_pipewire.so ;"} } ctl_type.pipewire { libs.native = ${cfg.package}/lib/alsa-lib/libasound_module_ctl_pipewire.so ; - ${optionalString enable32BitAlsaPlugins "libs.32Bit = ${pkgs.pkgsi686Linux.pipewire}/lib/alsa-lib/libasound_module_ctl_pipewire.so ;"} + ${lib.optionalString enable32BitAlsaPlugins "libs.32Bit = ${pkgs.pkgsi686Linux.pipewire}/lib/alsa-lib/libasound_module_ctl_pipewire.so ;"} } ''; }; - "alsa/conf.d/50-pipewire.conf" = mkIf cfg.alsa.enable { + "alsa/conf.d/50-pipewire.conf" = lib.mkIf cfg.alsa.enable { source = "${cfg.package}/share/alsa/alsa.conf.d/50-pipewire.conf"; }; - "alsa/conf.d/99-pipewire-default.conf" = mkIf cfg.alsa.enable { + "alsa/conf.d/99-pipewire-default.conf" = lib.mkIf cfg.alsa.enable { source = "${cfg.package}/share/alsa/alsa.conf.d/99-pipewire-default.conf"; }; pipewire.source = "${configs}/share/pipewire"; }; - environment.sessionVariables.LD_LIBRARY_PATH = mkIf cfg.jack.enable [ "${cfg.package.jack}/lib" ]; + environment.sessionVariables.LD_LIBRARY_PATH = lib.mkIf cfg.jack.enable [ "${cfg.package.jack}/lib" ]; - networking.firewall.allowedUDPPorts = mkIf cfg.raopOpenFirewall [ + networking.firewall.allowedUDPPorts = lib.mkIf cfg.raopOpenFirewall [ 6001 6002 ]; @@ -456,13 +432,13 @@ in ]; users = { - users.pipewire = mkIf cfg.systemWide { + users.pipewire = lib.mkIf cfg.systemWide { uid = config.ids.uids.pipewire; group = "pipewire"; extraGroups = [ "audio" "video" - ] ++ optional config.security.rtkit.enable "rtkit"; + ] ++ lib.optional config.security.rtkit.enable "rtkit"; description = "PipeWire system service user"; isSystemUser = true; home = "/var/lib/pipewire"; diff --git a/nixos/modules/services/desktops/pipewire/wireplumber.nix b/nixos/modules/services/desktops/pipewire/wireplumber.nix index cccb892cecf7a..9e5ae4dfd23b5 100644 --- a/nixos/modules/services/desktops/pipewire/wireplumber.nix +++ b/nixos/modules/services/desktops/pipewire/wireplumber.nix @@ -1,16 +1,6 @@ { config, lib, pkgs, ... }: let - inherit (builtins) concatMap; - inherit (lib) maintainers; - inherit (lib.attrsets) attrByPath mapAttrsToList; - inherit (lib.lists) flatten optional; - inherit (lib.modules) mkIf; - inherit (lib.options) literalExpression mkOption; - inherit (lib.strings) concatStringsSep makeSearchPath; - inherit (lib.types) bool listOf attrsOf package lines; - inherit (lib.path) subpath; - pwCfg = config.services.pipewire; cfg = pwCfg.wireplumber; pwUsedForAudio = pwCfg.audio.enable; @@ -20,48 +10,48 @@ let configSectionsToConfFile = path: value: pkgs.writeTextDir path - (concatStringsSep "\n" ( - mapAttrsToList + (lib.concatStringsSep "\n" ( + lib.mapAttrsToList (section: content: "${section} = " + (builtins.toJSON content)) value )); mapConfigToFiles = config: - mapAttrsToList + lib.mapAttrsToList (name: value: configSectionsToConfFile "share/wireplumber/wireplumber.conf.d/${name}.conf" value) config; mapScriptsToFiles = scripts: - mapAttrsToList - (relativePath: value: pkgs.writeTextDir (subpath.join ["share/wireplumber/scripts" relativePath]) value) + lib.mapAttrsToList + (relativePath: value: pkgs.writeTextDir (lib.subpath.join ["share/wireplumber/scripts" relativePath]) value) scripts; in { - meta.maintainers = [ maintainers.k900 ]; + meta.maintainers = [ lib.maintainers.k900 ]; options = { services.pipewire.wireplumber = { - enable = mkOption { - type = bool; + enable = lib.mkOption { + type = lib.bool; default = pwCfg.enable; - defaultText = literalExpression "config.services.pipewire.enable"; + defaultText = lib.literalExpression "config.services.pipewire.enable"; description = "Whether to enable WirePlumber, a modular session / policy manager for PipeWire"; }; - package = mkOption { - type = package; + package = lib.mkOption { + type = lib.package; default = pkgs.wireplumber; - defaultText = literalExpression "pkgs.wireplumber"; + defaultText = lib.literalExpression "pkgs.wireplumber"; description = "The WirePlumber derivation to use."; }; - extraConfig = mkOption { + extraConfig = lib.mkOption { # Two layer attrset is necessary before using JSON, because of the whole # config file not being a JSON object, but a concatenation of JSON objects # in sections. - type = attrsOf (attrsOf json.type); + type = lib.attrsOf (lib.attrsOf json.type); default = { }; - example = literalExpression ''{ + example = lib.literalExpression ''{ "log-level-debug" = { "context.properties" = { # Output Debug log messages as opposed to only the default level (Notice) @@ -112,8 +102,8 @@ in ''; }; - extraScripts = mkOption { - type = attrsOf lines; + extraScripts = lib.mkOption { + type = lib.types.attrsOf lib.types.lines; default = { }; example = { "test/hello-world.lua" = '' @@ -163,10 +153,10 @@ in ''; }; - configPackages = mkOption { - type = listOf package; + configPackages = lib.mkOption { + type = lib.types.listOf lib.types.package; default = [ ]; - example = literalExpression ''[ + example = lib.literalExpression ''[ (pkgs.writeTextDir "share/wireplumber/wireplumber.conf.d/10-bluez.conf" ''' monitor.bluez.properties = { bluez5.roles = [ a2dp_sink a2dp_source bap_sink bap_source hsp_hs hsp_ag hfp_hf hfp_ag ] @@ -185,10 +175,10 @@ in ''; }; - extraLv2Packages = mkOption { - type = listOf package; + extraLv2Packages = lib.mkOption { + type = lib.types.listOf lib.types.package; default = [ ]; - example = literalExpression "[ pkgs.lsp-plugins ]"; + example = lib.literalExpression "[ pkgs.lsp-plugins ]"; description = '' List of packages that provide LV2 plugins in `lib/lv2` that should be made available to WirePlumber for [filter chains][wiki-filter-chain]. @@ -229,7 +219,7 @@ in configPackages = cfg.configPackages ++ [ extraConfigPkg extraScriptsPkg ] - ++ optional (!pwUsedForAudio) pwNotForAudioConfigPkg; + ++ lib.optional (!pwUsedForAudio) pwNotForAudioConfigPkg; configs = pkgs.buildEnv { name = "wireplumber-configs"; @@ -237,11 +227,11 @@ in pathsToLink = [ "/share/wireplumber" ]; }; - requiredLv2Packages = flatten + requiredLv2Packages = lib.flatten ( - concatMap + lib.concatMap (p: - attrByPath [ "passthru" "requiredLv2Packages" ] [ ] p + lib.attrByPath [ "passthru" "requiredLv2Packages" ] [ ] p ) configPackages ); @@ -252,7 +242,7 @@ in pathsToLink = [ "/lib/lv2" ]; }; in - mkIf cfg.enable { + lib.mkIf cfg.enable { assertions = [ { assertion = !config.hardware.bluetooth.hsphfpd.enable; @@ -270,18 +260,18 @@ in systemd.services.wireplumber.wantedBy = [ "pipewire.service" ]; systemd.user.services.wireplumber.wantedBy = [ "pipewire.service" ]; - systemd.services.wireplumber.environment = mkIf pwCfg.systemWide { + systemd.services.wireplumber.environment = lib.mkIf pwCfg.systemWide { # Force WirePlumber to use system dbus. DBUS_SESSION_BUS_ADDRESS = "unix:path=/run/dbus/system_bus_socket"; # Make WirePlumber find our config/script files and lv2 plugins required by those # (but also the configs/scripts shipped with WirePlumber) - XDG_DATA_DIRS = makeSearchPath "share" [ configs cfg.package ]; + XDG_DATA_DIRS = lib.makeSearchPath "share" [ configs cfg.package ]; LV2_PATH = "${lv2Plugins}/lib/lv2"; }; - systemd.user.services.wireplumber.environment = mkIf (!pwCfg.systemWide) { - XDG_DATA_DIRS = makeSearchPath "share" [ configs cfg.package ]; + systemd.user.services.wireplumber.environment = lib.mkIf (!pwCfg.systemWide) { + XDG_DATA_DIRS = lib.makeSearchPath "share" [ configs cfg.package ]; LV2_PATH = "${lv2Plugins}/lib/lv2"; }; }; diff --git a/nixos/modules/services/desktops/seatd.nix b/nixos/modules/services/desktops/seatd.nix index bedcc9a431204..0f7fdb79eca14 100644 --- a/nixos/modules/services/desktops/seatd.nix +++ b/nixos/modules/services/desktops/seatd.nix @@ -7,26 +7,25 @@ let cfg = config.services.seatd; - inherit (lib) mkEnableOption mkOption types; in { meta.maintainers = with lib.maintainers; [ sinanmohd ]; options.services.seatd = { - enable = mkEnableOption "seatd"; + enable = lib.mkEnableOption "seatd"; - user = mkOption { - type = types.str; + user = lib.mkOption { + type = lib.types.str; default = "root"; description = "User to own the seatd socket"; }; - group = mkOption { - type = types.str; + group = lib.mkOption { + type = lib.types.str; default = "seat"; description = "Group to own the seatd socket"; }; - logLevel = mkOption { - type = types.enum [ + logLevel = lib.mkOption { + type = lib.types.enum [ "debug" "info" "error" diff --git a/nixos/modules/services/desktops/system76-scheduler.nix b/nixos/modules/services/desktops/system76-scheduler.nix index 1a8abe810cd8b..a86c78a0b3fe4 100644 --- a/nixos/modules/services/desktops/system76-scheduler.nix +++ b/nixos/modules/services/desktops/system76-scheduler.nix @@ -8,37 +8,11 @@ let cfg = config.services.system76-scheduler; - inherit (builtins) - concatStringsSep - map - toString - attrNames - ; - inherit (lib) - boolToString - types - mkOption - literalExpression - optional - mkIf - mkMerge - ; - inherit (types) - nullOr - listOf - bool - int - ints - float - str - enum - ; - withDefaults = optionSpecs: defaults: - lib.genAttrs (attrNames optionSpecs) ( + lib.genAttrs (lib.attrNames optionSpecs) ( name: - mkOption ( + lib.mkOption ( optionSpecs.${name} // { default = optionSpecs.${name}.default or defaults.${name} or null; @@ -48,23 +22,23 @@ let latencyProfile = withDefaults { latency = { - type = int; + type = lib.types.int; description = "`sched_latency_ns`."; }; nr-latency = { - type = int; + type = lib.types.int; description = "`sched_nr_latency`."; }; wakeup-granularity = { - type = float; + type = lib.types.float; description = "`sched_wakeup_granularity_ns`."; }; bandwidth-size = { - type = int; + type = lib.types.int; description = "`sched_cfs_bandwidth_slice_us`."; }; preempt = { - type = enum [ + type = lib.types.enum [ "none" "voluntary" "full" @@ -74,43 +48,43 @@ let }; schedulerProfile = withDefaults { nice = { - type = nullOr (ints.between (-20) 19); + type = lib.types.nullOr (lib.types.ints.between (-20) 19); description = "Niceness."; }; class = { - type = nullOr (enum [ + type = lib.types.nullOr (lib.types.enum [ "idle" "batch" "other" "rr" "fifo" ]); - example = literalExpression "\"batch\""; + example = lib.literalExpression "\"batch\""; description = "CPU scheduler class."; }; prio = { - type = nullOr (ints.between 1 99); - example = literalExpression "49"; + type = lib.types.nullOr (lib.types.ints.between 1 99); + example = lib.literalExpression "49"; description = "CPU scheduler priority."; }; ioClass = { - type = nullOr (enum [ + type = lib.types.nullOr (lib.types.enum [ "idle" "best-effort" "realtime" ]); - example = literalExpression "\"best-effort\""; + example = lib.literalExpression "\"best-effort\""; description = "IO scheduler class."; }; ioPrio = { - type = nullOr (ints.between 0 7); - example = literalExpression "4"; + type = lib.types.nullOr (lib.types.ints.between 0 7); + example = lib.literalExpression "4"; description = "IO scheduler priority."; }; matchers = { - type = nullOr (listOf str); + type = lib.types.nullOr (lib.types.listOf lib.types.str); default = [ ]; - example = literalExpression '' + example = lib.literalExpression '' [ "include cgroup=\"/user.slice/*.service\" parent=\"systemd\"" "emacs" @@ -131,13 +105,13 @@ let schedulerProfileToString = name: a: indent: - concatStringsSep " " ( + lib.concatStringsSep " " ( [ "${indent}${name}" ] - ++ (optional (a.nice != null) "nice=${toString a.nice}") - ++ (optional (a.class != null) "sched=${prioToString a.class a.prio}") - ++ (optional (a.ioClass != null) "io=${prioToString a.ioClass a.ioPrio}") - ++ (optional ((builtins.length a.matchers) != 0) ( - "{\n${concatStringsSep "\n" (map (m: " ${indent}${m}") a.matchers)}\n${indent}}" + ++ (lib.optional (a.nice != null) "nice=${toString a.nice}") + ++ (lib.optional (a.class != null) "sched=${prioToString a.class a.prio}") + ++ (lib.optional (a.ioClass != null) "io=${prioToString a.ioClass a.ioPrio}") + ++ (lib.optional ((builtins.length a.matchers) != 0) ( + "{\n${lib.concatStringsSep "\n" (map (m: " ${indent}${m}") a.matchers)}\n${indent}}" )) ); @@ -147,15 +121,15 @@ in services.system76-scheduler = { enable = lib.mkEnableOption "system76-scheduler"; - package = mkOption { - type = types.package; + package = lib.mkOption { + type = lib.types.package; default = pkgs.system76-scheduler; - defaultText = literalExpression "pkgs.system76-scheduler"; + defaultText = lib.literalExpression "pkgs.system76-scheduler"; description = "Which System76-Scheduler package to use."; }; - useStockConfig = mkOption { - type = bool; + useStockConfig = lib.mkOption { + type = lib.types.bool; default = true; description = '' Use the (reasonable and featureful) stock configuration. @@ -167,8 +141,8 @@ in settings = { cfsProfiles = { - enable = mkOption { - type = bool; + enable = lib.mkOption { + type = lib.types.bool; default = true; description = "Tweak CFS latency parameters when going on/off battery"; }; @@ -190,27 +164,27 @@ in }; processScheduler = { - enable = mkOption { - type = bool; + enable = lib.mkOption { + type = lib.types.bool; default = true; description = "Tweak scheduling of individual processes in real time."; }; - useExecsnoop = mkOption { - type = bool; + useExecsnoop = lib.mkOption { + type = lib.types.bool; default = true; description = "Use execsnoop (otherwise poll the precess list periodically)."; }; - refreshInterval = mkOption { - type = int; + refreshInterval = lib.mkOption { + type = lib.types.int; default = 60; description = "Process list poll interval, in seconds"; }; foregroundBoost = { - enable = mkOption { - type = bool; + enable = lib.mkOption { + type = lib.types.bool; default = true; description = '' Boost foreground process priorities. @@ -232,8 +206,8 @@ in }; pipewireBoost = { - enable = mkOption { - type = bool; + enable = lib.mkOption { + type = lib.types.bool; default = true; description = "Boost Pipewire client priorities."; }; @@ -246,14 +220,14 @@ in }; }; - assignments = mkOption { - type = types.attrsOf ( - types.submodule { + assignments = lib.mkOption { + type = lib.types.attrsOf ( + lib.types.types.submodule { options = schedulerProfile { }; } ); default = { }; - example = literalExpression '' + example = lib.literalExpression '' { nix-builds = { nice = 15; @@ -268,10 +242,10 @@ in description = "Process profile assignments."; }; - exceptions = mkOption { - type = types.listOf str; + exceptions = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; - example = literalExpression '' + example = lib.literalExpression '' [ "include descends=\"schedtool\"" "schedtool" @@ -282,7 +256,7 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { environment.systemPackages = [ cfg.package ]; services.dbus.packages = [ cfg.package ]; @@ -303,8 +277,8 @@ in }; }; - environment.etc = mkMerge [ - (mkIf cfg.useStockConfig { + environment.etc = lib.mkMerge [ + (lib.mkIf cfg.useStockConfig { # No custom settings: just use stock configuration with a fix for Pipewire "system76-scheduler/config.kdl".source = "${cfg.package}/data/config.kdl"; "system76-scheduler/process-scheduler/00-dist.kdl".source = "${cfg.package}/data/pop_os.kdl"; @@ -318,16 +292,16 @@ in cfsp = settings.cfsProfiles; ps = settings.processScheduler; in - mkIf (!cfg.useStockConfig) { + lib.mkIf (!cfg.useStockConfig) { "system76-scheduler/config.kdl".text = '' version "2.0" autogroup-enabled false - cfs-profiles enable=${boolToString cfsp.enable} { + cfs-profiles enable=${lib.boolToString cfsp.enable} { ${cfsProfileToString "default"} ${cfsProfileToString "responsive"} } - process-scheduler enable=${boolToString ps.enable} { - execsnoop ${boolToString ps.useExecsnoop} + process-scheduler enable=${lib.boolToString ps.enable} { + execsnoop ${lib.boolToString ps.useExecsnoop} refresh-rate ${toString ps.refreshInterval} assignments { ${ @@ -356,10 +330,10 @@ in { "system76-scheduler/process-scheduler/02-config.kdl".text = - "exceptions {\n${concatStringsSep "\n" (map (e: " ${e}") cfg.exceptions)}\n}\n" + "exceptions {\n${lib.concatStringsSep "\n" (map (e: " ${e}") cfg.exceptions)}\n}\n" + "assignments {\n" - + (concatStringsSep "\n" ( - map (name: schedulerProfileToString name cfg.assignments.${name} " ") (attrNames cfg.assignments) + + (lib.concatStringsSep "\n" ( + map (name: schedulerProfileToString name cfg.assignments.${name} " ") (lib.attrNames cfg.assignments) )) + "\n}\n"; } diff --git a/nixos/modules/services/desktops/telepathy.nix b/nixos/modules/services/desktops/telepathy.nix index d4aac1aa0c26f..d2436692f6cfc 100644 --- a/nixos/modules/services/desktops/telepathy.nix +++ b/nixos/modules/services/desktops/telepathy.nix @@ -38,7 +38,7 @@ services.dbus.packages = [ pkgs.telepathy-mission-control ]; - # Enable runtime optional telepathy in gnome-shell + # Enable runtime lib.optional telepathy in gnome-shell services.xserver.desktopManager.gnome.sessionPath = with pkgs; [ telepathy-glib telepathy-logger diff --git a/nixos/modules/services/desktops/tumbler.nix b/nixos/modules/services/desktops/tumbler.nix index 521f8c0a58f13..c8ebf7e81e892 100644 --- a/nixos/modules/services/desktops/tumbler.nix +++ b/nixos/modules/services/desktops/tumbler.nix @@ -17,8 +17,8 @@ in (lib.mkRemovedOptionModule [ "services" "tumbler" "package" ] "") ]; - meta = with lib; { - maintainers = with lib.maintainers; [ ] ++ lib.teams.pantheon.members; + meta = { + maintainers = [ ] ++ lib.teams.pantheon.members; }; ###### interface diff --git a/nixos/modules/services/desktops/zeitgeist.nix b/nixos/modules/services/desktops/zeitgeist.nix index 5e9cba9930165..f830b964ca935 100644 --- a/nixos/modules/services/desktops/zeitgeist.nix +++ b/nixos/modules/services/desktops/zeitgeist.nix @@ -7,8 +7,8 @@ }: { - meta = with lib; { - maintainers = with maintainers; [ ] ++ teams.pantheon.members; + meta = { + maintainers = with lib.maintainers; [ ] ++ lib.teams.pantheon.members; }; ###### interface diff --git a/nixos/modules/services/display-managers/ly.nix b/nixos/modules/services/display-managers/ly.nix index 9475f183a16d3..3af9d983d4b97 100644 --- a/nixos/modules/services/display-managers/ly.nix +++ b/nixos/modules/services/display-managers/ly.nix @@ -16,20 +16,10 @@ let iniFmt = pkgs.formats.iniWithGlobalSection { }; - inherit (lib) - concatMapStrings - attrNames - getAttr - mkIf - mkOption - mkEnableOption - mkPackageOption - ; - xserverWrapper = pkgs.writeShellScript "xserver-wrapper" '' - ${concatMapStrings (n: '' - export ${n}="${getAttr n xEnv}" - '') (attrNames xEnv)} + ${lib.concatMapStrings (n: '' + export ${n}="${lib.getAttr n xEnv}" + '') (lib.attrNames xEnv)} exec systemd-cat -t xserver-wrapper ${xdmcfg.xserverBin} ${toString xdmcfg.xserverArgs} "$@" ''; @@ -58,11 +48,11 @@ in { options = { services.displayManager.ly = { - enable = mkEnableOption "ly as the display manager"; + enable = lib.mkEnableOption "ly as the display manager"; - package = mkPackageOption pkgs [ "ly" ] { }; + package = lib.mkPackageOption pkgs [ "ly" ] { }; - settings = mkOption { + settings = lib.mkOption { type = with lib.types; attrsOf (oneOf [ @@ -82,7 +72,7 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { assertions = [ { diff --git a/nixos/modules/services/display-managers/sddm.nix b/nixos/modules/services/display-managers/sddm.nix index 9f70867be4231..764cc554567bc 100644 --- a/nixos/modules/services/display-managers/sddm.nix +++ b/nixos/modules/services/display-managers/sddm.nix @@ -19,25 +19,8 @@ let iniFmt = pkgs.formats.ini { }; - inherit (lib) - concatMapStrings - concatStringsSep - getExe - attrNames - getAttr - optionalAttrs - optionalString - mkRemovedOptionModule - mkRenamedOptionModule - mkIf - mkEnableOption - mkOption - mkPackageOption - types - ; - xserverWrapper = pkgs.writeShellScript "xserver-wrapper" '' - ${concatMapStrings (n: "export ${n}=\"${getAttr n xEnv}\"\n") (attrNames xEnv)} + ${lib.concatMapStrings (n: "export ${n}=\"${lib.getAttr n xEnv}\"\n") (lib.attrNames xEnv)} exec systemd-cat -t xserver-wrapper ${xcfg.displayManager.xserverBin} ${toString xcfg.displayManager.xserverArgs} "$@" ''; @@ -59,13 +42,13 @@ let Numlock = if cfg.autoNumlock then "on" else "none"; # on, off none # Implementation is done via pkgs/applications/display-managers/sddm/sddm-default-session.patch - DefaultSession = optionalString ( + DefaultSession = lib.optionalString ( config.services.displayManager.defaultSession != null ) "${config.services.displayManager.defaultSession}.desktop"; DisplayServer = if cfg.wayland.enable then "wayland" else "x11"; } - // optionalAttrs (cfg.wayland.enable && cfg.wayland.compositor == "kwin") { + // lib.optionalAttrs (cfg.wayland.enable && cfg.wayland.compositor == "kwin") { GreeterEnvironment = "QT_WAYLAND_SHELL_INTEGRATION=layer-shell"; InputMethod = ""; # needed if we are using --inputmethod with kwin }; @@ -76,14 +59,14 @@ let ThemeDir = "/run/current-system/sw/share/sddm/themes"; FacesDir = "/run/current-system/sw/share/sddm/faces"; } - // optionalAttrs (cfg.theme == "breeze") { + // lib.optionalAttrs (cfg.theme == "breeze") { CursorTheme = "breeze_cursors"; CursorSize = 24; }; Users = { MaximumUid = config.ids.uids.nixbld; - HideUsers = concatStringsSep "," dmcfg.hiddenUsers; + HideUsers = lib.concatStringsSep "," dmcfg.hiddenUsers; HideShells = "/run/current-system/sw/bin/nologin"; }; @@ -94,7 +77,7 @@ let }; } - // optionalAttrs xcfg.enable { + // lib.optionalAttrs xcfg.enable { X11 = { MinimumVT = if xcfg.tty != null then xcfg.tty else 7; ServerPath = toString xserverWrapper; @@ -107,7 +90,7 @@ let EnableHiDPI = cfg.enableHidpi; }; } - // optionalAttrs dmcfg.autoLogin.enable { + // lib.optionalAttrs dmcfg.autoLogin.enable { Autologin = { User = dmcfg.autoLogin.user; Session = autoLoginSessionName; @@ -120,7 +103,7 @@ let autoLoginSessionName = "${dmcfg.sessionData.autologinSession}.desktop"; compositorCmds = { - kwin = concatStringsSep " " [ + kwin = lib.concatStringsSep " " [ "${lib.getBin pkgs.kdePackages.kwin}/bin/kwin_wayland" "--no-global-shortcuts" "--no-kactivities" @@ -144,76 +127,76 @@ let }; }; in - "${getExe pkgs.weston} --shell=kiosk -c ${westonIni}"; + "${lib.getExe pkgs.weston} --shell=kiosk -c ${westonIni}"; }; in { imports = [ - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "xserver" "displayManager" "sddm" "autoLogin" "minimumUid" ] [ "services" "displayManager" "sddm" "autoLogin" "minimumUid" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "xserver" "displayManager" "sddm" "autoLogin" "relogin" ] [ "services" "displayManager" "sddm" "autoLogin" "relogin" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "xserver" "displayManager" "sddm" "autoNumlock" ] [ "services" "displayManager" "sddm" "autoNumlock" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "xserver" "displayManager" "sddm" "enable" ] [ "services" "displayManager" "sddm" "enable" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "xserver" "displayManager" "sddm" "enableHidpi" ] [ "services" "displayManager" "sddm" "enableHidpi" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "xserver" "displayManager" "sddm" "extraPackages" ] [ "services" "displayManager" "sddm" "extraPackages" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "xserver" "displayManager" "sddm" "package" ] [ "services" "displayManager" "sddm" "package" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "xserver" "displayManager" "sddm" "settings" ] [ "services" "displayManager" "sddm" "settings" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "xserver" "displayManager" "sddm" "setupScript" ] [ "services" "displayManager" "sddm" "setupScript" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "xserver" "displayManager" "sddm" "stopScript" ] [ "services" "displayManager" "sddm" "stopScript" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "xserver" "displayManager" "sddm" "theme" ] [ "services" "displayManager" "sddm" "theme" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "xserver" "displayManager" "sddm" "wayland" "enable" ] [ "services" "displayManager" "sddm" "wayland" "enable" ] ) - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "displayManager" "sddm" "themes" ] "Set the option `services.displayManager.sddm.package' instead.") - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "displayManager" "sddm" "autoLogin" "enable" ] [ "services" "displayManager" "autoLogin" "enable" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "displayManager" "sddm" "autoLogin" "user" ] [ "services" "displayManager" "autoLogin" "user" ] ) - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "displayManager" "sddm" @@ -224,25 +207,25 @@ in options = { services.displayManager.sddm = { - enable = mkOption { - type = types.bool; + enable = lib.mkOption { + type = lib.types.bool; default = false; description = '' Whether to enable sddm as the display manager. ''; }; - package = mkPackageOption pkgs [ "plasma5Packages" "sddm" ] { }; + package = lib.mkPackageOption pkgs [ "plasma5Packages" "sddm" ] { }; - enableHidpi = mkOption { - type = types.bool; + enableHidpi = lib.mkOption { + type = lib.types.bool; default = true; description = '' Whether to enable automatic HiDPI mode. ''; }; - settings = mkOption { + settings = lib.mkOption { type = iniFmt.type; default = { }; example = { @@ -256,16 +239,16 @@ in ''; }; - theme = mkOption { - type = types.str; + theme = lib.mkOption { + type = lib.types.str; default = ""; description = '' Greeter theme to use. ''; }; - extraPackages = mkOption { - type = types.listOf types.package; + extraPackages = lib.mkOption { + type = lib.types.listOf lib.types.package; default = [ ]; defaultText = "[]"; description = '' @@ -273,16 +256,16 @@ in ''; }; - autoNumlock = mkOption { - type = types.bool; + autoNumlock = lib.mkOption { + type = lib.types.bool; default = false; description = '' Enable numlock at login. ''; }; - setupScript = mkOption { - type = types.str; + setupScript = lib.mkOption { + type = lib.types.str; default = ""; example = '' # workaround for using NVIDIA Optimus without Bumblebee @@ -295,8 +278,8 @@ in ''; }; - stopScript = mkOption { - type = types.str; + stopScript = lib.mkOption { + type = lib.types.str; default = ""; description = '' A script to execute when stopping the display server. @@ -305,8 +288,8 @@ in # Configuration for automatic login specific to SDDM autoLogin = { - relogin = mkOption { - type = types.bool; + relogin = lib.mkOption { + type = lib.types.bool; default = false; description = '' If true automatic login will kick in again on session exit (logout), otherwise it @@ -314,8 +297,8 @@ in ''; }; - minimumUid = mkOption { - type = types.ints.u16; + minimumUid = lib.mkOption { + type = lib.types.ints.u16; default = 1000; description = '' Minimum user ID for auto-login user. @@ -325,16 +308,16 @@ in # Experimental Wayland support wayland = { - enable = mkEnableOption "experimental Wayland support"; + enable = lib.mkEnableOption "experimental Wayland support"; - compositor = mkOption { + compositor = lib.mkOption { description = "The compositor to use: ${lib.concatStringsSep ", " (builtins.attrNames compositorCmds)}"; - type = types.enum (builtins.attrNames compositorCmds); + type = lib.types.enum (builtins.attrNames compositorCmds); default = "weston"; }; - compositorCommand = mkOption { - type = types.str; + compositorCommand = lib.mkOption { + type = lib.types.str; internal = true; default = compositorCmds.${cfg.wayland.compositor}; description = "Command used to start the selected compositor"; @@ -343,7 +326,7 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { assertions = [ { @@ -375,7 +358,7 @@ in sddm-greeter.text = '' auth required pam_succeed_if.so audit quiet_success user = sddm - auth optional pam_permit.so + auth lib.optional pam_permit.so account required pam_succeed_if.so audit quiet_success user = sddm account sufficient pam_unix.so @@ -384,9 +367,9 @@ in session required pam_succeed_if.so audit quiet_success user = sddm session required pam_env.so conffile=/etc/pam/environment readenv=0 - session optional ${config.systemd.package}/lib/security/pam_systemd.so - session optional pam_keyinit.so force revoke - session optional pam_permit.so + session lib.optional ${config.systemd.package}/lib/security/pam_systemd.so + session lib.optional pam_keyinit.so force revoke + session lib.optional pam_permit.so ''; sddm-autologin.text = '' diff --git a/nixos/modules/services/games/armagetronad.nix b/nixos/modules/services/games/armagetronad.nix index 17e449beb5477..df0f66f3aa58d 100644 --- a/nixos/modules/services/games/armagetronad.nix +++ b/nixos/modules/services/games/armagetronad.nix @@ -5,29 +5,14 @@ ... }: let - inherit (lib) - mkEnableOption - mkIf - mkOption - mkMerge - literalExpression - ; - inherit (lib) - mapAttrsToList - filterAttrs - unique - recursiveUpdate - types - ; mkValueStringArmagetron = - with lib; v: - if isInt v then + if lib.isInt v then toString v - else if isFloat v then + else if lib.isFloat v then toString v - else if isString v then + else if lib.isString v then v else if true == v then "1" @@ -54,13 +39,13 @@ in { options = { services.armagetronad = { - servers = mkOption { + servers = lib.mkOption { description = "Armagetron server definitions."; default = { }; - type = types.attrsOf ( - types.submodule { + type = lib.types.attrsOf ( + lib.types.submodule { options = { - enable = mkEnableOption "armagetronad"; + enable = lib.mkEnableOption "armagetronad"; package = lib.mkPackageOption pkgs "armagetronad-dedicated" { example = '' @@ -71,36 +56,36 @@ in ''; }; - host = mkOption { - type = types.str; + host = lib.mkOption { + type = lib.types.str; default = "0.0.0.0"; description = "Host to listen on. Used for SERVER_IP."; }; - port = mkOption { - type = types.port; + port = lib.mkOption { + type = lib.types.port; default = 4534; description = "Port to listen on. Used for SERVER_PORT."; }; - dns = mkOption { - type = types.nullOr types.str; + dns = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; description = "DNS address to use for this server. Optional."; }; - openFirewall = mkOption { - type = types.bool; + openFirewall = lib.mkOption { + type = lib.types.bool; default = true; description = "Set to true to open the configured UDP port for Armagetron Advanced."; }; - name = mkOption { - type = types.str; + name = lib.mkOption { + type = lib.types.str; description = "The name of this server."; }; - settings = mkOption { + settings = lib.mkOption { type = settingsFormat.type; default = { }; description = '' @@ -111,14 +96,14 @@ in This attrset is used to populate `settings_custom.cfg`; see: ''; - example = literalExpression '' + example = lib.literalExpression '' { CYCLE_RUBBER = 40; } ''; }; - roundSettings = mkOption { + roundSettings = lib.mkOption { type = settingsFormat.type; default = { }; description = '' @@ -129,7 +114,7 @@ in This attrset is used to populate `everytime.cfg`; see: ''; - example = literalExpression '' + example = lib.literalExpression '' { SAY = [ "Hosted on NixOS" @@ -146,9 +131,9 @@ in }; }; - config = mkIf (enabledServers != { }) { - systemd.tmpfiles.settings = mkMerge ( - mapAttrsToList ( + config = lib.mkIf (enabledServers != { }) { + systemd.tmpfiles.settings = lib.mkMerge ( + lib.mapAttrsToList ( serverName: serverCfg: let serverId = nameToId serverName; @@ -225,8 +210,8 @@ in ) enabledServers ); - systemd.services = mkMerge ( - mapAttrsToList ( + systemd.services = lib.mkMerge ( + lib.mapAttrsToList ( serverName: serverCfg: let serverId = nameToId serverName; @@ -275,14 +260,14 @@ in ) enabledServers ); - networking.firewall.allowedUDPPorts = unique ( - mapAttrsToList (serverName: serverCfg: serverCfg.port) ( - filterAttrs (serverName: serverCfg: serverCfg.openFirewall) enabledServers + networking.firewall.allowedUDPPorts = lib.unique ( + lib.mapAttrsToList (serverName: serverCfg: serverCfg.port) ( + lib.filterAttrs (serverName: serverCfg: serverCfg.openFirewall) enabledServers ) ); - users.users = mkMerge ( - mapAttrsToList (serverName: serverCfg: { + users.users = lib.mkMerge ( + lib.mapAttrsToList (serverName: serverCfg: { ${nameToId serverName} = { group = nameToId serverName; description = "Armagetron Advanced dedicated user for server ${serverName}"; @@ -291,8 +276,8 @@ in }) enabledServers ); - users.groups = mkMerge ( - mapAttrsToList (serverName: serverCfg: { + users.groups = lib.mkMerge ( + lib.mapAttrsToList (serverName: serverCfg: { ${nameToId serverName} = { }; }) enabledServers ); diff --git a/nixos/modules/services/games/openarena.nix b/nixos/modules/services/games/openarena.nix index d462bff805fb7..b8894bd70b37e 100644 --- a/nixos/modules/services/games/openarena.nix +++ b/nixos/modules/services/games/openarena.nix @@ -6,29 +6,22 @@ }: let - inherit (lib) - concatStringsSep - mkEnableOption - mkIf - mkOption - types - ; cfg = config.services.openarena; in { options = { services.openarena = { - enable = mkEnableOption "OpenArena game server"; + enable = lib.mkEnableOption "OpenArena game server"; package = lib.mkPackageOption pkgs "openarena" { }; - openPorts = mkOption { - type = types.bool; + openPorts = lib.mkOption { + type = lib.types.bool; default = false; description = "Whether to open firewall ports for OpenArena"; }; - extraFlags = mkOption { - type = types.listOf types.str; + extraFlags = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; description = "Extra flags to pass to {command}`oa_ded`"; example = [ @@ -41,8 +34,8 @@ in }; }; - config = mkIf cfg.enable { - networking.firewall = mkIf cfg.openPorts { + config = lib.mkIf cfg.enable { + networking.firewall = lib.mkIf cfg.openPorts { allowedUDPPorts = [ 27960 ]; }; @@ -54,7 +47,7 @@ in serviceConfig = { DynamicUser = true; StateDirectory = "openarena"; - ExecStart = "${cfg.package}/bin/oa_ded +set fs_basepath ${cfg.package}/share/openarena +set fs_homepath /var/lib/openarena ${concatStringsSep " " cfg.extraFlags}"; + ExecStart = "${cfg.package}/bin/oa_ded +set fs_basepath ${cfg.package}/share/openarena +set fs_homepath /var/lib/openarena ${lib.concatStringsSep " " cfg.extraFlags}"; Restart = "on-failure"; # Hardening diff --git a/nixos/modules/services/games/quake3-server.nix b/nixos/modules/services/games/quake3-server.nix index d0bc521022778..71a782aad65d7 100644 --- a/nixos/modules/services/games/quake3-server.nix +++ b/nixos/modules/services/games/quake3-server.nix @@ -6,13 +6,6 @@ }: let - inherit (lib) - literalMD - mkEnableOption - mkIf - mkOption - types - ; cfg = config.services.quake3-server; configFile = pkgs.writeText "q3ds-extra.cfg" '' @@ -52,27 +45,27 @@ in { options = { services.quake3-server = { - enable = mkEnableOption "Quake 3 dedicated server"; + enable = lib.mkEnableOption "Quake 3 dedicated server"; package = lib.mkPackageOption pkgs "ioquake3" { }; - port = mkOption { - type = types.port; + port = lib.mkOption { + type = lib.types.port; default = 27960; description = '' UDP Port the server should listen on. ''; }; - openFirewall = mkOption { - type = types.bool; + openFirewall = lib.mkOption { + type = lib.types.bool; default = false; description = '' Open the firewall. ''; }; - extraConfig = mkOption { - type = types.lines; + extraConfig = lib.mkOption { + type = lib.types.lines; default = ""; example = '' seta rconPassword "superSecret" // sets RCON password for remote console @@ -84,10 +77,10 @@ in ''; }; - baseq3 = mkOption { - type = types.either types.package types.path; + baseq3 = lib.mkOption { + type = lib.types.either lib.types.package lib.types.path; default = defaultBaseq3; - defaultText = literalMD "Manually downloaded Quake 3 installation directory."; + defaultText = lib.literalMD "Manually downloaded Quake 3 installation directory."; example = "/var/lib/q3ds"; description = '' Path to the baseq3 files (pak*.pk3). If this is on the nix store (type = package) all .pk3 files should be saved @@ -102,8 +95,8 @@ in let baseq3InStore = builtins.typeOf cfg.baseq3 == "set"; in - mkIf cfg.enable { - networking.firewall.allowedUDPPorts = mkIf cfg.openFirewall [ cfg.port ]; + lib.mkIf cfg.enable { + networking.firewall.allowedUDPPorts = lib.mkIf cfg.openFirewall [ cfg.port ]; systemd.services.q3ds = { description = "Quake 3 dedicated server"; @@ -112,14 +105,14 @@ in environment.HOME = if baseq3InStore then home else cfg.baseq3; - serviceConfig = with lib; { + serviceConfig = { Restart = "always"; DynamicUser = true; WorkingDirectory = home; # It is possible to alter configuration files via RCON. To ensure reproducibility we have to prevent this ReadOnlyPaths = if baseq3InStore then home else cfg.baseq3; - ExecStartPre = optionalString ( + ExecStartPre = lib.optionalString ( !baseq3InStore ) "+${pkgs.coreutils}/bin/cp ${configFile} ${cfg.baseq3}/.q3a/baseq3/nix.cfg"; diff --git a/nixos/modules/services/hardware/auto-epp.nix b/nixos/modules/services/hardware/auto-epp.nix index 88f49106a258c..b057ba278e45d 100644 --- a/nixos/modules/services/hardware/auto-epp.nix +++ b/nixos/modules/services/hardware/auto-epp.nix @@ -8,8 +8,6 @@ let cfg = config.services.auto-epp; format = pkgs.formats.ini { }; - - inherit (lib) mkOption types; in { options = { @@ -18,13 +16,13 @@ in package = lib.mkPackageOption pkgs "auto-epp" { }; - settings = mkOption { - type = types.submodule { + settings = lib.mkOption { + type = lib.types.submodule { freeformType = format.type; options = { Settings = { - epp_state_for_AC = mkOption { - type = types.str; + epp_state_for_AC = lib.mkOption { + type = lib.types.str; default = "balance_performance"; description = '' energy_performance_preference when on plugged in @@ -36,8 +34,8 @@ in ''; }; - epp_state_for_BAT = mkOption { - type = types.str; + epp_state_for_BAT = lib.mkOption { + type = lib.types.str; default = "power"; description = '' `energy_performance_preference` when on battery diff --git a/nixos/modules/services/hardware/bluetooth.nix b/nixos/modules/services/hardware/bluetooth.nix index e90a612700cc1..b9e7f2e176801 100644 --- a/nixos/modules/services/hardware/bluetooth.nix +++ b/nixos/modules/services/hardware/bluetooth.nix @@ -8,24 +8,6 @@ let cfg = config.hardware.bluetooth; package = cfg.package; - inherit (lib) - mkDefault - mkEnableOption - mkIf - mkOption - mkPackageOption - mkRenamedOptionModule - mkRemovedOptionModule - concatStringsSep - escapeShellArgs - literalExpression - optional - optionals - optionalAttrs - recursiveUpdate - types - ; - cfgFmt = pkgs.formats.ini { }; defaults = { @@ -38,8 +20,8 @@ let in { imports = [ - (mkRenamedOptionModule [ "hardware" "bluetooth" "config" ] [ "hardware" "bluetooth" "settings" ]) - (mkRemovedOptionModule [ "hardware" "bluetooth" "extraConfig" ] '' + (lib.mkRenamedOptionModule [ "hardware" "bluetooth" "config" ] [ "hardware" "bluetooth" "settings" ]) + (lib.mkRemovedOptionModule [ "hardware" "bluetooth" "extraConfig" ] '' Use hardware.bluetooth.settings instead. This is part of the general move to use structured settings instead of raw @@ -53,25 +35,25 @@ in options = { hardware.bluetooth = { - enable = mkEnableOption "support for Bluetooth"; + enable = lib.mkEnableOption "support for Bluetooth"; - hsphfpd.enable = mkEnableOption "support for hsphfpd[-prototype] implementation"; + hsphfpd.enable = lib.mkEnableOption "support for hsphfpd[-prototype] implementation"; - powerOnBoot = mkOption { - type = types.bool; + powerOnBoot = lib.mkOption { + type = lib.types.bool; default = true; description = "Whether to power up the default Bluetooth controller on boot."; }; - package = mkPackageOption pkgs "bluez" { }; + package = lib.mkPackageOption pkgs "bluez" { }; - disabledPlugins = mkOption { - type = types.listOf types.str; + disabledPlugins = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; description = "Built-in plugins to disable"; }; - settings = mkOption { + settings = lib.mkOption { type = cfgFmt.type; default = { }; example = { @@ -85,7 +67,7 @@ in ''; }; - input = mkOption { + input = lib.mkOption { type = cfgFmt.type; default = { }; example = { @@ -100,7 +82,7 @@ in ''; }; - network = mkOption { + network = lib.mkOption { type = cfgFmt.type; default = { }; example = { @@ -118,16 +100,16 @@ in ###### implementation - config = mkIf cfg.enable { - environment.systemPackages = [ package ] ++ optional cfg.hsphfpd.enable pkgs.hsphfpd; + config = lib.mkIf cfg.enable { + environment.systemPackages = [ package ] ++ lib.optional cfg.hsphfpd.enable pkgs.hsphfpd; environment.etc."bluetooth/input.conf".source = cfgFmt.generate "input.conf" cfg.input; environment.etc."bluetooth/network.conf".source = cfgFmt.generate "network.conf" cfg.network; environment.etc."bluetooth/main.conf".source = cfgFmt.generate "main.conf" ( - recursiveUpdate defaults cfg.settings + lib.recursiveUpdate defaults cfg.settings ); services.udev.packages = [ package ]; - services.dbus.packages = [ package ] ++ optional cfg.hsphfpd.enable pkgs.hsphfpd; + services.dbus.packages = [ package ] ++ lib.optional cfg.hsphfpd.enable pkgs.hsphfpd; systemd.packages = [ package ]; systemd.services = @@ -141,20 +123,20 @@ in args = [ "-f" "/etc/bluetooth/main.conf" - ] ++ optional hasDisabledPlugins "--noplugin=${concatStringsSep "," cfg.disabledPlugins}"; + ] ++ lib.optional hasDisabledPlugins "--noplugin=${lib.concatStringsSep "," cfg.disabledPlugins}"; in { wantedBy = [ "bluetooth.target" ]; aliases = [ "dbus-org.bluez.service" ]; serviceConfig.ExecStart = [ "" - "${package}/libexec/bluetooth/bluetoothd ${escapeShellArgs args}" + "${package}/libexec/bluetooth/bluetoothd ${lib.escapeShellArgs args}" ]; # restarting can leave people without a mouse/keyboard unitConfig.X-RestartIfChanged = false; }; } - // (optionalAttrs cfg.hsphfpd.enable { + // (lib.optionalAttrs cfg.hsphfpd.enable { hsphfpd = { after = [ "bluetooth.service" ]; requires = [ "bluetooth.service" ]; @@ -169,7 +151,7 @@ in { obex.aliases = [ "dbus-org.bluez.obex.service" ]; } - // optionalAttrs cfg.hsphfpd.enable { + // lib.optionalAttrs cfg.hsphfpd.enable { telephony_client = { wantedBy = [ "default.target" ]; diff --git a/nixos/modules/services/hardware/buffyboard.nix b/nixos/modules/services/hardware/buffyboard.nix index f6cab16138c02..a076917b902a1 100644 --- a/nixos/modules/services/hardware/buffyboard.nix +++ b/nixos/modules/services/hardware/buffyboard.nix @@ -28,12 +28,12 @@ in meta.maintainers = with lib.maintainers; [ colinsane ]; options = { - services.buffyboard = with lib; { - enable = mkEnableOption "buffyboard framebuffer keyboard (on-screen keyboard)"; - package = mkPackageOption pkgs "buffybox" { }; + services.buffyboard = { + enable = lib.mkEnableOption "buffyboard framebuffer keyboard (on-screen keyboard)"; + package = lib.mkPackageOption pkgs "buffybox" { }; - extraFlags = mkOption { - type = types.listOf types.str; + extraFlags = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; description = '' Extra CLI arguments to pass to buffyboard. @@ -46,7 +46,7 @@ in ]; }; - configFile = mkOption { + configFile = lib.mkOption { type = lib.types.path; default = ini.generate "buffyboard.conf" (lib.filterAttrsRecursive (_: v: v != null) cfg.settings); defaultText = lib.literalExpression ''ini.generate "buffyboard.conf" cfg.settings''; @@ -59,33 +59,33 @@ in ''; }; - settings = mkOption { + settings = lib.mkOption { description = '' Settings to include in /etc/buffyboard.conf. - Every option here is strictly optional: + Every option here is strictly lib.optional: Buffyboard will use its own baked-in defaults for those options left unset. ''; - type = types.submodule { + type = lib.types.submodule { freeformType = ini.type; - options.input.pointer = mkOption { - type = types.nullOr types.bool; + options.input.pointer = lib.mkOption { + type = lib.types.nullOr lib.types.bool; default = null; description = '' Enable or disable the use of a hardware mouse or other pointing device. ''; }; - options.input.touchscreen = mkOption { - type = types.nullOr types.bool; + options.input.touchscreen = lib.mkOption { + type = lib.types.nullOr lib.types.bool; default = null; description = '' Enable or disable the use of the touchscreen. ''; }; - options.theme.default = mkOption { - type = types.either types.str ( - types.enum [ + options.theme.default = lib.mkOption { + type = lib.types.either lib.types.str ( + lib.types.enum [ null "adwaita-dark" "breezy-dark" @@ -101,8 +101,8 @@ in Selects the default theme on boot. Can be changed at runtime to the alternative theme. ''; }; - options.quirks.fbdev_force_refresh = mkOption { - type = types.nullOr types.bool; + options.quirks.fbdev_force_refresh = lib.mkOption { + type = lib.types.nullOr lib.types.bool; default = null; description = '' If true and using the framebuffer backend, this triggers a display refresh after every draw operation. @@ -119,7 +119,7 @@ in systemd.packages = [ cfg.package ]; systemd.services.buffyboard = { # upstream provides the service (including systemd hardening): we just configure it to start by default - # and override ExecStart so as to optionally pass extra arguments + # and override ExecStart so as to lib.optionally pass extra arguments serviceConfig.ExecStart = [ "" # clear default ExecStart (utils.escapeSystemdExecArgs ( diff --git a/nixos/modules/services/hardware/handheld-daemon.nix b/nixos/modules/services/hardware/handheld-daemon.nix index 4ea5eb79593fd..54f8df7dce27d 100644 --- a/nixos/modules/services/hardware/handheld-daemon.nix +++ b/nixos/modules/services/hardware/handheld-daemon.nix @@ -4,30 +4,29 @@ pkgs, ... }: -with lib; let cfg = config.services.handheld-daemon; in { options.services.handheld-daemon = { - enable = mkEnableOption "Handheld Daemon"; - package = mkPackageOption pkgs "handheld-daemon" { }; + enable = lib.mkEnableOption "Handheld Daemon"; + package = lib.mkPackageOption pkgs "handheld-daemon" { }; ui = { - enable = mkEnableOption "Handheld Daemon UI"; - package = mkPackageOption pkgs "handheld-daemon-ui" { }; + enable = lib.mkEnableOption "Handheld Daemon UI"; + package = lib.mkPackageOption pkgs "handheld-daemon-ui" { }; }; - user = mkOption { - type = types.str; + user = lib.mkOption { + type = lib.types.str; description = '' The user to run Handheld Daemon with. ''; }; }; - config = mkIf cfg.enable { - services.handheld-daemon.ui.enable = mkDefault true; + config = lib.mkIf cfg.enable { + services.handheld-daemon.ui.enable = lib.mkDefault true; environment.systemPackages = [ cfg.package ] ++ lib.optional cfg.ui.enable cfg.ui.package; @@ -41,7 +40,7 @@ in restartIfChanged = true; - path = mkIf cfg.ui.enable [ + path = lib.mkIf cfg.ui.enable [ cfg.ui.package pkgs.lsof ]; @@ -55,5 +54,5 @@ in }; }; - meta.maintainers = [ maintainers.appsforartists ]; + meta.maintainers = [ lib.maintainers.appsforartists ]; } diff --git a/nixos/modules/services/hardware/hddfancontrol.nix b/nixos/modules/services/hardware/hddfancontrol.nix index 8705109dd0359..dac9ad7827160 100644 --- a/nixos/modules/services/hardware/hddfancontrol.nix +++ b/nixos/modules/services/hardware/hddfancontrol.nix @@ -16,7 +16,7 @@ in services.hddfancontrol.enable = lib.mkEnableOption "hddfancontrol daemon"; services.hddfancontrol.disks = lib.mkOption { - type = with types; listOf path; + type = with lib.types; listOf path; default = [ ]; description = '' Drive(s) to get temperature from @@ -25,7 +25,7 @@ in }; services.hddfancontrol.pwmPaths = lib.mkOption { - type = with types; listOf path; + type = with lib.types; listOf path; default = [ ]; description = '' PWM filepath(s) to control fan speed (under /sys) @@ -34,7 +34,7 @@ in }; services.hddfancontrol.smartctl = lib.mkOption { - type = types.bool; + type = lib.types.bool; default = false; description = '' Probe temperature using smartctl instead of hddtemp or hdparm @@ -42,7 +42,7 @@ in }; services.hddfancontrol.extraArgs = lib.mkOption { - type = with types; listOf str; + type = with lib.types; listOf str; default = [ ]; description = '' Extra commandline arguments for hddfancontrol diff --git a/nixos/modules/services/hardware/lcd.nix b/nixos/modules/services/hardware/lcd.nix index 0b39281667cc7..9f9b4fd986ec2 100644 --- a/nixos/modules/services/hardware/lcd.nix +++ b/nixos/modules/services/hardware/lcd.nix @@ -33,40 +33,39 @@ let }; in -with lib; { - meta.maintainers = with maintainers; [ peterhoeg ]; + meta.maintainers = with lib.maintainers; [ peterhoeg ]; - options = with types; { + options = { services.hardware.lcd = { - serverHost = mkOption { - type = str; + serverHost = lib.mkOption { + type = lib.types.str; default = "localhost"; description = "Host on which LCDd is listening."; }; - serverPort = mkOption { - type = int; + serverPort = lib.mkOption { + type = lib.types.int; default = 13666; description = "Port on which LCDd is listening."; }; server = { - enable = mkOption { - type = bool; + enable = lib.mkOption { + type = lib.types.bool; default = false; description = "Enable the LCD panel server (LCDd)"; }; - openPorts = mkOption { - type = bool; + openPorts = lib.mkOption { + type = lib.types.bool; default = false; description = "Open the ports in the firewall"; }; - usbPermissions = mkOption { - type = bool; + usbPermissions = lib.mkOption { + type = lib.types.bool; default = false; description = '' Set group-write permissions on a USB device. @@ -87,46 +86,46 @@ with lib; ''; }; - usbVid = mkOption { - type = str; + usbVid = lib.mkOption { + type = lib.types.str; default = ""; description = "The vendor ID of the USB device to claim."; }; - usbPid = mkOption { - type = str; + usbPid = lib.mkOption { + type = lib.types.str; default = ""; description = "The product ID of the USB device to claim."; }; - usbGroup = mkOption { - type = str; + usbGroup = lib.mkOption { + type = lib.types.str; default = "dialout"; description = "The group to use for settings permissions. This group must exist or you will have to create it."; }; - extraConfig = mkOption { - type = lines; + extraConfig = lib.mkOption { + type = lib.types.lines; default = ""; description = "Additional configuration added verbatim to the server config."; }; }; client = { - enable = mkOption { - type = bool; + enable = lib.mkOption { + type = lib.types.bool; default = false; description = "Enable the LCD panel client (LCDproc)"; }; - extraConfig = mkOption { - type = lines; + extraConfig = lib.mkOption { + type = lib.types.lines; default = ""; description = "Additional configuration added verbatim to the client config."; }; - restartForever = mkOption { - type = bool; + restartForever = lib.mkOption { + type = lib.types.bool; default = true; description = "Try restarting the client forever."; }; @@ -134,17 +133,17 @@ with lib; }; }; - config = mkIf (cfg.server.enable || cfg.client.enable) { - networking.firewall.allowedTCPPorts = mkIf (cfg.server.enable && cfg.server.openPorts) [ + config = lib.mkIf (cfg.server.enable || cfg.client.enable) { + networking.firewall.allowedTCPPorts = lib.mkIf (cfg.server.enable && cfg.server.openPorts) [ cfg.serverPort ]; - services.udev.extraRules = mkIf (cfg.server.enable && cfg.server.usbPermissions) '' + services.udev.extraRules = lib.mkIf (cfg.server.enable && cfg.server.usbPermissions) '' ACTION=="add", SUBSYSTEMS=="usb", ATTRS{idVendor}=="${cfg.server.usbVid}", ATTRS{idProduct}=="${cfg.server.usbPid}", MODE="660", GROUP="${cfg.server.usbGroup}" ''; systemd.services = { - lcdd = mkIf cfg.server.enable { + lcdd = lib.mkIf cfg.server.enable { description = "LCDproc - server"; wantedBy = [ "lcd.target" ]; serviceConfig = serviceCfg // { @@ -153,7 +152,7 @@ with lib; }; }; - lcdproc = mkIf cfg.client.enable { + lcdproc = lib.mkIf cfg.client.enable { description = "LCDproc - client"; after = [ "lcdd.service" ]; wantedBy = [ "lcd.target" ]; diff --git a/nixos/modules/services/hardware/monado.nix b/nixos/modules/services/hardware/monado.nix index 137b63c774200..7464542642d33 100644 --- a/nixos/modules/services/hardware/monado.nix +++ b/nixos/modules/services/hardware/monado.nix @@ -5,27 +5,18 @@ ... }: let - inherit (lib) - mkDefault - mkEnableOption - mkIf - mkOption - mkPackageOption - types - ; - cfg = config.services.monado; runtimeManifest = "${cfg.package}/share/openxr/1/openxr_monado.json"; in { options.services.monado = { - enable = mkEnableOption "Monado user service"; + enable = lib.mkEnableOption "Monado user service"; - package = mkPackageOption pkgs "monado" { }; + package = lib.mkPackageOption pkgs "monado" { }; - defaultRuntime = mkOption { - type = types.bool; + defaultRuntime = lib.mkOption { + type = lib.types.bool; description = '' Whether to enable Monado as the default OpenXR runtime on the system. @@ -36,8 +27,8 @@ in example = true; }; - forceDefaultRuntime = mkOption { - type = types.bool; + forceDefaultRuntime = lib.mkOption { + type = lib.types.bool; description = '' Whether to ensure that Monado is the active runtime set for the current user. @@ -50,12 +41,12 @@ in }; highPriority = - mkEnableOption "high priority capability for monado-service" - // mkOption { default = true; }; + lib.mkEnableOption "high priority capability for monado-service" + // lib.mkOption { default = true; }; }; - config = mkIf cfg.enable { - security.wrappers."monado-service" = mkIf cfg.highPriority { + config = lib.mkIf cfg.enable { + security.wrappers."monado-service" = lib.mkIf cfg.highPriority { setuid = false; owner = "root"; group = "root"; @@ -77,12 +68,12 @@ in environment = { # Default options # https://gitlab.freedesktop.org/monado/monado/-/blob/4548e1738591d0904f8db4df8ede652ece889a76/src/xrt/targets/service/monado.in.service#L12 - XRT_COMPOSITOR_LOG = mkDefault "debug"; - XRT_PRINT_OPTIONS = mkDefault "on"; - IPC_EXIT_ON_DISCONNECT = mkDefault "off"; + XRT_COMPOSITOR_LOG = lib.mkDefault "debug"; + XRT_PRINT_OPTIONS = lib.mkDefault "on"; + IPC_EXIT_ON_DISCONNECT = lib.mkDefault "off"; }; - preStart = mkIf cfg.forceDefaultRuntime '' + preStart = lib.mkIf cfg.forceDefaultRuntime '' XDG_CONFIG_HOME="''${XDG_CONFIG_HOME:-$HOME/.config}" targetDir="$XDG_CONFIG_HOME/openxr/1" activeRuntimePath="$targetDir/active_runtime.json" @@ -129,7 +120,7 @@ in hardware.graphics.extraPackages = [ pkgs.monado-vulkan-layers ]; - environment.etc."xdg/openxr/1/active_runtime.json" = mkIf cfg.defaultRuntime { + environment.etc."xdg/openxr/1/active_runtime.json" = lib.mkIf cfg.defaultRuntime { source = runtimeManifest; }; }; diff --git a/nixos/modules/services/hardware/sane_extra_backends/brscan4_etc_files.nix b/nixos/modules/services/hardware/sane_extra_backends/brscan4_etc_files.nix index 8ec6b72cb5ea5..7274807ffa8e3 100644 --- a/nixos/modules/services/hardware/sane_extra_backends/brscan4_etc_files.nix +++ b/nixos/modules/services/hardware/sane_extra_backends/brscan4_etc_files.nix @@ -65,11 +65,11 @@ stdenv.mkDerivation { dontStrip = true; dontPatchELF = true; - meta = with lib; { + meta = { description = "Brother brscan4 sane backend driver etc files"; homepage = "http://www.brother.com"; - platforms = platforms.linux; - license = licenses.unfree; - maintainers = with maintainers; [ jraygauthier ]; + platforms = lib.platforms.linux; + license = lib.licenses.unfree; + maintainers = [ lib.maintainers.jraygauthier ]; }; } diff --git a/nixos/modules/services/hardware/sane_extra_backends/brscan5_etc_files.nix b/nixos/modules/services/hardware/sane_extra_backends/brscan5_etc_files.nix index 9ad64c41ee69d..deb03e8f04828 100644 --- a/nixos/modules/services/hardware/sane_extra_backends/brscan5_etc_files.nix +++ b/nixos/modules/services/hardware/sane_extra_backends/brscan5_etc_files.nix @@ -73,11 +73,11 @@ stdenv.mkDerivation { dontInstall = true; - meta = with lib; { + meta = { description = "Brother brscan5 sane backend driver etc files"; homepage = "https://www.brother.com"; - platforms = platforms.linux; - license = licenses.unfree; - maintainers = with maintainers; [ mattchrist ]; + platforms = lib.platforms.linux; + license = lib.licenses.unfree; + maintainers = [ lib.maintainers.mattchrist ]; }; } diff --git a/nixos/modules/services/hardware/vdr.nix b/nixos/modules/services/hardware/vdr.nix index 59aaffcb12646..c6d08137d229f 100644 --- a/nixos/modules/services/hardware/vdr.nix +++ b/nixos/modules/services/hardware/vdr.nix @@ -6,50 +6,41 @@ }: let cfg = config.services.vdr; - - inherit (lib) - mkEnableOption - mkPackageOption - mkOption - types - mkIf - optional - ; in { options = { services.vdr = { - enable = mkEnableOption "VDR, a video disk recorder"; + enable = lib.mkEnableOption "VDR, a video disk recorder"; - package = mkPackageOption pkgs "vdr" { + package = lib.mkPackageOption pkgs "vdr" { example = "wrapVdr.override { plugins = with pkgs.vdrPlugins; [ hello ]; }"; }; - videoDir = mkOption { - type = types.path; + videoDir = lib.mkOption { + type = lib.types.path; default = "/srv/vdr/video"; description = "Recording directory"; }; - extraArguments = mkOption { - type = types.listOf types.str; + extraArguments = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; description = "Additional command line arguments to pass to VDR."; }; - enableLirc = mkEnableOption "LIRC"; + enableLirc = lib.mkEnableOption "LIRC"; - user = mkOption { - type = types.str; + user = lib.mkOption { + type = lib.types.str; default = "vdr"; description = '' User under which the VDR service runs. ''; }; - group = mkOption { - type = types.str; + group = lib.mkOption { + type = lib.types.str; default = "vdr"; description = '' Group under which the VDRvdr service runs. @@ -59,7 +50,7 @@ in }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { systemd.tmpfiles.rules = [ "d ${cfg.videoDir} 0755 ${cfg.user} ${cfg.group} -" @@ -69,8 +60,8 @@ in systemd.services.vdr = { description = "VDR"; wantedBy = [ "multi-user.target" ]; - wants = optional cfg.enableLirc "lircd.service"; - after = [ "network.target" ] ++ optional cfg.enableLirc "lircd.service"; + wants = lib.optional cfg.enableLirc "lircd.service"; + after = [ "network.target" ] ++ lib.optional cfg.enableLirc "lircd.service"; serviceConfig = { ExecStart = let @@ -78,7 +69,7 @@ in [ "--video=${cfg.videoDir}" ] - ++ optional cfg.enableLirc "--lirc=${config.passthru.lirc.socket}" + ++ lib.optional cfg.enableLirc "--lirc=${config.passthru.lirc.socket}" ++ cfg.extraArguments; in "${cfg.package}/bin/vdr ${lib.escapeShellArgs args}"; @@ -93,7 +84,7 @@ in environment.systemPackages = [ cfg.package ]; - users.users = mkIf (cfg.user == "vdr") { + users.users = lib.mkIf (cfg.user == "vdr") { vdr = { inherit (cfg) group; home = "/run/vdr"; @@ -101,11 +92,11 @@ in extraGroups = [ "video" "audio" - ] ++ optional cfg.enableLirc "lirc"; + ] ++ lib.optional cfg.enableLirc "lirc"; }; }; - users.groups = mkIf (cfg.group == "vdr") { vdr = { }; }; + users.groups = lib.mkIf (cfg.group == "vdr") { vdr = { }; }; }; } diff --git a/nixos/modules/services/home-automation/esphome.nix b/nixos/modules/services/home-automation/esphome.nix index 0673454aab89c..7f1054c01a7de 100644 --- a/nixos/modules/services/home-automation/esphome.nix +++ b/nixos/modules/services/home-automation/esphome.nix @@ -6,15 +6,6 @@ }: let - inherit (lib) - literalExpression - maintainers - mkEnableOption - mkIf - mkOption - types - ; - cfg = config.services.esphome; stateDir = "/var/lib/esphome"; @@ -26,38 +17,38 @@ let "--address ${cfg.address} --port ${toString cfg.port}"; in { - meta.maintainers = with maintainers; [ oddlama ]; + meta.maintainers = with lib.maintainers; [ oddlama ]; options.services.esphome = { - enable = mkEnableOption "esphome, for making custom firmwares for ESP32/ESP8266"; + enable = lib.mkEnableOption "esphome, for making custom firmwares for ESP32/ESP8266"; package = lib.mkPackageOption pkgs "esphome" { }; - enableUnixSocket = mkOption { - type = types.bool; + enableUnixSocket = lib.mkOption { + type = lib.types.bool; default = false; description = "Listen on a unix socket `/run/esphome/esphome.sock` instead of the TCP port."; }; - address = mkOption { - type = types.str; + address = lib.mkOption { + type = lib.types.str; default = "localhost"; description = "esphome address"; }; - port = mkOption { - type = types.port; + port = lib.mkOption { + type = lib.types.port; default = 6052; description = "esphome port"; }; - openFirewall = mkOption { + openFirewall = lib.mkOption { default = false; - type = types.bool; + type = lib.types.bool; description = "Whether to open the firewall for the specified port."; }; - allowedDevices = mkOption { + allowedDevices = lib.mkOption { default = [ "char-ttyS" "char-ttyUSB" @@ -71,18 +62,18 @@ in Beware that if a device is referred to by an absolute path instead of a device category, it will only allow devices that already are plugged in when the service is started. ''; - type = types.listOf types.str; + type = lib.types.listOf lib.types.str; }; - usePing = mkOption { + usePing = lib.mkOption { default = false; - type = types.bool; + type = lib.types.bool; description = "Use ping to check online status of devices instead of mDNS"; }; }; - config = mkIf cfg.enable { - networking.firewall.allowedTCPPorts = mkIf (cfg.openFirewall && !cfg.enableUnixSocket) [ cfg.port ]; + config = lib.mkIf cfg.enable { + networking.firewall.allowedTCPPorts = lib.mkIf (cfg.openFirewall && !cfg.enableUnixSocket) [ cfg.port ]; systemd.services.esphome = { description = "ESPHome dashboard"; @@ -104,7 +95,7 @@ in StateDirectory = "esphome"; StateDirectoryMode = "0750"; Restart = "on-failure"; - RuntimeDirectory = mkIf cfg.enableUnixSocket "esphome"; + RuntimeDirectory = lib.mkIf cfg.enableUnixSocket "esphome"; RuntimeDirectoryMode = "0750"; # Hardening diff --git a/nixos/modules/services/home-automation/home-assistant.nix b/nixos/modules/services/home-automation/home-assistant.nix index 2e91ee55f95ee..f6fd542637e61 100644 --- a/nixos/modules/services/home-automation/home-assistant.nix +++ b/nixos/modules/services/home-automation/home-assistant.nix @@ -1,37 +1,6 @@ { config, lib, pkgs, utils, ... }: let - inherit (lib) - any - attrByPath - attrValues - concatMap - converge - elem - escapeShellArg - escapeShellArgs - filter - filterAttrsRecursive - hasAttrByPath - isAttrs - isDerivation - isList - literalExpression - mkEnableOption - mkIf - mkMerge - mkOption - mkRemovedOptionModule - mkRenamedOptionModule - optionals - optionalString - recursiveUpdate - singleton - splitString - types - unique - ; - inherit (utils) escapeSystemdExecArgs ; @@ -51,8 +20,8 @@ let ''; # Filter null values from the configuration, so that we can still advertise - # optional options in the config attribute. - filteredConfig = converge (filterAttrsRecursive (_: v: ! elem v [ null ])) (recursiveUpdate customLovelaceModulesResources (cfg.config or {})); + # lib.optional options in the config attribute. + filteredConfig = lib.converge (lib.filterAttrsRecursive (_: v: ! lib.elem v [ null ])) (lib.recursiveUpdate customLovelaceModulesResources (cfg.config or {})); configFile = renderYAMLFile "configuration.yaml" filteredConfig; lovelaceConfigFile = renderYAMLFile "ui-lovelace.yaml" cfg.lovelaceConfig; @@ -62,7 +31,7 @@ let # Components that were added by overriding the package explicitComponents = cfg.package.extraComponents; - useExplicitComponent = component: elem component explicitComponents; + useExplicitComponent = component: lib.elem component explicitComponents; # Given a component "platform", looks up whether it is used in the config # as `platform = "platform";`. @@ -74,27 +43,27 @@ let # } ]; usedPlatforms = config: # don't recurse into derivations possibly creating an infinite recursion - if isDerivation config then + if lib.isDerivation config then [ ] - else if isAttrs config then - optionals (config ? platform) [ config.platform ] - ++ concatMap usedPlatforms (attrValues config) - else if isList config then - concatMap usedPlatforms config + else if lib.isAttrs config then + lib.optionals (config ? platform) [ config.platform ] + ++ lib.concatMap usedPlatforms (lib.attrValues config) + else if lib.isList config then + lib.concatMap usedPlatforms config else [ ]; - useComponentPlatform = component: elem component (usedPlatforms cfg.config); + useComponentPlatform = component: lib.elem component (usedPlatforms cfg.config); # Returns whether component is used in config, explicitly passed into package or # configured in the module. useComponent = component: - hasAttrByPath (splitString "." component) cfg.config + lib.hasAttrByPath (lib.splitString "." component) cfg.config || useComponentPlatform component || useExplicitComponent component || builtins.elem component (cfg.extraComponents ++ cfg.defaultIntegrations); # Final list of components passed into the package to include required dependencies - extraComponents = filter useComponent availableComponents; + extraComponents = lib.filter useComponent availableComponents; package = (cfg.package.override (oldArgs: { # Respect overrides that already exist in the passed package and @@ -102,7 +71,7 @@ let extraComponents = oldArgs.extraComponents or [] ++ extraComponents; extraPackages = ps: (oldArgs.extraPackages or (_: []) ps) ++ (cfg.extraPackages ps) - ++ (concatMap (component: component.propagatedBuildInputs or []) cfg.customComponents); + ++ (lib.concatMap (component: component.propagatedBuildInputs or []) cfg.customComponents); })); # Create a directory that holds all lovelace modules @@ -121,9 +90,9 @@ let in { imports = [ # Migrations in NixOS 22.05 - (mkRemovedOptionModule [ "services" "home-assistant" "applyDefaultConfig" ] "The default config was migrated into services.home-assistant.config") - (mkRemovedOptionModule [ "services" "home-assistant" "autoExtraComponents" ] "Components are now parsed from services.home-assistant.config unconditionally") - (mkRenamedOptionModule [ "services" "home-assistant" "port" ] [ "services" "home-assistant" "config" "http" "server_port" ]) + (lib.mkRemovedOptionModule [ "services" "home-assistant" "applyDefaultConfig" ] "The default config was migrated into services.home-assistant.config") + (lib.mkRemovedOptionModule [ "services" "home-assistant" "autoExtraComponents" ] "Components are now parsed from services.home-assistant.config unconditionally") + (lib.mkRenamedOptionModule [ "services" "home-assistant" "port" ] [ "services" "home-assistant" "config" "http" "server_port" ]) ]; meta = { @@ -134,10 +103,10 @@ in { options.services.home-assistant = { # Running home-assistant on NixOS is considered an installation method that is unsupported by the upstream project. # https://github.com/home-assistant/architecture/blob/master/adr/0012-define-supported-installation-method.md#decision - enable = mkEnableOption "Home Assistant. Please note that this installation method is unsupported upstream"; + enable = lib.mkEnableOption "Home Assistant. Please note that this installation method is unsupported upstream"; - extraArgs = mkOption { - type = types.listOf types.str; + extraArgs = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; example = [ "--debug" ]; description = '' @@ -145,14 +114,14 @@ in { ''; }; - configDir = mkOption { + configDir = lib.mkOption { default = "/var/lib/hass"; - type = types.path; + type = lib.types.path; description = "The config directory, where your {file}`configuration.yaml` is located."; }; - defaultIntegrations = mkOption { - type = types.listOf (types.enum availableComponents); + defaultIntegrations = lib.mkOption { + type = lib.types.listOf (lib.types.enum availableComponents); # https://github.com/home-assistant/core/blob/dev/homeassistant/bootstrap.py#L109 default = [ "application_credentials" @@ -190,19 +159,19 @@ in { ''; }; - extraComponents = mkOption { - type = types.listOf (types.enum availableComponents); + extraComponents = lib.mkOption { + type = lib.types.listOf (lib.types.enum availableComponents); default = [ # List of components required to complete the onboarding "default_config" "met" "esphome" - ] ++ optionals pkgs.stdenv.hostPlatform.isAarch [ + ] ++ lib.optionals pkgs.stdenv.hostPlatform.isAarch [ # Use the platform as an indicator that we might be running on a RaspberryPi and include # relevant components "rpi_power" ]; - example = literalExpression '' + example = lib.literalExpression '' [ "analytics" "default_config" @@ -219,13 +188,13 @@ in { ''; }; - extraPackages = mkOption { - type = types.functionTo (types.listOf types.package); + extraPackages = lib.mkOption { + type = lib.types.functionTo (lib.types.listOf lib.types.package); default = _: []; - defaultText = literalExpression '' + defaultText = lib.literalExpression '' python3Packages: with python3Packages; []; ''; - example = literalExpression '' + example = lib.literalExpression '' python3Packages: with python3Packages; [ # postgresql support psycopg2 @@ -239,15 +208,15 @@ in { ''; }; - customComponents = mkOption { - type = types.listOf ( - types.addCheck types.package (p: p.isHomeAssistantComponent or false) // { + customComponents = lib.mkOption { + type = lib.types.listOf ( + lib.types.addCheck lib.types.package (p: p.isHomeAssistantComponent or false) // { name = "home-assistant-component"; description = "package that is a Home Assistant component"; } ); default = []; - example = literalExpression '' + example = lib.literalExpression '' with pkgs.home-assistant-custom-components; [ prometheus_sensor ]; @@ -259,10 +228,10 @@ in { ''; }; - customLovelaceModules = mkOption { - type = types.listOf types.package; + customLovelaceModules = lib.mkOption { + type = lib.types.listOf lib.types.package; default = []; - example = literalExpression '' + example = lib.literalExpression '' with pkgs.home-assistant-custom-lovelace-modules; [ mini-graph-card mini-media-player @@ -279,8 +248,8 @@ in { ''; }; - config = mkOption { - type = types.nullOr (types.submodule { + config = lib.mkOption { + type = lib.types.nullOr (lib.types.submodule { freeformType = format.type; options = { # This is a partial selection of the most common options, so new users can quickly @@ -289,8 +258,8 @@ in { homeassistant = { # https://www.home-assistant.io/docs/configuration/basic/ - name = mkOption { - type = types.nullOr types.str; + name = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; example = "Home"; description = '' @@ -298,8 +267,8 @@ in { ''; }; - latitude = mkOption { - type = types.nullOr (types.either types.float types.str); + latitude = lib.mkOption { + type = lib.types.nullOr (lib.types.either lib.types.float lib.types.str); default = null; example = 52.3; description = '' @@ -307,8 +276,8 @@ in { ''; }; - longitude = mkOption { - type = types.nullOr (types.either types.float types.str); + longitude = lib.mkOption { + type = lib.types.nullOr (lib.types.either lib.types.float lib.types.str); default = null; example = 4.9; description = '' @@ -316,8 +285,8 @@ in { ''; }; - unit_system = mkOption { - type = types.nullOr (types.enum [ "metric" "imperial" ]); + unit_system = lib.mkOption { + type = lib.types.nullOr (lib.types.enum [ "metric" "imperial" ]); default = null; example = "metric"; description = '' @@ -325,8 +294,8 @@ in { ''; }; - temperature_unit = mkOption { - type = types.nullOr (types.enum [ "C" "F" ]); + temperature_unit = lib.mkOption { + type = lib.types.nullOr (lib.types.enum [ "C" "F" ]); default = null; example = "C"; description = '' @@ -334,10 +303,10 @@ in { ''; }; - time_zone = mkOption { - type = types.nullOr types.str; + time_zone = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = config.time.timeZone or null; - defaultText = literalExpression '' + defaultText = lib.literalExpression '' config.time.timeZone or null ''; example = "Europe/Amsterdam"; @@ -349,8 +318,8 @@ in { http = { # https://www.home-assistant.io/integrations/http/ - server_host = mkOption { - type = types.either types.str (types.listOf types.str); + server_host = lib.mkOption { + type = lib.types.either lib.types.str (lib.types.listOf lib.types.str); default = [ "0.0.0.0" "::" @@ -361,9 +330,9 @@ in { ''; }; - server_port = mkOption { + server_port = lib.mkOption { default = 8123; - type = types.port; + type = lib.types.port; description = '' The port on which to listen. ''; @@ -372,12 +341,12 @@ in { lovelace = { # https://www.home-assistant.io/lovelace/dashboards/ - mode = mkOption { - type = types.enum [ "yaml" "storage" ]; + mode = lib.mkOption { + type = lib.types.enum [ "yaml" "storage" ]; default = if cfg.lovelaceConfig != null then "yaml" else "storage"; - defaultText = literalExpression '' + defaultText = lib.literalExpression '' if cfg.lovelaceConfig != null then "yaml" else "storage"; @@ -390,7 +359,7 @@ in { }; }; }); - example = literalExpression '' + example = lib.literalExpression '' { homeassistant = { name = "Home"; @@ -419,9 +388,9 @@ in { ''; }; - configWritable = mkOption { + configWritable = lib.mkOption { default = false; - type = types.bool; + type = lib.types.bool; description = '' Whether to make {file}`configuration.yaml` writable. @@ -432,11 +401,11 @@ in { ''; }; - lovelaceConfig = mkOption { + lovelaceConfig = lib.mkOption { default = null; - type = types.nullOr format.type; + type = lib.types.nullOr format.type; # from https://www.home-assistant.io/lovelace/dashboards/ - example = literalExpression '' + example = lib.literalExpression '' { title = "My Awesome Home"; views = [ { @@ -457,9 +426,9 @@ in { ''; }; - lovelaceConfigWritable = mkOption { + lovelaceConfigWritable = lib.mkOption { default = false; - type = types.bool; + type = lib.types.bool; description = '' Whether to make {file}`ui-lovelace.yaml` writable. @@ -470,17 +439,17 @@ in { ''; }; - package = mkOption { + package = lib.mkOption { default = pkgs.home-assistant.overrideAttrs (oldAttrs: { doInstallCheck = false; }); - defaultText = literalExpression '' + defaultText = lib.literalExpression '' pkgs.home-assistant.overrideAttrs (oldAttrs: { doInstallCheck = false; }) ''; - type = types.package; - example = literalExpression '' + type = lib.types.package; + example = lib.literalExpression '' pkgs.home-assistant.override { extraPackages = python3Packages: with python3Packages; [ psycopg2 @@ -497,14 +466,14 @@ in { ''; }; - openFirewall = mkOption { + openFirewall = lib.mkOption { default = false; - type = types.bool; + type = lib.types.bool; description = "Whether to open the firewall for the specified port."; }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { assertions = [ { assertion = cfg.openFirewall -> cfg.config != null; @@ -512,15 +481,15 @@ in { } ]; - networking.firewall.allowedTCPPorts = mkIf cfg.openFirewall [ cfg.config.http.server_port ]; + networking.firewall.allowedTCPPorts = lib.mkIf cfg.openFirewall [ cfg.config.http.server_port ]; # symlink the configuration to /etc/home-assistant - environment.etc = mkMerge [ - (mkIf (cfg.config != null && !cfg.configWritable) { + environment.etc = lib.mkMerge [ + (lib.mkIf (cfg.config != null && !cfg.configWritable) { "home-assistant/configuration.yaml".source = configFile; }) - (mkIf (cfg.lovelaceConfig != null && !cfg.lovelaceConfigWritable) { + (lib.mkIf (cfg.lovelaceConfig != null && !cfg.lovelaceConfigWritable) { "home-assistant/ui-lovelace.yaml".source = lovelaceConfigFile; }) ]; @@ -535,8 +504,8 @@ in { "mysql.service" "postgresql.service" ]; - reloadTriggers = optionals (cfg.config != null) [ configFile ] - ++ optionals (cfg.lovelaceConfig != null) [ lovelaceConfigFile ]; + reloadTriggers = lib.optionals (cfg.config != null) [ configFile ] + ++ lib.optionals (cfg.lovelaceConfig != null) [ lovelaceConfigFile ]; preStart = let copyConfig = if cfg.configWritable then '' @@ -563,13 +532,13 @@ in { # remove components symlinked in from below the /nix/store readarray -d "" components < <(find "${cfg.configDir}/custom_components" -maxdepth 1 -type l -print0) for component in "''${components[@]}"; do - if [[ "$(readlink "$component")" =~ ^${escapeShellArg builtins.storeDir} ]]; then + if [[ "$(readlink "$component")" =~ ^${lib.escapeShellArg builtins.storeDir} ]]; then rm "$component" fi done # recreate symlinks for desired components - declare -a components=(${escapeShellArgs cfg.customComponents}) + declare -a components=(${lib.escapeShellArgs cfg.customComponents}) for component in "''${components[@]}"; do readarray -t manifests < <(find "$component" -name manifest.json) readarray -t paths < <(dirname "''${manifests[@]}") @@ -577,28 +546,28 @@ in { done ''; in - (optionalString (cfg.config != null) copyConfig) + - (optionalString (cfg.lovelaceConfig != null) copyLovelaceConfig) + + (lib.optionalString (cfg.config != null) copyConfig) + + (lib.optionalString (cfg.lovelaceConfig != null) copyLovelaceConfig) + copyCustomLovelaceModules + copyCustomComponents ; environment.PYTHONPATH = package.pythonPath; serviceConfig = let # List of capabilities to equip home-assistant with, depending on configured components - capabilities = unique ([ + capabilities = lib.unique ([ # Empty string first, so we will never accidentally have an empty capability bounding set # https://github.com/NixOS/nixpkgs/issues/120617#issuecomment-830685115 "" - ] ++ optionals (any useComponent componentsUsingBluetooth) [ + ] ++ lib.optionals (lib.any useComponent componentsUsingBluetooth) [ # Required for interaction with hci devices and bluetooth sockets, identified by bluetooth-adapters dependency # https://www.home-assistant.io/integrations/bluetooth_le_tracker/#rootless-setup-on-core-installs "CAP_NET_ADMIN" "CAP_NET_RAW" - ] ++ optionals (useComponent "emulated_hue") [ + ] ++ lib.optionals (useComponent "emulated_hue") [ # Alexa looks for the service on port 80 # https://www.home-assistant.io/integrations/emulated_hue "CAP_NET_BIND_SERVICE" - ] ++ optionals (useComponent "nmap_tracker") [ + ] ++ lib.optionals (useComponent "nmap_tracker") [ # https://www.home-assistant.io/integrations/nmap_tracker#linux-capabilities "CAP_NET_ADMIN" "CAP_NET_BIND_SERVICE" @@ -732,7 +701,7 @@ in { # Hardening AmbientCapabilities = capabilities; CapabilityBoundingSet = capabilities; - DeviceAllow = (optionals (any useComponent componentsUsingSerialDevices) [ + DeviceAllow = (lib.optionals (lib.any useComponent componentsUsingSerialDevices) [ "char-ttyACM rw" "char-ttyAMA rw" "char-ttyUSB rw" @@ -757,28 +726,28 @@ in { ReadWritePaths = let # Allow rw access to explicitly configured paths cfgPath = [ "config" "homeassistant" "allowlist_external_dirs" ]; - value = attrByPath cfgPath [] cfg; - allowPaths = if isList value then value else singleton value; + value = lib.attrByPath cfgPath [] cfg; + allowPaths = if lib.isList value then value else lib.singleton value; in [ "${cfg.configDir}" ] ++ allowPaths; RestrictAddressFamilies = [ "AF_INET" "AF_INET6" "AF_NETLINK" "AF_UNIX" - ] ++ optionals (any useComponent componentsUsingBluetooth) [ + ] ++ lib.optionals (lib.any useComponent componentsUsingBluetooth) [ "AF_BLUETOOTH" ]; RestrictNamespaces = true; RestrictRealtime = true; RestrictSUIDSGID = true; - SupplementaryGroups = optionals (any useComponent componentsUsingSerialDevices) [ + SupplementaryGroups = lib.optionals (lib.any useComponent componentsUsingSerialDevices) [ "dialout" ]; SystemCallArchitectures = "native"; SystemCallFilter = [ "@system-service" "~@privileged" - ] ++ optionals (any useComponent componentsUsingPing) [ + ] ++ lib.optionals (lib.any useComponent componentsUsingPing) [ "capset" "setuid" ]; diff --git a/nixos/modules/services/home-automation/wyoming/faster-whisper.nix b/nixos/modules/services/home-automation/wyoming/faster-whisper.nix index 69407efba0c61..342544aa27c4c 100644 --- a/nixos/modules/services/home-automation/wyoming/faster-whisper.nix +++ b/nixos/modules/services/home-automation/wyoming/faster-whisper.nix @@ -8,14 +8,6 @@ let cfg = config.services.wyoming.faster-whisper; - inherit (lib) - escapeShellArgs - mkOption - mkEnableOption - mkPackageOption - types - ; - inherit (builtins) toString ; @@ -23,23 +15,23 @@ let in { - options.services.wyoming.faster-whisper = with types; { - package = mkPackageOption pkgs "wyoming-faster-whisper" { }; + options.services.wyoming.faster-whisper = { + package = lib.mkPackageOption pkgs "wyoming-faster-whisper" { }; - servers = mkOption { + servers = lib.mkOption { default = { }; description = '' Attribute set of faster-whisper instances to spawn. ''; - type = types.attrsOf ( - types.submodule ( + type = lib.types.attrsOf ( + lib.types.submodule ( { ... }: { options = { - enable = mkEnableOption "Wyoming faster-whisper server"; + enable = lib.mkEnableOption "Wyoming faster-whisper server"; - model = mkOption { - type = str; + model = lib.mkOption { + type = lib.types.str; default = "tiny-int8"; example = "Systran/faster-distil-whisper-small.en"; description = '' @@ -49,17 +41,17 @@ in ''; }; - uri = mkOption { - type = strMatching "^(tcp|unix)://.*$"; + uri = lib.mkOption { + type = lib.types.strMatching "^(tcp|unix)://.*$"; example = "tcp://0.0.0.0:10300"; description = '' URI to bind the wyoming server to. ''; }; - device = mkOption { + device = lib.mkOption { # https://opennmt.net/CTranslate2/python/ctranslate2.models.Whisper.html# - type = types.enum [ + type = lib.types.enum [ "cpu" "cuda" "auto" @@ -70,8 +62,8 @@ in ''; }; - language = mkOption { - type = enum [ + language = lib.mkOption { + type = lib.types.enum [ # https://github.com/home-assistant/addons/blob/master/whisper/config.yaml#L20 "auto" "af" @@ -180,8 +172,8 @@ in ''; }; - beamSize = mkOption { - type = ints.unsigned; + beamSize = lib.mkOption { + type = lib.types.ints.unsigned; default = 1; example = 5; description = '' @@ -190,13 +182,13 @@ in apply = toString; }; - extraArgs = mkOption { - type = listOf str; + extraArgs = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; description = '' Extra arguments to pass to the server commandline. ''; - apply = escapeShellArgs; + apply = lib.escapeShellArgs; }; }; } @@ -206,17 +198,10 @@ in }; config = - let - inherit (lib) - mapAttrs' - mkIf - nameValuePair - ; - in - mkIf (cfg.servers != { }) { - systemd.services = mapAttrs' ( + lib.mkIf (cfg.servers != { }) { + systemd.services = lib.mapAttrs' ( server: options: - nameValuePair "wyoming-faster-whisper-${server}" { + lib.nameValuePair "wyoming-faster-whisper-${server}" { inherit (options) enable; description = "Wyoming faster-whisper server instance ${server}"; wants = [ @@ -248,7 +233,7 @@ in CapabilityBoundingSet = ""; DeviceAllow = if - builtins.elem options.device [ + lib.elem options.device [ "cuda" "auto" ] diff --git a/nixos/modules/services/home-automation/wyoming/openwakeword.nix b/nixos/modules/services/home-automation/wyoming/openwakeword.nix index be6c2b74e1222..17c0ad4e369b1 100644 --- a/nixos/modules/services/home-automation/wyoming/openwakeword.nix +++ b/nixos/modules/services/home-automation/wyoming/openwakeword.nix @@ -8,18 +8,6 @@ let cfg = config.services.wyoming.openwakeword; - inherit (lib) - concatStringsSep - concatMapStringsSep - escapeShellArgs - mkOption - mkEnableOption - mkIf - mkPackageOption - mkRemovedOptionModule - types - ; - inherit (builtins) toString ; @@ -28,7 +16,7 @@ in { imports = [ - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "wyoming" "openwakeword" @@ -38,13 +26,13 @@ in meta.buildDocsInSandbox = false; - options.services.wyoming.openwakeword = with types; { - enable = mkEnableOption "Wyoming openWakeWord server"; + options.services.wyoming.openwakeword = { + enable = lib.mkEnableOption "Wyoming openWakeWord server"; - package = mkPackageOption pkgs "wyoming-openwakeword" { }; + package = lib.mkPackageOption pkgs "wyoming-openwakeword" { }; - uri = mkOption { - type = strMatching "^(tcp|unix)://.*$"; + uri = lib.mkOption { + type = lib.types.strMatching "^(tcp|unix)://.*$"; default = "tcp://0.0.0.0:10400"; example = "tcp://192.0.2.1:5000"; description = '' @@ -52,16 +40,16 @@ in ''; }; - customModelsDirectories = mkOption { - type = listOf types.path; + customModelsDirectories = lib.mkOption { + type = lib.types.listOf lib.types.types.path; default = [ ]; description = '' Paths to directories with custom wake word models (*.tflite model files). ''; }; - preloadModels = mkOption { - type = listOf str; + preloadModels = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ "ok_nabu" ]; @@ -78,8 +66,8 @@ in ''; }; - threshold = mkOption { - type = float; + threshold = lib.mkOption { + type = lib.types.float; default = 0.5; description = '' Activation threshold (0-1), where higher means fewer activations. @@ -90,8 +78,8 @@ in apply = toString; }; - triggerLevel = mkOption { - type = int; + triggerLevel = lib.mkOption { + type = lib.types.int; default = 1; description = '' Number of activations before a detection is registered. @@ -101,17 +89,17 @@ in apply = toString; }; - extraArgs = mkOption { - type = listOf str; + extraArgs = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; description = '' Extra arguments to pass to the server commandline. ''; - apply = escapeShellArgs; + apply = lib.escapeShellArgs; }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { systemd.services."wyoming-openwakeword" = { description = "Wyoming openWakeWord server"; wants = [ @@ -127,11 +115,11 @@ in DynamicUser = true; User = "wyoming-openwakeword"; # https://github.com/home-assistant/addons/blob/master/openwakeword/rootfs/etc/s6-overlay/s6-rc.d/openwakeword/run - ExecStart = concatStringsSep " " [ + ExecStart = lib.concatStringsSep " " [ "${cfg.package}/bin/wyoming-openwakeword" "--uri ${cfg.uri}" - (concatMapStringsSep " " (model: "--preload-model ${model}") cfg.preloadModels) - (concatMapStringsSep " " (dir: "--custom-model-dir ${toString dir}") cfg.customModelsDirectories) + (lib.concatMapStringsSep " " (model: "--preload-model ${model}") cfg.preloadModels) + (lib.concatMapStringsSep " " (dir: "--custom-model-dir ${toString dir}") cfg.customModelsDirectories) "--threshold ${cfg.threshold}" "--trigger-level ${cfg.triggerLevel}" "${cfg.extraArgs}" diff --git a/nixos/modules/services/home-automation/wyoming/piper.nix b/nixos/modules/services/home-automation/wyoming/piper.nix index 0f3af57e3aea8..656a22192c2c5 100644 --- a/nixos/modules/services/home-automation/wyoming/piper.nix +++ b/nixos/modules/services/home-automation/wyoming/piper.nix @@ -8,14 +8,6 @@ let cfg = config.services.wyoming.piper; - inherit (lib) - escapeShellArgs - mkOption - mkEnableOption - mkPackageOption - types - ; - inherit (builtins) toString ; @@ -25,25 +17,25 @@ in { meta.buildDocsInSandbox = false; - options.services.wyoming.piper = with types; { - package = mkPackageOption pkgs "wyoming-piper" { }; + options.services.wyoming.piper = { + package = lib.mkPackageOption pkgs "wyoming-piper" { }; - servers = mkOption { + servers = lib.mkOption { default = { }; description = '' Attribute set of piper instances to spawn. ''; - type = types.attrsOf ( - types.submodule ( + type = lib.types.attrsOf ( + lib.types.submodule ( { ... }: { options = { - enable = mkEnableOption "Wyoming Piper server"; + enable = lib.mkEnableOption "Wyoming Piper server"; - piper = mkPackageOption pkgs "piper-tts" { }; + piper = lib.mkPackageOption pkgs "piper-tts" { }; - voice = mkOption { - type = str; + voice = lib.mkOption { + type = lib.types.str; example = "en-us-ryan-medium"; description = '' Name of the voice model to use. See the following website for samples: @@ -51,16 +43,16 @@ in ''; }; - uri = mkOption { - type = strMatching "^(tcp|unix)://.*$"; + uri = lib.mkOption { + type = lib.types.strMatching "^(tcp|unix)://.*$"; example = "tcp://0.0.0.0:10200"; description = '' URI to bind the wyoming server to. ''; }; - speaker = mkOption { - type = ints.unsigned; + speaker = lib.mkOption { + type = lib.types.ints.unsigned; default = 0; description = '' ID of a specific speaker in a multi-speaker model. @@ -68,8 +60,8 @@ in apply = toString; }; - noiseScale = mkOption { - type = float; + noiseScale = lib.mkOption { + type = lib.types.float; default = 0.667; description = '' Generator noise value. @@ -77,8 +69,8 @@ in apply = toString; }; - noiseWidth = mkOption { - type = float; + noiseWidth = lib.mkOption { + type = lib.types.float; default = 0.333; description = '' Phoneme width noise value. @@ -86,8 +78,8 @@ in apply = toString; }; - lengthScale = mkOption { - type = float; + lengthScale = lib.mkOption { + type = lib.types.float; default = 1.0; description = '' Phoneme length value. @@ -95,13 +87,13 @@ in apply = toString; }; - extraArgs = mkOption { - type = listOf str; + extraArgs = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; description = '' Extra arguments to pass to the server commandline. ''; - apply = escapeShellArgs; + apply = lib.escapeShellArgs; }; }; } @@ -111,17 +103,10 @@ in }; config = - let - inherit (lib) - mapAttrs' - mkIf - nameValuePair - ; - in - mkIf (cfg.servers != { }) { - systemd.services = mapAttrs' ( + lib.mkIf (cfg.servers != { }) { + systemd.services = lib.mapAttrs' ( server: options: - nameValuePair "wyoming-piper-${server}" { + lib.nameValuePair "wyoming-piper-${server}" { inherit (options) enable; description = "Wyoming Piper server instance ${server}"; wants = [ diff --git a/nixos/modules/services/home-automation/wyoming/satellite.nix b/nixos/modules/services/home-automation/wyoming/satellite.nix index b0064569cc325..3e8dd5e77c017 100644 --- a/nixos/modules/services/home-automation/wyoming/satellite.nix +++ b/nixos/modules/services/home-automation/wyoming/satellite.nix @@ -8,66 +8,52 @@ let cfg = config.services.wyoming.satellite; - inherit (lib) - elem - escapeShellArgs - getExe - literalExpression - mkOption - mkEnableOption - mkIf - mkPackageOption - optional - optionals - types - ; - finalPackage = cfg.package.overridePythonAttrs (oldAttrs: { propagatedBuildInputs = oldAttrs.propagatedBuildInputs # for audio enhancements like auto-gain, noise suppression ++ cfg.package.optional-dependencies.webrtc - # vad is currently optional, because it is broken on aarch64-linux - ++ optionals cfg.vad.enable cfg.package.optional-dependencies.silerovad; + # vad is currently lib.optional, because it is broken on aarch64-linux + ++ lib.optionals cfg.vad.enable cfg.package.optional-dependencies.silerovad; }); in { meta.buildDocsInSandbox = false; - options.services.wyoming.satellite = with types; { - enable = mkEnableOption "Wyoming Satellite"; + options.services.wyoming.satellite = { + enable = lib.mkEnableOption "Wyoming Satellite"; - package = mkPackageOption pkgs "wyoming-satellite" { }; + package = lib.mkPackageOption pkgs "wyoming-satellite" { }; - user = mkOption { - type = str; + user = lib.mkOption { + type = lib.types.str; example = "alice"; description = '' User to run wyoming-satellite under. ''; }; - group = mkOption { - type = str; + group = lib.mkOption { + type = lib.types.str; default = "users"; description = '' Group to run wyoming-satellite under. ''; }; - uri = mkOption { - type = str; + uri = lib.mkOption { + type = lib.types.str; default = "tcp://0.0.0.0:10700"; description = '' URI where wyoming-satellite will bind its socket. ''; }; - name = mkOption { - type = str; + name = lib.mkOption { + type = lib.types.str; default = config.networking.hostName; - defaultText = literalExpression '' + defaultText = lib.literalExpression '' config.networking.hostName ''; description = '' @@ -75,8 +61,8 @@ in ''; }; - area = mkOption { - type = nullOr str; + area = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; example = "Kitchen"; description = '' @@ -85,16 +71,16 @@ in }; microphone = { - command = mkOption { - type = str; + command = lib.mkOption { + type = lib.types.str; default = "arecord -r 16000 -c 1 -f S16_LE -t raw"; description = '' Program to run for audio input. ''; }; - autoGain = mkOption { - type = ints.between 0 31; + autoGain = lib.mkOption { + type = lib.types.ints.between 0 31; default = 5; example = 15; description = '' @@ -102,8 +88,8 @@ in ''; }; - noiseSuppression = mkOption { - type = ints.between 0 4; + noiseSuppression = lib.mkOption { + type = lib.types.ints.between 0 4; default = 2; example = 3; description = '' @@ -114,8 +100,8 @@ in }; sound = { - command = mkOption { - type = nullOr str; + command = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = "aplay -r 22050 -c 1 -f S16_LE -t raw"; description = '' Program to run for sound output. @@ -124,16 +110,16 @@ in }; sounds = { - awake = mkOption { - type = nullOr path; + awake = lib.mkOption { + type = lib.types.nullOr lib.types.path; default = null; description = '' Path to audio file in WAV format to play when wake word is detected. ''; }; - done = mkOption { - type = nullOr path; + done = lib.mkOption { + type = lib.types.nullOr lib.types.path; default = null; description = '' Path to audio file in WAV format to play when voice command recording has ended. @@ -142,8 +128,8 @@ in }; vad = { - enable = mkOption { - type = bool; + enable = lib.mkOption { + type = lib.types.bool; default = true; description = '' Whether to enable voice activity detection. @@ -154,8 +140,8 @@ in }; }; - extraArgs = mkOption { - type = listOf str; + extraArgs = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; description = '' Extra arguments to pass to the executable. @@ -165,7 +151,7 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { systemd.services."wyoming-satellite" = { description = "Wyoming Satellite"; after = [ @@ -184,11 +170,11 @@ in ]; script = let - optionalParam = + lib.optionalParam = param: argument: - optionals + lib.optionals ( - !elem argument [ + !lib.elem argument [ null 0 false @@ -201,9 +187,9 @@ in in '' export XDG_RUNTIME_DIR=/run/user/$UID - ${escapeShellArgs ( + ${lib.escapeShellArgs ( [ - (getExe finalPackage) + (lib.getExe finalPackage) "--uri" cfg.uri "--name" @@ -211,13 +197,13 @@ in "--mic-command" cfg.microphone.command ] - ++ optionalParam "--mic-auto-gain" cfg.microphone.autoGain - ++ optionalParam "--mic-noise-suppression" cfg.microphone.noiseSuppression - ++ optionalParam "--area" cfg.area - ++ optionalParam "--snd-command" cfg.sound.command - ++ optionalParam "--awake-wav" cfg.sounds.awake - ++ optionalParam "--done-wav" cfg.sounds.done - ++ optional cfg.vad.enable "--vad" + ++ lib.optionalParam "--mic-auto-gain" cfg.microphone.autoGain + ++ lib.optionalParam "--mic-noise-suppression" cfg.microphone.noiseSuppression + ++ lib.optionalParam "--area" cfg.area + ++ lib.optionalParam "--snd-command" cfg.sound.command + ++ lib.optionalParam "--awake-wav" cfg.sounds.awake + ++ lib.optionalParam "--done-wav" cfg.sounds.done + ++ lib.optional cfg.vad.enable "--vad" ++ cfg.extraArgs )} ''; diff --git a/nixos/modules/services/logging/filebeat.nix b/nixos/modules/services/logging/filebeat.nix index 53a00be860d7e..90ba8becc13ec 100644 --- a/nixos/modules/services/logging/filebeat.nix +++ b/nixos/modules/services/logging/filebeat.nix @@ -7,16 +7,6 @@ }: let - inherit (lib) - attrValues - literalExpression - mkEnableOption - mkPackageOption - mkIf - mkOption - types - ; - cfg = config.services.filebeat; json = pkgs.formats.json { }; @@ -26,13 +16,13 @@ in services.filebeat = { - enable = mkEnableOption "filebeat"; + enable = lib.mkEnableOption "filebeat"; - package = mkPackageOption pkgs "filebeat" { + package = lib.mkPackageOption pkgs "filebeat" { example = "filebeat7"; }; - inputs = mkOption { + inputs = lib.mkOption { description = '' Inputs specify how Filebeat locates and processes input data. @@ -49,14 +39,14 @@ in See . ''; default = { }; - type = types.attrsOf ( - types.submodule ( + type = lib.types.attrsOf ( + lib.types.submodule ( { name, ... }: { freeformType = json.type; options = { - type = mkOption { - type = types.str; + type = lib.mkOption { + type = lib.types.str; default = name; description = '' The input type. @@ -70,7 +60,7 @@ in } ) ); - example = literalExpression '' + example = lib.literalExpression '' { journald.id = "everything"; # Only for filebeat7 log = { @@ -83,7 +73,7 @@ in ''; }; - modules = mkOption { + modules = lib.mkOption { description = '' Filebeat modules provide a quick way to get started processing common log formats. They contain default @@ -104,14 +94,14 @@ in See . ''; default = { }; - type = types.attrsOf ( - types.submodule ( + type = lib.types.attrsOf ( + lib.types.submodule ( { name, ... }: { freeformType = json.type; options = { - module = mkOption { - type = types.str; + module = lib.mkOption { + type = lib.types.str; default = name; description = '' The name of the module. @@ -125,7 +115,7 @@ in } ) ); - example = literalExpression '' + example = lib.literalExpression '' { nginx = { access = { @@ -141,14 +131,14 @@ in ''; }; - settings = mkOption { - type = types.submodule { + settings = lib.mkOption { + type = lib.types.submodule { freeformType = json.type; options = { - output.elasticsearch.hosts = mkOption { - type = with types; listOf str; + output.elasticsearch.hosts = lib.mkOption { + type = with lib.types; listOf str; default = [ "127.0.0.1:9200" ]; example = [ "myEShost:9200" ]; description = '' @@ -167,8 +157,8 @@ in }; filebeat = { - inputs = mkOption { - type = types.listOf json.type; + inputs = lib.mkOption { + type = lib.types.listOf json.type; default = [ ]; internal = true; description = '' @@ -178,8 +168,8 @@ in See . ''; }; - modules = mkOption { - type = types.listOf json.type; + modules = lib.mkOption { + type = lib.types.listOf json.type; default = [ ]; internal = true; description = '' @@ -198,7 +188,7 @@ in }; }; default = { }; - example = literalExpression '' + example = lib.literalExpression '' { settings = { output.elasticsearch = { @@ -230,10 +220,10 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { - services.filebeat.settings.filebeat.inputs = attrValues cfg.inputs; - services.filebeat.settings.filebeat.modules = attrValues cfg.modules; + services.filebeat.settings.filebeat.inputs = lib.attrValues cfg.inputs; + services.filebeat.settings.filebeat.modules = lib.attrValues cfg.modules; systemd.services.filebeat = { description = "Filebeat log shipper"; diff --git a/nixos/modules/services/logging/journaldriver.nix b/nixos/modules/services/logging/journaldriver.nix index efb53de0b4842..f296bf1077362 100644 --- a/nixos/modules/services/logging/journaldriver.nix +++ b/nixos/modules/services/logging/journaldriver.nix @@ -16,14 +16,13 @@ ... }: -with lib; let cfg = config.services.journaldriver; in { options.services.journaldriver = { - enable = mkOption { - type = types.bool; + enable = lib.mkOption { + type = lib.types.bool; default = false; description = '' Whether to enable journaldriver to forward journald logs to @@ -31,16 +30,16 @@ in ''; }; - logLevel = mkOption { - type = types.str; + logLevel = lib.mkOption { + type = lib.types.str; default = "info"; description = '' Log level at which journaldriver logs its own output. ''; }; - logName = mkOption { - type = with types; nullOr str; + logName = lib.mkOption { + type = with lib.types; nullOr str; default = null; description = '' Configures the name of the target log in Stackdriver Logging. @@ -50,8 +49,8 @@ in ''; }; - googleCloudProject = mkOption { - type = with types; nullOr str; + googleCloudProject = lib.mkOption { + type = with lib.types; nullOr str; default = null; description = '' Configures the name of the Google Cloud project to which to @@ -62,8 +61,8 @@ in ''; }; - logStream = mkOption { - type = with types; nullOr str; + logStream = lib.mkOption { + type = with lib.types; nullOr str; default = null; description = '' Configures the name of the Stackdriver Logging log stream into @@ -74,8 +73,8 @@ in ''; }; - applicationCredentials = mkOption { - type = with types; nullOr path; + applicationCredentials = lib.mkOption { + type = with lib.types; nullOr path; default = null; description = '' Path to the service account private key (in JSON-format) used @@ -88,7 +87,7 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { systemd.services.journaldriver = { description = "Stackdriver Logging journal forwarder"; script = "${pkgs.journaldriver}/bin/journaldriver"; diff --git a/nixos/modules/services/logging/promtail.nix b/nixos/modules/services/logging/promtail.nix index d6038055c05c6..4efcef59d641b 100644 --- a/nixos/modules/services/logging/promtail.nix +++ b/nixos/modules/services/logging/promtail.nix @@ -1,4 +1,4 @@ -{ config, lib, pkgs, ... }: with lib; +{ config, lib, pkgs, ... }: let cfg = config.services.promtail; @@ -16,10 +16,10 @@ let else prettyJSON cfg.configuration; in { - options.services.promtail = with types; { - enable = mkEnableOption "the Promtail ingresser"; + options.services.promtail = { + enable = lib.mkEnableOption "the Promtail ingresser"; - configuration = mkOption { + configuration = lib.mkOption { type = (pkgs.formats.json {}).type; description = '' Specify the configuration for Promtail in Nix. @@ -27,8 +27,8 @@ in { ''; }; - configFile = mkOption { - type = nullOr path; + configFile = lib.mkOption { + type = lib.types.nullOr lib.types.path; default = null; description = '' Config file path for Promtail. @@ -36,8 +36,8 @@ in { ''; }; - extraFlags = mkOption { - type = listOf str; + extraFlags = lib.mkOption { + type = lib.types.listOf lib.types.str; default = []; example = [ "--server.http-listen-port=3101" ]; description = '' @@ -47,8 +47,8 @@ in { }; }; - config = mkIf cfg.enable { - services.promtail.configuration.positions.filename = mkDefault "/var/cache/promtail/positions.yaml"; + config = lib.mkIf cfg.enable { + services.promtail.configuration.positions.filename = lib.mkDefault "/var/cache/promtail/positions.yaml"; systemd.services.promtail = { description = "Promtail log ingress"; @@ -63,7 +63,7 @@ in { Restart = "on-failure"; TimeoutStopSec = 10; - ExecStart = "${pkgs.promtail}/bin/promtail -config.file=${configFile} ${escapeShellArgs cfg.extraFlags}"; + ExecStart = "${pkgs.promtail}/bin/promtail -config.file=${configFile} ${lib.escapeShellArgs cfg.extraFlags}"; ProtectSystem = "strict"; ProtectHome = true; @@ -94,7 +94,7 @@ in { PrivateUsers = true; SupplementaryGroups = lib.optional (allowSystemdJournal) "systemd-journal"; - } // (optionalAttrs (!pkgs.stdenv.hostPlatform.isAarch64) { # FIXME: figure out why this breaks on aarch64 + } // (lib.optionalAttrs (!pkgs.stdenv.hostPlatform.isAarch64) { # FIXME: figure out why this breaks on aarch64 SystemCallFilter = "@system-service"; }); }; diff --git a/nixos/modules/services/mail/cyrus-imap.nix b/nixos/modules/services/mail/cyrus-imap.nix index f5ace168b045f..fb5ccb76426ef 100644 --- a/nixos/modules/services/mail/cyrus-imap.nix +++ b/nixos/modules/services/mail/cyrus-imap.nix @@ -7,46 +7,25 @@ let cfg = config.services.cyrus-imap; cyrus-imapdPkg = pkgs.cyrus-imapd; - inherit (lib) - mkEnableOption - mkIf - mkOption - optionalAttrs - optionalString - generators - mapAttrsToList - ; - inherit (lib.strings) concatStringsSep; - inherit (lib.types) - attrsOf - submodule - listOf - oneOf - str - int - bool - nullOr - path - ; mkCyrusConfig = settings: let mkCyrusOptionsList = v: - mapAttrsToList ( + lib.mapAttrsToList ( p: q: if (q != null) then if builtins.isInt q then "${p}=${builtins.toString q}" else - "${p}=\"${if builtins.isList q then (concatStringsSep " " q) else q}\"" + "${p}=\"${if builtins.isList q then (lib.concatStringsSep " " q) else q}\"" else "" ) v; - mkCyrusOptionsString = v: concatStringsSep " " (mkCyrusOptionsList v); + mkCyrusOptionsString = v: lib.concatStringsSep " " (mkCyrusOptionsList v); in - concatStringsSep "\n " (mapAttrsToList (n: v: n + " " + (mkCyrusOptionsString v)) settings); + lib.concatStringsSep "\n " (lib.mapAttrsToList (n: v: n + " " + (mkCyrusOptionsString v)) settings); cyrusConfig = lib.concatStringsSep "\n" ( lib.mapAttrsToList (n: v: '' @@ -57,52 +36,51 @@ let ); imapdConfig = - with generators; - toKeyValue { - mkKeyValue = mkKeyValueDefault { + lib.generators.toKeyValue { + mkKeyValue = lib.generators.mkKeyValueDefault { mkValueString = v: if builtins.isBool v then if v then "yes" else "no" else if builtins.isList v then - concatStringsSep " " v + lib.concatStringsSep " " v else - mkValueStringDefault { } v; + lib.generators.mkValueStringDefault { } v; } ": "; } cfg.imapdSettings; in { options.services.cyrus-imap = { - enable = mkEnableOption "Cyrus IMAP, an email, contacts and calendar server"; - debug = mkEnableOption "debugging messages for the Cyrus master process"; + enable = lib.mkEnableOption "Cyrus IMAP, an email, contacts and calendar server"; + debug = lib.mkEnableOption "debugging messages for the Cyrus master process"; - listenQueue = mkOption { - type = int; + listenQueue = lib.mkOption { + type = lib.types.int; default = 32; description = '' Socket listen queue backlog size. See listen(2) for more information about a backlog. Default is 32, which may be increased if you have a very high connection rate. ''; }; - tmpDBDir = mkOption { - type = path; + tmpDBDir = lib.mkOption { + type = lib.types.path; default = "/run/cyrus/db"; description = '' Location where DB files are stored. Databases in this directory are recreated upon startup, so ideally they should live in ephemeral storage for best performance. ''; }; - cyrusSettings = mkOption { - type = submodule { - freeformType = attrsOf ( - attrsOf (oneOf [ - bool - int - (listOf str) + cyrusSettings = lib.mkOption { + type = lib.types.submodule { + freeformType = lib.types.attrsOf ( + lib.types.attrsOf (lib.types.oneOf [ + lib.types.bool + lib.types.int + (lib.types.listOf lib.types.str) ]) ); options = { - START = mkOption { + START = lib.mkOption { default = { recover = { cmd = [ @@ -117,7 +95,7 @@ in Master itself will not startup until all tasks in START have completed, so put no blocking commands here. ''; }; - SERVICES = mkOption { + SERVICES = lib.mkOption { default = { imap = { cmd = [ "imapd" ]; @@ -145,7 +123,7 @@ in This section is the heart of the cyrus.conf file. It lists the processes that should be spawned to handle client connections made on certain Internet/UNIX sockets. ''; }; - EVENTS = mkOption { + EVENTS = lib.mkOption { default = { tlsprune = { cmd = [ "tls_prune" ]; @@ -191,7 +169,7 @@ in This section lists processes that should be run at specific intervals, similar to cron jobs. This section is typically used to perform scheduled cleanup/maintenance. ''; }; - DAEMON = mkOption { + DAEMON = lib.mkOption { default = { }; description = '' This section lists long running daemons to start before any SERVICES are spawned. master(8) will ensure that these processes are running, restarting any process which dies or forks. All listed processes will be shutdown when master(8) is exiting. @@ -201,38 +179,38 @@ in }; description = "Cyrus configuration settings. See [cyrus.conf(5)](https://www.cyrusimap.org/imap/reference/manpages/configs/cyrus.conf.html)"; }; - imapdSettings = mkOption { - type = submodule { - freeformType = attrsOf (oneOf [ - str - int - bool - (listOf str) + imapdSettings = lib.mkOption { + type = lib.types.submodule { + freeformType = lib.types.attrsOf (lib.types.oneOf [ + lib.types.str + lib.types.int + lib.types.bool + (lib.types.listOf lib.types.str) ]); options = { - configdirectory = mkOption { - type = path; + configdirectory = lib.mkOption { + type = lib.types.path; default = "/var/lib/cyrus"; description = '' The pathname of the IMAP configuration directory. ''; }; - lmtpsocket = mkOption { - type = path; + lmtpsocket = lib.mkOption { + type = lib.types.path; default = "/run/cyrus/lmtp"; description = '' Unix socket that lmtpd listens on, used by deliver(8). This should match the path specified in cyrus.conf(5). ''; }; - idlesocket = mkOption { - type = path; + idlesocket = lib.mkOption { + type = lib.types.path; default = "/run/cyrus/idle"; description = '' Unix socket that idled listens on. ''; }; - notifysocket = mkOption { - type = path; + notifysocket = lib.mkOption { + type = lib.types.path; default = "/run/cyrus/notify"; description = '' Unix domain socket that the mail notification daemon listens on. @@ -269,59 +247,59 @@ in description = "IMAP configuration settings. See [imapd.conf(5)](https://www.cyrusimap.org/imap/reference/manpages/configs/imapd.conf.html)"; }; - user = mkOption { - type = nullOr str; + user = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; description = "Cyrus IMAP user name. If this is not set, a user named `cyrus` will be created."; }; - group = mkOption { - type = nullOr str; + group = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; description = "Cyrus IMAP group name. If this is not set, a group named `cyrus` will be created."; }; - imapdConfigFile = mkOption { - type = nullOr path; + imapdConfigFile = lib.mkOption { + type = lib.types.nullOr lib.types.path; default = null; description = "Path to the configuration file used for cyrus-imap."; apply = v: if v != null then v else pkgs.writeText "imapd.conf" imapdConfig; }; - cyrusConfigFile = mkOption { - type = nullOr path; + cyrusConfigFile = lib.mkOption { + type = lib.types.nullOr lib.types.path; default = null; description = "Path to the configuration file used for Cyrus."; apply = v: if v != null then v else pkgs.writeText "cyrus.conf" cyrusConfig; }; - sslCACert = mkOption { - type = nullOr str; + sslCACert = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; description = "File path which containing one or more CA certificates to use."; }; - sslServerCert = mkOption { - type = nullOr str; + sslServerCert = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; description = "File containing the global certificate used for all services (IMAP, POP3, LMTP, Sieve)"; }; - sslServerKey = mkOption { - type = nullOr str; + sslServerKey = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; description = "File containing the private key belonging to the global server certificate."; }; }; - config = mkIf cfg.enable { - users.users.cyrus = optionalAttrs (cfg.user == null) { + config = lib.mkIf cfg.enable { + users.users.cyrus = lib.optionalAttrs (cfg.user == null) { description = "Cyrus IMAP user"; isSystemUser = true; - group = optionalString (cfg.group == null) "cyrus"; + group = lib.optionalString (cfg.group == null) "cyrus"; }; - users.groups.cyrus = optionalAttrs (cfg.group == null) { }; + users.groups.cyrus = lib.optionalAttrs (cfg.group == null) { }; environment.etc."imapd.conf".source = cfg.imapdConfigFile; environment.etc."cyrus.conf".source = cfg.cyrusConfigFile; @@ -338,7 +316,7 @@ in startLimitIntervalSec = 60; environment = { - CYRUS_VERBOSE = mkIf cfg.debug "1"; + CYRUS_VERBOSE = lib.mkIf cfg.debug "1"; LISTENQUEUE = builtins.toString cfg.listenQueue; }; serviceConfig = { diff --git a/nixos/modules/services/mail/dovecot.nix b/nixos/modules/services/mail/dovecot.nix index 4388be30a9350..4d93fe92cfe79 100644 --- a/nixos/modules/services/mail/dovecot.nix +++ b/nixos/modules/services/mail/dovecot.nix @@ -6,62 +6,36 @@ }: let - inherit (lib) - attrValues - concatMapStringsSep - concatStrings - concatStringsSep - flatten - imap1 - literalExpression - mapAttrsToList - mkEnableOption - mkIf - mkOption - mkRemovedOptionModule - optional - optionalAttrs - optionalString - singleton - types - mkRenamedOptionModule - nameValuePair - mapAttrs' - listToAttrs - filter - ; - inherit (lib.strings) match; - cfg = config.services.dovecot2; dovecotPkg = pkgs.dovecot; baseDir = "/run/dovecot2"; stateDir = "/var/lib/dovecot"; - sieveScriptSettings = mapAttrs' ( - to: _: nameValuePair "sieve_${to}" "${stateDir}/sieve/${to}" + sieveScriptSettings = lib.mapAttrs' ( + to: _: lib.nameValuePair "sieve_${to}" "${stateDir}/sieve/${to}" ) cfg.sieve.scripts; - imapSieveMailboxSettings = listToAttrs ( - flatten ( - imap1 ( + imapSieveMailboxSettings = lib.listToAttrs ( + lib.flatten ( + lib.imap1 ( idx: el: - singleton { + lib.singleton { name = "imapsieve_mailbox${toString idx}_name"; value = el.name; } - ++ optional (el.from != null) { + ++ lib.optional (el.from != null) { name = "imapsieve_mailbox${toString idx}_from"; value = el.from; } - ++ optional (el.causes != [ ]) { + ++ lib.optional (el.causes != [ ]) { name = "imapsieve_mailbox${toString idx}_causes"; - value = concatStringsSep "," el.causes; + value = lib.concatStringsSep "," el.causes; } - ++ optional (el.before != null) { + ++ lib.optional (el.before != null) { name = "imapsieve_mailbox${toString idx}_before"; value = "file:${stateDir}/imapsieve/before/${baseNameOf el.before}"; } - ++ optional (el.after != null) { + ++ lib.optional (el.after != null) { name = "imapsieve_mailbox${toString idx}_after"; value = "file:${stateDir}/imapsieve/after/${baseNameOf el.after}"; } @@ -93,10 +67,10 @@ let # The idea is to match everything that looks like `$term =` # but not `# $term something something` # or `# $term = some value` because those are comments. - configContainsSetting = lines: term: (match "^[^#]*\b${term}\b.*=" lines) != null; + configContainsSetting = lines: term: (lib.match "^[^#]*\b${term}\b.*=" lines) != null; warnAboutExtraConfigCollisions = map mkExtraConfigCollisionWarning ( - filter (configContainsSetting cfg.extraConfig) automaticallySetPluginSettings + lib.filter (configContainsSetting cfg.extraConfig) automaticallySetPluginSettings ); sievePipeBinScriptDirectory = pkgs.linkFarm "sieve-pipe-bins" ( @@ -106,19 +80,19 @@ let }) cfg.sieve.pipeBins ); - dovecotConf = concatStrings [ + dovecotConf = lib.concatStrings [ '' base_dir = ${baseDir} - protocols = ${concatStringsSep " " cfg.protocols} + protocols = ${lib.concatStringsSep " " cfg.protocols} sendmail_path = /run/wrappers/bin/sendmail # defining mail_plugins must be done before the first protocol {} filter because of https://doc.dovecot.org/configuration_manual/config_file/config_file_syntax/#variable-expansion - mail_plugins = $mail_plugins ${concatStringsSep " " cfg.mailPlugins.globally.enable} + mail_plugins = $mail_plugins ${lib.concatStringsSep " " cfg.mailPlugins.globally.enable} '' - (concatStringsSep "\n" ( - mapAttrsToList (protocol: plugins: '' + (lib.concatStringsSep "\n" ( + lib.mapAttrsToList (protocol: plugins: '' protocol ${protocol} { - mail_plugins = $mail_plugins ${concatStringsSep " " plugins.enable} + mail_plugins = $mail_plugins ${lib.concatStringsSep " " plugins.enable} } '') cfg.mailPlugins.perProtocol )) @@ -133,8 +107,8 @@ let '' ssl_cert = <${cfg.sslServerCert} ssl_key = <${cfg.sslServerKey} - ${optionalString (cfg.sslCACert != null) ("ssl_ca = <" + cfg.sslCACert)} - ${optionalString cfg.enableDHE ''ssl_dh = <${config.security.dhparams.params.dovecot2.path}''} + ${lib.optionalString (cfg.sslCACert != null) ("ssl_ca = <" + cfg.sslCACert)} + ${lib.optionalString cfg.enableDHE ''ssl_dh = <${config.security.dhparams.params.dovecot2.path}''} disable_plaintext_auth = yes '' ) @@ -142,8 +116,8 @@ let '' default_internal_user = ${cfg.user} default_internal_group = ${cfg.group} - ${optionalString (cfg.mailUser != null) "mail_uid = ${cfg.mailUser}"} - ${optionalString (cfg.mailGroup != null) "mail_gid = ${cfg.mailGroup}"} + ${lib.optionalString (cfg.mailUser != null) "mail_uid = ${cfg.mailUser}"} + ${lib.optionalString (cfg.mailGroup != null) "mail_gid = ${cfg.mailGroup}"} mail_location = ${cfg.mailLocation} @@ -157,25 +131,25 @@ let } '' - (optionalString cfg.enablePAM '' + (lib.optionalString cfg.enablePAM '' userdb { driver = passwd } passdb { driver = pam - args = ${optionalString cfg.showPAMFailure "failure_show_msg=yes"} dovecot2 + args = ${lib.optionalString cfg.showPAMFailure "failure_show_msg=yes"} dovecot2 } '') - (optionalString (cfg.mailboxes != { }) '' + (lib.optionalString (cfg.mailboxes != { }) '' namespace inbox { inbox=yes - ${concatStringsSep "\n" (map mailboxConfig (attrValues cfg.mailboxes))} + ${lib.concatStringsSep "\n" (map mailboxConfig (lib.attrValues cfg.mailboxes))} } '') - (optionalString cfg.enableQuota '' + (lib.optionalString cfg.enableQuota '' service quota-status { executable = ${dovecotPkg}/libexec/dovecot/quota-status -p postfix inet_listener { @@ -200,7 +174,7 @@ let # the control flow. '' plugin { - ${concatStringsSep "\n" (mapAttrsToList (key: value: " ${key} = ${value}") cfg.pluginSettings)} + ${lib.concatStringsSep "\n" (lib.mapAttrsToList (key: value: " ${key} = ${value}") cfg.pluginSettings)} } '' @@ -220,10 +194,10 @@ let mailbox "${mailbox.name}" { auto = ${toString mailbox.auto} '' - + optionalString (mailbox.autoexpunge != null) '' + + lib.optionalString (mailbox.autoexpunge != null) '' autoexpunge = ${mailbox.autoexpunge} '' - + optionalString (mailbox.specialUse != null) '' + + lib.optionalString (mailbox.specialUse != null) '' special_use = \${toString mailbox.specialUse} '' + "}"; @@ -232,15 +206,15 @@ let { name, ... }: { options = { - name = mkOption { - type = types.strMatching ''[^"]+''; + name = lib.mkOption { + type = lib.types.strMatching ''[^"]+''; example = "Spam"; default = name; readOnly = true; description = "The name of the mailbox."; }; - auto = mkOption { - type = types.enum [ + auto = lib.mkOption { + type = lib.types.enum [ "no" "create" "subscribe" @@ -249,9 +223,9 @@ let example = "subscribe"; description = "Whether to automatically create or create and subscribe to the mailbox or not."; }; - specialUse = mkOption { - type = types.nullOr ( - types.enum [ + specialUse = lib.mkOption { + type = lib.types.nullOr ( + lib.types.enum [ "All" "Archive" "Drafts" @@ -265,8 +239,8 @@ let example = "Junk"; description = "Null if no special use flag is set. Other than that every use flag mentioned in the RFC is valid."; }; - autoexpunge = mkOption { - type = types.nullOr types.str; + autoexpunge = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; example = "60d"; description = '' @@ -279,44 +253,44 @@ let in { imports = [ - (mkRemovedOptionModule [ "services" "dovecot2" "package" ] "") - (mkRenamedOptionModule + (lib.mkRemovedOptionModule [ "services" "dovecot2" "package" ] "") + (lib.mkRenamedOptionModule [ "services" "dovecot2" "sieveScripts" ] [ "services" "dovecot2" "sieve" "scripts" ] ) ]; options.services.dovecot2 = { - enable = mkEnableOption "the dovecot 2.x POP3/IMAP server"; + enable = lib.mkEnableOption "the dovecot 2.x POP3/IMAP server"; - enablePop3 = mkEnableOption "starting the POP3 listener (when Dovecot is enabled)"; + enablePop3 = lib.mkEnableOption "starting the POP3 listener (when Dovecot is enabled)"; - enableImap = mkEnableOption "starting the IMAP listener (when Dovecot is enabled)" // { + enableImap = lib.mkEnableOption "starting the IMAP listener (when Dovecot is enabled)" // { default = true; }; - enableLmtp = mkEnableOption "starting the LMTP listener (when Dovecot is enabled)"; + enableLmtp = lib.mkEnableOption "starting the LMTP listener (when Dovecot is enabled)"; - protocols = mkOption { - type = types.listOf types.str; + protocols = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; description = "Additional listeners to start when Dovecot is enabled."; }; - user = mkOption { - type = types.str; + user = lib.mkOption { + type = lib.types.str; default = "dovecot2"; description = "Dovecot user name."; }; - group = mkOption { - type = types.str; + group = lib.mkOption { + type = lib.types.str; default = "dovecot2"; description = "Dovecot group name."; }; - extraConfig = mkOption { - type = types.lines; + extraConfig = lib.mkOption { + type = lib.types.lines; default = ""; example = "mail_debug = yes"; description = "Additional entries to put verbatim into Dovecot's config file."; @@ -326,22 +300,21 @@ in let plugins = hint: - types.submodule { + lib.types.submodule { options = { - enable = mkOption { - type = types.listOf types.str; + enable = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; description = "mail plugins to enable as a list of strings to append to the ${hint} `$mail_plugins` configuration variable"; }; }; }; in - mkOption { + lib.mkOption { type = - with types; - submodule { + lib.types.submodule { options = { - globally = mkOption { + globally = lib.mkOption { description = "Additional entries to add to the mail_plugins variable for all protocols"; type = plugins "top-level"; example = { @@ -351,9 +324,9 @@ in enable = [ ]; }; }; - perProtocol = mkOption { + perProtocol = lib.mkOption { description = "Additional entries to add to the mail_plugins variable, per protocol"; - type = attrsOf (plugins "corresponding per-protocol"); + type = lib.types.attrsOf (plugins "corresponding per-protocol"); default = { }; example = { imap = [ "imap_acl" ]; @@ -372,15 +345,15 @@ in }; }; - configFile = mkOption { - type = types.nullOr types.path; + configFile = lib.mkOption { + type = lib.types.nullOr lib.types.path; default = null; description = "Config file used for the whole dovecot configuration."; apply = v: if v != null then v else pkgs.writeText "dovecot.conf" dovecotConf; }; - mailLocation = mkOption { - type = types.str; + mailLocation = lib.mkOption { + type = lib.types.str; default = "maildir:/var/spool/mail/%u"; # Same as inbox, as postfix example = "maildir:~/mail:INBOX=/var/spool/mail/%u"; description = '' @@ -388,20 +361,20 @@ in ''; }; - mailUser = mkOption { - type = types.nullOr types.str; + mailUser = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; description = "Default user to store mail for virtual users."; }; - mailGroup = mkOption { - type = types.nullOr types.str; + mailGroup = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; description = "Default group to store mail for virtual users."; }; createMailUser = - mkEnableOption '' + lib.mkEnableOption '' automatically creating the user given in {option}`services.dovecot.user` and the group given in {option}`services.dovecot.group`'' @@ -409,10 +382,10 @@ in default = true; }; - modules = mkOption { - type = types.listOf types.package; + modules = lib.mkOption { + type = lib.types.listOf lib.types.package; default = [ ]; - example = literalExpression "[ pkgs.dovecot_pigeonhole ]"; + example = lib.literalExpression "[ pkgs.dovecot_pigeonhole ]"; description = '' Symlinks the contents of lib/dovecot of every given package into /etc/dovecot/modules. This will make the given modules available @@ -420,48 +393,47 @@ in ''; }; - sslCACert = mkOption { - type = types.nullOr types.str; + sslCACert = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; description = "Path to the server's CA certificate key."; }; - sslServerCert = mkOption { - type = types.nullOr types.str; + sslServerCert = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; description = "Path to the server's public key."; }; - sslServerKey = mkOption { - type = types.nullOr types.str; + sslServerKey = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; description = "Path to the server's private key."; }; - enablePAM = mkEnableOption "creating a own Dovecot PAM service and configure PAM user logins" // { + enablePAM = lib.mkEnableOption "creating a own Dovecot PAM service and configure PAM user logins" // { default = true; }; - enableDHE = mkEnableOption "ssl_dh and generation of primes for the key exchange" // { + enableDHE = lib.mkEnableOption "ssl_dh and generation of primes for the key exchange" // { default = true; }; - showPAMFailure = mkEnableOption "showing the PAM failure message on authentication error (useful for OTPW)"; + showPAMFailure = lib.mkEnableOption "showing the PAM failure message on authentication error (useful for OTPW)"; - mailboxes = mkOption { + mailboxes = lib.mkOption { type = - with types; - coercedTo (listOf unspecified) ( + lib.types.coercedTo (lib.types.listOf lib.types.unspecified) ( list: - listToAttrs ( + lib.listToAttrs ( map (entry: { name = entry.name; value = removeAttrs entry [ "name" ]; }) list ) - ) (attrsOf (submodule mailboxes)); + ) (lib.attrsOf (lib.submodule mailboxes)); default = { }; - example = literalExpression '' + example = lib.literalExpression '' { Spam = { specialUse = "Junk"; auto = "create"; }; } @@ -469,33 +441,33 @@ in description = "Configure mailboxes and auto create or subscribe them."; }; - enableQuota = mkEnableOption "the dovecot quota service"; + enableQuota = lib.mkEnableOption "the dovecot quota service"; - quotaPort = mkOption { - type = types.str; + quotaPort = lib.mkOption { + type = lib.types.str; default = "12340"; description = '' The Port the dovecot quota service binds to. If using postfix, add check_policy_service inet:localhost:12340 to your smtpd_recipient_restrictions in your postfix config. ''; }; - quotaGlobalPerUser = mkOption { - type = types.str; + quotaGlobalPerUser = lib.mkOption { + type = lib.types.str; default = "100G"; example = "10G"; description = "Quota limit for the user in bytes. Supports suffixes b, k, M, G, T and %."; }; - pluginSettings = mkOption { + pluginSettings = lib.mkOption { # types.str does not coerce from packages, like `sievePipeBinScriptDirectory`. - type = types.attrsOf ( - types.oneOf [ - types.str - types.package + type = lib.types.attrsOf ( + lib.types.oneOf [ + lib.types.str + lib.types.package ] ); default = { }; - example = literalExpression '' + example = lib.literalExpression '' { sieve = "file:~/sieve;active=~/.dovecot.sieve"; } @@ -510,15 +482,15 @@ in ''; }; - imapsieve.mailbox = mkOption { + imapsieve.mailbox = lib.mkOption { default = [ ]; description = "Configure Sieve filtering rules on IMAP actions"; - type = types.listOf ( - types.submodule ( + type = lib.types.listOf ( + lib.types.submodule ( { config, ... }: { options = { - name = mkOption { + name = lib.mkOption { description = '' This setting configures the name of a mailbox for which administrator scripts are configured. @@ -527,10 +499,10 @@ in This setting supports wildcards with a syntax compatible with the IMAP LIST command, meaning that this setting can apply to multiple or even all ("*") mailboxes. ''; example = "Junk"; - type = types.str; + type = lib.types.str; }; - from = mkOption { + from = lib.mkOption { default = null; description = '' Only execute the administrator Sieve scripts for the mailbox configured with services.dovecot2.imapsieve.mailbox..name when the message originates from the indicated mailbox. @@ -538,10 +510,10 @@ in This setting supports wildcards with a syntax compatible with the IMAP LIST command, meaning that this setting can apply to multiple or even all ("*") mailboxes. ''; example = "*"; - type = types.nullOr types.str; + type = lib.types.nullOr lib.types.str; }; - causes = mkOption { + causes = lib.mkOption { default = [ ]; description = '' Only execute the administrator Sieve scripts for the mailbox configured with services.dovecot2.imapsieve.mailbox..name when one of the listed IMAPSIEVE causes apply. @@ -552,8 +524,8 @@ in "COPY" "APPEND" ]; - type = types.listOf ( - types.enum [ + type = lib.types.listOf ( + lib.types.enum [ "APPEND" "COPY" "FLAG" @@ -561,26 +533,26 @@ in ); }; - before = mkOption { + before = lib.mkOption { default = null; description = '' When an IMAP event of interest occurs, this sieve script is executed before any user script respectively. This setting each specify the location of a single sieve script. The semantics of this setting is similar to sieve_before: the specified scripts form a sequence together with the user script in which the next script is only executed when an (implicit) keep action is executed. ''; - example = literalExpression "./report-spam.sieve"; - type = types.nullOr types.path; + example = lib.literalExpression "./report-spam.sieve"; + type = lib.types.nullOr lib.types.path; }; - after = mkOption { + after = lib.mkOption { default = null; description = '' When an IMAP event of interest occurs, this sieve script is executed after any user script respectively. This setting each specify the location of a single sieve script. The semantics of this setting is similar to sieve_after: the specified scripts form a sequence together with the user script in which the next script is only executed when an (implicit) keep action is executed. ''; - example = literalExpression "./report-spam.sieve"; - type = types.nullOr types.path; + example = lib.literalExpression "./report-spam.sieve"; + type = lib.types.nullOr lib.types.path; }; }; } @@ -589,14 +561,14 @@ in }; sieve = { - plugins = mkOption { + plugins = lib.mkOption { default = [ ]; example = [ "sieve_extprograms" ]; description = "Sieve plugins to load"; - type = types.listOf types.str; + type = lib.types.listOf lib.types.str; }; - extensions = mkOption { + extensions = lib.mkOption { default = [ ]; description = "Sieve extensions for use in user scripts"; example = [ @@ -604,64 +576,64 @@ in "imapflags" "vnd.dovecot.filter" ]; - type = types.listOf types.str; + type = lib.types.listOf lib.types.str; }; - globalExtensions = mkOption { + globalExtensions = lib.mkOption { default = [ ]; example = [ "vnd.dovecot.environment" ]; description = "Sieve extensions for use in global scripts"; - type = types.listOf types.str; + type = lib.types.listOf lib.types.str; }; - scripts = mkOption { - type = types.attrsOf types.path; + scripts = lib.mkOption { + type = lib.types.attrsOf lib.types.path; default = { }; description = "Sieve scripts to be executed. Key is a sequence, e.g. 'before2', 'after' etc."; }; - pipeBins = mkOption { + pipeBins = lib.mkOption { default = [ ]; - example = literalExpression '' + example = lib.literalExpression '' map lib.getExe [ (pkgs.writeShellScriptBin "learn-ham.sh" "exec ''${pkgs.rspamd}/bin/rspamc learn_ham") (pkgs.writeShellScriptBin "learn-spam.sh" "exec ''${pkgs.rspamd}/bin/rspamc learn_spam") ] ''; description = "Programs available for use by the vnd.dovecot.pipe extension"; - type = types.listOf types.path; + type = lib.types.listOf lib.types.path; }; }; }; - config = mkIf cfg.enable { - security.pam.services.dovecot2 = mkIf cfg.enablePAM { }; + config = lib.mkIf cfg.enable { + security.pam.services.dovecot2 = lib.mkIf cfg.enablePAM { }; - security.dhparams = mkIf (cfg.sslServerCert != null && cfg.enableDHE) { + security.dhparams = lib.mkIf (cfg.sslServerCert != null && cfg.enableDHE) { enable = true; params.dovecot2 = { }; }; services.dovecot2 = { protocols = - optional cfg.enableImap "imap" ++ optional cfg.enablePop3 "pop3" ++ optional cfg.enableLmtp "lmtp"; + lib.optional cfg.enableImap "imap" ++ lib.optional cfg.enablePop3 "pop3" ++ lib.optional cfg.enableLmtp "lmtp"; - mailPlugins = mkIf cfg.enableQuota { + mailPlugins = lib.mkIf cfg.enableQuota { globally.enable = [ "quota" ]; perProtocol.imap.enable = [ "imap_quota" ]; }; sieve.plugins = - optional (cfg.imapsieve.mailbox != [ ]) "sieve_imapsieve" - ++ optional (cfg.sieve.pipeBins != [ ]) "sieve_extprograms"; + lib.optional (cfg.imapsieve.mailbox != [ ]) "sieve_imapsieve" + ++ lib.optional (cfg.sieve.pipeBins != [ ]) "sieve_extprograms"; - sieve.globalExtensions = optional (cfg.sieve.pipeBins != [ ]) "vnd.dovecot.pipe"; + sieve.globalExtensions = lib.optional (cfg.sieve.pipeBins != [ ]) "vnd.dovecot.pipe"; pluginSettings = lib.mapAttrs (n: lib.mkDefault) ( { - sieve_plugins = concatStringsSep " " cfg.sieve.plugins; - sieve_extensions = concatStringsSep " " (map (el: "+${el}") cfg.sieve.extensions); - sieve_global_extensions = concatStringsSep " " (map (el: "+${el}") cfg.sieve.globalExtensions); + sieve_plugins = lib.concatStringsSep " " cfg.sieve.plugins; + sieve_extensions = lib.concatStringsSep " " (map (el: "+${el}") cfg.sieve.extensions); + sieve_global_extensions = lib.concatStringsSep " " (map (el: "+${el}") cfg.sieve.globalExtensions); sieve_pipe_bin_dir = sievePipeBinScriptDirectory; } // sieveScriptSettings @@ -677,28 +649,28 @@ in group = "dovenull"; }; } - // optionalAttrs (cfg.user == "dovecot2") { + // lib.optionalAttrs (cfg.user == "dovecot2") { dovecot2 = { uid = config.ids.uids.dovecot2; description = "Dovecot user"; group = cfg.group; }; } - // optionalAttrs (cfg.createMailUser && cfg.mailUser != null) { + // lib.optionalAttrs (cfg.createMailUser && cfg.mailUser != null) { ${cfg.mailUser} = { description = "Virtual Mail User"; isSystemUser = true; - } // optionalAttrs (cfg.mailGroup != null) { group = cfg.mailGroup; }; + } // lib.optionalAttrs (cfg.mailGroup != null) { group = cfg.mailGroup; }; }; users.groups = { dovenull.gid = config.ids.gids.dovenull2; } - // optionalAttrs (cfg.group == "dovecot2") { + // lib.optionalAttrs (cfg.group == "dovecot2") { dovecot2.gid = config.ids.gids.dovecot2; } - // optionalAttrs (cfg.createMailUser && cfg.mailGroup != null) { + // lib.optionalAttrs (cfg.createMailUser && cfg.mailGroup != null) { ${cfg.mailGroup} = { }; }; @@ -732,10 +704,10 @@ in '' rm -rf ${stateDir}/sieve ${stateDir}/imapsieve '' - + optionalString (cfg.sieve.scripts != { }) '' + + lib.optionalString (cfg.sieve.scripts != { }) '' mkdir -p ${stateDir}/sieve - ${concatStringsSep "\n" ( - mapAttrsToList (to: from: '' + ${lib.concatStringsSep "\n" ( + lib.mapAttrsToList (to: from: '' if [ -d '${from}' ]; then mkdir '${stateDir}/sieve/${to}' cp -p "${from}/"*.sieve '${stateDir}/sieve/${to}' @@ -747,22 +719,22 @@ in )} chown -R '${cfg.mailUser}:${cfg.mailGroup}' '${stateDir}/sieve' '' - + optionalString (cfg.imapsieve.mailbox != [ ]) '' + + lib.optionalString (cfg.imapsieve.mailbox != [ ]) '' mkdir -p ${stateDir}/imapsieve/{before,after} - ${concatMapStringsSep "\n" ( + ${lib.concatMapStringsSep "\n" ( el: - optionalString (el.before != null) '' + lib.optionalString (el.before != null) '' cp -p ${el.before} ${stateDir}/imapsieve/before/${baseNameOf el.before} ${pkgs.dovecot_pigeonhole}/bin/sievec '${stateDir}/imapsieve/before/${baseNameOf el.before}' '' - + optionalString (el.after != null) '' + + lib.optionalString (el.after != null) '' cp -p ${el.after} ${stateDir}/imapsieve/after/${baseNameOf el.after} ${pkgs.dovecot_pigeonhole}/bin/sievec '${stateDir}/imapsieve/after/${baseNameOf el.after}' '' ) cfg.imapsieve.mailbox} - ${optionalString ( + ${lib.optionalString ( cfg.mailUser != null && cfg.mailGroup != null ) "chown -R '${cfg.mailUser}:${cfg.mailGroup}' '${stateDir}/imapsieve'"} ''; diff --git a/nixos/modules/services/mail/exim.nix b/nixos/modules/services/mail/exim.nix index 77f8bd4b0dca3..c080f6b121398 100644 --- a/nixos/modules/services/mail/exim.nix +++ b/nixos/modules/services/mail/exim.nix @@ -6,14 +6,6 @@ }: let - inherit (lib) - literalExpression - mkIf - mkOption - singleton - types - mkPackageOption - ; inherit (pkgs) coreutils; cfg = config.services.exim; in @@ -26,14 +18,14 @@ in services.exim = { - enable = mkOption { - type = types.bool; + enable = lib.mkOption { + type = lib.types.bool; default = false; description = "Whether to enable the Exim mail transfer agent."; }; - config = mkOption { - type = types.lines; + config = lib.mkOption { + type = lib.types.lines; default = ""; description = '' Verbatim Exim configuration. This should not contain exim_user, @@ -41,8 +33,8 @@ in ''; }; - user = mkOption { - type = types.str; + user = lib.mkOption { + type = lib.types.str; default = "exim"; description = '' User to use when no root privileges are required. @@ -53,30 +45,30 @@ in ''; }; - group = mkOption { - type = types.str; + group = lib.mkOption { + type = lib.types.str; default = "exim"; description = '' Group to use when no root privileges are required. ''; }; - spoolDir = mkOption { - type = types.path; + spoolDir = lib.mkOption { + type = lib.types.path; default = "/var/spool/exim"; description = '' Location of the spool directory of exim. ''; }; - package = mkPackageOption pkgs "exim" { + package = lib.mkPackageOption pkgs "exim" { extraDescription = '' This can be used to enable features such as LDAP or PAM support. ''; }; - queueRunnerInterval = mkOption { - type = types.str; + queueRunnerInterval = lib.mkOption { + type = lib.types.str; default = "5m"; description = '' How often to spawn a new queue runner. @@ -88,7 +80,7 @@ in ###### implementation - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { environment = { etc."exim.conf".text = '' diff --git a/nixos/modules/services/mail/maddy.nix b/nixos/modules/services/mail/maddy.nix index 41d25eaf7885f..56b7c592771a5 100644 --- a/nixos/modules/services/mail/maddy.nix +++ b/nixos/modules/services/mail/maddy.nix @@ -29,11 +29,11 @@ let } table.chain local_rewrites { - optional_step regexp "(.+)\+(.+)@(.+)" "$1@$3" - optional_step static { + lib.optional_step regexp "(.+)\+(.+)@(.+)" "$1@$3" + lib.optional_step static { entry postmaster postmaster@$(primary_domain) } - optional_step file /etc/maddy/aliases + lib.optional_step file /etc/maddy/aliases } msgpipeline local_routing { diff --git a/nixos/modules/services/mail/mailcatcher.nix b/nixos/modules/services/mail/mailcatcher.nix index 9232e0f1d7e28..565f140e8ca94 100644 --- a/nixos/modules/services/mail/mailcatcher.nix +++ b/nixos/modules/services/mail/mailcatcher.nix @@ -7,14 +7,6 @@ let cfg = config.services.mailcatcher; - - inherit (lib) - mkEnableOption - mkIf - mkOption - types - optionalString - ; in { # interface @@ -22,35 +14,35 @@ in options = { services.mailcatcher = { - enable = mkEnableOption "MailCatcher, an SMTP server and web interface to locally test outbound emails"; + enable = lib.mkEnableOption "MailCatcher, an SMTP server and web interface to locally test outbound emails"; - http.ip = mkOption { - type = types.str; + http.ip = lib.mkOption { + type = lib.types.str; default = "127.0.0.1"; description = "The ip address of the http server."; }; - http.port = mkOption { - type = types.port; + http.port = lib.mkOption { + type = lib.types.port; default = 1080; description = "The port address of the http server."; }; - http.path = mkOption { - type = with types; nullOr str; + http.path = lib.mkOption { + type = with lib.types; nullOr str; default = null; description = "Prefix to all HTTP paths."; example = "/mailcatcher"; }; - smtp.ip = mkOption { - type = types.str; + smtp.ip = lib.mkOption { + type = lib.types.str; default = "127.0.0.1"; description = "The ip address of the smtp server."; }; - smtp.port = mkOption { - type = types.port; + smtp.port = lib.mkOption { + type = lib.types.port; default = 1025; description = "The port address of the smtp server."; }; @@ -60,7 +52,7 @@ in # implementation - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { environment.systemPackages = [ pkgs.mailcatcher ]; systemd.services.mailcatcher = { @@ -73,8 +65,8 @@ in Restart = "always"; ExecStart = "${pkgs.mailcatcher}/bin/mailcatcher --foreground --no-quit --http-ip ${cfg.http.ip} --http-port ${toString cfg.http.port} --smtp-ip ${cfg.smtp.ip} --smtp-port ${toString cfg.smtp.port}" - + optionalString (cfg.http.path != null) " --http-path ${cfg.http.path}"; - AmbientCapabilities = optionalString ( + + lib.optionalString (cfg.http.path != null) " --http-path ${cfg.http.path}"; + AmbientCapabilities = lib.optionalString ( cfg.http.port < 1024 || cfg.smtp.port < 1024 ) "cap_net_bind_service"; }; diff --git a/nixos/modules/services/mail/mailpit.nix b/nixos/modules/services/mail/mailpit.nix index 6bc368e91f5f1..ca7c687726685 100644 --- a/nixos/modules/services/mail/mailpit.nix +++ b/nixos/modules/services/mail/mailpit.nix @@ -7,38 +7,25 @@ let inherit (config.services.mailpit) instances; - inherit (lib) - cli - concatStringsSep - const - filterAttrs - getExe - mapAttrs' - mkIf - mkOption - nameValuePair - types - ; - isNonNull = v: v != null; genCliFlags = - settings: concatStringsSep " " (cli.toGNUCommandLine { } (filterAttrs (const isNonNull) settings)); + settings: lib.concatStringsSep " " (lib.cli.toGNUCommandLine { } (lib.filterAttrs (lib.const isNonNull) settings)); in { - options.services.mailpit.instances = mkOption { + options.services.mailpit.instances = lib.mkOption { default = { }; - type = types.attrsOf ( - types.submodule { - freeformType = types.attrsOf ( - types.oneOf [ - types.str - types.int - types.bool + type = lib.types.attrsOf ( + lib.types.submodule { + freeformType = lib.types.attrsOf ( + lib.types.oneOf [ + lib.types.str + lib.types.int + lib.types.bool ] ); options = { - database = mkOption { - type = types.nullOr types.str; + database = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; example = "mailpit.db"; description = '' @@ -48,8 +35,8 @@ in state directory then. ''; }; - max = mkOption { - type = types.ints.unsigned; + max = lib.mkOption { + type = lib.types.ints.unsigned; default = 500; description = '' Maximum number of emails to keep. If the number is exceeded, old emails @@ -58,16 +45,16 @@ in Set to `0` to never prune old emails. ''; }; - listen = mkOption { + listen = lib.mkOption { default = "127.0.0.1:8025"; - type = types.str; + type = lib.types.str; description = '' HTTP bind interface and port for UI. ''; }; - smtp = mkOption { + smtp = lib.mkOption { default = "127.0.0.1:1025"; - type = types.str; + type = lib.types.str; description = '' SMTP bind interface and port. ''; @@ -84,10 +71,10 @@ in ''; }; - config = mkIf (instances != { }) { - systemd.services = mapAttrs' ( + config = lib.mkIf (instances != { }) { + systemd.services = lib.mapAttrs' ( name: cfg: - nameValuePair "mailpit-${name}" { + lib.nameValuePair "mailpit-${name}" { wantedBy = [ "multi-user.target" ]; after = [ "network-online.target" ]; wants = [ "network-online.target" ]; @@ -95,7 +82,7 @@ in DynamicUser = true; StateDirectory = "mailpit"; WorkingDirectory = "%S/mailpit"; - ExecStart = "${getExe pkgs.mailpit} ${genCliFlags cfg}"; + ExecStart = "${lib.getExe pkgs.mailpit} ${genCliFlags cfg}"; Restart = "on-failure"; }; } diff --git a/nixos/modules/services/mail/nullmailer.nix b/nixos/modules/services/mail/nullmailer.nix index 6dc278f89f290..905165b36ab24 100644 --- a/nixos/modules/services/mail/nullmailer.nix +++ b/nixos/modules/services/mail/nullmailer.nix @@ -167,7 +167,7 @@ default = null; description = '' A list of remote servers to which to send each message. Each line - contains a remote host name or address followed by an optional + contains a remote host name or address followed by an lib.optional protocol string, separated by white space. See `man 8 nullmailer-send` for syntax and available diff --git a/nixos/modules/services/mail/postgrey.nix b/nixos/modules/services/mail/postgrey.nix index 7ce9d40a912af..273a87b6e19a6 100644 --- a/nixos/modules/services/mail/postgrey.nix +++ b/nixos/modules/services/mail/postgrey.nix @@ -5,27 +5,26 @@ ... }: -with lib; let cfg = config.services.postgrey; - natural = with types; addCheck int (x: x >= 0); - natural' = with types; addCheck int (x: x > 0); + natural = with lib.types; addCheck int (x: x >= 0); + natural' = with lib.types; addCheck int (x: x > 0); socket = - with types; + with lib.types; addCheck (either (submodule unixSocket) (submodule inetSocket)) (x: x ? path || x ? port); - inetSocket = with types; { + inetSocket = with lib.types; { options = { - addr = mkOption { + addr = lib.mkOption { type = nullOr str; default = null; example = "127.0.0.1"; description = "The address to bind to. Localhost if null"; }; - port = mkOption { + port = lib.mkOption { type = natural'; default = 10030; description = "Tcp port to bind to"; @@ -33,15 +32,15 @@ let }; }; - unixSocket = with types; { + unixSocket = with lib.types; { options = { - path = mkOption { + path = lib.mkOption { type = path; default = "/run/postgrey.sock"; description = "Path of the unix socket"; }; - mode = mkOption { + mode = lib.mkOption { type = str; default = "0777"; description = "Mode of the unix socket"; @@ -52,7 +51,7 @@ let in { imports = [ - (mkMergedOptionModule + (lib.mkMergedOptionModule [ [ "services" @@ -69,7 +68,7 @@ in ( config: let - value = p: getAttrFromPath p config; + value = p: lib.getAttrFromPath p config; inetAddr = [ "services" "postgrey" @@ -93,13 +92,13 @@ in ]; options = { - services.postgrey = with types; { - enable = mkOption { + services.postgrey = with lib.types; { + enable = lib.mkOption { type = bool; default = false; description = "Whether to run the Postgrey daemon"; }; - socket = mkOption { + socket = lib.mkOption { type = socket; default = { path = "/run/postgrey.sock"; @@ -111,68 +110,68 @@ in }; description = "Socket to bind to"; }; - greylistText = mkOption { + greylistText = lib.mkOption { type = str; default = "Greylisted for %%s seconds"; description = "Response status text for greylisted messages; use %%s for seconds left until greylisting is over and %%r for mail domain of recipient"; }; - greylistAction = mkOption { + greylistAction = lib.mkOption { type = str; default = "DEFER_IF_PERMIT"; description = "Response status for greylisted messages (see access(5))"; }; - greylistHeader = mkOption { + greylistHeader = lib.mkOption { type = str; default = "X-Greylist: delayed %%t seconds by postgrey-%%v at %%h; %%d"; description = "Prepend header to greylisted mails; use %%t for seconds delayed due to greylisting, %%v for the version of postgrey, %%d for the date, and %%h for the host"; }; - delay = mkOption { + delay = lib.mkOption { type = natural; default = 300; description = "Greylist for N seconds"; }; - maxAge = mkOption { + maxAge = lib.mkOption { type = natural; default = 35; description = "Delete entries from whitelist if they haven't been seen for N days"; }; - retryWindow = mkOption { + retryWindow = lib.mkOption { type = either str natural; default = 2; example = "12h"; description = "Allow N days for the first retry. Use string with appended 'h' to specify time in hours"; }; - lookupBySubnet = mkOption { + lookupBySubnet = lib.mkOption { type = bool; default = true; description = "Strip the last N bits from IP addresses, determined by IPv4CIDR and IPv6CIDR"; }; - IPv4CIDR = mkOption { + IPv4CIDR = lib.mkOption { type = natural; default = 24; description = "Strip N bits from IPv4 addresses if lookupBySubnet is true"; }; - IPv6CIDR = mkOption { + IPv6CIDR = lib.mkOption { type = natural; default = 64; description = "Strip N bits from IPv6 addresses if lookupBySubnet is true"; }; - privacy = mkOption { + privacy = lib.mkOption { type = bool; default = true; description = "Store data using one-way hash functions (SHA1)"; }; - autoWhitelist = mkOption { + autoWhitelist = lib.mkOption { type = nullOr natural'; default = 5; description = "Whitelist clients after successful delivery of N messages"; }; - whitelistClients = mkOption { + whitelistClients = lib.mkOption { type = listOf path; default = [ ]; description = "Client address whitelist files (see postgrey(8))"; }; - whitelistRecipients = mkOption { + whitelistRecipients = lib.mkOption { type = listOf path; default = [ ]; description = "Recipient address whitelist files (see postgrey(8))"; @@ -180,7 +179,7 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { environment.systemPackages = [ pkgs.postgrey ]; @@ -206,7 +205,7 @@ in "--unix=${cfg.socket.path} --socketmode=${cfg.socket.mode}" else ''--inet=${ - optionalString (cfg.socket.addr != null) (cfg.socket.addr + ":") + lib.optionalString (cfg.socket.addr != null) (cfg.socket.addr + ":") }${toString cfg.socket.port}''; in { @@ -230,15 +229,15 @@ in --retry-window=${toString cfg.retryWindow} \ ${if cfg.lookupBySubnet then "--lookup-by-subnet" else "--lookup-by-host"} \ --ipv4cidr=${toString cfg.IPv4CIDR} --ipv6cidr=${toString cfg.IPv6CIDR} \ - ${optionalString cfg.privacy "--privacy"} \ + ${lib.optionalString cfg.privacy "--privacy"} \ --auto-whitelist-clients=${ toString (if cfg.autoWhitelist == null then 0 else cfg.autoWhitelist) } \ --greylist-action=${cfg.greylistAction} \ --greylist-text="${cfg.greylistText}" \ --x-greylist-header="${cfg.greylistHeader}" \ - ${concatMapStringsSep " " (x: "--whitelist-clients=" + x) cfg.whitelistClients} \ - ${concatMapStringsSep " " (x: "--whitelist-recipients=" + x) cfg.whitelistRecipients} + ${lib.concatMapStringsSep " " (x: "--whitelist-clients=" + x) cfg.whitelistClients} \ + ${lib.concatMapStringsSep " " (x: "--whitelist-recipients=" + x) cfg.whitelistRecipients} ''; Restart = "always"; RestartSec = 5; diff --git a/nixos/modules/services/mail/public-inbox.nix b/nixos/modules/services/mail/public-inbox.nix index b1e4daa9f0e41..3cacc861a9831 100644 --- a/nixos/modules/services/mail/public-inbox.nix +++ b/nixos/modules/services/mail/public-inbox.nix @@ -5,8 +5,6 @@ ... }: -with lib; - let cfg = config.services.public-inbox; stateDir = "/var/lib/public-inbox"; @@ -19,13 +17,13 @@ let || cfg.settings.publicinboxwatch.spamcheck == "spamc"; publicInboxDaemonOptions = proto: defaultPort: { - args = mkOption { - type = with types; listOf str; + args = lib.mkOption { + type = with lib.types; listOf str; default = [ ]; description = "Command-line arguments to pass to {manpage}`public-inbox-${proto}d(1)`."; }; - port = mkOption { - type = with types; nullOr (either str port); + port = lib.mkOption { + type = with lib.types; nullOr (either str port); default = defaultPort; description = '' Listening port. @@ -34,14 +32,14 @@ let if you need a more advanced listening. ''; }; - cert = mkOption { - type = with types; nullOr str; + cert = lib.mkOption { + type = with lib.types; nullOr str; default = null; example = "/path/to/fullchain.pem"; description = "Path to TLS certificate to use for connections to {manpage}`public-inbox-${proto}d(1)`."; }; - key = mkOption { - type = with types; nullOr str; + key = lib.mkOption { + type = with lib.types; nullOr str; default = null; example = "/path/to/key.pem"; description = "Path to TLS key to use for connections to {manpage}`public-inbox-${proto}d(1)`."; @@ -51,7 +49,7 @@ let serviceConfig = srv: let - proto = removeSuffix "d" srv; + proto = lib.removeSuffix "d" srv; needNetwork = builtins.hasAttr proto cfg && cfg.${proto}.port == null; in { @@ -80,11 +78,11 @@ let "/run/systemd" "${config.i18n.glibcLocales}" ] - ++ mapAttrsToList (name: inbox: inbox.description) cfg.inboxes + ++ lib.mapAttrsToList (name: inbox: inbox.description) cfg.inboxes ++ # Without confinement the whole Nix store # is made available to the service - optionals (!config.systemd.services."public-inbox-${srv}".confinement.enable) [ + lib.optionals (!config.systemd.services."public-inbox-${srv}".confinement.enable) [ "${pkgs.dash}/bin/dash:/bin/sh" builtins.storeDir ]; @@ -97,7 +95,7 @@ let LockPersonality = true; MemoryDenyWriteExecute = true; NoNewPrivileges = true; - PrivateNetwork = mkDefault (!needNetwork); + PrivateNetwork = lib.mkDefault (!needNetwork); ProcSubset = "pid"; ProtectClock = true; ProtectHome = "tmpfs"; @@ -108,7 +106,7 @@ let RemoveIPC = true; RestrictAddressFamilies = [ "AF_UNIX" ] - ++ optionals needNetwork [ + ++ lib.optionals needNetwork [ "AF_INET" "AF_INET6" ]; @@ -153,7 +151,7 @@ let binSh = "${pkgs.dash}/bin/dash"; packages = [ pkgs.iana-etc - (getLib pkgs.nss) + (lib.getLib pkgs.nss) pkgs.tzdata ]; }; @@ -162,61 +160,61 @@ in { options.services.public-inbox = { - enable = mkEnableOption "the public-inbox mail archiver"; - package = mkPackageOption pkgs "public-inbox" { }; - path = mkOption { - type = with types; listOf package; + enable = lib.mkEnableOption "the public-inbox mail archiver"; + package = lib.mkPackageOption pkgs "public-inbox" { }; + path = lib.mkOption { + type = with lib.types; listOf package; default = [ ]; - example = literalExpression "with pkgs; [ spamassassin ]"; + example = lib.literalExpression "with pkgs; [ spamassassin ]"; description = '' Additional packages to place in the path of public-inbox-mda, public-inbox-watch, etc. ''; }; - inboxes = mkOption { + inboxes = lib.mkOption { description = '' Inboxes to configure, where attribute names are inbox names. ''; default = { }; - type = types.attrsOf ( - types.submodule ( + type = lib.types.attrsOf ( + lib.types.submodule ( { name, ... }: { - freeformType = types.attrsOf iniAtom; - options.inboxdir = mkOption { - type = types.str; + freeformType = lib.types.attrsOf iniAtom; + options.inboxdir = lib.mkOption { + type = lib.types.str; default = "${stateDir}/inboxes/${name}"; description = "The absolute path to the directory which hosts the public-inbox."; }; - options.address = mkOption { - type = with types; listOf str; + options.address = lib.mkOption { + type = with lib.types; listOf str; example = "example-discuss@example.org"; description = "The email addresses of the public-inbox."; }; - options.url = mkOption { - type = types.nonEmptyStr; + options.url = lib.mkOption { + type = lib.types.nonEmptyStr; example = "https://example.org/lists/example-discuss"; description = "URL where this inbox can be accessed over HTTP."; }; - options.description = mkOption { - type = types.str; + options.description = lib.mkOption { + type = lib.types.str; example = "user/dev discussion of public-inbox itself"; description = "User-visible description for the repository."; apply = pkgs.writeText "public-inbox-description-${name}"; }; - options.newsgroup = mkOption { - type = with types; nullOr str; + options.newsgroup = lib.mkOption { + type = with lib.types; nullOr str; default = null; description = "NNTP group name for the inbox."; }; - options.watch = mkOption { - type = with types; listOf str; + options.watch = lib.mkOption { + type = with lib.types; listOf str; default = [ ]; description = "Paths for {manpage}`public-inbox-watch(1)` to monitor for new mail."; example = [ "maildir:/path/to/test.example.com.git" ]; }; - options.watchheader = mkOption { - type = with types; nullOr str; + options.watchheader = lib.mkOption { + type = with lib.types; nullOr str; default = null; example = "List-Id:"; description = '' @@ -224,8 +222,8 @@ in mail containing a matching header. ''; }; - options.coderepo = mkOption { - type = (types.listOf (types.enum (attrNames cfg.settings.coderepo))) // { + options.coderepo = lib.mkOption { + type = (lib.types.listOf (lib.types.enum (lib.attrNames cfg.settings.coderepo))) // { description = "list of coderepo names"; }; default = [ ]; @@ -236,12 +234,12 @@ in ); }; imap = { - enable = mkEnableOption "the public-inbox IMAP server"; + enable = lib.mkEnableOption "the public-inbox IMAP server"; } // publicInboxDaemonOptions "imap" 993; http = { - enable = mkEnableOption "the public-inbox HTTP server"; - mounts = mkOption { - type = with types; listOf str; + enable = lib.mkEnableOption "the public-inbox HTTP server"; + mounts = lib.mkOption { + type = with lib.types; listOf str; default = [ "/" ]; example = [ "/lists/archives" ]; description = '' @@ -251,8 +249,8 @@ in ''; }; args = (publicInboxDaemonOptions "http" 80).args; - port = mkOption { - type = with types; nullOr (either str port); + port = lib.mkOption { + type = with lib.types; nullOr (either str port); default = 80; example = "/run/public-inbox-httpd.sock"; description = '' @@ -265,56 +263,56 @@ in }; }; mda = { - enable = mkEnableOption "the public-inbox Mail Delivery Agent"; - args = mkOption { - type = with types; listOf str; + enable = lib.mkEnableOption "the public-inbox Mail Delivery Agent"; + args = lib.mkOption { + type = with lib.types; listOf str; default = [ ]; description = "Command-line arguments to pass to {manpage}`public-inbox-mda(1)`."; }; }; - postfix.enable = mkEnableOption "the integration into Postfix"; + postfix.enable = lib.mkEnableOption "the integration into Postfix"; nntp = { - enable = mkEnableOption "the public-inbox NNTP server"; + enable = lib.mkEnableOption "the public-inbox NNTP server"; } // publicInboxDaemonOptions "nntp" 563; - spamAssassinRules = mkOption { - type = with types; nullOr path; + spamAssassinRules = lib.mkOption { + type = with lib.types; nullOr path; default = "${cfg.package.sa_config}/user/.spamassassin/user_prefs"; - defaultText = literalExpression "\${cfg.package.sa_config}/user/.spamassassin/user_prefs"; + defaultText = lib.literalExpression "\${cfg.package.sa_config}/user/.spamassassin/user_prefs"; description = "SpamAssassin configuration specific to public-inbox."; }; - settings = mkOption { + settings = lib.mkOption { description = '' Settings for the [public-inbox config file](https://public-inbox.org/public-inbox-config.html). ''; default = { }; - type = types.submodule { + type = lib.types.submodule { freeformType = gitIni.type; - options.publicinbox = mkOption { + options.publicinbox = lib.mkOption { default = { }; description = "public inboxes"; - type = types.submodule { + type = lib.types.submodule { # Support both global options like `services.public-inbox.settings.publicinbox.imapserver` # and inbox specific options like `services.public-inbox.settings.publicinbox.foo.address`. freeformType = - with types; + with lib.types; attrsOf (oneOf [ iniAtom (attrsOf iniAtom) ]); - options.css = mkOption { - type = with types; listOf str; + options.css = lib.mkOption { + type = with lib.types; listOf str; default = [ ]; description = "The local path name of a CSS file for the PSGI web interface."; }; - options.imapserver = mkOption { - type = with types; listOf str; + options.imapserver = lib.mkOption { + type = with lib.types; listOf str; default = [ ]; example = [ "imap.public-inbox.org" ]; description = "IMAP URLs to this public-inbox instance"; }; - options.nntpserver = mkOption { - type = with types; listOf str; + options.nntpserver = lib.mkOption { + type = with lib.types; listOf str; default = [ ]; example = [ "nntp://news.public-inbox.org" @@ -322,15 +320,15 @@ in ]; description = "NNTP URLs to this public-inbox instance"; }; - options.pop3server = mkOption { - type = with types; listOf str; + options.pop3server = lib.mkOption { + type = with lib.types; listOf str; default = [ ]; example = [ "pop.public-inbox.org" ]; description = "POP3 URLs to this public-inbox instance"; }; - options.wwwlisting = mkOption { + options.wwwlisting = lib.mkOption { type = - with types; + with lib.types; enum [ "all" "404" @@ -344,9 +342,9 @@ in }; }; }; - options.publicinboxmda.spamcheck = mkOption { + options.publicinboxmda.spamcheck = lib.mkOption { type = - with types; + with lib.types; enum [ "spamc" "none" @@ -357,9 +355,9 @@ in using SpamAssassin. ''; }; - options.publicinboxwatch.spamcheck = mkOption { + options.publicinboxwatch.spamcheck = lib.mkOption { type = - with types; + with lib.types; enum [ "spamc" "none" @@ -370,8 +368,8 @@ in using SpamAssassin. ''; }; - options.publicinboxwatch.watchspam = mkOption { - type = with types; nullOr str; + options.publicinboxwatch.watchspam = lib.mkOption { + type = with lib.types; nullOr str; default = null; example = "maildir:/path/to/spam"; description = '' @@ -379,18 +377,18 @@ in deleted from all watched inboxes ''; }; - options.coderepo = mkOption { + options.coderepo = lib.mkOption { default = { }; description = "code repositories"; - type = types.attrsOf ( - types.submodule { - freeformType = types.attrsOf iniAtom; - options.cgitUrl = mkOption { - type = types.str; + type = lib.types.attrsOf ( + lib.types.submodule { + freeformType = lib.types.attrsOf iniAtom; + options.cgitUrl = lib.mkOption { + type = lib.types.str; description = "URL of a cgit instance"; }; - options.dir = mkOption { - type = types.str; + options.dir = lib.mkOption { + type = lib.types.str; description = "Path to a git repository"; }; } @@ -398,9 +396,9 @@ in }; }; }; - openFirewall = mkEnableOption "opening the firewall when using a port option"; + openFirewall = lib.mkEnableOption "opening the firewall when using a port option"; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { assertions = [ { assertion = config.services.spamassassin.enable || !useSpamAssassin; @@ -422,8 +420,8 @@ in ''; } ]; - services.public-inbox.settings = filterAttrsRecursive (n: v: v != null) { - publicinbox = mapAttrs (n: filterAttrs (n: v: n != "description")) cfg.inboxes; + services.public-inbox.settings = lib.filterAttrsRecursive (n: v: v != null) { + publicinbox = lib.mapAttrs (n: lib.filterAttrs (n: v: n != "description")) cfg.inboxes; }; users = { users.public-inbox = { @@ -433,10 +431,10 @@ in }; groups.public-inbox = { }; }; - networking.firewall = mkIf cfg.openFirewall { - allowedTCPPorts = mkMerge ( + networking.firewall = lib.mkIf cfg.openFirewall { + allowedTCPPorts = lib.mkMerge ( map - (proto: (mkIf (cfg.${proto}.enable && types.port.check cfg.${proto}.port) [ cfg.${proto}.port ])) + (proto: (lib.mkIf (cfg.${proto}.enable && lib.types.port.check cfg.${proto}.port) [ cfg.${proto}.port ])) [ "imap" "http" @@ -444,21 +442,21 @@ in ] ); }; - services.postfix = mkIf (cfg.postfix.enable && cfg.mda.enable) { + services.postfix = lib.mkIf (cfg.postfix.enable && cfg.mda.enable) { # Not sure limiting to 1 is necessary, but better safe than sorry. config.public-inbox_destination_recipient_limit = "1"; # Register the addresses as existing - virtual = concatStringsSep "\n" ( - mapAttrsToList ( - _: inbox: concatMapStringsSep "\n" (address: "${address} ${address}") inbox.address + virtual = lib.concatStringsSep "\n" ( + lib.mapAttrsToList ( + _: inbox: lib.concatMapStringsSep "\n" (address: "${address} ${address}") inbox.address ) cfg.inboxes ); # Deliver the addresses with the public-inbox transport - transport = concatStringsSep "\n" ( - mapAttrsToList ( - _: inbox: concatMapStringsSep "\n" (address: "${address} public-inbox:${address}") inbox.address + transport = lib.concatStringsSep "\n" ( + lib.mapAttrsToList ( + _: inbox: lib.concatMapStringsSep "\n" (address: "${address} public-inbox:${address}") inbox.address ) cfg.inboxes ); @@ -476,17 +474,17 @@ in "argv=${pkgs.writeShellScript "public-inbox-transport" '' export HOME="${stateDir}" export ORIGINAL_RECIPIENT="''${2:-1}" - export PATH="${makeBinPath cfg.path}:$PATH" - exec ${cfg.package}/bin/public-inbox-mda ${escapeShellArgs cfg.mda.args} + export PATH="${lib.makeBinPath cfg.path}:$PATH" + exec ${cfg.package}/bin/public-inbox-mda ${lib.escapeShellArgs cfg.mda.args} ''} \${original_recipient} \${nexthop}" ]; }; }; - systemd.sockets = mkMerge ( + systemd.sockets = lib.mkMerge ( map ( proto: - mkIf (cfg.${proto}.enable && cfg.${proto}.port != null) { + lib.mkIf (cfg.${proto}.enable && cfg.${proto}.port != null) { "public-inbox-${proto}d" = { listenStreams = [ (toString cfg.${proto}.port) ]; wantedBy = [ "sockets.target" ]; @@ -499,9 +497,9 @@ in "nntp" ] ); - systemd.services = mkMerge [ - (mkIf cfg.imap.enable { - public-inbox-imapd = mkMerge [ + systemd.services = lib.mkMerge [ + (lib.mkIf cfg.imap.enable { + public-inbox-imapd = lib.mkMerge [ (serviceConfig "imapd") { after = [ @@ -510,14 +508,14 @@ in ]; requires = [ "public-inbox-init.service" ]; serviceConfig = { - ExecStart = escapeShellArgs ( + ExecStart = lib.escapeShellArgs ( [ "${cfg.package}/bin/public-inbox-imapd" ] ++ cfg.imap.args - ++ optionals (cfg.imap.cert != null) [ + ++ lib.optionals (cfg.imap.cert != null) [ "--cert" cfg.imap.cert ] - ++ optionals (cfg.imap.key != null) [ + ++ lib.optionals (cfg.imap.key != null) [ "--key" cfg.imap.key ] @@ -526,8 +524,8 @@ in } ]; }) - (mkIf cfg.http.enable { - public-inbox-httpd = mkMerge [ + (lib.mkIf cfg.http.enable { + public-inbox-httpd = lib.mkMerge [ (serviceConfig "httpd") { after = [ @@ -537,7 +535,7 @@ in requires = [ "public-inbox-init.service" ]; serviceConfig = { BindReadOnlyPaths = map (c: c.dir) (lib.attrValues cfg.settings.coderepo); - ExecStart = escapeShellArgs ( + ExecStart = lib.escapeShellArgs ( [ "${cfg.package}/bin/public-inbox-httpd" ] ++ cfg.http.args ++ @@ -564,7 +562,7 @@ in enable 'Head'; # Route according to configured domains and root paths. - ${concatMapStrings (path: '' + ${lib.concatMapStrings (path: '' mount q(${path}) => sub { $www->call(@_); }; '') cfg.http.mounts} } @@ -575,8 +573,8 @@ in } ]; }) - (mkIf cfg.nntp.enable { - public-inbox-nntpd = mkMerge [ + (lib.mkIf cfg.nntp.enable { + public-inbox-nntpd = lib.mkMerge [ (serviceConfig "nntpd") { after = [ @@ -585,14 +583,14 @@ in ]; requires = [ "public-inbox-init.service" ]; serviceConfig = { - ExecStart = escapeShellArgs ( + ExecStart = lib.escapeShellArgs ( [ "${cfg.package}/bin/public-inbox-nntpd" ] ++ cfg.nntp.args - ++ optionals (cfg.nntp.cert != null) [ + ++ lib.optionals (cfg.nntp.cert != null) [ "--cert" cfg.nntp.cert ] - ++ optionals (cfg.nntp.key != null) [ + ++ lib.optionals (cfg.nntp.key != null) [ "--key" cfg.nntp.key ] @@ -601,20 +599,20 @@ in } ]; }) - (mkIf + (lib.mkIf ( - any (inbox: inbox.watch != [ ]) (attrValues cfg.inboxes) + lib.any (inbox: inbox.watch != [ ]) (lib.attrValues cfg.inboxes) || cfg.settings.publicinboxwatch.watchspam != null ) { - public-inbox-watch = mkMerge [ + public-inbox-watch = lib.mkMerge [ (serviceConfig "watch") { inherit (cfg) path; wants = [ "public-inbox-init.service" ]; requires = [ "public-inbox-init.service" - ] ++ optional (cfg.settings.publicinboxwatch.spamcheck == "spamc") "spamassassin.service"; + ] ++ lib.optional (cfg.settings.publicinboxwatch.spamcheck == "spamc") "spamassassin.service"; wantedBy = [ "multi-user.target" ]; serviceConfig = { ExecStart = "${cfg.package}/bin/public-inbox-watch"; @@ -628,10 +626,10 @@ in public-inbox-init = let PI_CONFIG = gitIni.generate "public-inbox.ini" ( - filterAttrsRecursive (n: v: v != null) cfg.settings + lib.filterAttrsRecursive (n: v: v != null) cfg.settings ); in - mkMerge [ + lib.mkMerge [ (serviceConfig "init") { wantedBy = [ "multi-user.target" ]; @@ -642,15 +640,15 @@ in set -ux install -D -p ${PI_CONFIG} ${stateDir}/.public-inbox/config '' - + optionalString useSpamAssassin '' + + lib.optionalString useSpamAssassin '' install -m 0700 -o spamd -d ${stateDir}/.spamassassin - ${optionalString (cfg.spamAssassinRules != null) '' + ${lib.optionalString (cfg.spamAssassinRules != null) '' ln -sf ${cfg.spamAssassinRules} ${stateDir}/.spamassassin/user_prefs ''} '' - + concatStrings ( - mapAttrsToList (name: inbox: '' - if [ ! -e ${stateDir}/inboxes/${escapeShellArg name} ]; then + + lib.concatStrings ( + lib.mapAttrsToList (name: inbox: '' + if [ ! -e ${stateDir}/inboxes/${lib.escapeShellArg name} ]; then # public-inbox-init creates an inbox and adds it to a config file. # It tries to atomically write the config file by creating # another file in the same directory, and renaming it. @@ -660,7 +658,7 @@ in PI_CONFIG=$conf_dir/conf \ ${cfg.package}/bin/public-inbox-init -V2 \ - ${escapeShellArgs ( + ${lib.escapeShellArgs ( [ name "${stateDir}/inboxes/${name}" @@ -673,9 +671,9 @@ in fi ln -sf ${inbox.description} \ - ${stateDir}/inboxes/${escapeShellArg name}/description + ${stateDir}/inboxes/${lib.escapeShellArg name}/description - export GIT_DIR=${stateDir}/inboxes/${escapeShellArg name}/all.git + export GIT_DIR=${stateDir}/inboxes/${lib.escapeShellArg name}/all.git if test -d "$GIT_DIR"; then # Config is inherited by each epoch repository, # so just needs to be set for all.git. @@ -696,7 +694,7 @@ in ]; }) ]; - environment.systemPackages = with pkgs; [ cfg.package ]; + environment.systemPackages = [ cfg.package ]; }; meta.maintainers = with lib.maintainers; [ julm diff --git a/nixos/modules/services/mail/rspamd.nix b/nixos/modules/services/mail/rspamd.nix index 323339af97e92..8b3b80769a2ba 100644 --- a/nixos/modules/services/mail/rspamd.nix +++ b/nixos/modules/services/mail/rspamd.nix @@ -6,8 +6,6 @@ ... }: -with lib; - let cfg = config.services.rspamd; @@ -18,38 +16,38 @@ let { options, config, ... }: { options = { - socket = mkOption { - type = types.str; + socket = lib.mkOption { + type = lib.types.str; example = "localhost:11333"; description = '' Socket for this worker to listen on in a format acceptable by rspamd. ''; }; - mode = mkOption { - type = types.str; + mode = lib.mkOption { + type = lib.types.str; default = "0644"; description = "Mode to set on unix socket"; }; - owner = mkOption { - type = types.str; + owner = lib.mkOption { + type = lib.types.str; default = "${cfg.user}"; description = "Owner to set on unix socket"; }; - group = mkOption { - type = types.str; + group = lib.mkOption { + type = lib.types.str; default = "${cfg.group}"; description = "Group to set on unix socket"; }; - rawEntry = mkOption { - type = types.str; + rawEntry = lib.mkOption { + type = lib.types.str; internal = true; }; }; config.rawEntry = let - maybeOption = option: optionalString options.${option}.isDefined " ${option}=${config.${option}}"; + maybeOption = option: lib.optionalString options.${option}.isDefined " ${option}=${config.${option}}"; in - if (!(hasPrefix "/" config.socket)) then + if (!(lib.hasPrefix "/" config.socket)) then "${config.socket}" else "${config.socket}${maybeOption "mode"}${maybeOption "owner"}${maybeOption "group"}"; @@ -61,19 +59,19 @@ let { name, options, ... }: { options = { - enable = mkOption { - type = types.nullOr types.bool; + enable = lib.mkOption { + type = lib.types.nullOr lib.types.bool; default = null; description = "Whether to run the rspamd worker."; }; - name = mkOption { - type = types.nullOr types.str; + name = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = name; description = "Name of the worker"; }; - type = mkOption { - type = types.nullOr ( - types.enum [ + type = lib.mkOption { + type = lib.types.nullOr ( + lib.types.enum [ "normal" "controller" "fuzzy" @@ -91,12 +89,12 @@ let let from = "services.rspamd.workers.\"${name}\".type"; files = options.type.files; - warning = "The option `${from}` defined in ${showFiles files} has enum value `proxy` which has been renamed to `rspamd_proxy`"; + warning = "The option `${from}` defined in ${lib.showFiles files} has enum value `proxy` which has been renamed to `rspamd_proxy`"; in x: if x == "proxy" then traceWarning warning "rspamd_proxy" else x; }; - bindSockets = mkOption { - type = types.listOf (types.either types.str (types.submodule bindSocketOpts)); + bindSockets = lib.mkOption { + type = lib.types.listOf (lib.types.either lib.types.str (lib.types.submodule bindSocketOpts)); default = [ ]; description = '' List of sockets to listen, in format acceptable by rspamd @@ -113,7 +111,7 @@ let value: map ( each: - if (isString each) then + if (lib.isString each) then if (isUnixSocket each) then { socket = each; @@ -131,31 +129,31 @@ let each ) value; }; - count = mkOption { - type = types.nullOr types.int; + count = lib.mkOption { + type = lib.types.nullOr lib.types.int; default = null; description = '' Number of worker instances to run ''; }; - includes = mkOption { - type = types.listOf types.str; + includes = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; description = '' List of files to include in configuration ''; }; - extraConfig = mkOption { - type = types.lines; + extraConfig = lib.mkOption { + type = lib.types.lines; default = ""; description = "Additional entries to put verbatim into worker section of rspamd config file."; }; }; config = - mkIf (name == "normal" || name == "controller" || name == "fuzzy" || name == "rspamd_proxy") + lib.mkIf (name == "normal" || name == "controller" || name == "fuzzy" || name == "rspamd_proxy") { - type = mkDefault name; - includes = mkDefault [ "$CONFDIR/worker-${if name == "rspamd_proxy" then "proxy" else name}.inc" ]; + type = lib.mkDefault name; + includes = lib.mkDefault [ "$CONFDIR/worker-${if name == "rspamd_proxy" then "proxy" else name}.inc" ]; bindSockets = let unixSocket = name: { @@ -165,7 +163,7 @@ let group = cfg.group; }; in - mkDefault ( + lib.mkDefault ( if name == "normal" then [ (unixSocket "rspamd") ] else if name == "controller" then @@ -178,11 +176,11 @@ let }; }; - isUnixSocket = socket: hasPrefix "/" (if (isString socket) then socket else socket.socket); + isUnixSocket = socket: lib.hasPrefix "/" (if (lib.isString socket) then socket else socket.socket); mkBindSockets = enabled: socks: - concatStringsSep "\n " (flatten (map (each: "bind_socket = \"${each.rawEntry}\";") socks)); + lib.concatStringsSep "\n " (lib.flatten (map (each: "bind_socket = \"${each.rawEntry}\";") socks)); rspamdConfFile = pkgs.writeText "rspamd.conf" '' .include "$CONFDIR/common.conf" @@ -201,22 +199,22 @@ let .include(try=true; priority=10) "$LOCAL_CONFDIR/override.d/logging.inc" } - ${concatStringsSep "\n" ( - mapAttrsToList ( + ${lib.concatStringsSep "\n" ( + lib.mapAttrsToList ( name: value: let includeName = if name == "rspamd_proxy" then "proxy" else name; - tryOverride = boolToString (value.extraConfig == ""); + tryOverride = lib.boolToString (value.extraConfig == ""); in '' worker "${value.type}" { type = "${value.type}"; - ${optionalString (value.enable != null) + ${lib.optionalString (value.enable != null) "enabled = ${if value.enable != false then "yes" else "no"};" } ${mkBindSockets value.enable value.bindSockets} - ${optionalString (value.count != null) "count = ${toString value.count};"} - ${concatStringsSep "\n " (map (each: ".include \"${each}\"") value.includes)} + ${lib.optionalString (value.count != null) "count = ${toString value.count};"} + ${lib.concatStringsSep "\n " (map (each: ".include \"${each}\"") value.includes)} .include(try=true; priority=1,duplicate=merge) "$LOCAL_CONFDIR/local.d/worker-${includeName}.inc" .include(try=${tryOverride}; priority=10) "$LOCAL_CONFDIR/override.d/worker-${includeName}.inc" } @@ -224,22 +222,22 @@ let ) cfg.workers )} - ${optionalString (cfg.extraConfig != "") '' + ${lib.optionalString (cfg.extraConfig != "") '' .include(priority=10) "$LOCAL_CONFDIR/override.d/extra-config.inc" ''} ''; - filterFiles = files: filterAttrs (n: v: v.enable) files; + filterFiles = files: lib.filterAttrs (n: v: v.enable) files; rspamdDir = pkgs.linkFarm "etc-rspamd-dir" ( - (mapAttrsToList (name: file: { + (lib.mapAttrsToList (name: file: { name = "local.d/${name}"; path = file.source; }) (filterFiles cfg.locals)) - ++ (mapAttrsToList (name: file: { + ++ (lib.mapAttrsToList (name: file: { name = "override.d/${name}"; path = file.source; }) (filterFiles cfg.overrides)) - ++ (optional (cfg.localLuaRules != null) { + ++ (lib.optional (cfg.localLuaRules != null) { name = "rspamd.local.lua"; path = cfg.localLuaRules; }) @@ -256,8 +254,8 @@ let { name, config, ... }: { options = { - enable = mkOption { - type = types.bool; + enable = lib.mkOption { + type = lib.types.bool; default = true; description = '' Whether this file ${prefix} should be generated. This @@ -265,34 +263,34 @@ let ''; }; - text = mkOption { + text = lib.mkOption { default = null; - type = types.nullOr types.lines; + type = lib.types.nullOr lib.types.lines; description = "Text of the file."; }; - source = mkOption { - type = types.path; + source = lib.mkOption { + type = lib.types.path; description = "Path of the source file."; }; }; config = { - source = mkIf (config.text != null) ( + source = lib.mkIf (config.text != null) ( let name' = "rspamd-${prefix}-" + baseNameOf name; in - mkDefault (pkgs.writeText name' config.text) + lib.mkDefault (pkgs.writeText name' config.text) ); }; }; configOverrides = - (mapAttrs' ( + (lib.mapAttrs' ( n: v: - nameValuePair "worker-${if n == "rspamd_proxy" then "proxy" else n}.inc" { + lib.nameValuePair "worker-${if n == "rspamd_proxy" then "proxy" else n}.inc" { text = v.extraConfig; } - ) (filterAttrs (n: v: v.extraConfig != "") cfg.workers)) + ) (lib.filterAttrs (n: v: v.extraConfig != "") cfg.workers)) // (lib.optionalAttrs (cfg.extraConfig != "") { "extra-config.inc".text = cfg.extraConfig; }); @@ -305,51 +303,51 @@ in services.rspamd = { - enable = mkEnableOption "rspamd, the Rapid spam filtering system"; + enable = lib.mkEnableOption "rspamd, the Rapid spam filtering system"; - debug = mkOption { - type = types.bool; + debug = lib.mkOption { + type = lib.types.bool; default = false; description = "Whether to run the rspamd daemon in debug mode."; }; - locals = mkOption { - type = with types; attrsOf (submodule (configFileModule "locals")); + locals = lib.mkOption { + type = with lib.types; attrsOf (submodule (configFileModule "locals")); default = { }; description = '' Local configuration files, written into {file}`/etc/rspamd/local.d/{name}`. ''; - example = literalExpression '' + example = lib.literalExpression '' { "redis.conf".source = "/nix/store/.../etc/dir/redis.conf"; "arc.conf".text = "allow_envfrom_empty = true;"; } ''; }; - overrides = mkOption { - type = with types; attrsOf (submodule (configFileModule "overrides")); + overrides = lib.mkOption { + type = with lib.types; attrsOf (submodule (configFileModule "overrides")); default = { }; description = '' Overridden configuration files, written into {file}`/etc/rspamd/override.d/{name}`. ''; - example = literalExpression '' + example = lib.literalExpression '' { "redis.conf".source = "/nix/store/.../etc/dir/redis.conf"; "arc.conf".text = "allow_envfrom_empty = true;"; } ''; }; - localLuaRules = mkOption { + localLuaRules = lib.mkOption { default = null; - type = types.nullOr types.path; + type = lib.types.nullOr lib.types.path; description = '' Path of file to link to {file}`/etc/rspamd/rspamd.local.lua` for local rules written in Lua ''; }; - workers = mkOption { - type = with types; attrsOf (submodule workerOpts); + workers = lib.mkOption { + type = with lib.types; attrsOf (submodule workerOpts); description = '' Attribute set of workers to start. ''; @@ -357,7 +355,7 @@ in normal = { }; controller = { }; }; - example = literalExpression '' + example = lib.literalExpression '' { normal = { includes = [ "$CONFDIR/worker-normal.inc" ]; @@ -376,8 +374,8 @@ in ''; }; - extraConfig = mkOption { - type = types.lines; + extraConfig = lib.mkOption { + type = lib.types.lines; default = ""; description = '' Extra configuration to add at the end of the rspamd configuration @@ -385,16 +383,16 @@ in ''; }; - user = mkOption { - type = types.str; + user = lib.mkOption { + type = lib.types.str; default = "rspamd"; description = '' User to use when no root privileges are required. ''; }; - group = mkOption { - type = types.str; + group = lib.mkOption { + type = lib.types.str; default = "rspamd"; description = '' Group to use when no root privileges are required. @@ -402,15 +400,15 @@ in }; postfix = { - enable = mkOption { - type = types.bool; + enable = lib.mkOption { + type = lib.types.bool; default = false; description = "Add rspamd milter to postfix main.conf"; }; - config = mkOption { + config = lib.mkOption { type = - with types; + with lib.types; attrsOf (oneOf [ bool str @@ -430,9 +428,9 @@ in ###### implementation - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { services.rspamd.overrides = configOverrides; - services.rspamd.workers = mkIf cfg.postfix.enable { + services.rspamd.workers = lib.mkIf cfg.postfix.enable { controller = { }; rspamd_proxy = { bindSockets = [ @@ -451,9 +449,9 @@ in ''; }; }; - services.postfix.config = mkIf cfg.postfix.enable cfg.postfix.config; + services.postfix.config = lib.mkIf cfg.postfix.enable cfg.postfix.config; - systemd.services.postfix = mkIf cfg.postfix.enable { + systemd.services.postfix = lib.mkIf cfg.postfix.enable { serviceConfig.SupplementaryGroups = [ postfixCfg.group ]; }; @@ -480,12 +478,12 @@ in restartTriggers = [ rspamdDir ]; serviceConfig = { - ExecStart = "${pkgs.rspamd}/bin/rspamd ${optionalString cfg.debug "-d"} -c /etc/rspamd/rspamd.conf -f"; + ExecStart = "${pkgs.rspamd}/bin/rspamd ${lib.optionalString cfg.debug "-d"} -c /etc/rspamd/rspamd.conf -f"; Restart = "always"; User = "${cfg.user}"; Group = "${cfg.group}"; - SupplementaryGroups = mkIf cfg.postfix.enable [ postfixCfg.group ]; + SupplementaryGroups = lib.mkIf cfg.postfix.enable [ postfixCfg.group ]; RuntimeDirectory = "rspamd"; RuntimeDirectoryMode = "0755"; @@ -526,20 +524,20 @@ in }; }; imports = [ - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "rspamd" "socketActivation" ] "Socket activation never worked correctly and could at this time not be fixed and so was removed") - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "rspamd" "bindSocket" ] [ "services" "rspamd" "workers" "normal" "bindSockets" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "rspamd" "bindUISocket" ] [ "services" "rspamd" "workers" "controller" "bindSockets" ] ) - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "rmilter" ] "Use services.rspamd.* instead to set up milter service") diff --git a/nixos/modules/services/matrix/dendrite.nix b/nixos/modules/services/matrix/dendrite.nix index 2f17bb9f07276..44fe8bcc9d7fd 100644 --- a/nixos/modules/services/matrix/dendrite.nix +++ b/nixos/modules/services/matrix/dendrite.nix @@ -97,7 +97,7 @@ in type = lib.types.str; example = "example.com"; description = '' - The domain name of the server, with optional explicit port. + The domain name of the server, with lib.optional explicit port. This is used by remote servers to connect to this server. This is also the last part of your UserID. ''; diff --git a/nixos/modules/services/matrix/hebbot.nix b/nixos/modules/services/matrix/hebbot.nix index ba676422ca1fd..ccebb59a8b506 100644 --- a/nixos/modules/services/matrix/hebbot.nix +++ b/nixos/modules/services/matrix/hebbot.nix @@ -5,12 +5,11 @@ }: let - inherit (lib) mkEnableOption mkOption mkIf types; format = pkgs.formats.toml { }; cfg = config.services.hebbot; settingsFile = format.generate "config.toml" cfg.settings; - mkTemplateOption = templateName: mkOption { - type = types.path; + mkTemplateOption = templateName: lib.mkOption { + type = lib.types.path; description = '' A path to the Markdown file for the ${templateName}. ''; @@ -19,9 +18,9 @@ in { meta.maintainers = [ lib.maintainers.raitobezarius ]; options.services.hebbot = { - enable = mkEnableOption "hebbot"; - botPasswordFile = mkOption { - type = types.path; + enable = lib.mkEnableOption "hebbot"; + botPasswordFile = lib.mkOption { + type = lib.types.path; description = '' A path to the password file for your bot. @@ -34,7 +33,7 @@ in report = mkTemplateOption "report template"; section = mkTemplateOption "section template"; }; - settings = mkOption { + settings = lib.mkOption { type = format.type; default = { }; description = '' @@ -46,7 +45,7 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { systemd.services.hebbot = { description = "hebbot - a TWIM-style Matrix bot written in Rust"; after = [ "network.target" ]; diff --git a/nixos/modules/services/matrix/maubot.nix b/nixos/modules/services/matrix/maubot.nix index 6a7f36378e3d5..fd794f41d274c 100644 --- a/nixos/modules/services/matrix/maubot.nix +++ b/nixos/modules/services/matrix/maubot.nix @@ -58,15 +58,15 @@ let hasLocalPostgresDB = localPostgresDBs != [ ]; in { - options.services.maubot = with lib; { - enable = mkEnableOption "maubot"; + options.services.maubot = { + enable = lib.mkEnableOption "maubot"; package = lib.mkPackageOption pkgs "maubot" { }; - plugins = mkOption { - type = types.listOf types.package; + plugins = lib.mkOption { + type = lib.types.listOf lib.types.package; default = [ ]; - example = literalExpression '' + example = lib.literalExpression '' with config.services.maubot.package.plugins; [ xyz.maubot.reactbot xyz.maubot.rss @@ -77,10 +77,10 @@ in ''; }; - pythonPackages = mkOption { - type = types.listOf types.package; + pythonPackages = lib.mkOption { + type = lib.types.listOf lib.types.package; default = [ ]; - example = literalExpression '' + example = lib.literalExpression '' with pkgs.python3Packages; [ aiohttp ]; @@ -90,18 +90,18 @@ in ''; }; - dataDir = mkOption { - type = types.str; + dataDir = lib.mkOption { + type = lib.types.str; default = "/var/lib/maubot"; description = '' The directory where maubot stores its stateful data. ''; }; - extraConfigFile = mkOption { - type = types.str; + extraConfigFile = lib.mkOption { + type = lib.types.str; default = "./config.yaml"; - defaultText = literalExpression ''"''${config.services.maubot.dataDir}/config.yaml"''; + defaultText = lib.literalExpression ''"''${config.services.maubot.dataDir}/config.yaml"''; description = '' A file for storing secrets. You can pass homeserver registration keys here. If it already exists, **it must contain `server.unshared_secret`** which is used for signing API keys. @@ -109,15 +109,15 @@ in ''; }; - configMutable = mkOption { - type = types.bool; + configMutable = lib.mkOption { + type = lib.types.bool; default = false; description = '' Whether maubot should write updated config into `extraConfigFile`. **This will make your Nix module settings have no effect besides the initial config, as extraConfigFile takes precedence over NixOS settings!** ''; }; - settings = mkOption { + settings = lib.mkOption { default = { }; description = '' YAML settings for maubot. See the @@ -127,10 +127,10 @@ in Secrets should be passed in by using `extraConfigFile`. ''; type = - with types; + with lib.types; submodule { options = { - database = mkOption { + database = lib.mkOption { type = str; default = "sqlite:maubot.db"; example = "postgresql://username:password@hostname/dbname"; @@ -140,7 +140,7 @@ in ''; }; - crypto_database = mkOption { + crypto_database = lib.mkOption { type = str; default = "default"; example = "postgresql://username:password@hostname/dbname"; @@ -149,39 +149,39 @@ in ''; }; - database_opts = mkOption { - type = types.attrs; + database_opts = lib.mkOption { + type = lib.types.attrs; default = { }; description = '' Additional arguments for asyncpg.create_pool() or sqlite3.connect() ''; }; - plugin_directories = mkOption { + plugin_directories = lib.mkOption { default = { }; description = "Plugin directory paths"; type = submodule { options = { - upload = mkOption { - type = types.str; + upload = lib.mkOption { + type = lib.types.str; default = "./plugins"; - defaultText = literalExpression ''"''${config.services.maubot.dataDir}/plugins"''; + defaultText = lib.literalExpression ''"''${config.services.maubot.dataDir}/plugins"''; description = '' The directory where uploaded new plugins should be stored. ''; }; - load = mkOption { - type = types.listOf types.str; + load = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ "./plugins" ]; - defaultText = literalExpression ''[ "''${config.services.maubot.dataDir}/plugins" ]''; + defaultText = lib.literalExpression ''[ "''${config.services.maubot.dataDir}/plugins" ]''; description = '' The directories from which plugins should be loaded. Duplicate plugin IDs will be moved to the trash. ''; }; - trash = mkOption { - type = with types; nullOr str; + trash = lib.mkOption { + type = with lib.types; nullOr str; default = "./trash"; - defaultText = literalExpression ''"''${config.services.maubot.dataDir}/trash"''; + defaultText = lib.literalExpression ''"''${config.services.maubot.dataDir}/trash"''; description = '' The directory where old plugin versions and conflicting plugins should be moved. Set to null to delete files immediately. ''; @@ -190,39 +190,39 @@ in }; }; - plugin_databases = mkOption { + plugin_databases = lib.mkOption { description = "Plugin database settings"; default = { }; type = submodule { options = { - sqlite = mkOption { - type = types.str; + sqlite = lib.mkOption { + type = lib.types.str; default = "./plugins"; - defaultText = literalExpression ''"''${config.services.maubot.dataDir}/plugins"''; + defaultText = lib.literalExpression ''"''${config.services.maubot.dataDir}/plugins"''; description = '' The directory where SQLite plugin databases should be stored. ''; }; - postgres = mkOption { - type = types.nullOr types.str; + postgres = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = if isPostgresql cfg.settings.database then "default" else null; - defaultText = literalExpression ''if isPostgresql config.services.maubot.settings.database then "default" else null''; + defaultText = lib.literalExpression ''if isPostgresql config.services.maubot.settings.database then "default" else null''; description = '' The connection URL for plugin database. See [example config](https://github.com/maubot/maubot/blob/master/maubot/example-config.yaml) for exact format. ''; }; - postgres_max_conns_per_plugin = mkOption { - type = types.nullOr types.int; + postgres_max_conns_per_plugin = lib.mkOption { + type = lib.types.nullOr lib.types.int; default = 3; description = '' Maximum number of connections per plugin instance. ''; }; - postgres_opts = mkOption { - type = types.attrs; + postgres_opts = lib.mkOption { + type = lib.types.attrs; default = { }; description = '' Overrides for the default database_opts when using a non-default postgres connection URL. @@ -232,52 +232,52 @@ in }; }; - server = mkOption { + server = lib.mkOption { default = { }; description = "Listener config"; type = submodule { options = { - hostname = mkOption { - type = types.str; + hostname = lib.mkOption { + type = lib.types.str; default = "127.0.0.1"; description = '' The IP to listen on ''; }; - port = mkOption { - type = types.port; + port = lib.mkOption { + type = lib.types.port; default = 29316; description = '' The port to listen on ''; }; - public_url = mkOption { - type = types.str; + public_url = lib.mkOption { + type = lib.types.str; default = "http://${cfg.settings.server.hostname}:${toString cfg.settings.server.port}"; - defaultText = literalExpression ''"http://''${config.services.maubot.settings.server.hostname}:''${toString config.services.maubot.settings.server.port}"''; + defaultText = lib.literalExpression ''"http://''${config.services.maubot.settings.server.hostname}:''${toString config.services.maubot.settings.server.port}"''; description = '' Public base URL where the server is visible. ''; }; - ui_base_path = mkOption { - type = types.str; + ui_base_path = lib.mkOption { + type = lib.types.str; default = "/_matrix/maubot"; description = '' The base path for the UI. ''; }; - plugin_base_path = mkOption { - type = types.str; + plugin_base_path = lib.mkOption { + type = lib.types.str; default = "${config.services.maubot.settings.server.ui_base_path}/plugin/"; - defaultText = literalExpression '' + defaultText = lib.literalExpression '' "''${config.services.maubot.settings.server.ui_base_path}/plugin/" ''; description = '' The base path for plugin endpoints. The instance ID will be appended directly. ''; }; - override_resource_path = mkOption { - type = types.nullOr types.str; + override_resource_path = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; description = '' Override path from where to load UI resources. @@ -287,12 +287,12 @@ in }; }; - homeservers = mkOption { - type = types.attrsOf ( + homeservers = lib.mkOption { + type = lib.types.attrsOf ( types.submodule { options = { - url = mkOption { - type = types.str; + url = lib.mkOption { + type = lib.types.str; description = '' Client-server API URL ''; @@ -311,8 +311,8 @@ in ''; }; - admins = mkOption { - type = types.attrsOf types.str; + admins = lib.mkOption { + type = lib.types.attrsOf lib.types.str; default = { root = ""; }; @@ -322,8 +322,8 @@ in ''; }; - api_features = mkOption { - type = types.attrsOf bool; + api_features = lib.mkOption { + type = lib.types.attrsOf bool; default = { login = true; plugin = true; @@ -341,8 +341,8 @@ in ''; }; - logging = mkOption { - type = types.attrs; + logging = lib.mkOption { + type = lib.types.attrs; description = '' Python logging configuration. See [section 16.7.2 of the Python documentation](https://docs.python.org/3.6/library/logging.config.html#configuration-dictionary-schema) diff --git a/nixos/modules/services/matrix/mautrix-meta.nix b/nixos/modules/services/matrix/mautrix-meta.nix index e64f1d923564a..38c03e381390c 100644 --- a/nixos/modules/services/matrix/mautrix-meta.nix +++ b/nixos/modules/services/matrix/mautrix-meta.nix @@ -584,33 +584,33 @@ in { instagram = { settings = { - network.mode = mkDefault "instagram"; + network.mode = lib.mkDefault "instagram"; appservice = { - id = mkDefault "instagram"; - port = mkDefault 29320; + id = lib.mkDefault "instagram"; + port = lib.mkDefault 29320; bot = { - username = mkDefault "instagrambot"; - displayname = mkDefault "Instagram bridge bot"; - avatar = mkDefault "mxc://maunium.net/JxjlbZUlCPULEeHZSwleUXQv"; + username = lib.mkDefault "instagrambot"; + displayname = lib.mkDefault "Instagram bridge bot"; + avatar = lib.mkDefault "mxc://maunium.net/JxjlbZUlCPULEeHZSwleUXQv"; }; - username_template = mkDefault "instagram_{{.}}"; + username_template = lib.mkDefault "instagram_{{.}}"; }; }; }; facebook = { settings = { - network.mode = mkDefault "facebook"; + network.mode = lib.mkDefault "facebook"; appservice = { - id = mkDefault "facebook"; - port = mkDefault 29321; + id = lib.mkDefault "facebook"; + port = lib.mkDefault 29321; bot = { - username = mkDefault "facebookbot"; - displayname = mkDefault "Facebook bridge bot"; - avatar = mkDefault "mxc://maunium.net/ygtkteZsXnGJLJHRchUwYWak"; + username = lib.mkDefault "facebookbot"; + displayname = lib.mkDefault "Facebook bridge bot"; + avatar = lib.mkDefault "mxc://maunium.net/ygtkteZsXnGJLJHRchUwYWak"; }; - username_template = mkDefault "facebook_{{.}}"; + username_template = lib.mkDefault "facebook_{{.}}"; }; }; }; diff --git a/nixos/modules/services/matrix/mautrix-telegram.nix b/nixos/modules/services/matrix/mautrix-telegram.nix index a489c9c72485b..41d0b310aef5b 100644 --- a/nixos/modules/services/matrix/mautrix-telegram.nix +++ b/nixos/modules/services/matrix/mautrix-telegram.nix @@ -106,7 +106,7 @@ in `MAUTRIX_TELEGRAM_APPSERVICE_AS_TOKEN`, `MAUTRIX_TELEGRAM_APPSERVICE_HS_TOKEN`, `MAUTRIX_TELEGRAM_TELEGRAM_API_ID`, - `MAUTRIX_TELEGRAM_TELEGRAM_API_HASH` and optionally + `MAUTRIX_TELEGRAM_TELEGRAM_API_HASH` and lib.optionally `MAUTRIX_TELEGRAM_TELEGRAM_BOT_TOKEN`. These environment variables can also be used to set other options by diff --git a/nixos/modules/services/matrix/mautrix-whatsapp.nix b/nixos/modules/services/matrix/mautrix-whatsapp.nix index 89bf7f9e9fac0..d238bf91bd613 100644 --- a/nixos/modules/services/matrix/mautrix-whatsapp.nix +++ b/nixos/modules/services/matrix/mautrix-whatsapp.nix @@ -93,7 +93,7 @@ in { default = null; description = '' File containing environment variables to be passed to the mautrix-whatsapp service, - in which secret tokens can be specified securely by optionally defining a value for + in which secret tokens can be specified securely by lib.optionally defining a value for `MAUTRIX_WHATSAPP_BRIDGE_LOGIN_SHARED_SECRET`. ''; }; @@ -102,7 +102,7 @@ in { type = with lib.types; listOf str; default = lib.optional config.services.matrix-synapse.enable config.services.matrix-synapse.serviceUnit; defaultText = lib.literalExpression '' - optional config.services.matrix-synapse.enable config.services.matrix-synapse.serviceUnits + lib.optional config.services.matrix-synapse.enable config.services.matrix-synapse.serviceUnits ''; description = '' List of Systemd services to require and wait for when starting the application service. diff --git a/nixos/modules/services/matrix/synapse.nix b/nixos/modules/services/matrix/synapse.nix index 48372d9c48741..25ed79024b18d 100644 --- a/nixos/modules/services/matrix/synapse.nix +++ b/nixos/modules/services/matrix/synapse.nix @@ -6,18 +6,16 @@ ... }: -with lib; - let cfg = config.services.matrix-synapse; format = pkgs.formats.yaml { }; filterRecursiveNull = o: - if isAttrs o then - mapAttrs (_: v: filterRecursiveNull v) (filterAttrs (_: v: v != null) o) - else if isList o then - map filterRecursiveNull (filter (v: v != null) o) + if lib.isAttrs o then + lib.mapAttrs (_: v: filterRecursiveNull v) (lib.filterAttrs (_: v: v != null) o) + else if lib.isList o then + map filterRecursiveNull (lib.filter (v: v != null) o) else o; @@ -33,7 +31,7 @@ let usePostgresql && ( !(args ? host) - || (elem args.host [ + || (lib.elem args.host [ "localhost" "127.0.0.1" "::1" @@ -45,20 +43,20 @@ let listenerSupportsResource = resource: listener: lib.any ({ names, ... }: builtins.elem resource names) listener.resources; - clientListener = findFirst (listenerSupportsResource "client") null ( + clientListener = lib.findFirst (listenerSupportsResource "client") null ( cfg.settings.listeners - ++ concatMap ({ worker_listeners, ... }: worker_listeners) (attrValues cfg.workers) + ++ lib.concatMap ({ worker_listeners, ... }: worker_listeners) (lib.attrValues cfg.workers) ); registerNewMatrixUser = let - isIpv6 = hasInfix ":"; + isIpv6 = lib.hasInfix ":"; # add a tail, so that without any bind_addresses we still have a useable address - bindAddress = head (clientListener.bind_addresses ++ [ "127.0.0.1" ]); + bindAddress = lib.head (clientListener.bind_addresses ++ [ "127.0.0.1" ]); listenerProtocol = if clientListener.tls then "https" else "http"; in - assert assertMsg ( + assert lib.assertMsg ( clientListener != null ) "No client listener found in synapse or one of its workers"; pkgs.writeShellScriptBin "matrix-synapse-register_new_matrix_user" '' @@ -107,7 +105,7 @@ let disable_existing_loggers = false; }; - defaultCommonLogConfigText = generators.toPretty { } defaultCommonLogConfig; + defaultCommonLogConfigText = lib.generators.toPretty { } defaultCommonLogConfig; logConfigText = logName: @@ -115,8 +113,8 @@ let Path to a yaml file generated from this Nix expression: ``` - ${generators.toPretty { } ( - recursiveUpdate defaultCommonLogConfig { handlers.journal.SYSLOG_IDENTIFIER = logName; } + ${lib.generators.toPretty { } ( + lib.recursiveUpdate defaultCommonLogConfig { handlers.journal.SYSLOG_IDENTIFIER = logName; } )} ``` ''; @@ -125,7 +123,7 @@ let logName: format.generate "synapse-log-${logName}.yaml" ( cfg.log - // optionalAttrs (cfg.log ? handlers.journal) { + // lib.optionalAttrs (cfg.log ? handlers.journal) { handlers.journal = cfg.log.handlers.journal // { SYSLOG_IDENTIFIER = logName; }; @@ -146,16 +144,16 @@ in imports = [ - (mkRemovedOptionModule [ "services" "matrix-synapse" "trusted_third_party_id_servers" ] '' + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "trusted_third_party_id_servers" ] '' The `trusted_third_party_id_servers` option as been removed in `matrix-synapse` v1.4.0 as the behavior is now obsolete. '') - (mkRemovedOptionModule [ "services" "matrix-synapse" "create_local_database" ] '' + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "create_local_database" ] '' Database configuration must be done manually. An exemplary setup is demonstrated in '') - (mkRemovedOptionModule [ "services" "matrix-synapse" "web_client" ] "") - (mkRemovedOptionModule [ "services" "matrix-synapse" "room_invite_state_types" ] '' + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "web_client" ] "") + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "room_invite_state_types" ] '' You may add additional event types via `services.matrix-synapse.room_prejoin_state.additional_event_types` and disable the default events via @@ -163,252 +161,252 @@ in '') # options that don't exist in synapse anymore - (mkRemovedOptionModule [ "services" "matrix-synapse" "bind_host" ] "Use listener settings instead.") - (mkRemovedOptionModule [ "services" "matrix-synapse" "bind_port" ] "Use listener settings instead.") - (mkRemovedOptionModule [ "services" "matrix-synapse" "expire_access_tokens" ] "") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "bind_host" ] "Use listener settings instead.") + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "bind_port" ] "Use listener settings instead.") + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "expire_access_tokens" ] "") + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "no_tls" ] "It is no longer supported by synapse.") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "tls_dh_param_path" ] "It was removed from synapse.") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "unsecure_port" ] "Use settings.listeners instead.") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "user_creation_max_duration" ] "It is no longer supported by synapse.") - (mkRemovedOptionModule [ "services" "matrix-synapse" "verbose" ] "Use a log config instead.") + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "verbose" ] "Use a log config instead.") # options that were moved into rfc42 style settings - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "app_service_config_files" ] "Use settings.app_service_config_files instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "database_args" ] "Use settings.database.args instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "database_name" ] "Use settings.database.args.database instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "database_type" ] "Use settings.database.name instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "database_user" ] "Use settings.database.args.user instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "dynamic_thumbnails" ] "Use settings.dynamic_thumbnails instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "enable_metrics" ] "Use settings.enable_metrics instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "enable_registration" ] "Use settings.enable_registration instead") - (mkRemovedOptionModule [ "services" "matrix-synapse" "extraConfig" ] "Use settings instead.") - (mkRemovedOptionModule [ "services" "matrix-synapse" "listeners" ] "Use settings.listeners instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "extraConfig" ] "Use settings instead.") + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "listeners" ] "Use settings.listeners instead") + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "logConfig" ] "Use settings.log_config instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "max_image_pixels" ] "Use settings.max_image_pixels instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "max_upload_size" ] "Use settings.max_upload_size instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "presence" "enabled" ] "Use settings.presence.enabled instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "public_baseurl" ] "Use settings.public_baseurl instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "report_stats" ] "Use settings.report_stats instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "server_name" ] "Use settings.server_name instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "servers" ] "Use settings.trusted_key_servers instead.") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "tls_certificate_path" ] "Use settings.tls_certificate_path instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "tls_private_key_path" ] "Use settings.tls_private_key_path instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "turn_shared_secret" ] "Use settings.turn_shared_secret instead") - (mkRemovedOptionModule [ "services" "matrix-synapse" "turn_uris" ] "Use settings.turn_uris instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "turn_uris" ] "Use settings.turn_uris instead") + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "turn_user_lifetime" ] "Use settings.turn_user_lifetime instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "url_preview_enabled" ] "Use settings.url_preview_enabled instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "url_preview_ip_range_blacklist" ] "Use settings.url_preview_ip_range_blacklist instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "url_preview_ip_range_whitelist" ] "Use settings.url_preview_ip_range_whitelist instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "url_preview_url_blacklist" ] "Use settings.url_preview_url_blacklist instead") # options that are too specific to mention them explicitly in settings - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "account_threepid_delegates" "email" ] "Use settings.account_threepid_delegates.email instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "account_threepid_delegates" "msisdn" ] "Use settings.account_threepid_delegates.msisdn instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "allow_guest_access" ] "Use settings.allow_guest_access instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "bcrypt_rounds" ] "Use settings.bcrypt_rounds instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "enable_registration_captcha" ] "Use settings.enable_registration_captcha instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "event_cache_size" ] "Use settings.event_cache_size instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "federation_rc_concurrent" ] "Use settings.rc_federation.concurrent instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "federation_rc_reject_limit" ] "Use settings.rc_federation.reject_limit instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "federation_rc_sleep_delay" ] "Use settings.rc_federation.sleep_delay instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "federation_rc_sleep_limit" ] "Use settings.rc_federation.sleep_limit instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "federation_rc_window_size" ] "Use settings.rc_federation.window_size instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "key_refresh_interval" ] "Use settings.key_refresh_interval instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "rc_messages_burst_count" ] "Use settings.rc_messages.burst_count instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "rc_messages_per_second" ] "Use settings.rc_messages.per_second instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "recaptcha_private_key" ] "Use settings.recaptcha_private_key instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "recaptcha_public_key" ] "Use settings.recaptcha_public_key instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "redaction_retention_period" ] "Use settings.redaction_retention_period instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "room_prejoin_state" "additional_event_types" ] "Use settings.room_prejoin_state.additional_event_types instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "room_prejoin_state" @@ -416,12 +414,12 @@ in ] "Use settings.room_prejoin-state.disable_default_event_types instead") # Options that should be passed via extraConfigFiles, so they are not persisted into the nix store - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "macaroon_secret_key" ] "Pass this value via extraConfigFiles instead") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "matrix-synapse" "registration_shared_secret" @@ -433,12 +431,12 @@ in let listenerType = workerContext: - types.submodule ( + lib.types.submodule ( { config, ... }: { options = { - port = mkOption { - type = types.nullOr types.port; + port = lib.mkOption { + type = lib.types.nullOr lib.types.port; default = null; example = 8448; description = '' @@ -446,8 +444,8 @@ in ''; }; - bind_addresses = mkOption { - type = types.nullOr (types.listOf types.str); + bind_addresses = lib.mkOption { + type = lib.types.nullOr (lib.types.listOf lib.types.str); default = if config.path != null then null @@ -456,7 +454,7 @@ in "::1" "127.0.0.1" ]; - defaultText = literalExpression '' + defaultText = lib.literalExpression '' if path != null then null else @@ -465,7 +463,7 @@ in "127.0.0.1" ] ''; - example = literalExpression '' + example = lib.literalExpression '' [ "::" "0.0.0.0" @@ -476,8 +474,8 @@ in ''; }; - path = mkOption { - type = types.nullOr types.path; + path = lib.mkOption { + type = lib.types.nullOr lib.types.path; default = null; description = '' Unix domain socket path to bind this listener to. @@ -489,10 +487,10 @@ in ''; }; - mode = mkOption { - type = types.nullOr (types.strMatching "^[0,2-7]{3,4}$"); + mode = lib.mkOption { + type = lib.types.nullOr (lib.types.strMatching "^[0,2-7]{3,4}$"); default = if config.path != null then "660" else null; - defaultText = literalExpression '' + defaultText = lib.literalExpression '' if path != null then "660" else @@ -505,8 +503,8 @@ in apply = toDecimalFilePermission; }; - type = mkOption { - type = types.enum [ + type = lib.mkOption { + type = lib.types.enum [ "http" "manhole" "metrics" @@ -519,8 +517,8 @@ in ''; }; - tls = mkOption { - type = types.nullOr types.bool; + tls = lib.mkOption { + type = lib.types.nullOr lib.types.bool; default = if config.path != null then null else !workerContext; defaultText = '' Enabled for the main instance listener, unless it is configured with a UNIX domain socket path. @@ -535,8 +533,8 @@ in ''; }; - x_forwarded = mkOption { - type = types.bool; + x_forwarded = lib.mkOption { + type = lib.types.bool; default = config.path != null; defaultText = '' Enabled if the listener is configured with a UNIX domain socket path @@ -548,13 +546,13 @@ in ''; }; - resources = mkOption { - type = types.listOf ( - types.submodule { + resources = lib.mkOption { + type = lib.types.listOf ( + lib.types.submodule { options = { - names = mkOption { - type = types.listOf ( - types.enum [ + names = lib.mkOption { + type = lib.types.listOf ( + lib.types.enum [ "client" "consent" "federation" @@ -574,9 +572,9 @@ in "client" ]; }; - compress = mkOption { + compress = lib.mkOption { default = false; - type = types.bool; + type = lib.types.bool; description = '' Whether synapse should compress HTTP responses to clients that support it. This should be disabled if running synapse behind a load balancer @@ -596,10 +594,10 @@ in in { services.matrix-synapse = { - enable = mkEnableOption "matrix.org synapse, the reference homeserver"; + enable = lib.mkEnableOption "matrix.org synapse, the reference homeserver"; - enableRegistrationScript = mkOption { - type = types.bool; + enableRegistrationScript = lib.mkOption { + type = lib.types.bool; default = clientListener.bind_addresses != [ ]; example = false; defaultText = '' @@ -627,8 +625,8 @@ in ''; }; - configFile = mkOption { - type = types.path; + configFile = lib.mkOption { + type = lib.types.path; readOnly = true; description = '' Path to the configuration file on the target system. Useful to configure e.g. workers @@ -636,8 +634,8 @@ in ''; }; - package = mkOption { - type = types.package; + package = lib.mkOption { + type = lib.types.package; readOnly = true; description = '' Reference to the `matrix-synapse` wrapper with all extras @@ -657,12 +655,12 @@ in ''; }; - extras = mkOption { - type = types.listOf ( - types.enum (lib.attrNames pkgs.matrix-synapse-unwrapped.optional-dependencies) + extras = lib.mkOption { + type = lib.types.listOf ( + lib.types.enum (lib.attrNames pkgs.matrix-synapse-unwrapped.optional-dependencies) ); default = defaultExtras; - example = literalExpression '' + example = lib.literalExpression '' [ "cache-memory" # Provide statistics about caching memory consumption "jwt" # JSON Web Token authentication @@ -689,10 +687,10 @@ in ''; }; - plugins = mkOption { - type = types.listOf types.package; + plugins = lib.mkOption { + type = lib.types.listOf lib.types.package; default = [ ]; - example = literalExpression '' + example = lib.literalExpression '' with config.services.matrix-synapse.package.plugins; [ matrix-synapse-ldap3 matrix-synapse-pam @@ -703,16 +701,16 @@ in ''; }; - withJemalloc = mkOption { - type = types.bool; + withJemalloc = lib.mkOption { + type = lib.types.bool; default = true; description = '' Whether to preload jemalloc to reduce memory fragmentation and overall usage. ''; }; - dataDir = mkOption { - type = types.str; + dataDir = lib.mkOption { + type = lib.types.str; default = "/var/lib/matrix-synapse"; description = '' The directory where matrix-synapse stores its stateful data such as @@ -720,9 +718,9 @@ in ''; }; - log = mkOption { - type = types.attrsOf format.type; - defaultText = literalExpression defaultCommonLogConfigText; + log = lib.mkOption { + type = lib.types.attrsOf format.type; + defaultText = lib.literalExpression defaultCommonLogConfigText; description = '' Default configuration for the loggers used by `matrix-synapse` and its workers. The defaults are added with the default priority which means that @@ -763,7 +761,7 @@ in ''; }; - settings = mkOption { + settings = lib.mkOption { default = { }; description = '' The primary synapse configuration. See the @@ -773,7 +771,7 @@ in Secrets should be passed in by using the `extraConfigFiles` option. ''; type = - with types; + with lib.types; submodule { freeformType = format.type; options = { @@ -781,13 +779,13 @@ in # Do not add every available option here, they can be specified # by the user at their own discretion. This is a freeform type! - server_name = mkOption { - type = types.str; + server_name = lib.mkOption { + type = lib.types.str; example = "example.com"; default = config.networking.hostName; - defaultText = literalExpression "config.networking.hostName"; + defaultText = lib.literalExpression "config.networking.hostName"; description = '' - The domain name of the server, with optional explicit port. + The domain name of the server, with lib.optional explicit port. This is used by remote servers to look up the server address. This is also the last part of your UserID. @@ -795,16 +793,16 @@ in ''; }; - enable_registration = mkOption { - type = types.bool; + enable_registration = lib.mkOption { + type = lib.types.bool; default = false; description = '' Enable registration for new users. ''; }; - registration_shared_secret = mkOption { - type = types.nullOr types.str; + registration_shared_secret = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; description = '' If set, allows registration by anyone who also has the shared @@ -814,8 +812,8 @@ in ''; }; - macaroon_secret_key = mkOption { - type = types.nullOr types.str; + macaroon_secret_key = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; description = '' Secret key for authentication tokens. If none is specified, @@ -826,32 +824,32 @@ in ''; }; - enable_metrics = mkOption { - type = types.bool; + enable_metrics = lib.mkOption { + type = lib.types.bool; default = false; description = '' Enable collection and rendering of performance metrics ''; }; - report_stats = mkOption { - type = types.bool; + report_stats = lib.mkOption { + type = lib.types.bool; default = false; description = '' Whether or not to report anonymized homeserver usage statistics. ''; }; - signing_key_path = mkOption { - type = types.path; + signing_key_path = lib.mkOption { + type = lib.types.path; default = "${cfg.dataDir}/homeserver.signing.key"; description = '' Path to the signing key to sign messages with. ''; }; - pid_file = mkOption { - type = types.path; + pid_file = lib.mkOption { + type = lib.types.path; default = "/run/matrix-synapse.pid"; readOnly = true; description = '' @@ -859,8 +857,8 @@ in ''; }; - log_config = mkOption { - type = types.path; + log_config = lib.mkOption { + type = lib.types.path; default = genLogConfigFile "synapse"; defaultText = logConfigText "synapse"; description = '' @@ -868,8 +866,8 @@ in ''; }; - media_store_path = mkOption { - type = types.path; + media_store_path = lib.mkOption { + type = lib.types.path; default = if lib.versionAtLeast config.system.stateVersion "22.05" then "${cfg.dataDir}/media_store" @@ -881,8 +879,8 @@ in ''; }; - public_baseurl = mkOption { - type = types.nullOr types.str; + public_baseurl = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; example = "https://example.com:8448/"; description = '' @@ -890,8 +888,8 @@ in ''; }; - tls_certificate_path = mkOption { - type = types.nullOr types.str; + tls_certificate_path = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; example = "/var/lib/acme/example.com/fullchain.pem"; description = '' @@ -903,8 +901,8 @@ in ''; }; - tls_private_key_path = mkOption { - type = types.nullOr types.str; + tls_private_key_path = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; example = "/var/lib/acme/example.com/key.pem"; description = '' @@ -913,8 +911,8 @@ in ''; }; - presence.enabled = mkOption { - type = types.bool; + presence.enabled = lib.mkOption { + type = lib.types.bool; default = true; example = false; description = '' @@ -925,8 +923,8 @@ in ''; }; - listeners = mkOption { - type = types.listOf (listenerType false); + listeners = lib.mkOption { + type = lib.types.listOf (listenerType false); default = [ { @@ -966,13 +964,13 @@ in ''; }; - database.name = mkOption { - type = types.enum [ + database.name = lib.mkOption { + type = lib.types.enum [ "sqlite3" "psycopg2" ]; default = if versionAtLeast config.system.stateVersion "18.03" then "psycopg2" else "sqlite3"; - defaultText = literalExpression '' + defaultText = lib.literalExpression '' if versionAtLeast config.system.stateVersion "18.03" then "psycopg2" else "sqlite3" @@ -982,15 +980,15 @@ in ''; }; - database.args.database = mkOption { - type = types.str; + database.args.database = lib.mkOption { + type = lib.types.str; default = { sqlite3 = "${cfg.dataDir}/homeserver.db"; psycopg2 = "matrix-synapse"; } .${cfg.settings.database.name}; - defaultText = literalExpression '' + defaultText = lib.literalExpression '' { sqlite3 = "''${${options.services.matrix-synapse.dataDir}}/homeserver.db"; psycopg2 = "matrix-synapse"; @@ -1002,8 +1000,8 @@ in ''; }; - database.args.user = mkOption { - type = types.nullOr types.str; + database.args.user = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = { sqlite3 = null; @@ -1022,8 +1020,8 @@ in ''; }; - url_preview_enabled = mkOption { - type = types.bool; + url_preview_enabled = lib.mkOption { + type = lib.types.bool; default = true; example = false; description = '' @@ -1033,8 +1031,8 @@ in ''; }; - url_preview_ip_range_blacklist = mkOption { - type = types.listOf types.str; + url_preview_ip_range_blacklist = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ "10.0.0.0/8" "100.64.0.0/10" @@ -1062,8 +1060,8 @@ in ''; }; - url_preview_ip_range_whitelist = mkOption { - type = types.listOf types.str; + url_preview_ip_range_whitelist = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; description = '' List of IP address CIDR ranges that the URL preview spider is allowed @@ -1071,9 +1069,9 @@ in ''; }; - url_preview_url_blacklist = mkOption { + url_preview_url_blacklist = lib.mkOption { # FIXME revert to just `listOf (attrsOf str)` after some time(tm). - type = types.listOf ( + type = lib.types.listOf ( types.coercedTo types.str (const (throw '' Setting `config.services.matrix-synapse.settings.url_preview_url_blacklist` to a list of strings has never worked. Due to a bug, this was the type accepted @@ -1085,7 +1083,7 @@ in '')) (types.attrsOf types.str) ); default = [ ]; - example = literalExpression '' + example = lib.literalExpression '' [ { scheme = "http"; } # no http previews { netloc = "www.acme.com"; path = "/foo"; } # block http(s)://www.acme.com/foo @@ -1097,8 +1095,8 @@ in ''; }; - max_upload_size = mkOption { - type = types.str; + max_upload_size = lib.mkOption { + type = lib.types.str; default = "50M"; example = "100M"; description = '' @@ -1106,8 +1104,8 @@ in ''; }; - max_image_pixels = mkOption { - type = types.str; + max_image_pixels = lib.mkOption { + type = lib.types.str; default = "32M"; example = "64M"; description = '' @@ -1115,8 +1113,8 @@ in ''; }; - dynamic_thumbnails = mkOption { - type = types.bool; + dynamic_thumbnails = lib.mkOption { + type = lib.types.bool; default = false; example = true; description = '' @@ -1128,8 +1126,8 @@ in ''; }; - turn_uris = mkOption { - type = types.listOf types.str; + turn_uris = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; example = [ "turn:turn.example.com:3487?transport=udp" @@ -1141,10 +1139,10 @@ in The public URIs of the TURN server to give to clients ''; }; - turn_shared_secret = mkOption { - type = types.str; + turn_shared_secret = lib.mkOption { + type = lib.types.str; default = ""; - example = literalExpression '' + example = lib.literalExpression '' config.services.coturn.static-auth-secret ''; description = '' @@ -1154,13 +1152,13 @@ in ''; }; - trusted_key_servers = mkOption { - type = types.listOf ( + trusted_key_servers = lib.mkOption { + type = lib.types.listOf ( types.submodule { freeformType = format.type; options = { - server_name = mkOption { - type = types.str; + server_name = lib.mkOption { + type = lib.types.str; example = "matrix.org"; description = '' Hostname of the trusted server. @@ -1182,8 +1180,8 @@ in ''; }; - app_service_config_files = mkOption { - type = types.listOf types.path; + app_service_config_files = lib.mkOption { + type = lib.types.listOf lib.types.path; default = [ ]; description = '' A list of application service config file to use @@ -1191,11 +1189,11 @@ in }; redis = lib.mkOption { - type = types.submodule { + type = lib.types.submodule { freeformType = format.type; options = { enabled = lib.mkOption { - type = types.bool; + type = lib.types.bool; default = false; description = '' Whether to use redis support @@ -1241,14 +1239,14 @@ in for the available endpoints per worker application. ::: ''; - type = types.attrsOf ( - types.submodule ( + type = lib.types.attrsOf ( + lib.types.submodule ( { name, ... }: { freeformType = format.type; options = { worker_app = lib.mkOption { - type = types.enum [ + type = lib.types.enum [ "synapse.app.generic_worker" "synapse.app.media_repository" ]; @@ -1257,13 +1255,13 @@ in }; worker_listeners = lib.mkOption { default = [ ]; - type = types.listOf (listenerType true); + type = lib.types.listOf (listenerType true); description = '' List of ports that this worker should listen on, their purpose and their configuration. ''; }; worker_log_config = lib.mkOption { - type = types.path; + type = lib.types.path; default = genLogConfigFile "synapse-${name}"; defaultText = logConfigText "synapse-${name}"; description = '' @@ -1300,8 +1298,8 @@ in ''; }; - extraConfigFiles = mkOption { - type = types.listOf types.path; + extraConfigFiles = lib.mkOption { + type = lib.types.listOf lib.types.path; default = [ ]; description = '' Extra config files to include. @@ -1314,7 +1312,7 @@ in }; configureRedisLocally = lib.mkOption { - type = types.bool; + type = lib.types.bool; default = false; description = '' Whether to automatically configure a local redis server for matrix-synapse. @@ -1323,7 +1321,7 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { assertions = [ { @@ -1421,7 +1419,7 @@ in # default them, so they are additive services.matrix-synapse.extras = defaultExtras; - services.matrix-synapse.log = mapAttrsRecursive (const mkDefault) defaultCommonLogConfig; + services.matrix-synapse.log = lib.mapAttrsRecursive (lib.const lib.mkDefault) defaultCommonLogConfig; users.users.matrix-synapse = { group = "matrix-synapse"; @@ -1438,7 +1436,7 @@ in systemd.targets.matrix-synapse = lib.mkIf hasWorkers { description = "Synapse Matrix parent target"; wants = [ "network-online.target" ]; - after = [ "network-online.target" ] ++ optional hasLocalPostgresDB "postgresql.service"; + after = [ "network-online.target" ] ++ lib.optional hasLocalPostgresDB "postgresql.service"; wantedBy = [ "multi-user.target" ]; }; @@ -1450,17 +1448,17 @@ in partOf = [ "matrix-synapse.target" ]; wantedBy = [ "matrix-synapse.target" ]; unitConfig.ReloadPropagatedFrom = "matrix-synapse.target"; - requires = optional hasLocalPostgresDB "postgresql.service"; + requires = lib.optional hasLocalPostgresDB "postgresql.service"; } else { wants = [ "network-online.target" ]; - after = [ "network-online.target" ] ++ optional hasLocalPostgresDB "postgresql.service"; - requires = optional hasLocalPostgresDB "postgresql.service"; + after = [ "network-online.target" ] ++ lib.optional hasLocalPostgresDB "postgresql.service"; + requires = lib.optional hasLocalPostgresDB "postgresql.service"; wantedBy = [ "multi-user.target" ]; }; baseServiceConfig = { - environment = optionalAttrs (cfg.withJemalloc) { + environment = lib.optionalAttrs (cfg.withJemalloc) { LD_PRELOAD = "${pkgs.jemalloc}/lib/libjemalloc.so"; PYTHONMALLOC = "malloc"; }; @@ -1499,7 +1497,7 @@ in cfg.settings.media_store_path ] ++ (map (listener: dirOf listener.path) ( - filter (listener: listener.path != null) cfg.settings.listeners + lib.filter (listener: listener.path != null) cfg.settings.listeners )); RemoveIPC = true; RestrictAddressFamilies = [ @@ -1538,7 +1536,7 @@ in serviceConfig = { ExecStart = '' ${cfg.package}/bin/synapse_worker \ - ${concatMapStringsSep "\n " (x: "--config-path ${x} \\") ( + ${lib.concatMapStringsSep "\n " (x: "--config-path ${x} \\") ( [ configFile workerConfigFile @@ -1575,7 +1573,7 @@ in ]; ExecStart = '' ${cfg.package}/bin/synapse_homeserver \ - ${concatMapStringsSep "\n " (x: "--config-path ${x} \\") ( + ${lib.concatMapStringsSep "\n " (x: "--config-path ${x} \\") ( [ configFile ] ++ cfg.extraConfigFiles )} --keys-directory ${cfg.dataDir} @@ -1599,7 +1597,7 @@ in meta = { buildDocsInSandbox = false; doc = ./synapse.md; - maintainers = teams.matrix.members; + maintainers = lib.teams.matrix.members; }; } diff --git a/nixos/modules/services/misc/anki-sync-server.nix b/nixos/modules/services/misc/anki-sync-server.nix index 923811d845c82..5efa7e7227d36 100644 --- a/nixos/modules/services/misc/anki-sync-server.nix +++ b/nixos/modules/services/misc/anki-sync-server.nix @@ -4,18 +4,18 @@ pkgs, ... }: -with lib; let +let cfg = config.services.anki-sync-server; name = "anki-sync-server"; - specEscape = replaceStrings ["%"] ["%%"]; + specEscape = lib.replaceStrings ["%"] ["%%"]; usersWithIndexes = - lists.imap1 (i: user: { + lib.lists.imap1 (i: user: { i = i; user = user; }) cfg.users; - usersWithIndexesFile = filter (x: x.user.passwordFile != null) usersWithIndexes; - usersWithIndexesNoFile = filter (x: x.user.passwordFile == null && x.user.password != null) usersWithIndexes; + usersWithIndexesFile = lib.filter (x: x.user.passwordFile != null) usersWithIndexes; + usersWithIndexesNoFile = lib.filter (x: x.user.passwordFile == null && x.user.password != null) usersWithIndexes; anki-sync-server-run = pkgs.writeShellScript "anki-sync-server-run" '' # When services.anki-sync-server.users.passwordFile is set, # each password file is passed as a systemd credential, which is mounted in @@ -23,32 +23,32 @@ with lib; let # the credential files to pass them as environment variables to the Anki # sync server. ${ - concatMapStringsSep + lib.concatMapStringsSep "\n" (x: '' - read -r pass < "''${CREDENTIALS_DIRECTORY}/"${escapeShellArg x.user.username} - export SYNC_USER${toString x.i}=${escapeShellArg x.user.username}:"$pass" + read -r pass < "''${CREDENTIALS_DIRECTORY}/"${lib.escapeShellArg x.user.username} + export SYNC_USER${toString x.i}=${lib.escapeShellArg x.user.username}:"$pass" '') usersWithIndexesFile } # For users where services.anki-sync-server.users.password isn't set, # export passwords in environment variables in plaintext. ${ - concatMapStringsSep + lib.concatMapStringsSep "\n" - (x: ''export SYNC_USER${toString x.i}=${escapeShellArg x.user.username}:${escapeShellArg x.user.password}'') + (x: ''export SYNC_USER${toString x.i}=${lib.escapeShellArg x.user.username}:${lib.escapeShellArg x.user.password}'') usersWithIndexesNoFile } exec ${lib.getExe cfg.package} ''; in { options.services.anki-sync-server = { - enable = mkEnableOption "anki-sync-server"; + enable = lib.mkEnableOption "anki-sync-server"; - package = mkPackageOption pkgs "anki-sync-server" { }; + package = lib.mkPackageOption pkgs "anki-sync-server" { }; - address = mkOption { - type = types.str; + address = lib.mkOption { + type = lib.types.str; default = "::1"; description = '' IP address anki-sync-server listens to. @@ -56,34 +56,34 @@ in { ''; }; - port = mkOption { - type = types.port; + port = lib.mkOption { + type = lib.types.port; default = 27701; description = "Port number anki-sync-server listens to."; }; - baseDirectory = mkOption { - type = types.str; + baseDirectory = lib.mkOption { + type = lib.types.str; default = "%S/%N"; description = "Base directory where user(s) synchronized data will be stored."; }; - openFirewall = mkOption { + openFirewall = lib.mkOption { default = false; - type = types.bool; + type = lib.types.bool; description = "Whether to open the firewall for the specified port."; }; - users = mkOption { - type = with types; + users = lib.mkOption { + type = with lib.types; listOf (submodule { options = { - username = mkOption { + username = lib.mkOption { type = str; description = "User name accepted by anki-sync-server."; }; - password = mkOption { + password = lib.mkOption { type = nullOr str; default = null; description = '' @@ -94,7 +94,7 @@ in { a more secure option. ''; }; - passwordFile = mkOption { + passwordFile = lib.mkOption { type = nullOr path; default = null; description = '' @@ -109,14 +109,14 @@ in { }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { assertions = [ { assertion = (builtins.length usersWithIndexesFile) + (builtins.length usersWithIndexesNoFile) > 0; message = "At least one username-password pair must be set."; } ]; - networking.firewall.allowedTCPPorts = mkIf cfg.openFirewall [cfg.port]; + networking.firewall.allowedTCPPorts = lib.mkIf cfg.openFirewall [cfg.port]; systemd.services.anki-sync-server = { description = "anki-sync-server: Anki sync server built into Anki"; @@ -144,7 +144,7 @@ in { }; meta = { - maintainers = with maintainers; [telotortium]; + maintainers = with lib.maintainers; [telotortium]; doc = ./anki-sync-server.md; }; } diff --git a/nixos/modules/services/misc/atuin.nix b/nixos/modules/services/misc/atuin.nix index 59bdae6388704..347118626e952 100644 --- a/nixos/modules/services/misc/atuin.nix +++ b/nixos/modules/services/misc/atuin.nix @@ -5,7 +5,6 @@ ... }: let - inherit (lib) mkOption types mkIf; cfg = config.services.atuin; in { @@ -15,51 +14,51 @@ in package = lib.mkPackageOption pkgs "atuin" { }; - openRegistration = mkOption { - type = types.bool; + openRegistration = lib.mkOption { + type = lib.types.bool; default = false; description = "Allow new user registrations with the atuin server."; }; - path = mkOption { - type = types.str; + path = lib.mkOption { + type = lib.types.str; default = ""; description = "A path to prepend to all the routes of the server."; }; - host = mkOption { - type = types.str; + host = lib.mkOption { + type = lib.types.str; default = "127.0.0.1"; description = "The host address the atuin server should listen on."; }; - maxHistoryLength = mkOption { - type = types.int; + maxHistoryLength = lib.mkOption { + type = lib.types.int; default = 8192; description = "The max length of each history item the atuin server should store."; }; - port = mkOption { - type = types.port; + port = lib.mkOption { + type = lib.types.port; default = 8888; description = "The port the atuin server should listen on."; }; - openFirewall = mkOption { - type = types.bool; + openFirewall = lib.mkOption { + type = lib.types.bool; default = false; description = "Open ports in the firewall for the atuin server."; }; database = { - createLocally = mkOption { - type = types.bool; + createLocally = lib.mkOption { + type = lib.types.bool; default = true; description = "Create the database and database user locally."; }; - uri = mkOption { - type = types.nullOr types.str; + uri = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = "postgresql:///atuin?host=/run/postgresql"; example = "postgresql://atuin@localhost:5432/atuin"; description = '' @@ -71,7 +70,7 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { assertions = [ { assertion = cfg.database.createLocally -> config.services.postgresql.enable; @@ -79,7 +78,7 @@ in } ]; - services.postgresql = mkIf cfg.database.createLocally { + services.postgresql = lib.mkIf cfg.database.createLocally { enable = true; ensureUsers = [ { @@ -153,6 +152,6 @@ in }; }; - networking.firewall.allowedTCPPorts = mkIf cfg.openFirewall [ cfg.port ]; + networking.firewall.allowedTCPPorts = lib.mkIf cfg.openFirewall [ cfg.port ]; }; } diff --git a/nixos/modules/services/misc/autosuspend.nix b/nixos/modules/services/misc/autosuspend.nix index 53f872d3e040f..d5342356105af 100644 --- a/nixos/modules/services/misc/autosuspend.nix +++ b/nixos/modules/services/misc/autosuspend.nix @@ -5,34 +5,19 @@ ... }: let - inherit (lib) - mapAttrs' - nameValuePair - filterAttrs - types - mkEnableOption - mkPackageOption - mkOption - literalExpression - mkIf - flatten - maintainers - attrValues - ; - cfg = config.services.autosuspend; settingsFormat = pkgs.formats.ini { }; - checks = mapAttrs' (n: v: nameValuePair "check.${n}" (filterAttrs (_: v: v != null) v)) cfg.checks; - wakeups = mapAttrs' ( - n: v: nameValuePair "wakeup.${n}" (filterAttrs (_: v: v != null) v) + checks = lib.mapAttrs' (n: v: lib.nameValuePair "check.${n}" (lib.filterAttrs (_: v: v != null) v)) cfg.checks; + wakeups = lib.mapAttrs' ( + n: v: lib.nameValuePair "wakeup.${n}" (lib.filterAttrs (_: v: v != null) v) ) cfg.wakeups; # Whether the given check is enabled hasCheck = class: - (filterAttrs (n: v: v.enabled && (if v.class == null then n else v.class) == class) cfg.checks) + (lib.filterAttrs (n: v: v.enabled && (if v.class == null then n else v.class) == class) cfg.checks) != { }; # Dependencies needed by specific checks @@ -50,17 +35,17 @@ let autosuspend = cfg.package; - checkType = types.submodule { + checkType = lib.types.submodule { freeformType = settingsFormat.type.nestedTypes.elemType; - options.enabled = mkEnableOption "this activity check" // { + options.enabled = lib.mkEnableOption "this activity check" // { default = true; }; - options.class = mkOption { + options.class = lib.mkOption { default = null; type = - with types; + with lib.types; nullOr (enum [ "ActiveCalendarEvent" "ActiveConnection" @@ -87,17 +72,17 @@ let }; }; - wakeupType = types.submodule { + wakeupType = lib.types.submodule { freeformType = settingsFormat.type.nestedTypes.elemType; - options.enabled = mkEnableOption "this wake-up check" // { + options.enabled = lib.mkEnableOption "this wake-up check" // { default = true; }; - options.class = mkOption { + options.class = lib.mkOption { default = null; type = - with types; + with lib.types; nullOr (enum [ "Calendar" "Command" @@ -117,27 +102,27 @@ in { options = { services.autosuspend = { - enable = mkEnableOption "the autosuspend daemon"; + enable = lib.mkEnableOption "the autosuspend daemon"; - package = mkPackageOption pkgs "autosuspend" { }; + package = lib.mkPackageOption pkgs "autosuspend" { }; - settings = mkOption { - type = types.submodule { + settings = lib.mkOption { + type = lib.types.submodule { freeformType = settingsFormat.type.nestedTypes.elemType; options = { # Provide reasonable defaults for these two (required) options - suspend_cmd = mkOption { + suspend_cmd = lib.mkOption { default = "systemctl suspend"; - type = with types; str; + type = with lib.types; str; description = '' The command to execute in case the host shall be suspended. This line can contain additional command line arguments to the command to execute. ''; }; - wakeup_cmd = mkOption { + wakeup_cmd = lib.mkOption { default = ''sh -c 'echo 0 > /sys/class/rtc/rtc0/wakealarm && echo {timestamp:.0f} > /sys/class/rtc/rtc0/wakealarm' ''; - type = with types; str; + type = with lib.types; str; description = '' The command to execute for scheduling a wake up of the system. The given string is processed using Python’s `str.format()` and a format argument called `timestamp` @@ -148,7 +133,7 @@ in }; }; default = { }; - example = literalExpression '' + example = lib.literalExpression '' { enable = true; interval = 30; @@ -162,15 +147,15 @@ in ''; }; - checks = mkOption { + checks = lib.mkOption { default = { }; - type = with types; attrsOf checkType; + type = with lib.types; attrsOf checkType; description = '' Checks for activity. For more information, see: - - ''; - example = literalExpression '' + example = lib.literalExpression '' { # Basic activity check configuration. # The check class name is derived from the section header (Ping in this case). @@ -204,15 +189,15 @@ in ''; }; - wakeups = mkOption { + wakeups = lib.mkOption { default = { }; - type = with types; attrsOf wakeupType; + type = with lib.types; attrsOf wakeupType; description = '' Checks for wake up. For more information, see: - - ''; - example = literalExpression '' + example = lib.literalExpression '' { # Wake up checks reuse the same configuration mechanism as activity checks. Calendar = { @@ -224,13 +209,13 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { systemd.services.autosuspend = { description = "A daemon to suspend your server in case of inactivity"; documentation = [ "https://autosuspend.readthedocs.io/en/latest/systemd_integration.html" ]; wantedBy = [ "multi-user.target" ]; after = [ "network.target" ]; - path = flatten (attrValues (filterAttrs (n: _: hasCheck n) dependenciesForChecks)); + path = lib.flatten (lib.attrValues (lib.filterAttrs (n: _: hasCheck n) dependenciesForChecks)); serviceConfig = { ExecStart = ''${autosuspend}/bin/autosuspend -l ${autosuspend}/etc/autosuspend-logging.conf -c ${autosuspend-conf} daemon''; }; @@ -248,6 +233,6 @@ in }; meta = { - maintainers = with maintainers; [ xlambein ]; + maintainers = with lib.maintainers; [ xlambein ]; }; } diff --git a/nixos/modules/services/misc/blenderfarm.nix b/nixos/modules/services/misc/blenderfarm.nix index dbe6bcad13654..be0fb5f62bc0a 100644 --- a/nixos/modules/services/misc/blenderfarm.nix +++ b/nixos/modules/services/misc/blenderfarm.nix @@ -54,12 +54,12 @@ in Port = lib.mkOption { description = "Default port blendfarm server listens on."; default = 15000; - type = types.port; + type = lib.types.port; }; BroadcastPort = lib.mkOption { description = "Default port blendfarm server advertises itself on."; default = 16342; - type = types.port; + type = lib.types.port; }; BypassScriptUpdate = lib.mkOption { diff --git a/nixos/modules/services/misc/db-rest.nix b/nixos/modules/services/misc/db-rest.nix index 6cb9dd3da5772..bd2eab50a8945 100644 --- a/nixos/modules/services/misc/db-rest.nix +++ b/nixos/modules/services/misc/db-rest.nix @@ -5,97 +5,87 @@ ... }: let - inherit (lib) - mkOption - types - mkIf - mkMerge - mkDefault - mkEnableOption - mkPackageOption - maintainers - ; cfg = config.services.db-rest; in { options = { services.db-rest = { - enable = mkEnableOption "db-rest service"; + enable = lib.mkEnableOption "db-rest service"; - user = mkOption { - type = types.str; + user = lib.mkOption { + type = lib.types.str; default = "db-rest"; description = "User account under which db-rest runs."; }; - group = mkOption { - type = types.str; + group = lib.mkOption { + type = lib.types.str; default = "db-rest"; description = "Group under which db-rest runs."; }; - host = mkOption { - type = types.str; + host = lib.mkOption { + type = lib.types.str; default = "127.0.0.1"; description = "The host address the db-rest server should listen on."; }; - port = mkOption { - type = types.port; + port = lib.mkOption { + type = lib.types.port; default = 3000; description = "The port the db-rest server should listen on."; }; redis = { - enable = mkOption { - type = types.bool; + enable = lib.mkOption { + type = lib.types.bool; default = false; description = "Enable caching with redis for db-rest."; }; - createLocally = mkOption { - type = types.bool; + createLocally = lib.mkOption { + type = lib.types.bool; default = true; description = "Configure a local redis server for db-rest."; }; - host = mkOption { - type = with types; nullOr str; + host = lib.mkOption { + type = with lib.types; nullOr str; default = null; description = "Redis host."; }; - port = mkOption { - type = with types; nullOr port; + port = lib.mkOption { + type = with lib.types; nullOr port; default = null; description = "Redis port."; }; - user = mkOption { - type = with types; nullOr str; + user = lib.mkOption { + type = with lib.types; nullOr str; default = null; description = "Optional username used for authentication with redis."; }; - passwordFile = mkOption { - type = with types; nullOr path; + passwordFile = lib.mkOption { + type = with lib.types; nullOr path; default = null; example = "/run/keys/db-rest/pasword-redis-db"; description = "Path to a file containing the redis password."; }; - useSSL = mkOption { - type = types.bool; + useSSL = lib.mkOption { + type = lib.types.bool; default = true; description = "Use SSL if using a redis network connection."; }; }; - package = mkPackageOption pkgs "db-rest" { }; + package = lib.mkPackageOption pkgs "db-rest" { }; }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { assertions = [ { assertion = @@ -113,7 +103,7 @@ in } ]; - systemd.services.db-rest = mkMerge [ + systemd.services.db-rest = lib.mkMerge [ { description = "db-rest service"; after = [ "network.target" ] ++ lib.optional cfg.redis.createLocally "redis-db-rest.service"; @@ -135,7 +125,7 @@ in LoadCredential = lib.optional ( cfg.redis.enable && cfg.redis.passwordFile != null ) "REDIS_PASSWORD:${cfg.redis.passwordFile}"; - ExecStart = mkDefault "${cfg.package}/bin/db-rest"; + ExecStart = lib.mkDefault "${cfg.package}/bin/db-rest"; RemoveIPC = true; NoNewPrivileges = true; @@ -167,7 +157,7 @@ in PORT = toString cfg.port; }; } - (mkIf cfg.redis.enable ( + (lib.mkIf cfg.redis.enable ( if cfg.redis.createLocally then { environment.REDIS_URL = config.services.redis.servers.db-rest.unixSocket; } else @@ -201,5 +191,5 @@ in services.redis.servers.db-rest.enable = cfg.redis.enable && cfg.redis.createLocally; }; - meta.maintainers = with maintainers; [ marie ]; + meta.maintainers = with lib.maintainers; [ marie ]; } diff --git a/nixos/modules/services/misc/forgejo.nix b/nixos/modules/services/misc/forgejo.nix index 08e1b85a75443..f108845dd2706 100644 --- a/nixos/modules/services/misc/forgejo.nix +++ b/nixos/modules/services/misc/forgejo.nix @@ -31,117 +31,100 @@ let string: lib.replaceStrings [ "." "-" ] [ "_0X2E_" "_0X2D_" ] (lib.strings.toUpper string); in lib.flatten (lib.mapAttrsToList mkSecret cfg.secrets); - - inherit (lib) - literalExpression - mkChangedOptionModule - mkDefault - mkEnableOption - mkIf - mkMerge - mkOption - mkPackageOption - mkRemovedOptionModule - mkRenamedOptionModule - optionalAttrs - optionals - optionalString - types - ; in { imports = [ - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "forgejo" "appName" ] [ "services" "forgejo" "settings" "DEFAULT" "APP_NAME" ] ) - (mkRemovedOptionModule [ "services" "forgejo" "extraConfig" ] + (lib.mkRemovedOptionModule [ "services" "forgejo" "extraConfig" ] "services.forgejo.extraConfig has been removed. Please use the freeform services.forgejo.settings option instead" ) - (mkRemovedOptionModule [ "services" "forgejo" "database" "password" ] + (lib.mkRemovedOptionModule [ "services" "forgejo" "database" "password" ] "services.forgejo.database.password has been removed. Please use services.forgejo.database.passwordFile instead" ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "forgejo" "mailerPasswordFile" ] [ "services" "forgejo" "secrets" "mailer" "PASSWD" ] ) # copied from services.gitea; remove at some point - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "forgejo" "cookieSecure" ] [ "services" "forgejo" "settings" "session" "COOKIE_SECURE" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "forgejo" "disableRegistration" ] [ "services" "forgejo" "settings" "service" "DISABLE_REGISTRATION" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "forgejo" "domain" ] [ "services" "forgejo" "settings" "server" "DOMAIN" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "forgejo" "httpAddress" ] [ "services" "forgejo" "settings" "server" "HTTP_ADDR" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "forgejo" "httpPort" ] [ "services" "forgejo" "settings" "server" "HTTP_PORT" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "forgejo" "log" "level" ] [ "services" "forgejo" "settings" "log" "LEVEL" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "forgejo" "log" "rootPath" ] [ "services" "forgejo" "settings" "log" "ROOT_PATH" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "forgejo" "rootUrl" ] [ "services" "forgejo" "settings" "server" "ROOT_URL" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "forgejo" "ssh" "clonePort" ] [ "services" "forgejo" "settings" "server" "SSH_PORT" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "forgejo" "staticRootPath" ] [ "services" "forgejo" "settings" "server" "STATIC_ROOT_PATH" ] ) - (mkChangedOptionModule + (lib.mkChangedOptionModule [ "services" "forgejo" "enableUnixSocket" ] [ "services" "forgejo" "settings" "server" "PROTOCOL" ] (config: if config.services.forgejo.enableUnixSocket then "http+unix" else "http") ) - (mkRemovedOptionModule [ "services" "forgejo" "ssh" "enable" ] + (lib.mkRemovedOptionModule [ "services" "forgejo" "ssh" "enable" ] "services.forgejo.ssh.enable has been migrated into freeform setting services.forgejo.settings.server.DISABLE_SSH. Keep in mind that the setting is inverted" ) ]; options = { services.forgejo = { - enable = mkEnableOption "Forgejo, a software forge"; + enable = lib.mkEnableOption "Forgejo, a software forge"; - package = mkPackageOption pkgs "forgejo-lts" { }; + package = lib.mkPackageOption pkgs "forgejo-lts" { }; - useWizard = mkOption { + useWizard = lib.mkOption { default = false; - type = types.bool; + type = lib.types.bool; description = '' Whether to use the built-in installation wizard instead of declaratively managing the {file}`app.ini` config file in nix. ''; }; - stateDir = mkOption { + stateDir = lib.mkOption { default = "/var/lib/forgejo"; - type = types.str; + type = lib.types.str; description = "Forgejo data directory."; }; - customDir = mkOption { + customDir = lib.mkOption { default = "${cfg.stateDir}/custom"; - defaultText = literalExpression ''"''${config.${opt.stateDir}}/custom"''; - type = types.str; + defaultText = lib.literalExpression ''"''${config.${opt.stateDir}}/custom"''; + type = lib.types.str; description = '' Base directory for custom templates and other options. @@ -150,21 +133,21 @@ in ''; }; - user = mkOption { - type = types.str; + user = lib.mkOption { + type = lib.types.str; default = "forgejo"; description = "User account under which Forgejo runs."; }; - group = mkOption { - type = types.str; + group = lib.mkOption { + type = lib.types.str; default = "forgejo"; description = "Group under which Forgejo runs."; }; database = { - type = mkOption { - type = types.enum [ + type = lib.mkOption { + type = lib.types.enum [ "sqlite3" "mysql" "postgres" @@ -174,16 +157,16 @@ in description = "Database engine to use."; }; - host = mkOption { - type = types.str; + host = lib.mkOption { + type = lib.types.str; default = "127.0.0.1"; description = "Database host address."; }; - port = mkOption { - type = types.port; + port = lib.mkOption { + type = lib.types.port; default = if usePostgresql then pg.settings.port else 3306; - defaultText = literalExpression '' + defaultText = lib.literalExpression '' if config.${opt.database.type} != "postgresql" then 3306 else 5432 @@ -191,20 +174,20 @@ in description = "Database host port."; }; - name = mkOption { - type = types.str; + name = lib.mkOption { + type = lib.types.str; default = "forgejo"; description = "Database name."; }; - user = mkOption { - type = types.str; + user = lib.mkOption { + type = lib.types.str; default = "forgejo"; description = "Database user."; }; - passwordFile = mkOption { - type = types.nullOr types.path; + passwordFile = lib.mkOption { + type = lib.types.nullOr lib.types.path; default = null; example = "/run/keys/forgejo-dbpassword"; description = '' @@ -213,8 +196,8 @@ in ''; }; - socket = mkOption { - type = types.nullOr types.path; + socket = lib.mkOption { + type = lib.types.nullOr lib.types.path; default = if (cfg.database.createDatabase && usePostgresql) then "/run/postgresql" @@ -222,30 +205,30 @@ in "/run/mysqld/mysqld.sock" else null; - defaultText = literalExpression "null"; + defaultText = lib.literalExpression "null"; example = "/run/mysqld/mysqld.sock"; description = "Path to the unix socket file to use for authentication."; }; - path = mkOption { - type = types.str; + path = lib.mkOption { + type = lib.types.str; default = "${cfg.stateDir}/data/forgejo.db"; - defaultText = literalExpression ''"''${config.${opt.stateDir}}/data/forgejo.db"''; + defaultText = lib.literalExpression ''"''${config.${opt.stateDir}}/data/forgejo.db"''; description = "Path to the sqlite3 database file."; }; - createDatabase = mkOption { - type = types.bool; + createDatabase = lib.mkOption { + type = lib.types.bool; default = true; description = "Whether to create a local database automatically."; }; }; dump = { - enable = mkEnableOption "periodic dumps via the [built-in {command}`dump` command](https://forgejo.org/docs/latest/admin/command-line/#dump)"; + enable = lib.mkEnableOption "periodic dumps via the [built-in {command}`dump` command](https://forgejo.org/docs/latest/admin/command-line/#dump)"; - interval = mkOption { - type = types.str; + interval = lib.mkOption { + type = lib.types.str; default = "04:31"; example = "hourly"; description = '' @@ -256,15 +239,15 @@ in ''; }; - backupDir = mkOption { - type = types.str; + backupDir = lib.mkOption { + type = lib.types.str; default = "${cfg.stateDir}/dump"; - defaultText = literalExpression ''"''${config.${opt.stateDir}}/dump"''; + defaultText = lib.literalExpression ''"''${config.${opt.stateDir}}/dump"''; description = "Path to the directory where the dump archives will be stored."; }; - type = mkOption { - type = types.enum [ + type = lib.mkOption { + type = lib.types.enum [ "zip" "tar" "tar.sz" @@ -279,8 +262,8 @@ in description = "Archive format used to store the dump file."; }; - file = mkOption { - type = types.nullOr types.str; + file = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; description = "Filename to be used for the dump. If `null` a default name is chosen by forgejo."; example = "forgejo-dump"; @@ -288,34 +271,34 @@ in }; lfs = { - enable = mkOption { - type = types.bool; + enable = lib.mkOption { + type = lib.types.bool; default = false; description = "Enables git-lfs support."; }; - contentDir = mkOption { - type = types.str; + contentDir = lib.mkOption { + type = lib.types.str; default = "${cfg.stateDir}/data/lfs"; - defaultText = literalExpression ''"''${config.${opt.stateDir}}/data/lfs"''; + defaultText = lib.literalExpression ''"''${config.${opt.stateDir}}/data/lfs"''; description = "Where to store LFS files."; }; }; - repositoryRoot = mkOption { - type = types.str; + repositoryRoot = lib.mkOption { + type = lib.types.str; default = "${cfg.stateDir}/repositories"; - defaultText = literalExpression ''"''${config.${opt.stateDir}}/repositories"''; + defaultText = lib.literalExpression ''"''${config.${opt.stateDir}}/repositories"''; description = "Path to the git repositories."; }; - settings = mkOption { + settings = lib.mkOption { default = { }; description = '' Free-form settings written directly to the `app.ini` configfile file. Refer to for supported values. ''; - example = literalExpression '' + example = lib.literalExpression '' { DEFAULT = { RUN_MODE = "dev"; @@ -336,19 +319,19 @@ in }; } ''; - type = types.submodule { + type = lib.types.submodule { freeformType = format.type; options = { log = { - ROOT_PATH = mkOption { + ROOT_PATH = lib.mkOption { default = "${cfg.stateDir}/log"; - defaultText = literalExpression ''"''${config.${opt.stateDir}}/log"''; - type = types.str; + defaultText = lib.literalExpression ''"''${config.${opt.stateDir}}/log"''; + type = lib.types.str; description = "Root path for log files."; }; - LEVEL = mkOption { + LEVEL = lib.mkOption { default = "Info"; - type = types.enum [ + type = lib.types.enum [ "Trace" "Debug" "Info" @@ -361,8 +344,8 @@ in }; server = { - PROTOCOL = mkOption { - type = types.enum [ + PROTOCOL = lib.mkOption { + type = lib.types.enum [ "http" "https" "fcgi" @@ -373,52 +356,52 @@ in description = ''Listen protocol. `+unix` means "over unix", not "in addition to."''; }; - HTTP_ADDR = mkOption { - type = types.either types.str types.path; + HTTP_ADDR = lib.mkOption { + type = lib.types.either lib.types.str lib.types.path; default = if lib.hasSuffix "+unix" cfg.settings.server.PROTOCOL then "/run/forgejo/forgejo.sock" else "0.0.0.0"; - defaultText = literalExpression ''if lib.hasSuffix "+unix" cfg.settings.server.PROTOCOL then "/run/forgejo/forgejo.sock" else "0.0.0.0"''; + defaultText = lib.literalExpression ''if lib.hasSuffix "+unix" cfg.settings.server.PROTOCOL then "/run/forgejo/forgejo.sock" else "0.0.0.0"''; description = "Listen address. Must be a path when using a unix socket."; }; - HTTP_PORT = mkOption { - type = types.port; + HTTP_PORT = lib.mkOption { + type = lib.types.port; default = 3000; description = "Listen port. Ignored when using a unix socket."; }; - DOMAIN = mkOption { - type = types.str; + DOMAIN = lib.mkOption { + type = lib.types.str; default = "localhost"; description = "Domain name of your server."; }; - ROOT_URL = mkOption { - type = types.str; + ROOT_URL = lib.mkOption { + type = lib.types.str; default = "http://${cfg.settings.server.DOMAIN}:${toString cfg.settings.server.HTTP_PORT}/"; - defaultText = literalExpression ''"http://''${config.services.forgejo.settings.server.DOMAIN}:''${toString config.services.forgejo.settings.server.HTTP_PORT}/"''; + defaultText = lib.literalExpression ''"http://''${config.services.forgejo.settings.server.DOMAIN}:''${toString config.services.forgejo.settings.server.HTTP_PORT}/"''; description = "Full public URL of Forgejo server."; }; - STATIC_ROOT_PATH = mkOption { - type = types.either types.str types.path; + STATIC_ROOT_PATH = lib.mkOption { + type = lib.types.either lib.types.str lib.types.path; default = cfg.package.data; - defaultText = literalExpression "config.${opt.package}.data"; + defaultText = lib.literalExpression "config.${opt.package}.data"; example = "/var/lib/forgejo/data"; description = "Upper level of template and static files path."; }; - DISABLE_SSH = mkOption { - type = types.bool; + DISABLE_SSH = lib.mkOption { + type = lib.types.bool; default = false; description = "Disable external SSH feature."; }; - SSH_PORT = mkOption { - type = types.port; + SSH_PORT = lib.mkOption { + type = lib.types.port; default = 22; example = 2222; description = '' @@ -430,8 +413,8 @@ in }; session = { - COOKIE_SECURE = mkOption { - type = types.bool; + COOKIE_SECURE = lib.mkOption { + type = lib.types.bool; default = false; description = '' Marks session cookies as "secure" as a hint for browsers to only send @@ -443,7 +426,7 @@ in }; }; - secrets = mkOption { + secrets = lib.mkOption { default = { }; description = '' This is a small wrapper over systemd's `LoadCredential`. @@ -461,7 +444,7 @@ in Keys specified here take priority over the ones in {option}`services.forgejo.settings`! ::: ''; - example = literalExpression '' + example = lib.literalExpression '' { metrics = { TOKEN = "/run/keys/forgejo-metrics-token"; @@ -475,15 +458,15 @@ in }; } ''; - type = types.submodule { - freeformType = with types; attrsOf (attrsOf path); + type = lib.types.submodule { + freeformType = with lib.types; attrsOf (attrsOf path); options = { }; }; }; }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { assertions = [ { assertion = cfg.database.createDatabase -> useSqlite || cfg.database.user == cfg.user; @@ -502,16 +485,16 @@ in services.forgejo.settings = { DEFAULT = { - RUN_MODE = mkDefault "prod"; - RUN_USER = mkDefault cfg.user; - WORK_PATH = mkDefault cfg.stateDir; + RUN_MODE = lib.mkDefault "prod"; + RUN_USER = lib.mkDefault cfg.user; + WORK_PATH = lib.mkDefault cfg.stateDir; }; - database = mkMerge [ + database = lib.mkMerge [ { DB_TYPE = cfg.database.type; } - (mkIf (useMysql || usePostgresql) { + (lib.mkIf (useMysql || usePostgresql) { HOST = if cfg.database.socket != null then cfg.database.socket @@ -520,10 +503,10 @@ in NAME = cfg.database.name; USER = cfg.database.user; }) - (mkIf useSqlite { + (lib.mkIf useSqlite { PATH = cfg.database.path; }) - (mkIf usePostgresql { + (lib.mkIf usePostgresql { SSL_MODE = "disable"; }) ]; @@ -532,19 +515,19 @@ in ROOT = cfg.repositoryRoot; }; - server = mkIf cfg.lfs.enable { + server = lib.mkIf cfg.lfs.enable { LFS_START_SERVER = true; }; session = { - COOKIE_NAME = mkDefault "session"; + COOKIE_NAME = lib.mkDefault "session"; }; security = { INSTALL_LOCK = true; }; - lfs = mkIf cfg.lfs.enable { + lfs = lib.mkIf cfg.lfs.enable { PATH = cfg.lfs.contentDir; }; }; @@ -559,17 +542,17 @@ in JWT_SECRET = "${cfg.customDir}/conf/oauth2_jwt_secret"; }; - database = mkIf (cfg.database.passwordFile != null) { + database = lib.mkIf (cfg.database.passwordFile != null) { PASSWD = cfg.database.passwordFile; }; - server = mkIf cfg.lfs.enable { + server = lib.mkIf cfg.lfs.enable { LFS_JWT_SECRET = "${cfg.customDir}/conf/lfs_jwt_secret"; }; }; - services.postgresql = optionalAttrs (usePostgresql && cfg.database.createDatabase) { - enable = mkDefault true; + services.postgresql = lib.optionalAttrs (usePostgresql && cfg.database.createDatabase) { + enable = lib.mkDefault true; ensureDatabases = [ cfg.database.name ]; ensureUsers = [ @@ -580,9 +563,9 @@ in ]; }; - services.mysql = optionalAttrs (useMysql && cfg.database.createDatabase) { - enable = mkDefault true; - package = mkDefault pkgs.mariadb; + services.mysql = lib.optionalAttrs (useMysql && cfg.database.createDatabase) { + enable = lib.mkDefault true; + package = lib.mkDefault pkgs.mariadb; ensureDatabases = [ cfg.database.name ]; ensureUsers = [ @@ -620,12 +603,12 @@ in "L+ '${cfg.stateDir}/conf/locale' - - - - ${cfg.package.out}/locale" ] - ++ optionals cfg.lfs.enable [ + ++ lib.optionals cfg.lfs.enable [ "d '${cfg.lfs.contentDir}' 0750 ${cfg.user} ${cfg.group} - -" "z '${cfg.lfs.contentDir}' 0750 ${cfg.user} ${cfg.group} - -" ]; - systemd.services.forgejo-secrets = mkIf (!cfg.useWizard) { + systemd.services.forgejo-secrets = lib.mkIf (!cfg.useWizard) { description = "Forgejo secret bootstrap helper"; script = '' if [ ! -s '${cfg.secrets.security.SECRET_KEY}' ]; then @@ -636,7 +619,7 @@ in ${exe} generate secret JWT_SECRET > '${cfg.secrets.oauth2.JWT_SECRET}' fi - ${optionalString cfg.lfs.enable '' + ${lib.optionalString cfg.lfs.enable '' if [ ! -s '${cfg.secrets.server.LFS_JWT_SECRET}' ]; then ${exe} generate secret LFS_JWT_SECRET > '${cfg.secrets.server.LFS_JWT_SECRET}' fi @@ -662,23 +645,23 @@ in [ "network.target" ] - ++ optionals usePostgresql [ + ++ lib.optionals usePostgresql [ "postgresql.service" ] - ++ optionals useMysql [ + ++ lib.optionals useMysql [ "mysql.service" ] - ++ optionals (!cfg.useWizard) [ + ++ lib.optionals (!cfg.useWizard) [ "forgejo-secrets.service" ]; requires = - optionals (cfg.database.createDatabase && usePostgresql) [ + lib.optionals (cfg.database.createDatabase && usePostgresql) [ "postgresql.service" ] - ++ optionals (cfg.database.createDatabase && useMysql) [ + ++ lib.optionals (cfg.database.createDatabase && useMysql) [ "mysql.service" ] - ++ optionals (!cfg.useWizard) [ + ++ lib.optionals (!cfg.useWizard) [ "forgejo-secrets.service" ]; wantedBy = [ "multi-user.target" ]; @@ -696,7 +679,7 @@ in # lfs_jwt_secret. # We have to consider this to stay compatible with older installations. preStart = '' - ${optionalString (!cfg.useWizard) '' + ${lib.optionalString (!cfg.useWizard) '' function forgejo_setup { config='${cfg.customDir}/conf/app.ini' cp -f '${format.generate "app.ini" cfg.settings}' "$config" @@ -789,11 +772,11 @@ in } // lib.listToAttrs (map (e: lib.nameValuePair e.env "%d/${e.env}") secrets); }; - services.openssh.settings.AcceptEnv = mkIf ( + services.openssh.settings.AcceptEnv = lib.mkIf ( !cfg.settings.server.START_SSH_SERVER or false ) "GIT_PROTOCOL"; - users.users = mkIf (cfg.user == "forgejo") { + users.users = lib.mkIf (cfg.user == "forgejo") { forgejo = { home = cfg.stateDir; useDefaultShell = true; @@ -802,11 +785,11 @@ in }; }; - users.groups = mkIf (cfg.group == "forgejo") { + users.groups = lib.mkIf (cfg.group == "forgejo") { forgejo = { }; }; - systemd.services.forgejo-dump = mkIf cfg.dump.enable { + systemd.services.forgejo-dump = lib.mkIf cfg.dump.enable { description = "forgejo dump"; after = [ "forgejo.service" ]; path = [ cfg.package ]; @@ -823,12 +806,12 @@ in User = cfg.user; ExecStart = "${exe} dump --type ${cfg.dump.type}" - + optionalString (cfg.dump.file != null) " --file ${cfg.dump.file}"; + + lib.optionalString (cfg.dump.file != null) " --file ${cfg.dump.file}"; WorkingDirectory = cfg.dump.backupDir; }; }; - systemd.timers.forgejo-dump = mkIf cfg.dump.enable { + systemd.timers.forgejo-dump = lib.mkIf cfg.dump.enable { description = "Forgejo dump timer"; partOf = [ "forgejo-dump.service" ]; wantedBy = [ "timers.target" ]; diff --git a/nixos/modules/services/misc/gitea.nix b/nixos/modules/services/misc/gitea.nix index d43250c882683..50be40aecfcf2 100644 --- a/nixos/modules/services/misc/gitea.nix +++ b/nixos/modules/services/misc/gitea.nix @@ -1,7 +1,5 @@ { config, lib, options, pkgs, ... }: -with lib; - let cfg = config.services.gitea; opt = options.services.gitea; @@ -17,91 +15,91 @@ let RUN_MODE = prod WORK_PATH = ${cfg.stateDir} - ${generators.toINI {} cfg.settings} + ${lib.generators.toINI {} cfg.settings} - ${optionalString (cfg.extraConfig != null) cfg.extraConfig} + ${lib.optionalString (cfg.extraConfig != null) cfg.extraConfig} ''; in { imports = [ - (mkRenamedOptionModule [ "services" "gitea" "cookieSecure" ] [ "services" "gitea" "settings" "session" "COOKIE_SECURE" ]) - (mkRenamedOptionModule [ "services" "gitea" "disableRegistration" ] [ "services" "gitea" "settings" "service" "DISABLE_REGISTRATION" ]) - (mkRenamedOptionModule [ "services" "gitea" "domain" ] [ "services" "gitea" "settings" "server" "DOMAIN" ]) - (mkRenamedOptionModule [ "services" "gitea" "httpAddress" ] [ "services" "gitea" "settings" "server" "HTTP_ADDR" ]) - (mkRenamedOptionModule [ "services" "gitea" "httpPort" ] [ "services" "gitea" "settings" "server" "HTTP_PORT" ]) - (mkRenamedOptionModule [ "services" "gitea" "log" "level" ] [ "services" "gitea" "settings" "log" "LEVEL" ]) - (mkRenamedOptionModule [ "services" "gitea" "log" "rootPath" ] [ "services" "gitea" "settings" "log" "ROOT_PATH" ]) - (mkRenamedOptionModule [ "services" "gitea" "rootUrl" ] [ "services" "gitea" "settings" "server" "ROOT_URL" ]) - (mkRenamedOptionModule [ "services" "gitea" "ssh" "clonePort" ] [ "services" "gitea" "settings" "server" "SSH_PORT" ]) - (mkRenamedOptionModule [ "services" "gitea" "staticRootPath" ] [ "services" "gitea" "settings" "server" "STATIC_ROOT_PATH" ]) - - (mkChangedOptionModule [ "services" "gitea" "enableUnixSocket" ] [ "services" "gitea" "settings" "server" "PROTOCOL" ] ( + (lib.mkRenamedOptionModule [ "services" "gitea" "cookieSecure" ] [ "services" "gitea" "settings" "session" "COOKIE_SECURE" ]) + (lib.mkRenamedOptionModule [ "services" "gitea" "disableRegistration" ] [ "services" "gitea" "settings" "service" "DISABLE_REGISTRATION" ]) + (lib.mkRenamedOptionModule [ "services" "gitea" "domain" ] [ "services" "gitea" "settings" "server" "DOMAIN" ]) + (lib.mkRenamedOptionModule [ "services" "gitea" "httpAddress" ] [ "services" "gitea" "settings" "server" "HTTP_ADDR" ]) + (lib.mkRenamedOptionModule [ "services" "gitea" "httpPort" ] [ "services" "gitea" "settings" "server" "HTTP_PORT" ]) + (lib.mkRenamedOptionModule [ "services" "gitea" "log" "level" ] [ "services" "gitea" "settings" "log" "LEVEL" ]) + (lib.mkRenamedOptionModule [ "services" "gitea" "log" "rootPath" ] [ "services" "gitea" "settings" "log" "ROOT_PATH" ]) + (lib.mkRenamedOptionModule [ "services" "gitea" "rootUrl" ] [ "services" "gitea" "settings" "server" "ROOT_URL" ]) + (lib.mkRenamedOptionModule [ "services" "gitea" "ssh" "clonePort" ] [ "services" "gitea" "settings" "server" "SSH_PORT" ]) + (lib.mkRenamedOptionModule [ "services" "gitea" "staticRootPath" ] [ "services" "gitea" "settings" "server" "STATIC_ROOT_PATH" ]) + + (lib.mkChangedOptionModule [ "services" "gitea" "enableUnixSocket" ] [ "services" "gitea" "settings" "server" "PROTOCOL" ] ( config: if config.services.gitea.enableUnixSocket then "http+unix" else "http" )) - (mkRemovedOptionModule [ "services" "gitea" "ssh" "enable" ] "services.gitea.ssh.enable has been migrated into freeform setting services.gitea.settings.server.DISABLE_SSH. Keep in mind that the setting is inverted") + (lib.mkRemovedOptionModule [ "services" "gitea" "ssh" "enable" ] "services.gitea.ssh.enable has been migrated into freeform setting services.gitea.settings.server.DISABLE_SSH. Keep in mind that the setting is inverted") ]; options = { services.gitea = { - enable = mkOption { + enable = lib.mkOption { default = false; - type = types.bool; + type = lib.types.bool; description = "Enable Gitea Service."; }; - package = mkPackageOption pkgs "gitea" { }; + package = lib.mkPackageOption pkgs "gitea" { }; - useWizard = mkOption { + useWizard = lib.mkOption { default = false; - type = types.bool; + type = lib.types.bool; description = "Do not generate a configuration and use gitea' installation wizard instead. The first registered user will be administrator."; }; - stateDir = mkOption { + stateDir = lib.mkOption { default = "/var/lib/gitea"; - type = types.str; + type = lib.types.str; description = "Gitea data directory."; }; - customDir = mkOption { + customDir = lib.mkOption { default = "${cfg.stateDir}/custom"; - defaultText = literalExpression ''"''${config.${opt.stateDir}}/custom"''; - type = types.str; + defaultText = lib.literalExpression ''"''${config.${opt.stateDir}}/custom"''; + type = lib.types.str; description = "Gitea custom directory. Used for config, custom templates and other options."; }; - user = mkOption { - type = types.str; + user = lib.mkOption { + type = lib.types.str; default = "gitea"; description = "User account under which gitea runs."; }; - group = mkOption { - type = types.str; + group = lib.mkOption { + type = lib.types.str; default = "gitea"; description = "Group under which gitea runs."; }; database = { - type = mkOption { - type = types.enum [ "sqlite3" "mysql" "postgres" ]; + type = lib.mkOption { + type = lib.types.enum [ "sqlite3" "mysql" "postgres" ]; example = "mysql"; default = "sqlite3"; description = "Database engine to use."; }; - host = mkOption { - type = types.str; + host = lib.mkOption { + type = lib.types.str; default = "127.0.0.1"; description = "Database host address."; }; - port = mkOption { - type = types.port; + port = lib.mkOption { + type = lib.types.port; default = if usePostgresql then pg.settings.port else 3306; - defaultText = literalExpression '' + defaultText = lib.literalExpression '' if config.${opt.database.type} != "postgresql" then 3306 else 5432 @@ -109,20 +107,20 @@ in description = "Database host port."; }; - name = mkOption { - type = types.str; + name = lib.mkOption { + type = lib.types.str; default = "gitea"; description = "Database name."; }; - user = mkOption { - type = types.str; + user = lib.mkOption { + type = lib.types.str; default = "gitea"; description = "Database user."; }; - password = mkOption { - type = types.str; + password = lib.mkOption { + type = lib.types.str; default = ""; description = '' The password corresponding to {option}`database.user`. @@ -131,8 +129,8 @@ in ''; }; - passwordFile = mkOption { - type = types.nullOr types.path; + passwordFile = lib.mkOption { + type = lib.types.nullOr lib.types.path; default = null; example = "/run/keys/gitea-dbpassword"; description = '' @@ -141,31 +139,31 @@ in ''; }; - socket = mkOption { - type = types.nullOr types.path; + socket = lib.mkOption { + type = lib.types.nullOr lib.types.path; default = if (cfg.database.createDatabase && usePostgresql) then "/run/postgresql" else if (cfg.database.createDatabase && useMysql) then "/run/mysqld/mysqld.sock" else null; - defaultText = literalExpression "null"; + defaultText = lib.literalExpression "null"; example = "/run/mysqld/mysqld.sock"; description = "Path to the unix socket file to use for authentication."; }; - path = mkOption { - type = types.str; + path = lib.mkOption { + type = lib.types.str; default = "${cfg.stateDir}/data/gitea.db"; - defaultText = literalExpression ''"''${config.${opt.stateDir}}/data/gitea.db"''; + defaultText = lib.literalExpression ''"''${config.${opt.stateDir}}/data/gitea.db"''; description = "Path to the sqlite3 database file."; }; - createDatabase = mkOption { - type = types.bool; + createDatabase = lib.mkOption { + type = lib.types.bool; default = true; description = "Whether to create a local database automatically."; }; }; dump = { - enable = mkOption { - type = types.bool; + enable = lib.mkOption { + type = lib.types.bool; default = false; description = '' Enable a timer that runs gitea dump to generate backup-files of the @@ -173,8 +171,8 @@ in ''; }; - interval = mkOption { - type = types.str; + interval = lib.mkOption { + type = lib.types.str; default = "04:31"; example = "hourly"; description = '' @@ -185,21 +183,21 @@ in ''; }; - backupDir = mkOption { - type = types.str; + backupDir = lib.mkOption { + type = lib.types.str; default = "${cfg.stateDir}/dump"; - defaultText = literalExpression ''"''${config.${opt.stateDir}}/dump"''; + defaultText = lib.literalExpression ''"''${config.${opt.stateDir}}/dump"''; description = "Path to the dump files."; }; - type = mkOption { - type = types.enum [ "zip" "rar" "tar" "sz" "tar.gz" "tar.xz" "tar.bz2" "tar.br" "tar.lz4" "tar.zst" ]; + type = lib.mkOption { + type = lib.types.enum [ "zip" "rar" "tar" "sz" "tar.gz" "tar.xz" "tar.bz2" "tar.br" "tar.lz4" "tar.zst" ]; default = "zip"; description = "Archive format used to store the dump file."; }; - file = mkOption { - type = types.nullOr types.str; + file = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; description = "Filename to be used for the dump. If `null` a default name is chosen by gitea."; example = "gitea-dump"; @@ -207,61 +205,61 @@ in }; lfs = { - enable = mkOption { - type = types.bool; + enable = lib.mkOption { + type = lib.types.bool; default = false; description = "Enables git-lfs support."; }; - contentDir = mkOption { - type = types.str; + contentDir = lib.mkOption { + type = lib.types.str; default = "${cfg.stateDir}/data/lfs"; - defaultText = literalExpression ''"''${config.${opt.stateDir}}/data/lfs"''; + defaultText = lib.literalExpression ''"''${config.${opt.stateDir}}/data/lfs"''; description = "Where to store LFS files."; }; }; - appName = mkOption { - type = types.str; + appName = lib.mkOption { + type = lib.types.str; default = "gitea: Gitea Service"; description = "Application name."; }; - repositoryRoot = mkOption { - type = types.str; + repositoryRoot = lib.mkOption { + type = lib.types.str; default = "${cfg.stateDir}/repositories"; - defaultText = literalExpression ''"''${config.${opt.stateDir}}/repositories"''; + defaultText = lib.literalExpression ''"''${config.${opt.stateDir}}/repositories"''; description = "Path to the git repositories."; }; - camoHmacKeyFile = mkOption { - type = types.nullOr types.str; + camoHmacKeyFile = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; example = "/var/lib/secrets/gitea/camoHmacKey"; description = "Path to a file containing the camo HMAC key."; }; - mailerPasswordFile = mkOption { - type = types.nullOr types.str; + mailerPasswordFile = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; example = "/var/lib/secrets/gitea/mailpw"; description = "Path to a file containing the SMTP password."; }; - metricsTokenFile = mkOption { - type = types.nullOr types.str; + metricsTokenFile = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; example = "/var/lib/secrets/gitea/metrics_token"; description = "Path to a file containing the metrics authentication token."; }; - settings = mkOption { + settings = lib.mkOption { default = {}; description = '' Gitea configuration. Refer to for details on supported values. ''; - example = literalExpression '' + example = lib.literalExpression '' { "cron.sync_external_users" = { RUN_AT_START = true; @@ -279,72 +277,72 @@ in }; } ''; - type = types.submodule { + type = lib.types.submodule { freeformType = format.type; options = { log = { - ROOT_PATH = mkOption { + ROOT_PATH = lib.mkOption { default = "${cfg.stateDir}/log"; - defaultText = literalExpression ''"''${config.${opt.stateDir}}/log"''; - type = types.str; + defaultText = lib.literalExpression ''"''${config.${opt.stateDir}}/log"''; + type = lib.types.str; description = "Root path for log files."; }; - LEVEL = mkOption { + LEVEL = lib.mkOption { default = "Info"; - type = types.enum [ "Trace" "Debug" "Info" "Warn" "Error" "Critical" ]; + type = lib.types.enum [ "Trace" "Debug" "Info" "Warn" "Error" "Critical" ]; description = "General log level."; }; }; server = { - PROTOCOL = mkOption { - type = types.enum [ "http" "https" "fcgi" "http+unix" "fcgi+unix" ]; + PROTOCOL = lib.mkOption { + type = lib.types.enum [ "http" "https" "fcgi" "http+unix" "fcgi+unix" ]; default = "http"; description = ''Listen protocol. `+unix` means "over unix", not "in addition to."''; }; - HTTP_ADDR = mkOption { - type = types.either types.str types.path; + HTTP_ADDR = lib.mkOption { + type = lib.types.either lib.types.str lib.types.path; default = if lib.hasSuffix "+unix" cfg.settings.server.PROTOCOL then "/run/gitea/gitea.sock" else "0.0.0.0"; - defaultText = literalExpression ''if lib.hasSuffix "+unix" cfg.settings.server.PROTOCOL then "/run/gitea/gitea.sock" else "0.0.0.0"''; + defaultText = lib.literalExpression ''if lib.hasSuffix "+unix" cfg.settings.server.PROTOCOL then "/run/gitea/gitea.sock" else "0.0.0.0"''; description = "Listen address. Must be a path when using a unix socket."; }; - HTTP_PORT = mkOption { - type = types.port; + HTTP_PORT = lib.mkOption { + type = lib.types.port; default = 3000; description = "Listen port. Ignored when using a unix socket."; }; - DOMAIN = mkOption { - type = types.str; + DOMAIN = lib.mkOption { + type = lib.types.str; default = "localhost"; description = "Domain name of your server."; }; - ROOT_URL = mkOption { - type = types.str; + ROOT_URL = lib.mkOption { + type = lib.types.str; default = "http://${cfg.settings.server.DOMAIN}:${toString cfg.settings.server.HTTP_PORT}/"; - defaultText = literalExpression ''"http://''${config.services.gitea.settings.server.DOMAIN}:''${toString config.services.gitea.settings.server.HTTP_PORT}/"''; + defaultText = lib.literalExpression ''"http://''${config.services.gitea.settings.server.DOMAIN}:''${toString config.services.gitea.settings.server.HTTP_PORT}/"''; description = "Full public URL of gitea server."; }; - STATIC_ROOT_PATH = mkOption { - type = types.either types.str types.path; + STATIC_ROOT_PATH = lib.mkOption { + type = lib.types.either lib.types.str lib.types.path; default = cfg.package.data; - defaultText = literalExpression "config.${opt.package}.data"; + defaultText = lib.literalExpression "config.${opt.package}.data"; example = "/var/lib/gitea/data"; description = "Upper level of template and static files path."; }; - DISABLE_SSH = mkOption { - type = types.bool; + DISABLE_SSH = lib.mkOption { + type = lib.types.bool; default = false; description = "Disable external SSH feature."; }; - SSH_PORT = mkOption { - type = types.port; + SSH_PORT = lib.mkOption { + type = lib.types.port; default = 22; example = 2222; description = '' @@ -356,7 +354,7 @@ in }; service = { - DISABLE_REGISTRATION = mkEnableOption "the registration lock" // { + DISABLE_REGISTRATION = lib.mkEnableOption "the registration lock" // { description = '' By default any user can create an account on this `gitea` instance. This can be disabled by using this option. @@ -370,8 +368,8 @@ in }; session = { - COOKIE_SECURE = mkOption { - type = types.bool; + COOKIE_SECURE = lib.mkOption { + type = lib.types.bool; default = false; description = '' Marks session cookies as "secure" as a hint for browsers to only send @@ -383,15 +381,15 @@ in }; }; - extraConfig = mkOption { - type = with types; nullOr str; + extraConfig = lib.mkOption { + type = with lib.types; nullOr str; default = null; description = "Configuration lines appended to the generated gitea configuration file."; }; }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { assertions = [ { assertion = cfg.database.createDatabase -> useSqlite || cfg.database.user == cfg.user; message = "services.gitea.database.user must match services.gitea.user if the database is to be automatically provisioned"; @@ -409,20 +407,20 @@ in services.gitea.settings = { "cron.update_checker".ENABLED = lib.mkDefault false; - database = mkMerge [ + database = lib.mkMerge [ { DB_TYPE = cfg.database.type; } - (mkIf (useMysql || usePostgresql) { + (lib.mkIf (useMysql || usePostgresql) { HOST = if cfg.database.socket != null then cfg.database.socket else cfg.database.host + ":" + toString cfg.database.port; NAME = cfg.database.name; USER = cfg.database.user; PASSWD = "#dbpass#"; }) - (mkIf useSqlite { + (lib.mkIf useSqlite { PATH = cfg.database.path; }) - (mkIf usePostgresql { + (lib.mkIf usePostgresql { SSL_MODE = "disable"; }) ]; @@ -431,12 +429,12 @@ in ROOT = cfg.repositoryRoot; }; - server = mkIf cfg.lfs.enable { + server = lib.mkIf cfg.lfs.enable { LFS_START_SERVER = true; LFS_JWT_SECRET = "#lfsjwtsecret#"; }; - camo = mkIf (cfg.camoHmacKeyFile != null) { + camo = lib.mkIf (cfg.camoHmacKeyFile != null) { HMAC_KEY = "#hmackey#"; }; @@ -450,11 +448,11 @@ in INSTALL_LOCK = true; }; - mailer = mkIf (cfg.mailerPasswordFile != null) { + mailer = lib.mkIf (cfg.mailerPasswordFile != null) { PASSWD = "#mailerpass#"; }; - metrics = mkIf (cfg.metricsTokenFile != null) { + metrics = lib.mkIf (cfg.metricsTokenFile != null) { TOKEN = "#metricstoken#"; }; @@ -462,15 +460,15 @@ in JWT_SECRET = "#oauth2jwtsecret#"; }; - lfs = mkIf cfg.lfs.enable { + lfs = lib.mkIf cfg.lfs.enable { PATH = cfg.lfs.contentDir; }; packages.CHUNKED_UPLOAD_PATH = "${cfg.stateDir}/tmp/package-upload"; }; - services.postgresql = optionalAttrs (usePostgresql && cfg.database.createDatabase) { - enable = mkDefault true; + services.postgresql = lib.optionalAttrs (usePostgresql && cfg.database.createDatabase) { + enable = lib.mkDefault true; ensureDatabases = [ cfg.database.name ]; ensureUsers = [ @@ -480,9 +478,9 @@ in ]; }; - services.mysql = optionalAttrs (useMysql && cfg.database.createDatabase) { - enable = mkDefault true; - package = mkDefault pkgs.mariadb; + services.mysql = lib.optionalAttrs (useMysql && cfg.database.createDatabase) { + enable = lib.mkDefault true; + package = lib.mkDefault pkgs.mariadb; ensureDatabases = [ cfg.database.name ]; ensureUsers = [ @@ -522,8 +520,8 @@ in systemd.services.gitea = { description = "gitea"; - after = [ "network.target" ] ++ optional usePostgresql "postgresql.service" ++ optional useMysql "mysql.service"; - requires = optional (cfg.database.createDatabase && usePostgresql) "postgresql.service" ++ optional (cfg.database.createDatabase && useMysql) "mysql.service"; + after = [ "network.target" ] ++ lib.optional usePostgresql "postgresql.service" ++ lib.optional useMysql "mysql.service"; + requires = lib.optional (cfg.database.createDatabase && usePostgresql) "postgresql.service" ++ lib.optional (cfg.database.createDatabase && useMysql) "mysql.service"; wantedBy = [ "multi-user.target" ]; path = [ cfg.package pkgs.git pkgs.gnupg ]; @@ -544,7 +542,7 @@ in replaceSecretBin = "${pkgs.replace-secret}/bin/replace-secret"; in '' # copy custom configuration and generate random secrets if needed - ${optionalString (!cfg.useWizard) '' + ${lib.optionalString (!cfg.useWizard) '' function gitea_setup { cp -f '${configFile}' '${runConfig}' @@ -663,7 +661,7 @@ in }; }; - users.users = mkIf (cfg.user == "gitea") { + users.users = lib.mkIf (cfg.user == "gitea") { gitea = { description = "Gitea Service"; home = cfg.stateDir; @@ -673,16 +671,16 @@ in }; }; - users.groups = mkIf (cfg.group == "gitea") { + users.groups = lib.mkIf (cfg.group == "gitea") { gitea = {}; }; warnings = - optional (cfg.database.password != "") "config.services.gitea.database.password will be stored as plaintext in the Nix store. Use database.passwordFile instead." ++ - optional (cfg.extraConfig != null) '' + lib.optional (cfg.database.password != "") "config.services.gitea.database.password will be stored as plaintext in the Nix store. Use database.passwordFile instead." ++ + lib.optional (cfg.extraConfig != null) '' services.gitea.`extraConfig` is deprecated, please use services.gitea.`settings`. '' ++ - optional (lib.getName cfg.package == "forgejo") '' + lib.optional (lib.getName cfg.package == "forgejo") '' Running forgejo via services.gitea.package is no longer supported. Please use services.forgejo instead. See https://nixos.org/manual/nixos/unstable/#module-forgejo for migration instructions. @@ -690,12 +688,12 @@ in # Create database passwordFile default when password is configured. services.gitea.database.passwordFile = - mkDefault (toString (pkgs.writeTextFile { + lib.mkDefault (toString (pkgs.writeTextFile { name = "gitea-database-password"; text = cfg.database.password; })); - systemd.services.gitea-dump = mkIf cfg.dump.enable { + systemd.services.gitea-dump = lib.mkIf cfg.dump.enable { description = "gitea dump"; after = [ "gitea.service" ]; path = [ cfg.package ]; @@ -710,12 +708,12 @@ in serviceConfig = { Type = "oneshot"; User = cfg.user; - ExecStart = "${exe} dump --type ${cfg.dump.type}" + optionalString (cfg.dump.file != null) " --file ${cfg.dump.file}"; + ExecStart = "${exe} dump --type ${cfg.dump.type}" + lib.optionalString (cfg.dump.file != null) " --file ${cfg.dump.file}"; WorkingDirectory = cfg.dump.backupDir; }; }; - systemd.timers.gitea-dump = mkIf cfg.dump.enable { + systemd.timers.gitea-dump = lib.mkIf cfg.dump.enable { description = "Update timer for gitea-dump"; partOf = [ "gitea-dump.service" ]; wantedBy = [ "timers.target" ]; diff --git a/nixos/modules/services/misc/gitlab.nix b/nixos/modules/services/misc/gitlab.nix index 80bbee5f49ce9..53c84b16ae2ed 100644 --- a/nixos/modules/services/misc/gitlab.nix +++ b/nixos/modules/services/misc/gitlab.nix @@ -1,7 +1,5 @@ { config, lib, options, pkgs, utils, ... }: -with lib; - let cfg = config.services.gitlab; opt = options.services.gitlab; @@ -18,7 +16,7 @@ let gitlabSocket = "${cfg.statePath}/tmp/sockets/gitlab.socket"; gitalySocket = "${cfg.statePath}/tmp/sockets/gitaly.socket"; - pathUrlQuote = url: replaceStrings ["/"] ["%2F"] url; + pathUrlQuote = url: lib.replaceStrings ["/"] ["%2F"] url; gitlabVersionAtLeast = version: lib.versionAtLeast (lib.getVersion cfg.packages.gitlab) version; @@ -68,14 +66,14 @@ let [gitlab.http-settings] self_signed_cert = false - ${concatStringsSep "\n" (attrValues (mapAttrs (k: v: '' + ${lib.concatStringsSep "\n" (lib.attrValues (lib.mapAttrs (k: v: '' [[storage]] name = "${lib.escape ["\""] k}" path = "${lib.escape ["\""] v.path}" '') gitlabConfig.production.repositories.storages))} ''; - gitlabShellConfig = flip recursiveUpdate cfg.extraShellConfig { + gitlabShellConfig = lib.flip lib.recursiveUpdate cfg.extraShellConfig { user = cfg.user; gitlab_url = "http+unix://${pathUrlQuote gitlabSocket}"; http_settings.self_signed_cert = false; @@ -99,7 +97,7 @@ let gitlabConfig = { # These are the default settings from config/gitlab.example.yml - production = flip recursiveUpdate cfg.extraConfig { + production = lib.flip lib.recursiveUpdate cfg.extraConfig { gitlab = { host = cfg.host; port = cfg.port; @@ -133,7 +131,7 @@ let gitaly_backup_path = "${cfg.packages.gitaly}/bin/gitaly-backup"; path = cfg.backup.path; keep_time = cfg.backup.keepTime; - } // (optionalAttrs (cfg.backup.uploadOptions != {}) { + } // (lib.optionalAttrs (cfg.backup.uploadOptions != {}) { upload = cfg.backup.uploadOptions; }); gitlab_shell = { @@ -165,7 +163,7 @@ let elasticsearch.indexer_path = "${pkgs.gitlab-elasticsearch-indexer}/bin/gitlab-elasticsearch-indexer"; extra = {}; uploads.storage_path = cfg.statePath; - pages = optionalAttrs cfg.pages.enable { + pages = lib.optionalAttrs cfg.pages.enable { enabled = cfg.pages.enable; port = 8090; host = cfg.pages.settings.pages-domain; @@ -204,7 +202,7 @@ let installPhase = '' mkdir -p $out/bin makeWrapper ${cfg.packages.gitlab.rubyEnv}/bin/rake $out/bin/gitlab-rake \ - ${concatStrings (mapAttrsToList (name: value: "--set ${name} '${value}' ") gitlabEnv)} \ + ${lib.concatStrings (lib.mapAttrsToList (name: value: "--set ${name} '${value}' ") gitlabEnv)} \ --set PATH '${lib.makeBinPath runtimeDeps}:$PATH' \ --set RAKEOPT '-f ${cfg.packages.gitlab}/share/gitlab/Rakefile' \ --chdir '${cfg.packages.gitlab}/share/gitlab' @@ -219,7 +217,7 @@ let installPhase = '' mkdir -p $out/bin makeWrapper ${cfg.packages.gitlab.rubyEnv}/bin/rails $out/bin/gitlab-rails \ - ${concatStrings (mapAttrsToList (name: value: "--set ${name} '${value}' ") gitlabEnv)} \ + ${lib.concatStrings (lib.mapAttrsToList (name: value: "--set ${name} '${value}' ") gitlabEnv)} \ --set PATH '${lib.makeBinPath runtimeDeps}:$PATH' \ --chdir '${cfg.packages.gitlab}/share/gitlab' ''; @@ -235,12 +233,12 @@ let ActionMailer::Base.smtp_settings = { address: "${cfg.smtp.address}", port: ${toString cfg.smtp.port}, - ${optionalString (cfg.smtp.username != null) ''user_name: "${cfg.smtp.username}",''} - ${optionalString (cfg.smtp.passwordFile != null) ''password: "@smtpPassword@",''} + ${lib.optionalString (cfg.smtp.username != null) ''user_name: "${cfg.smtp.username}",''} + ${lib.optionalString (cfg.smtp.passwordFile != null) ''password: "@smtpPassword@",''} domain: "${cfg.smtp.domain}", - ${optionalString (cfg.smtp.authentication != null) "authentication: :${cfg.smtp.authentication},"} - enable_starttls_auto: ${boolToString cfg.smtp.enableStartTLSAuto}, - tls: ${boolToString cfg.smtp.tls}, + ${lib.optionalString (cfg.smtp.authentication != null) "authentication: :${cfg.smtp.authentication},"} + enable_starttls_auto: ${lib.boolToString cfg.smtp.enableStartTLSAuto}, + tls: ${lib.boolToString cfg.smtp.tls}, ca_file: "/etc/ssl/certs/ca-certificates.crt", openssl_verify_mode: '${cfg.smtp.opensslVerifyMode}' } @@ -250,37 +248,37 @@ let in { imports = [ - (mkRenamedOptionModule [ "services" "gitlab" "stateDir" ] [ "services" "gitlab" "statePath" ]) - (mkRenamedOptionModule [ "services" "gitlab" "backupPath" ] [ "services" "gitlab" "backup" "path" ]) - (mkRemovedOptionModule [ "services" "gitlab" "satelliteDir" ] "") - (mkRemovedOptionModule [ "services" "gitlab" "logrotate" "extraConfig" ] "Modify services.logrotate.settings.gitlab directly instead") - (mkRemovedOptionModule [ "services" "gitlab" "pagesExtraArgs" ] "Use services.gitlab.pages.settings instead") + (lib.mkRenamedOptionModule [ "services" "gitlab" "stateDir" ] [ "services" "gitlab" "statePath" ]) + (lib.mkRenamedOptionModule [ "services" "gitlab" "backupPath" ] [ "services" "gitlab" "backup" "path" ]) + (lib.mkRemovedOptionModule [ "services" "gitlab" "satelliteDir" ] "") + (lib.mkRemovedOptionModule [ "services" "gitlab" "logrotate" "extraConfig" ] "Modify services.logrotate.settings.gitlab directly instead") + (lib.mkRemovedOptionModule [ "services" "gitlab" "pagesExtraArgs" ] "Use services.gitlab.pages.settings instead") ]; options = { services.gitlab = { - enable = mkOption { - type = types.bool; + enable = lib.mkOption { + type = lib.types.bool; default = false; description = '' Enable the gitlab service. ''; }; - packages.gitlab = mkPackageOption pkgs "gitlab" { + packages.gitlab = lib.mkPackageOption pkgs "gitlab" { example = "gitlab-ee"; }; - packages.gitlab-shell = mkPackageOption pkgs "gitlab-shell" { }; + packages.gitlab-shell = lib.mkPackageOption pkgs "gitlab-shell" { }; - packages.gitlab-workhorse = mkPackageOption pkgs "gitlab-workhorse" { }; + packages.gitlab-workhorse = lib.mkPackageOption pkgs "gitlab-workhorse" { }; - packages.gitaly = mkPackageOption pkgs "gitaly" { }; + packages.gitaly = lib.mkPackageOption pkgs "gitaly" { }; - packages.pages = mkPackageOption pkgs "gitlab-pages" { }; + packages.pages = lib.mkPackageOption pkgs "gitlab-pages" { }; - statePath = mkOption { - type = types.str; + statePath = lib.mkOption { + type = lib.types.str; default = "/var/gitlab/state"; description = '' GitLab state directory. Configuration, repositories and @@ -293,16 +291,16 @@ in { ''; }; - extraEnv = mkOption { - type = types.attrsOf types.str; + extraEnv = lib.mkOption { + type = lib.types.attrsOf lib.types.str; default = {}; description = '' Additional environment variables for the GitLab environment. ''; }; - backup.startAt = mkOption { - type = with types; either str (listOf str); + backup.startAt = lib.mkOption { + type = with lib.types; either str (listOf str); default = []; example = "03:00"; description = '' @@ -312,15 +310,15 @@ in { ''; }; - backup.path = mkOption { - type = types.str; + backup.path = lib.mkOption { + type = lib.types.str; default = cfg.statePath + "/backup"; - defaultText = literalExpression ''config.${opt.statePath} + "/backup"''; + defaultText = lib.literalExpression ''config.${opt.statePath} + "/backup"''; description = "GitLab path for backups."; }; - backup.keepTime = mkOption { - type = types.int; + backup.keepTime = lib.mkOption { + type = lib.types.int; default = 0; example = 48; apply = x: x * 60 * 60; @@ -330,8 +328,8 @@ in { ''; }; - backup.skip = mkOption { - type = with types; + backup.skip = lib.mkOption { + type = with lib.types; let value = enum [ "db" "uploads" @@ -347,7 +345,7 @@ in { either value (listOf value); default = []; example = [ "artifacts" "lfs" ]; - apply = x: if isString x then x else concatStringsSep "," x; + apply = x: if lib.isString x then x else lib.concatStringsSep "," x; description = '' Directories to exclude from the backup. The example excludes CI artifacts and LFS objects from the backups. The @@ -359,10 +357,10 @@ in { ''; }; - backup.uploadOptions = mkOption { - type = types.attrs; + backup.uploadOptions = lib.mkOption { + type = lib.types.attrs; default = {}; - example = literalExpression '' + example = lib.literalExpression '' { # Fog storage connection settings, see http://fog.io/storage/ connection = { @@ -380,10 +378,10 @@ in { # http://docs.aws.amazon.com/AmazonS3/latest/dev/uploadobjusingmpu.html multipart_chunk_size = 104857600; - # Turns on AWS Server-Side Encryption with Amazon S3-Managed Keys for backups, this is optional + # Turns on AWS Server-Side Encryption with Amazon S3-Managed Keys for backups, this is lib.optional encryption = "AES256"; - # Specifies Amazon S3 storage class to use for backups, this is optional + # Specifies Amazon S3 storage class to use for backups, this is lib.optional storage_class = "STANDARD"; }; ''; @@ -397,8 +395,8 @@ in { ''; }; - databaseHost = mkOption { - type = types.str; + databaseHost = lib.mkOption { + type = lib.types.str; default = ""; description = '' GitLab database hostname. An empty string means @@ -406,8 +404,8 @@ in { ''; }; - databasePasswordFile = mkOption { - type = with types; nullOr path; + databasePasswordFile = lib.mkOption { + type = with lib.types; nullOr path; default = null; description = '' File containing the GitLab database user password. @@ -417,8 +415,8 @@ in { ''; }; - databaseCreateLocally = mkOption { - type = types.bool; + databaseCreateLocally = lib.mkOption { + type = lib.types.bool; default = true; description = '' Whether a database should be automatically created on the @@ -428,39 +426,39 @@ in { ''; }; - databaseName = mkOption { - type = types.str; + databaseName = lib.mkOption { + type = lib.types.str; default = "gitlab"; description = "GitLab database name."; }; - databaseUsername = mkOption { - type = types.str; + databaseUsername = lib.mkOption { + type = lib.types.str; default = "gitlab"; description = "GitLab database user."; }; - databasePool = mkOption { - type = types.int; + databasePool = lib.mkOption { + type = lib.types.int; default = 5; description = "Database connection pool size."; }; - extraDatabaseConfig = mkOption { - type = types.attrs; + extraDatabaseConfig = lib.mkOption { + type = lib.types.attrs; default = {}; description = "Extra configuration in config/database.yml."; }; - redisUrl = mkOption { - type = types.str; + redisUrl = lib.mkOption { + type = lib.types.str; default = "unix:/run/gitlab/redis.sock"; example = "redis://localhost:6379/"; description = "Redis URL for all GitLab services."; }; - extraGitlabRb = mkOption { - type = types.str; + extraGitlabRb = lib.mkOption { + type = lib.types.str; default = ""; example = '' if Rails.env.production? @@ -479,15 +477,15 @@ in { ''; }; - host = mkOption { - type = types.str; + host = lib.mkOption { + type = lib.types.str; default = config.networking.hostName; - defaultText = literalExpression "config.networking.hostName"; + defaultText = lib.literalExpression "config.networking.hostName"; description = "GitLab host name. Used e.g. for copy-paste URLs."; }; - port = mkOption { - type = types.port; + port = lib.mkOption { + type = lib.types.port; default = 8080; description = '' GitLab server port for copy-paste URLs, e.g. 80 or 443 if you're @@ -495,34 +493,34 @@ in { ''; }; - https = mkOption { - type = types.bool; + https = lib.mkOption { + type = lib.types.bool; default = false; description = "Whether gitlab prints URLs with https as scheme."; }; - user = mkOption { - type = types.str; + user = lib.mkOption { + type = lib.types.str; default = "gitlab"; description = "User to run gitlab and all related services."; }; - group = mkOption { - type = types.str; + group = lib.mkOption { + type = lib.types.str; default = "gitlab"; description = "Group to run gitlab and all related services."; }; - initialRootEmail = mkOption { - type = types.str; + initialRootEmail = lib.mkOption { + type = lib.types.str; default = "admin@local.host"; description = '' Initial email address of the root account if this is a new install. ''; }; - initialRootPasswordFile = mkOption { - type = with types; nullOr path; + initialRootPasswordFile = lib.mkOption { + type = with lib.types; nullOr path; default = null; description = '' File containing the initial password of the root account if @@ -534,18 +532,18 @@ in { }; registry = { - enable = mkOption { - type = types.bool; + enable = lib.mkOption { + type = lib.types.bool; default = false; description = "Enable GitLab container registry."; }; - package = mkOption { - type = types.package; + package = lib.mkOption { + type = lib.types.package; default = - if versionAtLeast config.system.stateVersion "23.11" + if lib.versionAtLeast config.system.stateVersion "23.11" then pkgs.gitlab-container-registry else pkgs.docker-distribution; - defaultText = literalExpression "pkgs.docker-distribution"; + defaultText = lib.literalExpression "pkgs.docker-distribution"; description = '' Container registry package to use. @@ -553,79 +551,79 @@ in { anymore since GitLab 16.0.0. ''; }; - host = mkOption { - type = types.str; + host = lib.mkOption { + type = lib.types.str; default = config.services.gitlab.host; - defaultText = literalExpression "config.services.gitlab.host"; + defaultText = lib.literalExpression "config.services.gitlab.host"; description = "GitLab container registry host name."; }; - port = mkOption { - type = types.port; + port = lib.mkOption { + type = lib.types.port; default = 4567; description = "GitLab container registry port."; }; - certFile = mkOption { - type = types.path; + certFile = lib.mkOption { + type = lib.types.path; description = "Path to GitLab container registry certificate."; }; - keyFile = mkOption { - type = types.path; + keyFile = lib.mkOption { + type = lib.types.path; description = "Path to GitLab container registry certificate-key."; }; - defaultForProjects = mkOption { - type = types.bool; + defaultForProjects = lib.mkOption { + type = lib.types.bool; default = cfg.registry.enable; - defaultText = literalExpression "config.${opt.registry.enable}"; + defaultText = lib.literalExpression "config.${opt.registry.enable}"; description = "If GitLab container registry should be enabled by default for projects."; }; - issuer = mkOption { - type = types.str; + issuer = lib.mkOption { + type = lib.types.str; default = "gitlab-issuer"; description = "GitLab container registry issuer."; }; - serviceName = mkOption { - type = types.str; + serviceName = lib.mkOption { + type = lib.types.str; default = "container_registry"; description = "GitLab container registry service name."; }; - externalAddress = mkOption { - type = types.str; + externalAddress = lib.mkOption { + type = lib.types.str; default = ""; description = "External address used to access registry from the internet"; }; - externalPort = mkOption { - type = types.int; + externalPort = lib.mkOption { + type = lib.types.int; description = "External port used to access registry from the internet"; }; }; smtp = { - enable = mkOption { - type = types.bool; + enable = lib.mkOption { + type = lib.types.bool; default = false; description = "Enable gitlab mail delivery over SMTP."; }; - address = mkOption { - type = types.str; + address = lib.mkOption { + type = lib.types.str; default = "localhost"; description = "Address of the SMTP server for GitLab."; }; - port = mkOption { - type = types.port; + port = lib.mkOption { + type = lib.types.port; default = 25; description = "Port of the SMTP server for GitLab."; }; - username = mkOption { - type = with types; nullOr str; + username = lib.mkOption { + type = with lib.types; nullOr str; default = null; description = "Username of the SMTP server for GitLab."; }; - passwordFile = mkOption { - type = types.nullOr types.path; + passwordFile = lib.mkOption { + type = lib.types.nullOr lib.types.path; default = null; description = '' File containing the password of the SMTP server for GitLab. @@ -635,41 +633,41 @@ in { ''; }; - domain = mkOption { - type = types.str; + domain = lib.mkOption { + type = lib.types.str; default = "localhost"; description = "HELO domain to use for outgoing mail."; }; - authentication = mkOption { - type = with types; nullOr str; + authentication = lib.mkOption { + type = with lib.types; nullOr str; default = null; description = "Authentication type to use, see http://api.rubyonrails.org/classes/ActionMailer/Base.html"; }; - enableStartTLSAuto = mkOption { - type = types.bool; + enableStartTLSAuto = lib.mkOption { + type = lib.types.bool; default = true; description = "Whether to try to use StartTLS."; }; - tls = mkOption { - type = types.bool; + tls = lib.mkOption { + type = lib.types.bool; default = false; description = "Whether to use TLS wrapper-mode."; }; - opensslVerifyMode = mkOption { - type = types.str; + opensslVerifyMode = lib.mkOption { + type = lib.types.str; default = "peer"; description = "How OpenSSL checks the certificate, see http://api.rubyonrails.org/classes/ActionMailer/Base.html"; }; }; - pages.enable = mkEnableOption "the GitLab Pages service"; + pages.enable = lib.mkEnableOption "the GitLab Pages service"; - pages.settings = mkOption { - example = literalExpression '' + pages.settings = lib.mkOption { + example = lib.literalExpression '' { pages-domain = "example.com"; auth-client-id = "generated-id-xxxxxxx"; @@ -694,12 +692,12 @@ in { {file}`/var/keys/auth-secret` files respectively. ''; - type = types.submodule { - freeformType = with types; attrsOf (nullOr (oneOf [ str int bool attrs ])); + type = lib.types.submodule { + freeformType = with lib.types; attrsOf (nullOr (oneOf [ str int bool attrs ])); options = { - listen-http = mkOption { - type = with types; listOf str; + listen-http = lib.mkOption { + type = with lib.types; listOf str; apply = x: if x == [] then null else lib.concatStringsSep "," x; default = []; description = '' @@ -707,8 +705,8 @@ in { ''; }; - listen-https = mkOption { - type = with types; listOf str; + listen-https = lib.mkOption { + type = with lib.types; listOf str; apply = x: if x == [] then null else lib.concatStringsSep "," x; default = []; description = '' @@ -716,8 +714,8 @@ in { ''; }; - listen-proxy = mkOption { - type = with types; listOf str; + listen-proxy = lib.mkOption { + type = with lib.types; listOf str; apply = x: if x == [] then null else lib.concatStringsSep "," x; default = [ "127.0.0.1:8090" ]; description = '' @@ -725,9 +723,9 @@ in { ''; }; - artifacts-server = mkOption { - type = with types; nullOr str; - default = "http${optionalString cfg.https "s"}://${cfg.host}/api/v4"; + artifacts-server = lib.mkOption { + type = with lib.types; nullOr str; + default = "http${lib.optionalString cfg.https "s"}://${cfg.host}/api/v4"; defaultText = "http(s):///api/v4"; example = "https://gitlab.example.com/api/v4"; description = '' @@ -735,9 +733,9 @@ in { ''; }; - gitlab-server = mkOption { - type = with types; nullOr str; - default = "http${optionalString cfg.https "s"}://${cfg.host}"; + gitlab-server = lib.mkOption { + type = with lib.types; nullOr str; + default = "http${lib.optionalString cfg.https "s"}://${cfg.host}"; defaultText = "http(s)://"; example = "https://gitlab.example.com"; description = '' @@ -745,8 +743,8 @@ in { ''; }; - internal-gitlab-server = mkOption { - type = with types; nullOr str; + internal-gitlab-server = lib.mkOption { + type = with lib.types; nullOr str; default = null; defaultText = "http(s)://"; example = "https://gitlab.example.internal"; @@ -759,8 +757,8 @@ in { ''; }; - api-secret-key = mkOption { - type = with types; nullOr str; + api-secret-key = lib.mkOption { + type = with lib.types; nullOr str; default = "${cfg.statePath}/gitlab_pages_secret"; internal = true; description = '' @@ -769,18 +767,18 @@ in { ''; }; - pages-domain = mkOption { - type = with types; nullOr str; + pages-domain = lib.mkOption { + type = with lib.types; nullOr str; example = "example.com"; description = '' The domain to serve static pages on. ''; }; - pages-root = mkOption { - type = types.str; + pages-root = lib.mkOption { + type = lib.types.str; default = "${gitlabConfig.production.shared.path}/pages"; - defaultText = literalExpression ''config.${opt.extraConfig}.production.shared.path + "/pages"''; + defaultText = lib.literalExpression ''config.${opt.extraConfig}.production.shared.path + "/pages"''; description = '' The directory where pages are stored. ''; @@ -789,8 +787,8 @@ in { }; }; - secrets.secretFile = mkOption { - type = with types; nullOr path; + secrets.secretFile = lib.mkOption { + type = with lib.types; nullOr path; default = null; description = '' A file containing the secret used to encrypt variables in @@ -805,8 +803,8 @@ in { ''; }; - secrets.dbFile = mkOption { - type = with types; nullOr path; + secrets.dbFile = lib.mkOption { + type = with lib.types; nullOr path; default = null; description = '' A file containing the secret used to encrypt variables in @@ -821,8 +819,8 @@ in { ''; }; - secrets.otpFile = mkOption { - type = with types; nullOr path; + secrets.otpFile = lib.mkOption { + type = with lib.types; nullOr path; default = null; description = '' A file containing the secret used to encrypt secrets for OTP @@ -837,8 +835,8 @@ in { ''; }; - secrets.jwsFile = mkOption { - type = with types; nullOr path; + secrets.jwsFile = lib.mkOption { + type = with lib.types; nullOr path; default = null; description = '' A file containing the secret used to encrypt session @@ -855,14 +853,14 @@ in { ''; }; - extraShellConfig = mkOption { - type = types.attrs; + extraShellConfig = lib.mkOption { + type = lib.types.attrs; default = {}; description = "Extra configuration to merge into shell-config.yml"; }; - puma.workers = mkOption { - type = types.int; + puma.workers = lib.mkOption { + type = lib.types.int; default = 2; apply = x: builtins.toString x; description = '' @@ -877,8 +875,8 @@ in { ''; }; - puma.threadsMin = mkOption { - type = types.int; + puma.threadsMin = lib.mkOption { + type = lib.types.int; default = 0; apply = x: builtins.toString x; description = '' @@ -892,8 +890,8 @@ in { ''; }; - puma.threadsMax = mkOption { - type = types.int; + puma.threadsMax = lib.mkOption { + type = lib.types.int; default = 4; apply = x: builtins.toString x; description = '' @@ -910,8 +908,8 @@ in { ''; }; - sidekiq.concurrency = mkOption { - type = with types; nullOr int; + sidekiq.concurrency = lib.mkOption { + type = with lib.types; nullOr int; default = null; description = '' How many processor threads to use for processing sidekiq background job queues. When null, the GitLab default is used. @@ -920,8 +918,8 @@ in { ''; }; - sidekiq.memoryKiller.enable = mkOption { - type = types.bool; + sidekiq.memoryKiller.enable = lib.mkOption { + type = lib.types.bool; default = true; description = '' Whether the Sidekiq MemoryKiller should be turned @@ -933,8 +931,8 @@ in { ''; }; - sidekiq.memoryKiller.maxMemory = mkOption { - type = types.int; + sidekiq.memoryKiller.maxMemory = lib.mkOption { + type = lib.types.int; default = 2000; apply = x: builtins.toString (x * 1024); description = '' @@ -943,8 +941,8 @@ in { ''; }; - sidekiq.memoryKiller.graceTime = mkOption { - type = types.int; + sidekiq.memoryKiller.graceTime = lib.mkOption { + type = lib.types.int; default = 900; apply = x: builtins.toString x; description = '' @@ -953,8 +951,8 @@ in { ''; }; - sidekiq.memoryKiller.shutdownWait = mkOption { - type = types.int; + sidekiq.memoryKiller.shutdownWait = lib.mkOption { + type = lib.types.int; default = 30; apply = x: builtins.toString x; description = '' @@ -964,31 +962,31 @@ in { }; logrotate = { - enable = mkOption { - type = types.bool; + enable = lib.mkOption { + type = lib.types.bool; default = true; description = '' Enable rotation of log files. ''; }; - frequency = mkOption { - type = types.str; + frequency = lib.mkOption { + type = lib.types.str; default = "daily"; description = "How often to rotate the logs."; }; - keep = mkOption { - type = types.int; + keep = lib.mkOption { + type = lib.types.int; default = 30; description = "How many rotations to keep."; }; }; - workhorse.config = mkOption { + workhorse.config = lib.mkOption { type = toml.type; default = {}; - example = literalExpression '' + example = lib.literalExpression '' { object_storage.provider = "AWS"; object_storage.s3 = { @@ -1018,10 +1016,10 @@ in { ''; }; - extraConfig = mkOption { + extraConfig = lib.mkOption { type = yaml.type; default = {}; - example = literalExpression '' + example = lib.literalExpression '' { gitlab = { default_projects_features = { @@ -1076,15 +1074,15 @@ in { }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { warnings = [ - (mkIf - (cfg.registry.enable && versionAtLeast (getVersion cfg.packages.gitlab) "16.0.0" && cfg.registry.package == pkgs.docker-distribution) + (lib.mkIf + (cfg.registry.enable && lib.versionAtLeast (lib.getVersion cfg.packages.gitlab) "16.0.0" && cfg.registry.package == pkgs.docker-distribution) ''Support for container registries other than gitlab-container-registry has ended since GitLab 16.0.0 and is scheduled for removal in a future release. Please back up your data and migrate to the gitlab-container-registry package.'' ) - (mkIf - (versionAtLeast (getVersion cfg.packages.gitlab) "16.2.0" && versionOlder (getVersion cfg.packages.gitlab) "16.5.0") + (lib.mkIf + (lib.versionAtLeast (lib.getVersion cfg.packages.gitlab) "16.2.0" && lib.versionOlder (lib.getVersion cfg.packages.gitlab) "16.5.0") ''GitLab instances created or updated between versions [15.11.0, 15.11.2] have an incorrect database schema. Check the upstream documentation for a workaround: https://docs.gitlab.com/ee/update/versions/gitlab_16_changes.html#undefined-column-error-upgrading-to-162-or-later'' ) @@ -1120,7 +1118,7 @@ in { message = "services.gitlab.secrets.jwsFile must be set!"; } { - assertion = versionAtLeast postgresqlPackage.version "14.9"; + assertion = lib.versionAtLeast postgresqlPackage.version "14.9"; message = "PostgreSQL >= 14.9 is required to run GitLab 17. Follow the instructions in the manual section for upgrading PostgreSQL here: https://nixos.org/manual/nixos/stable/index.html#module-services-postgres-upgrading"; } ]; @@ -1139,16 +1137,16 @@ in { # Redis is required for the sidekiq queue runner. services.redis.servers.gitlab = { - enable = mkDefault true; - user = mkDefault cfg.user; - unixSocket = mkDefault "/run/gitlab/redis.sock"; - unixSocketPerm = mkDefault 770; + enable = lib.mkDefault true; + user = lib.mkDefault cfg.user; + unixSocket = lib.mkDefault "/run/gitlab/redis.sock"; + unixSocketPerm = lib.mkDefault 770; }; # We use postgres as the main data store. - services.postgresql = optionalAttrs databaseActuallyCreateLocally { + services.postgresql = lib.optionalAttrs databaseActuallyCreateLocally { enable = true; - ensureUsers = singleton { name = cfg.databaseUsername; }; + ensureUsers = lib.singleton { name = cfg.databaseUsername; }; }; # Enable rotation of log files @@ -1169,7 +1167,7 @@ in { # The postgresql module doesn't currently support concepts like # objects owners and extensions; for now we tack on what's needed # here. - systemd.services.gitlab-postgresql = let pgsql = config.services.postgresql; in mkIf databaseActuallyCreateLocally { + systemd.services.gitlab-postgresql = let pgsql = config.services.postgresql; in lib.mkIf databaseActuallyCreateLocally { after = [ "postgresql.service" ]; bindsTo = [ "postgresql.service" ]; wantedBy = [ "gitlab.target" ]; @@ -1209,7 +1207,7 @@ in { }; }; - systemd.services.gitlab-registry-cert = optionalAttrs cfg.registry.enable { + systemd.services.gitlab-registry-cert = lib.optionalAttrs cfg.registry.enable { path = with pkgs; [ openssl ]; script = '' @@ -1232,20 +1230,20 @@ in { }; # Ensure Docker Registry launches after the certificate generation job - systemd.services.docker-registry = optionalAttrs cfg.registry.enable { + systemd.services.docker-registry = lib.optionalAttrs cfg.registry.enable { wants = [ "gitlab-registry-cert.service" ]; after = [ "gitlab-registry-cert.service" ]; }; # Enable Docker Registry, if GitLab-Container Registry is enabled - services.dockerRegistry = optionalAttrs cfg.registry.enable { + services.dockerRegistry = lib.optionalAttrs cfg.registry.enable { enable = true; enableDelete = true; # This must be true, otherwise GitLab won't manage it correctly package = cfg.registry.package; port = cfg.registry.port; extraConfig = { auth.token = { - realm = "http${optionalString (cfg.https == true) "s"}://${cfg.host}/jwt/auth"; + realm = "http${lib.optionalString (cfg.https == true) "s"}://${cfg.host}/jwt/auth"; service = cfg.registry.serviceName; issuer = cfg.registry.issuer; rootcertbundle = cfg.registry.certFile; @@ -1254,7 +1252,7 @@ in { }; # Use postfix to send out mails. - services.postfix.enable = mkDefault (cfg.smtp.enable && cfg.smtp.address == "localhost"); + services.postfix.enable = lib.mkDefault (cfg.smtp.enable && cfg.smtp.address == "localhost"); users.users.${cfg.user} = { group = cfg.group; @@ -1351,9 +1349,9 @@ in { ${cfg.packages.gitlab-shell}/support/make_necessary_dirs - ${optionalString cfg.smtp.enable '' + ${lib.optionalString cfg.smtp.enable '' install -m u=rw ${smtpSettings} ${cfg.statePath}/config/initializers/smtp_settings.rb - ${optionalString (cfg.smtp.passwordFile != null) '' + ${lib.optionalString (cfg.smtp.passwordFile != null) '' replace-secret '@smtpPassword@' '${cfg.smtp.passwordFile}' '${cfg.statePath}/config/initializers/smtp_settings.rb' ''} ''} @@ -1362,7 +1360,7 @@ in { umask u=rwx,g=,o= openssl rand -hex 32 > ${cfg.statePath}/gitlab_shell_secret - ${optionalString cfg.pages.enable '' + ${lib.optionalString cfg.pages.enable '' openssl rand -base64 32 > ${cfg.pages.settings.api-secret-key} ''} @@ -1424,7 +1422,7 @@ in { systemd.services.gitlab-db-config = { after = [ "gitlab-config.service" "gitlab-postgresql.service" "postgresql.service" ]; - wants = optional (cfg.databaseHost == "") "postgresql.service" ++ optional databaseActuallyCreateLocally "gitlab-postgresql.service"; + wants = lib.optional (cfg.databaseHost == "") "postgresql.service" ++ lib.optional databaseActuallyCreateLocally "gitlab-postgresql.service"; bindsTo = [ "gitlab-config.service" ]; wantedBy = [ "gitlab.target" ]; partOf = [ "gitlab.target" ]; @@ -1462,10 +1460,10 @@ in { "gitlab-config.service" "gitlab-db-config.service" ]; - wants = [ "redis-gitlab.service" ] ++ optional (cfg.databaseHost == "") "postgresql.service"; + wants = [ "redis-gitlab.service" ] ++ lib.optional (cfg.databaseHost == "") "postgresql.service"; wantedBy = [ "gitlab.target" ]; partOf = [ "gitlab.target" ]; - environment = gitlabEnv // (optionalAttrs cfg.sidekiq.memoryKiller.enable { + environment = gitlabEnv // (lib.optionalAttrs cfg.sidekiq.memoryKiller.enable { SIDEKIQ_MEMORY_KILLER_MAX_RSS = cfg.sidekiq.memoryKiller.maxMemory; SIDEKIQ_MEMORY_KILLER_GRACE_TIME = cfg.sidekiq.memoryKiller.graceTime; SIDEKIQ_MEMORY_KILLER_SHUTDOWN_WAIT = cfg.sidekiq.memoryKiller.shutdownWait; @@ -1536,13 +1534,13 @@ in { systemd.services.gitlab-pages = let - filteredConfig = filterAttrs (_: v: v != null) cfg.pages.settings; - isSecret = v: isAttrs v && v ? _secret && isString v._secret; + filteredConfig = lib.filterAttrs (_: v: v != null) cfg.pages.settings; + isSecret = v: lib.isAttrs v && v ? _secret && lib.isString v._secret; mkPagesKeyValue = lib.generators.toKeyValue { mkKeyValue = lib.flip lib.generators.mkKeyValueDefault "=" rec { mkValueString = v: - if isInt v then toString v - else if isString v then v + if lib.isInt v then toString v + else if lib.isString v then v else if true == v then "true" else if false == v then "false" else if isSecret v then builtins.hashString "sha256" v._secret @@ -1556,7 +1554,7 @@ in { secretReplacements = lib.concatMapStrings mkSecretReplacement secretPaths; configFile = pkgs.writeText "gitlab-pages.conf" (mkPagesKeyValue filteredConfig); in - mkIf cfg.pages.enable { + lib.mkIf cfg.pages.enable { description = "GitLab static pages daemon"; after = [ "network.target" "gitlab-config.service" "gitlab.service" ]; bindsTo = [ "gitlab-config.service" "gitlab.service" ]; @@ -1625,7 +1623,7 @@ in { ''; ExecStart = "${cfg.packages.gitlab-workhorse}/bin/${ - optionalString (lib.versionAtLeast (lib.getVersion cfg.packages.gitlab-workhorse) "16.10") "gitlab-" + lib.optionalString (lib.versionAtLeast (lib.getVersion cfg.packages.gitlab-workhorse) "16.10") "gitlab-" }workhorse " + "-listenUmask 0 " + "-listenNetwork unix " @@ -1637,7 +1635,7 @@ in { }; }; - systemd.services.gitlab-mailroom = mkIf (gitlabConfig.production.incoming_email.enabled or false) { + systemd.services.gitlab-mailroom = lib.mkIf (gitlabConfig.production.incoming_email.enabled or false) { description = "GitLab incoming mail daemon"; after = [ "network.target" "redis-gitlab.service" "gitlab-config.service" ]; bindsTo = [ "gitlab-config.service" ]; @@ -1669,7 +1667,7 @@ in { "gitlab-config.service" "gitlab-db-config.service" ]; - wants = [ "redis-gitlab.service" ] ++ optional (cfg.databaseHost == "") "postgresql.service"; + wants = [ "redis-gitlab.service" ] ++ lib.optional (cfg.databaseHost == "") "postgresql.service"; requiredBy = [ "gitlab.target" ]; partOf = [ "gitlab.target" ]; environment = gitlabEnv; @@ -1689,7 +1687,7 @@ in { Restart = "on-failure"; WorkingDirectory = "${cfg.packages.gitlab}/share/gitlab"; Slice = "system-gitlab.slice"; - ExecStart = concatStringsSep " " [ + ExecStart = lib.concatStringsSep " " [ "${cfg.packages.gitlab.rubyEnv}/bin/bundle" "exec" "puma" "-e production" "-C ${cfg.statePath}/config/puma.rb" @@ -1707,7 +1705,7 @@ in { environment = { RAILS_ENV = "production"; CRON = "1"; - } // optionalAttrs (stringLength cfg.backup.skip > 0) { + } // lib.optionalAttrs (lib.stringLength cfg.backup.skip > 0) { SKIP = cfg.backup.skip; }; serviceConfig = { @@ -1721,5 +1719,5 @@ in { }; meta.doc = ./gitlab.md; - meta.maintainers = teams.gitlab.members; + meta.maintainers = lib.teams.gitlab.members; } diff --git a/nixos/modules/services/misc/gotenberg.nix b/nixos/modules/services/misc/gotenberg.nix index e92e11b50c71b..dbec09291170f 100644 --- a/nixos/modules/services/misc/gotenberg.nix +++ b/nixos/modules/services/misc/gotenberg.nix @@ -18,53 +18,43 @@ let "--libreoffice-max-queue-size=${toString cfg.libreoffice.maxQueueSize}" "--pdfengines-engines=${lib.concatStringsSep "," cfg.pdfEngines}" ] - ++ optional cfg.enableBasicAuth "--api-enable-basic-auth" - ++ optional cfg.chromium.autoStart "--chromium-auto-start" - ++ optional cfg.chromium.disableJavascript "--chromium-disable-javascript" - ++ optional cfg.chromium.disableRoutes "--chromium-disable-routes" - ++ optional cfg.libreoffice.autoStart "--libreoffice-auto-start" - ++ optional cfg.libreoffice.disableRoutes "--libreoffice-disable-routes"; - - inherit (lib) - mkEnableOption - mkPackageOption - mkOption - types - mkIf - optional - optionalAttrs - ; + ++ lib.optional cfg.enableBasicAuth "--api-enable-basic-auth" + ++ lib.optional cfg.chromium.autoStart "--chromium-auto-start" + ++ lib.optional cfg.chromium.disableJavascript "--chromium-disable-javascript" + ++ lib.optional cfg.chromium.disableRoutes "--chromium-disable-routes" + ++ lib.optional cfg.libreoffice.autoStart "--libreoffice-auto-start" + ++ lib.optional cfg.libreoffice.disableRoutes "--libreoffice-disable-routes"; in { options = { services.gotenberg = { - enable = mkEnableOption "Gotenberg, a stateless API for PDF files"; + enable = lib.mkEnableOption "Gotenberg, a stateless API for PDF files"; # Users can override only gotenberg, libreoffice and chromium if they want to (eg. ungoogled-chromium, different LO version, etc) # Don't allow setting the qpdf, pdftk, or unoconv paths, as those are very stable # and there's only one version of each. - package = mkPackageOption pkgs "gotenberg" { }; + package = lib.mkPackageOption pkgs "gotenberg" { }; - port = mkOption { - type = types.port; + port = lib.mkOption { + type = lib.types.port; default = 3000; description = "Port on which the API should listen."; }; - timeout = mkOption { - type = types.nullOr types.str; + timeout = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = "30s"; description = "Timeout for API requests."; }; - rootPath = mkOption { - type = types.str; + rootPath = lib.mkOption { + type = lib.types.str; default = "/"; description = "Root path for the Gotenberg API."; }; - enableBasicAuth = mkOption { - type = types.bool; + enableBasicAuth = lib.mkOption { + type = lib.types.bool; default = false; description = '' HTTP Basic Authentication. @@ -74,71 +64,71 @@ in ''; }; - extraFontPackages = mkOption { - type = types.listOf types.package; + extraFontPackages = lib.mkOption { + type = lib.types.listOf lib.types.package; default = [ ]; description = "Extra fonts to make available."; }; chromium = { - package = mkPackageOption pkgs "chromium" { }; + package = lib.mkPackageOption pkgs "chromium" { }; - maxQueueSize = mkOption { - type = types.int; + maxQueueSize = lib.mkOption { + type = lib.types.int; default = 0; description = "Maximum queue size for chromium-based conversions. Setting to 0 disables the limit."; }; - autoStart = mkOption { - type = types.bool; + autoStart = lib.mkOption { + type = lib.types.bool; default = false; description = "Automatically start chromium when Gotenberg starts. If false, Chromium will start on the first conversion request that uses it."; }; - disableJavascript = mkOption { - type = types.bool; + disableJavascript = lib.mkOption { + type = lib.types.bool; default = false; description = "Disable Javascript execution."; }; - disableRoutes = mkOption { - type = types.bool; + disableRoutes = lib.mkOption { + type = lib.types.bool; default = false; description = "Disable all routes allowing Chromium-based conversion."; }; }; libreoffice = { - package = mkPackageOption pkgs "libreoffice" { }; + package = lib.mkPackageOption pkgs "libreoffice" { }; - restartAfter = mkOption { - type = types.int; + restartAfter = lib.mkOption { + type = lib.types.int; default = 10; description = "Restart LibreOffice after this many conversions. Setting to 0 disables this feature."; }; - maxQueueSize = mkOption { - type = types.int; + maxQueueSize = lib.mkOption { + type = lib.types.int; default = 0; description = "Maximum queue size for LibreOffice-based conversions. Setting to 0 disables the limit."; }; - autoStart = mkOption { - type = types.bool; + autoStart = lib.mkOption { + type = lib.types.bool; default = false; description = "Automatically start LibreOffice when Gotenberg starts. If false, Chromium will start on the first conversion request that uses it."; }; - disableRoutes = mkOption { - type = types.bool; + disableRoutes = lib.mkOption { + type = lib.types.bool; default = false; description = "Disable all routes allowing LibreOffice-based conversion."; }; }; - pdfEngines = mkOption { - type = types.listOf ( - types.enum [ + pdfEngines = lib.mkOption { + type = lib.types.listOf ( + lib.types.enum [ "pdftk" "qpdf" "libreoffice-pdfengine" @@ -160,8 +150,8 @@ in ''; }; - logLevel = mkOption { - type = types.enum [ + logLevel = lib.mkOption { + type = lib.types.enum [ "error" "warn" "info" @@ -171,21 +161,21 @@ in description = "The logging level for Gotenberg."; }; - environmentFile = mkOption { - type = types.nullOr types.path; + environmentFile = lib.mkOption { + type = lib.types.nullOr lib.types.path; default = null; description = "Environment file to load extra environment variables from."; }; - extraArgs = mkOption { - type = types.listOf types.str; + extraArgs = lib.mkOption { + type = lib.types.listOf lib.types.str; default = [ ]; description = "Any extra command-line flags to pass to the Gotenberg service."; }; }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { assertions = [ { assertion = cfg.enableBasicAuth -> cfg.environmentFile != null; @@ -247,7 +237,7 @@ in SystemCallArchitectures = "native"; UMask = 77; - } // optionalAttrs (cfg.environmentFile != null) { EnvironmentFile = cfg.environmentFile; }; + } // lib.optionalAttrs (cfg.environmentFile != null) { EnvironmentFile = cfg.environmentFile; }; }; }; diff --git a/nixos/modules/services/misc/guix/default.nix b/nixos/modules/services/misc/guix/default.nix index 049a6a5b42223..efd207834b2c4 100644 --- a/nixos/modules/services/misc/guix/default.nix +++ b/nixos/modules/services/misc/guix/default.nix @@ -67,11 +67,11 @@ in { meta.maintainers = with lib.maintainers; [ foo-dogsquared ]; - options.services.guix = with lib; { - enable = mkEnableOption "Guix build daemon service"; + options.services.guix = { + enable = lib.mkEnableOption "Guix build daemon service"; - group = mkOption { - type = types.str; + group = lib.mkOption { + type = lib.types.str; default = "guixbuild"; example = "guixbuild"; description = '' @@ -79,8 +79,8 @@ in ''; }; - nrBuildUsers = mkOption { - type = types.ints.unsigned; + nrBuildUsers = lib.mkOption { + type = lib.types.ints.unsigned; description = '' Number of Guix build users to be used in the build pool. ''; @@ -88,8 +88,8 @@ in example = 20; }; - extraArgs = mkOption { - type = with types; listOf str; + extraArgs = lib.mkOption { + type = with lib.types; listOf str; default = [ ]; example = [ "--max-jobs=4" @@ -100,15 +100,15 @@ in ''; }; - package = mkPackageOption pkgs "guix" { + package = lib.mkPackageOption pkgs "guix" { extraDescription = '' It should contain {command}`guix-daemon` and {command}`guix` executable. ''; }; - storeDir = mkOption { - type = types.path; + storeDir = lib.mkOption { + type = lib.types.path; default = "/gnu/store"; description = '' The store directory where the Guix service will serve to/from. Take @@ -123,8 +123,8 @@ in ''; }; - stateDir = mkOption { - type = types.path; + stateDir = lib.mkOption { + type = lib.types.path; default = "/var"; description = '' The state directory where Guix service will store its data such as its @@ -190,10 +190,10 @@ in }; publish = { - enable = mkEnableOption "substitute server for your Guix store directory"; + enable = lib.mkEnableOption "substitute server for your Guix store directory"; - generateKeyPair = mkOption { - type = types.bool; + generateKeyPair = lib.mkOption { + type = lib.types.bool; description = '' Whether to generate signing keys in {file}`/etc/guix` which are required to initialize a substitute server. Otherwise, @@ -204,8 +204,8 @@ in example = false; }; - port = mkOption { - type = types.port; + port = lib.mkOption { + type = lib.types.port; default = 8181; example = 8200; description = '' @@ -213,16 +213,16 @@ in ''; }; - user = mkOption { - type = types.str; + user = lib.mkOption { + type = lib.types.str; default = "guix-publish"; description = '' Name of the user to change once the server is up. ''; }; - extraArgs = mkOption { - type = with types; listOf str; + extraArgs = lib.mkOption { + type = with lib.types; listOf str; description = '' Extra flags to pass to the substitute server. ''; @@ -235,10 +235,10 @@ in }; gc = { - enable = mkEnableOption "automatic garbage collection service for Guix"; + enable = lib.mkEnableOption "automatic garbage collection service for Guix"; - extraArgs = mkOption { - type = with types; listOf str; + extraArgs = lib.mkOption { + type = with lib.types; listOf str; default = [ ]; description = '' List of arguments to be passed to {command}`guix gc`. @@ -255,7 +255,7 @@ in }; dates = lib.mkOption { - type = types.str; + type = lib.types.str; default = "03:15"; example = "weekly"; description = '' diff --git a/nixos/modules/services/misc/jellyfin.nix b/nixos/modules/services/misc/jellyfin.nix index 89640b9a32118..9030aa8377b5d 100644 --- a/nixos/modules/services/misc/jellyfin.nix +++ b/nixos/modules/services/misc/jellyfin.nix @@ -6,38 +6,29 @@ }: let - inherit (lib) - mkIf - getExe - maintainers - mkEnableOption - mkOption - mkPackageOption - ; - inherit (lib.types) str path bool; cfg = config.services.jellyfin; in { options = { services.jellyfin = { - enable = mkEnableOption "Jellyfin Media Server"; + enable = lib.mkEnableOption "Jellyfin Media Server"; - package = mkPackageOption pkgs "jellyfin" { }; + package = lib.mkPackageOption pkgs "jellyfin" { }; - user = mkOption { - type = str; + user = lib.mkOption { + type = lib.types.str; default = "jellyfin"; description = "User account under which Jellyfin runs."; }; - group = mkOption { - type = str; + group = lib.mkOption { + type = lib.types.str; default = "jellyfin"; description = "Group under which jellyfin runs."; }; - dataDir = mkOption { - type = path; + dataDir = lib.mkOption { + type = lib.types.path; default = "/var/lib/jellyfin"; description = '' Base data directory, @@ -45,8 +36,8 @@ in ''; }; - configDir = mkOption { - type = path; + configDir = lib.mkOption { + type = lib.types.path; default = "${cfg.dataDir}/config"; defaultText = "\${cfg.dataDir}/config"; description = '' @@ -55,8 +46,8 @@ in ''; }; - cacheDir = mkOption { - type = path; + cacheDir = lib.mkOption { + type = lib.types.path; default = "/var/cache/jellyfin"; description = '' Directory containing the jellyfin server cache, @@ -64,8 +55,8 @@ in ''; }; - logDir = mkOption { - type = path; + logDir = lib.mkOption { + type = lib.types.path; default = "${cfg.dataDir}/log"; defaultText = "\${cfg.dataDir}/log"; description = '' @@ -74,8 +65,8 @@ in ''; }; - openFirewall = mkOption { - type = bool; + openFirewall = lib.mkOption { + type = lib.types.bool; default = false; description = '' Open the default ports in the firewall for the media server. The @@ -86,7 +77,7 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { systemd = { tmpfiles.settings.jellyfinDirs = { "${cfg.dataDir}"."d" = { @@ -120,7 +111,7 @@ in Group = cfg.group; UMask = "0077"; WorkingDirectory = cfg.dataDir; - ExecStart = "${getExe cfg.package} --datadir '${cfg.dataDir}' --configdir '${cfg.configDir}' --cachedir '${cfg.cacheDir}' --logdir '${cfg.logDir}'"; + ExecStart = "${lib.getExe cfg.package} --datadir '${cfg.dataDir}' --configdir '${cfg.configDir}' --cachedir '${cfg.cacheDir}' --logdir '${cfg.logDir}'"; Restart = "on-failure"; TimeoutSec = 15; SuccessExitStatus = [ @@ -175,18 +166,18 @@ in }; }; - users.users = mkIf (cfg.user == "jellyfin") { + users.users = lib.mkIf (cfg.user == "jellyfin") { jellyfin = { inherit (cfg) group; isSystemUser = true; }; }; - users.groups = mkIf (cfg.group == "jellyfin") { + users.groups = lib.mkIf (cfg.group == "jellyfin") { jellyfin = { }; }; - networking.firewall = mkIf cfg.openFirewall { + networking.firewall = lib.mkIf cfg.openFirewall { # from https://jellyfin.org/docs/general/networking/index.html allowedTCPPorts = [ 8096 @@ -200,7 +191,7 @@ in }; - meta.maintainers = with maintainers; [ + meta.maintainers = with lib.maintainers; [ minijackson fsnkty ]; diff --git a/nixos/modules/services/misc/metabase.nix b/nixos/modules/services/misc/metabase.nix index eebe582548a56..87a619182ee8f 100644 --- a/nixos/modules/services/misc/metabase.nix +++ b/nixos/modules/services/misc/metabase.nix @@ -3,9 +3,6 @@ let cfg = config.services.metabase; - inherit (lib) mkEnableOption mkIf mkOption; - inherit (lib) optional optionalAttrs types; - dataDir = "/var/lib/metabase"; in { @@ -13,19 +10,19 @@ in { options = { services.metabase = { - enable = mkEnableOption "Metabase service"; + enable = lib.mkEnableOption "Metabase service"; listen = { - ip = mkOption { - type = types.str; + ip = lib.mkOption { + type = lib.types.str; default = "0.0.0.0"; description = '' IP address that Metabase should listen on. ''; }; - port = mkOption { - type = types.port; + port = lib.mkOption { + type = lib.types.port; default = 3000; description = '' Listen port for Metabase. @@ -34,24 +31,24 @@ in { }; ssl = { - enable = mkOption { - type = types.bool; + enable = lib.mkOption { + type = lib.types.bool; default = false; description = '' Whether to enable SSL (https) support. ''; }; - port = mkOption { - type = types.port; + port = lib.mkOption { + type = lib.types.port; default = 8443; description = '' Listen port over SSL (https) for Metabase. ''; }; - keystore = mkOption { - type = types.nullOr types.path; + keystore = lib.mkOption { + type = lib.types.nullOr lib.types.path; default = "${dataDir}/metabase.jks"; example = "/etc/secrets/keystore.jks"; description = '' @@ -61,8 +58,8 @@ in { }; - openFirewall = mkOption { - type = types.bool; + openFirewall = lib.mkOption { + type = lib.types.bool; default = false; description = '' Open ports in the firewall for Metabase. @@ -72,7 +69,7 @@ in { }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { systemd.services.metabase = { description = "Metabase server"; @@ -84,7 +81,7 @@ in { MB_DB_FILE = "${dataDir}/metabase.db"; MB_JETTY_HOST = cfg.listen.ip; MB_JETTY_PORT = toString cfg.listen.port; - } // optionalAttrs (cfg.ssl.enable) { + } // lib.optionalAttrs (cfg.ssl.enable) { MB_JETTY_SSL = true; MB_JETTY_SSL_PORT = toString cfg.ssl.port; MB_JETTY_SSL_KEYSTORE = cfg.ssl.keystore; @@ -96,8 +93,8 @@ in { }; }; - networking.firewall = mkIf cfg.openFirewall { - allowedTCPPorts = [ cfg.listen.port ] ++ optional cfg.ssl.enable cfg.ssl.port; + networking.firewall = lib.mkIf cfg.openFirewall { + allowedTCPPorts = [ cfg.listen.port ] ++ lib.optional cfg.ssl.enable cfg.ssl.port; }; }; diff --git a/nixos/modules/services/misc/mollysocket.nix b/nixos/modules/services/misc/mollysocket.nix index 9f733612578b0..23d194b510216 100644 --- a/nixos/modules/services/misc/mollysocket.nix +++ b/nixos/modules/services/misc/mollysocket.nix @@ -6,67 +6,59 @@ }: let - inherit (lib) - getExe - mkIf - mkOption - mkEnableOption - types - ; - cfg = config.services.mollysocket; configuration = format.generate "mollysocket.conf" cfg.settings; format = pkgs.formats.toml { }; package = pkgs.writeShellScriptBin "mollysocket" '' - MOLLY_CONF=${configuration} exec ${getExe pkgs.mollysocket} "$@" + MOLLY_CONF=${configuration} exec ${lib.getExe pkgs.mollysocket} "$@" ''; in { options.services.mollysocket = { - enable = mkEnableOption '' + enable = lib.mkEnableOption '' [MollySocket](https://github.com/mollyim/mollysocket) for getting Signal notifications via UnifiedPush ''; - settings = mkOption { + settings = lib.mkOption { default = { }; description = '' Configuration for MollySocket. Available options are listed [here](https://github.com/mollyim/mollysocket#configuration). ''; - type = types.submodule { + type = lib.types.submodule { freeformType = format.type; options = { - host = mkOption { + host = lib.mkOption { default = "127.0.0.1"; description = "Listening address of the web server"; - type = types.str; + type = lib.types.str; }; - port = mkOption { + port = lib.mkOption { default = 8020; description = "Listening port of the web server"; - type = types.port; + type = lib.types.port; }; - allowed_endpoints = mkOption { + allowed_endpoints = lib.mkOption { default = [ "*" ]; description = "List of UnifiedPush servers"; example = [ "https://ntfy.sh" ]; - type = with types; listOf str; + type = with lib.types; listOf str; }; - allowed_uuids = mkOption { + allowed_uuids = lib.mkOption { default = [ "*" ]; description = "UUIDs of Signal accounts that may use this server"; example = [ "abcdef-12345-tuxyz-67890" ]; - type = with types; listOf str; + type = with lib.types; listOf str; }; }; }; }; - environmentFile = mkOption { + environmentFile = lib.mkOption { default = null; description = '' Environment file (see {manpage}`systemd.exec(5)` "EnvironmentFile=" @@ -74,18 +66,18 @@ in used to safely include secrets in the configuration. ''; example = "/run/secrets/mollysocket"; - type = with types; nullOr path; + type = with lib.types; nullOr path; }; - logLevel = mkOption { + logLevel = lib.mkOption { default = "info"; description = "Set the {env}`RUST_LOG` environment variable"; example = "debug"; - type = types.str; + type = lib.types.str; }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { environment.systemPackages = [ package ]; @@ -99,7 +91,7 @@ in environment.RUST_LOG = cfg.logLevel; serviceConfig = { EnvironmentFile = cfg.environmentFile; - ExecStart = "${getExe package} server"; + ExecStart = "${lib.getExe package} server"; KillSignal = "SIGINT"; Restart = "on-failure"; StateDirectory = "mollysocket"; diff --git a/nixos/modules/services/misc/ollama.nix b/nixos/modules/services/misc/ollama.nix index b26d5b37002d3..411206026caf3 100644 --- a/nixos/modules/services/misc/ollama.nix +++ b/nixos/modules/services/misc/ollama.nix @@ -40,7 +40,7 @@ in package = lib.mkPackageOption pkgs "ollama" { }; user = lib.mkOption { - type = with types; nullOr str; + type = with lib.types; nullOr str; default = null; example = "ollama"; description = '' @@ -51,9 +51,9 @@ in ''; }; group = lib.mkOption { - type = with types; nullOr str; + type = with lib.types; nullOr str; default = cfg.user; - defaultText = literalExpression "config.services.ollama.user"; + defaultText = lib.literalExpression "config.services.ollama.user"; example = "ollama"; description = '' Group under which to run ollama. Only used when `services.ollama.user` is set. @@ -63,7 +63,7 @@ in }; home = lib.mkOption { - type = types.str; + type = lib.types.str; default = "/var/lib/ollama"; example = "/home/foo"; description = '' @@ -71,7 +71,7 @@ in ''; }; models = lib.mkOption { - type = types.str; + type = lib.types.str; default = "${cfg.home}/models"; defaultText = "\${config.services.ollama.home}/models"; example = "/path/to/ollama/models"; @@ -81,7 +81,7 @@ in }; host = lib.mkOption { - type = types.str; + type = lib.types.str; default = "127.0.0.1"; example = "[::]"; description = '' @@ -89,7 +89,7 @@ in ''; }; port = lib.mkOption { - type = types.port; + type = lib.types.port; default = 11434; example = 11111; description = '' @@ -98,7 +98,7 @@ in }; acceleration = lib.mkOption { - type = types.nullOr ( + type = lib.types.nullOr ( types.enum [ false "rocm" @@ -122,7 +122,7 @@ in ''; }; rocmOverrideGfx = lib.mkOption { - type = types.nullOr types.str; + type = lib.types.nullOr lib.types.str; default = null; example = "10.3.0"; description = '' @@ -136,7 +136,7 @@ in }; environmentVariables = lib.mkOption { - type = types.attrsOf types.str; + type = lib.types.attrsOf lib.types.str; default = { }; example = { OLLAMA_LLM_LIBRARY = "cpu"; @@ -151,7 +151,7 @@ in ''; }; loadModels = lib.mkOption { - type = types.listOf types.str; + type = lib.types.listOf lib.types.str; default = [ ]; description = '' Download these models using `ollama pull` as soon as `ollama.service` has started. @@ -162,7 +162,7 @@ in ''; }; openFirewall = lib.mkOption { - type = types.bool; + type = lib.types.bool; default = false; description = '' Whether to open the firewall for ollama. diff --git a/nixos/modules/services/misc/open-webui.nix b/nixos/modules/services/misc/open-webui.nix index 37cf05fe012b0..4faf293d2724a 100644 --- a/nixos/modules/services/misc/open-webui.nix +++ b/nixos/modules/services/misc/open-webui.nix @@ -16,14 +16,14 @@ in package = lib.mkPackageOption pkgs "open-webui" { }; stateDir = lib.mkOption { - type = types.path; + type = lib.types.path; default = "/var/lib/open-webui"; example = "/home/foo"; description = "State directory of Open-WebUI."; }; host = lib.mkOption { - type = types.str; + type = lib.types.str; default = "127.0.0.1"; example = "0.0.0.0"; description = '' @@ -32,7 +32,7 @@ in }; port = lib.mkOption { - type = types.port; + type = lib.types.port; default = 8080; example = 11111; description = '' @@ -41,7 +41,7 @@ in }; environment = lib.mkOption { - type = types.attrsOf types.str; + type = lib.types.attrsOf lib.types.str; default = { SCARF_NO_ANALYTICS = "True"; DO_NOT_TRACK = "True"; @@ -72,7 +72,7 @@ in }; openFirewall = lib.mkOption { - type = types.bool; + type = lib.types.bool; default = false; description = '' Whether to open the firewall for Open-WebUI. diff --git a/nixos/modules/services/misc/packagekit.nix b/nixos/modules/services/misc/packagekit.nix index d55f736b3bed1..497108f2a5b2c 100644 --- a/nixos/modules/services/misc/packagekit.nix +++ b/nixos/modules/services/misc/packagekit.nix @@ -8,21 +8,11 @@ let cfg = config.services.packagekit; - inherit (lib) - mkEnableOption - mkOption - mkIf - mkRemovedOptionModule - types - listToAttrs - recursiveUpdate - ; - iniFmt = pkgs.formats.ini { }; confFiles = [ (iniFmt.generate "PackageKit.conf" ( - recursiveUpdate { + lib.recursiveUpdate { Daemon = { DefaultBackend = "test_nop"; KeepCache = false; @@ -31,7 +21,7 @@ let )) (iniFmt.generate "Vendor.conf" ( - recursiveUpdate { + lib.recursiveUpdate { PackagesNotFound = rec { DefaultUrl = "https://github.com/NixOS/nixpkgs"; CodecUrl = DefaultUrl; @@ -46,7 +36,7 @@ let in { imports = [ - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "packagekit" "backend" @@ -54,26 +44,26 @@ in ]; options.services.packagekit = { - enable = mkEnableOption '' + enable = lib.mkEnableOption '' PackageKit, a cross-platform D-Bus abstraction layer for installing software. Software utilizing PackageKit can install software regardless of the package manager ''; - settings = mkOption { + settings = lib.mkOption { type = iniFmt.type; default = { }; description = "Additional settings passed straight through to PackageKit.conf"; }; - vendorSettings = mkOption { + vendorSettings = lib.mkOption { type = iniFmt.type; default = { }; description = "Additional settings passed straight through to Vendor.conf"; }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { services.dbus.packages = with pkgs; [ packagekit ]; @@ -81,7 +71,7 @@ in systemd.packages = with pkgs; [ packagekit ]; - environment.etc = listToAttrs ( + environment.etc = lib.listToAttrs ( map (e: lib.nameValuePair "PackageKit/${e.name}" { source = e; }) confFiles ); }; diff --git a/nixos/modules/services/misc/podgrab.nix b/nixos/modules/services/misc/podgrab.nix index af4f4eacb53e1..ec760d6ba9f64 100644 --- a/nixos/modules/services/misc/podgrab.nix +++ b/nixos/modules/services/misc/podgrab.nix @@ -10,11 +10,11 @@ let stateDir = "/var/lib/podgrab"; in { - options.services.podgrab = with lib; { - enable = mkEnableOption "Podgrab, a self-hosted podcast manager"; + options.services.podgrab = { + enable = lib.mkEnableOption "Podgrab, a self-hosted podcast manager"; - passwordFile = mkOption { - type = with types; nullOr str; + passwordFile = lib.mkOption { + type = with lib.types; nullOr str; default = null; example = "/run/secrets/password.env"; description = '' @@ -23,28 +23,28 @@ in ''; }; - port = mkOption { - type = types.port; + port = lib.mkOption { + type = lib.types.port; default = 8080; example = 4242; description = "The port on which Podgrab will listen for incoming HTTP traffic."; }; - dataDirectory = mkOption { - type = types.path; + dataDirectory = lib.mkOption { + type = lib.types.path; default = "${stateDir}/data"; example = "/mnt/podcasts"; description = "Directory to store downloads."; }; - user = mkOption { - type = types.str; + user = lib.mkOption { + type = lib.types.str; default = "podgrab"; description = "User under which Podgrab runs, and which owns the download directory."; }; - group = mkOption { - type = types.str; + group = lib.mkOption { + type = lib.types.str; default = "podgrab"; description = "Group under which Podgrab runs, and which owns the download directory."; }; diff --git a/nixos/modules/services/misc/private-gpt.nix b/nixos/modules/services/misc/private-gpt.nix index e7974f93d66a6..50449509c4843 100644 --- a/nixos/modules/services/misc/private-gpt.nix +++ b/nixos/modules/services/misc/private-gpt.nix @@ -17,7 +17,7 @@ in package = lib.mkPackageOption pkgs "private-gpt" { }; stateDir = lib.mkOption { - type = types.path; + type = lib.types.path; default = "/var/lib/private-gpt"; description = "State directory of private-gpt."; }; diff --git a/nixos/modules/services/misc/redlib.nix b/nixos/modules/services/misc/redlib.nix index 3e3cd31a814cb..325209410080d 100644 --- a/nixos/modules/services/misc/redlib.nix +++ b/nixos/modules/services/misc/redlib.nix @@ -6,21 +6,9 @@ }: let - inherit (lib) - concatStringsSep - isBool - mapAttrs - mkEnableOption - mkIf - mkOption - mkPackageOption - mkRenamedOptionModule - types - ; - cfg = config.services.redlib; - args = concatStringsSep " " ([ + args = lib.concatStringsSep " " ([ "--port ${toString cfg.port}" "--address ${cfg.address}" ]); @@ -29,7 +17,7 @@ let in { imports = [ - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "libreddit" @@ -43,26 +31,26 @@ in options = { services.redlib = { - enable = mkEnableOption "Private front-end for Reddit"; + enable = lib.mkEnableOption "Private front-end for Reddit"; - package = mkPackageOption pkgs "redlib" { }; + package = lib.mkPackageOption pkgs "redlib" { }; - address = mkOption { + address = lib.mkOption { default = "0.0.0.0"; example = "127.0.0.1"; - type = types.str; + type = lib.types.str; description = "The address to listen on"; }; - port = mkOption { + port = lib.mkOption { default = 8080; example = 8000; - type = types.port; + type = lib.types.port; description = "The port to listen on"; }; - openFirewall = mkOption { - type = types.bool; + openFirewall = lib.mkOption { + type = lib.types.bool; default = false; description = "Open ports in the firewall for the redlib web interface"; }; @@ -70,7 +58,7 @@ in settings = lib.mkOption { type = lib.types.submodule { freeformType = - with types; + with lib.types; attrsOf ( nullOr (oneOf [ bool @@ -88,11 +76,11 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { systemd.packages = [ cfg.package ]; systemd.services.redlib = { wantedBy = [ "default.target" ]; - environment = mapAttrs (_: v: if isBool v then boolToString' v else toString v) cfg.settings; + environment = lib.mapAttrs (_: v: if lib.isBool v then boolToString' v else toString v) cfg.settings; serviceConfig = { ExecStart = [ @@ -115,7 +103,7 @@ in ); }; - networking.firewall = mkIf cfg.openFirewall { + networking.firewall = lib.mkIf cfg.openFirewall { allowedTCPPorts = [ cfg.port ]; }; }; diff --git a/nixos/modules/services/misc/redmine.nix b/nixos/modules/services/misc/redmine.nix index eceabc317d1a2..4a9c8e39fca1f 100644 --- a/nixos/modules/services/misc/redmine.nix +++ b/nixos/modules/services/misc/redmine.nix @@ -6,19 +6,6 @@ }: let - inherit (lib) - mkBefore - mkDefault - mkEnableOption - mkPackageOption - mkIf - mkOption - mkRemovedOptionModule - types - ; - inherit (lib) concatStringsSep literalExpression mapAttrsToList; - inherit (lib) optional optionalAttrs optionalString; - cfg = config.services.redmine; format = pkgs.formats.yaml { }; bundle = "${cfg.package}/share/redmine/bin/bundle"; @@ -30,7 +17,7 @@ let database = if cfg.database.type == "sqlite3" then "${cfg.stateDir}/database.sqlite3" else cfg.database.name; } - // optionalAttrs (cfg.database.type != "sqlite3") { + // lib.optionalAttrs (cfg.database.type != "sqlite3") { host = if (cfg.database.type == "postgresql" && cfg.database.socket != null) then cfg.database.socket @@ -39,10 +26,10 @@ let port = cfg.database.port; username = cfg.database.user; } - // optionalAttrs (cfg.database.type != "sqlite3" && cfg.database.passwordFile != null) { + // lib.optionalAttrs (cfg.database.type != "sqlite3" && cfg.database.passwordFile != null) { password = "#dbpass#"; } - // optionalAttrs (cfg.database.type == "mysql2" && cfg.database.socket != null) { + // lib.optionalAttrs (cfg.database.type == "mysql2" && cfg.database.socket != null) { socket = cfg.database.socket; }; }; @@ -75,12 +62,12 @@ let in { imports = [ - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "redmine" "extraConfig" ] "Use services.redmine.settings instead.") - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "services" "redmine" "database" @@ -91,43 +78,43 @@ in # interface options = { services.redmine = { - enable = mkEnableOption "Redmine, a project management web application"; + enable = lib.mkEnableOption "Redmine, a project management web application"; - package = mkPackageOption pkgs "redmine" { + package = lib.mkPackageOption pkgs "redmine" { example = "redmine.override { ruby = pkgs.ruby_3_2; }"; }; - user = mkOption { - type = types.str; + user = lib.mkOption { + type = lib.types.str; default = "redmine"; description = "User under which Redmine is ran."; }; - group = mkOption { - type = types.str; + group = lib.mkOption { + type = lib.types.str; default = "redmine"; description = "Group under which Redmine is ran."; }; - address = mkOption { - type = types.str; + address = lib.mkOption { + type = lib.types.str; default = "0.0.0.0"; description = "IP address Redmine should bind to."; }; - port = mkOption { - type = types.port; + port = lib.mkOption { + type = lib.types.port; default = 3000; description = "Port on which Redmine is ran."; }; - stateDir = mkOption { - type = types.path; + stateDir = lib.mkOption { + type = lib.types.path; default = "/var/lib/redmine"; description = "The state directory, logs and plugins are stored here."; }; - settings = mkOption { + settings = lib.mkOption { type = format.type; default = { }; description = '' @@ -135,7 +122,7 @@ in for details. ''; - example = literalExpression '' + example = lib.literalExpression '' { email_delivery = { delivery_method = "smtp"; @@ -148,8 +135,8 @@ in ''; }; - extraEnv = mkOption { - type = types.lines; + extraEnv = lib.mkOption { + type = lib.types.lines; default = ""; description = '' Extra configuration in additional_environment.rb. @@ -162,11 +149,11 @@ in ''; }; - themes = mkOption { - type = types.attrsOf types.path; + themes = lib.mkOption { + type = lib.types.attrsOf lib.types.path; default = { }; description = "Set of themes."; - example = literalExpression '' + example = lib.literalExpression '' { dkuk-redmine_alex_skin = builtins.fetchurl { url = "https://bitbucket.org/dkuk/redmine_alex_skin/get/1842ef675ef3.zip"; @@ -176,11 +163,11 @@ in ''; }; - plugins = mkOption { - type = types.attrsOf types.path; + plugins = lib.mkOption { + type = lib.types.attrsOf lib.types.path; default = { }; description = "Set of plugins."; - example = literalExpression '' + example = lib.literalExpression '' { redmine_env_auth = builtins.fetchurl { url = "https://github.com/Intera/redmine_env_auth/archive/0.6.zip"; @@ -191,8 +178,8 @@ in }; database = { - type = mkOption { - type = types.enum [ + type = lib.mkOption { + type = lib.types.enum [ "mysql2" "postgresql" "sqlite3" @@ -202,33 +189,33 @@ in description = "Database engine to use."; }; - host = mkOption { - type = types.str; + host = lib.mkOption { + type = lib.types.str; default = "localhost"; description = "Database host address."; }; - port = mkOption { - type = types.port; + port = lib.mkOption { + type = lib.types.port; default = if cfg.database.type == "postgresql" then 5432 else 3306; - defaultText = literalExpression "3306"; + defaultText = lib.literalExpression "3306"; description = "Database host port."; }; - name = mkOption { - type = types.str; + name = lib.mkOption { + type = lib.types.str; default = "redmine"; description = "Database name."; }; - user = mkOption { - type = types.str; + user = lib.mkOption { + type = lib.types.str; default = "redmine"; description = "Database user."; }; - passwordFile = mkOption { - type = types.nullOr types.path; + passwordFile = lib.mkOption { + type = lib.types.nullOr lib.types.path; default = null; example = "/run/keys/redmine-dbpassword"; description = '' @@ -237,8 +224,8 @@ in ''; }; - socket = mkOption { - type = types.nullOr types.path; + socket = lib.mkOption { + type = lib.types.nullOr lib.types.path; default = if mysqlLocal then "/run/mysqld/mysqld.sock" @@ -246,63 +233,63 @@ in "/run/postgresql" else null; - defaultText = literalExpression "/run/mysqld/mysqld.sock"; + defaultText = lib.literalExpression "/run/mysqld/mysqld.sock"; example = "/run/mysqld/mysqld.sock"; description = "Path to the unix socket file to use for authentication."; }; - createLocally = mkOption { - type = types.bool; + createLocally = lib.mkOption { + type = lib.types.bool; default = true; description = "Create the database and database user locally."; }; }; components = { - subversion = mkOption { - type = types.bool; + subversion = lib.mkOption { + type = lib.types.bool; default = false; description = "Subversion integration."; }; - mercurial = mkOption { - type = types.bool; + mercurial = lib.mkOption { + type = lib.types.bool; default = false; description = "Mercurial integration."; }; - git = mkOption { - type = types.bool; + git = lib.mkOption { + type = lib.types.bool; default = false; description = "git integration."; }; - cvs = mkOption { - type = types.bool; + cvs = lib.mkOption { + type = lib.types.bool; default = false; description = "cvs integration."; }; - breezy = mkOption { - type = types.bool; + breezy = lib.mkOption { + type = lib.types.bool; default = false; description = "bazaar integration."; }; - imagemagick = mkOption { - type = types.bool; + imagemagick = lib.mkOption { + type = lib.types.bool; default = false; description = "Allows exporting Gant diagrams as PNG."; }; - ghostscript = mkOption { - type = types.bool; + ghostscript = lib.mkOption { + type = lib.types.bool; default = false; description = "Allows exporting Gant diagrams as PDF."; }; - minimagick_font_path = mkOption { - type = types.str; + minimagick_font_path = lib.mkOption { + type = lib.types.str; default = ""; description = "MiniMagick font path"; example = "/run/current-system/sw/share/X11/fonts/LiberationSans-Regular.ttf"; @@ -312,7 +299,7 @@ in }; # implementation - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { assertions = [ { @@ -345,25 +332,25 @@ in services.redmine.settings = { production = { - scm_subversion_command = optionalString cfg.components.subversion "${pkgs.subversion}/bin/svn"; - scm_mercurial_command = optionalString cfg.components.mercurial "${pkgs.mercurial}/bin/hg"; - scm_git_command = optionalString cfg.components.git "${pkgs.git}/bin/git"; - scm_cvs_command = optionalString cfg.components.cvs "${pkgs.cvs}/bin/cvs"; - scm_bazaar_command = optionalString cfg.components.breezy "${pkgs.breezy}/bin/bzr"; - imagemagick_convert_command = optionalString cfg.components.imagemagick "${pkgs.imagemagick}/bin/convert"; - gs_command = optionalString cfg.components.ghostscript "${pkgs.ghostscript}/bin/gs"; + scm_subversion_command = lib.optionalString cfg.components.subversion "${pkgs.subversion}/bin/svn"; + scm_mercurial_command = lib.optionalString cfg.components.mercurial "${pkgs.mercurial}/bin/hg"; + scm_git_command = lib.optionalString cfg.components.git "${pkgs.git}/bin/git"; + scm_cvs_command = lib.optionalString cfg.components.cvs "${pkgs.cvs}/bin/cvs"; + scm_bazaar_command = lib.optionalString cfg.components.breezy "${pkgs.breezy}/bin/bzr"; + imagemagick_convert_command = lib.optionalString cfg.components.imagemagick "${pkgs.imagemagick}/bin/convert"; + gs_command = lib.optionalString cfg.components.ghostscript "${pkgs.ghostscript}/bin/gs"; minimagick_font_path = "${cfg.components.minimagick_font_path}"; }; }; - services.redmine.extraEnv = mkBefore '' + services.redmine.extraEnv = lib.mkBefore '' config.logger = Logger.new("${cfg.stateDir}/log/production.log", 14, 1048576) config.logger.level = Logger::INFO ''; - services.mysql = mkIf mysqlLocal { + services.mysql = lib.mkIf mysqlLocal { enable = true; - package = mkDefault pkgs.mariadb; + package = lib.mkDefault pkgs.mariadb; ensureDatabases = [ cfg.database.name ]; ensureUsers = [ { @@ -375,7 +362,7 @@ in ]; }; - services.postgresql = mkIf pgsqlLocal { + services.postgresql = lib.mkIf pgsqlLocal { enable = true; ensureDatabases = [ cfg.database.name ]; ensureUsers = [ @@ -413,8 +400,8 @@ in systemd.services.redmine = { after = [ "network.target" ] - ++ optional mysqlLocal "mysql.service" - ++ optional pgsqlLocal "postgresql.service"; + ++ lib.optional mysqlLocal "mysql.service" + ++ lib.optional pgsqlLocal "postgresql.service"; wantedBy = [ "multi-user.target" ]; environment.RAILS_ENV = "production"; environment.RAILS_CACHE = "${cfg.stateDir}/cache"; @@ -424,13 +411,13 @@ in with pkgs; [ ] - ++ optional cfg.components.subversion subversion - ++ optional cfg.components.mercurial mercurial - ++ optional cfg.components.git git - ++ optional cfg.components.cvs cvs - ++ optional cfg.components.breezy breezy - ++ optional cfg.components.imagemagick imagemagick - ++ optional cfg.components.ghostscript ghostscript; + ++ lib.optional cfg.components.subversion subversion + ++ lib.optional cfg.components.mercurial mercurial + ++ lib.optional cfg.components.git git + ++ lib.optional cfg.components.cvs cvs + ++ lib.optional cfg.components.breezy breezy + ++ lib.optional cfg.components.imagemagick imagemagick + ++ lib.optional cfg.components.ghostscript ghostscript; preStart = '' rm -rf "${cfg.stateDir}/plugins/"* @@ -451,7 +438,7 @@ in # link in all user specified themes - for theme in ${concatStringsSep " " (mapAttrsToList unpackTheme cfg.themes)}; do + for theme in ${lib.concatStringsSep " " (lib.mapAttrsToList unpackTheme cfg.themes)}; do ln -fs $theme/* "${cfg.stateDir}/public/themes" done @@ -460,7 +447,7 @@ in # link in all user specified plugins - for plugin in ${concatStringsSep " " (mapAttrsToList unpackPlugin cfg.plugins)}; do + for plugin in ${lib.concatStringsSep " " (lib.mapAttrsToList unpackPlugin cfg.plugins)}; do ln -fs $plugin/* "${cfg.stateDir}/plugins/''${plugin##*-redmine-plugin-}" done @@ -468,7 +455,7 @@ in # handle database.passwordFile & permissions cp -f ${databaseYml} "${cfg.stateDir}/config/database.yml" - ${optionalString ((cfg.database.type != "sqlite3") && (cfg.database.passwordFile != null)) '' + ${lib.optionalString ((cfg.database.type != "sqlite3") && (cfg.database.passwordFile != null)) '' DBPASS="$(head -n1 ${cfg.database.passwordFile})" sed -e "s,#dbpass#,$DBPASS,g" -i "${cfg.stateDir}/config/database.yml" ''} @@ -527,7 +514,7 @@ in }; - users.users = optionalAttrs (cfg.user == "redmine") { + users.users = lib.optionalAttrs (cfg.user == "redmine") { redmine = { group = cfg.group; home = cfg.stateDir; @@ -535,7 +522,7 @@ in }; }; - users.groups = optionalAttrs (cfg.group == "redmine") { + users.groups = lib.optionalAttrs (cfg.group == "redmine") { redmine.gid = config.ids.gids.redmine; }; diff --git a/nixos/modules/services/misc/renovate.nix b/nixos/modules/services/misc/renovate.nix index cc1185fb0580d..8441eb9b13d45 100644 --- a/nixos/modules/services/misc/renovate.nix +++ b/nixos/modules/services/misc/renovate.nix @@ -5,13 +5,6 @@ ... }: let - inherit (lib) - mkEnableOption - mkPackageOption - mkOption - types - mkIf - ; json = pkgs.formats.json { }; cfg = config.services.renovate; generateValidatedConfig = @@ -42,16 +35,16 @@ in ]; options.services.renovate = { - enable = mkEnableOption "renovate"; - package = mkPackageOption pkgs "renovate" { }; - schedule = mkOption { - type = with types; nullOr str; + enable = lib.mkEnableOption "renovate"; + package = lib.mkPackageOption pkgs "renovate" { }; + schedule = lib.mkOption { + type = with lib.types; nullOr str; description = "How often to run renovate. See {manpage}`systemd.time(7)` for the format."; example = "*:0/10"; default = null; }; - credentials = mkOption { - type = with types; attrsOf path; + credentials = lib.mkOption { + type = with lib.types; attrsOf path; description = '' Allows configuring environment variable credentials for renovate, read from files. This should always be used for passing confidential data to renovate. @@ -61,17 +54,17 @@ in }; default = { }; }; - runtimePackages = mkOption { - type = with types; listOf package; + runtimePackages = lib.mkOption { + type = with lib.types; listOf package; description = "Packages available to renovate."; default = [ ]; }; - validateSettings = mkOption { - type = types.bool; + validateSettings = lib.mkOption { + type = lib.types.bool; default = true; description = "Weither to run renovate's config validator on the built configuration."; }; - settings = mkOption { + settings = lib.mkOption { type = json.type; default = { }; example = { @@ -86,7 +79,7 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { services.renovate.settings = { cacheDir = "/var/cache/renovate"; baseDir = "/var/lib/renovate"; diff --git a/nixos/modules/services/misc/rippled.nix b/nixos/modules/services/misc/rippled.nix index 8b1f3c7df1178..10fba8ba7170a 100644 --- a/nixos/modules/services/misc/rippled.nix +++ b/nixos/modules/services/misc/rippled.nix @@ -305,7 +305,7 @@ in https://ripple.com/ripple.txt or if you prefer you can let it default to r.ripple.com 51235 - A port may optionally be specified after adding a space to the + A port may lib.optionally be specified after adding a space to the address. By convention, if known, IPs are listed in from most to least trusted. ''; @@ -321,7 +321,7 @@ in validation server that connects to the Ripple network through a public-facing server, or for building a set of cluster peers. - A port may optionally be specified after adding a space to the address + A port may lib.optionally be specified after adding a space to the address ''; type = lib.types.listOf lib.types.str; default = [ ]; diff --git a/nixos/modules/services/misc/sourcehut/default.nix b/nixos/modules/services/misc/sourcehut/default.nix index ebce033fd55c1..d63379825ea5d 100644 --- a/nixos/modules/services/misc/sourcehut/default.nix +++ b/nixos/modules/services/misc/sourcehut/default.nix @@ -6,38 +6,6 @@ }: let - inherit (builtins) head tail; - inherit (lib) generators maintainers types; - inherit (lib.attrsets) - attrValues - filterAttrs - mapAttrs - mapAttrsToList - recursiveUpdate - ; - inherit (lib.lists) flatten optional optionals; - inherit (lib.options) - literalExpression - mkEnableOption - mkOption - mkPackageOption - ; - inherit (lib.strings) - concatMapStringsSep - concatStringsSep - optionalString - versionOlder - ; - inherit (lib.trivial) mapNullable; - inherit (lib.modules) - mkBefore - mkDefault - mkForce - mkIf - mkMerge - mkRemovedOptionModule - mkRenamedOptionModule - ; inherit (config.services) nginx postfix @@ -48,11 +16,11 @@ let cfg = config.services.sourcehut; domain = cfg.settings."sr.ht".global-domain; settingsFormat = pkgs.formats.ini { - listToValue = concatMapStringsSep "," (generators.mkValueStringDefault { }); + listToValue = lib.concatMapStringsSep "," (lib.generators.mkValueStringDefault { }); mkKeyValue = k: v: - optionalString (v != null) ( - generators.mkKeyValueDefault { + lib.optionalString (v != null) ( + lib.generators.mkKeyValueDefault { mkValueString = v: if v == true then @@ -60,7 +28,7 @@ let else if v == false then "no" else - generators.mkValueStringDefault { } v; + lib.generators.mkValueStringDefault { } v; } "=" k v ); }; @@ -69,8 +37,8 @@ let settingsFormat.generate "sourcehut-${srv}-config.ini" # Each service needs access to only a subset of sections (and secrets). ( - filterAttrs (k: v: v != null) ( - mapAttrs + lib.filterAttrs (k: v: v != null) ( + lib.mapAttrs ( section: v: let @@ -78,11 +46,11 @@ let in if srvMatch == null # Include sections shared by all services - || head srvMatch == srv # Include sections for the service being configured + || lib.head srvMatch == srv # Include sections for the service being configured then v # Enable Web links and integrations between services. - else if tail srvMatch == [ null ] && cfg.${head srvMatch}.enable then + else if lib.tail srvMatch == [ null ] && cfg.${lib.head srvMatch}.enable then { inherit (v) origin; # mansrht crashes without it @@ -93,7 +61,7 @@ let null ) ( - recursiveUpdate cfg.settings { + lib.recursiveUpdate cfg.settings { # Those paths are mounted using BindPaths= or BindReadOnlyPaths= # for services needing access to them. "builds.sr.ht::worker".buildlogs = "/var/log/sourcehut/buildsrht-worker"; @@ -109,42 +77,42 @@ let ) ); commonServiceSettings = srv: { - origin = mkOption { + origin = lib.mkOption { description = "URL ${srv}.sr.ht is being served at (protocol://domain)"; - type = types.str; + type = lib.types.str; default = "https://${srv}.${domain}"; defaultText = "https://${srv}.example.com"; }; - debug-host = mkOption { + debug-host = lib.mkOption { description = "Address to bind the debug server to."; - type = with types; nullOr str; + type = with lib.types; nullOr str; default = null; }; - debug-port = mkOption { + debug-port = lib.mkOption { description = "Port to bind the debug server to."; - type = with types; nullOr str; + type = with lib.types; nullOr str; default = null; }; - connection-string = mkOption { + connection-string = lib.mkOption { description = "SQLAlchemy connection string for the database."; - type = types.str; + type = lib.types.str; default = "postgresql:///localhost?user=${srv}srht&host=/run/postgresql"; }; - migrate-on-upgrade = mkEnableOption "automatic migrations on package upgrade" // { + migrate-on-upgrade = lib.mkEnableOption "automatic migrations on package upgrade" // { default = true; }; - oauth-client-id = mkOption { + oauth-client-id = lib.mkOption { description = "${srv}.sr.ht's OAuth client id for meta.sr.ht."; - type = types.str; + type = lib.types.str; }; - oauth-client-secret = mkOption { + oauth-client-secret = lib.mkOption { description = "${srv}.sr.ht's OAuth client secret for meta.sr.ht."; - type = types.path; + type = lib.types.path; apply = s: "<" + toString s; }; - api-origin = mkOption { + api-origin = lib.mkOption { description = "Origin URL for the API"; - type = types.str; + type = lib.types.str; default = "http://${cfg.listenAddress}:${toString (cfg.${srv}.port + 100)}"; defaultText = lib.literalMD '' `"http://''${`[](#opt-services.sourcehut.listenAddress)`}:''${toString (`[](#opt-services.sourcehut.${srv}.port)` + 100)}"` @@ -174,30 +142,30 @@ let todosrht ] ); - mkOptionNullOrStr = + lib.mkOptionNullOrStr = description: - mkOption { + lib.mkOption { description = description; - type = with types; nullOr str; + type = with lib.types; nullOr str; default = null; }; in { options.services.sourcehut = { - enable = mkEnableOption '' + enable = lib.mkEnableOption '' sourcehut - git hosting, continuous integration, mailing list, ticket tracking, wiki and account management services ''; - listenAddress = mkOption { - type = types.str; + listenAddress = lib.mkOption { + type = lib.types.str; default = "localhost"; description = "Address to bind to."; }; - python = mkOption { + python = lib.mkOption { internal = true; - type = types.package; + type = lib.types.package; default = python; description = '' The python package to use. It should contain references to the *srht modules and also @@ -206,77 +174,77 @@ in }; minio = { - enable = mkEnableOption ''local minio integration''; + enable = lib.mkEnableOption ''local minio integration''; }; nginx = { - enable = mkEnableOption ''local nginx integration''; - virtualHost = mkOption { - type = types.attrs; + enable = lib.mkEnableOption ''local nginx integration''; + virtualHost = lib.mkOption { + type = lib.types.attrs; default = { }; description = "Virtual-host configuration merged with all Sourcehut's virtual-hosts."; }; }; postfix = { - enable = mkEnableOption ''local postfix integration''; + enable = lib.mkEnableOption ''local postfix integration''; }; postgresql = { - enable = mkEnableOption ''local postgresql integration''; + enable = lib.mkEnableOption ''local postgresql integration''; }; redis = { - enable = mkEnableOption ''local redis integration in a dedicated redis-server''; + enable = lib.mkEnableOption ''local redis integration in a dedicated redis-server''; }; - settings = mkOption { + settings = lib.mkOption { type = lib.types.submodule { freeformType = settingsFormat.type; options."sr.ht" = { - global-domain = mkOption { + global-domain = lib.mkOption { description = "Global domain name."; - type = types.str; + type = lib.types.str; example = "example.com"; }; - environment = mkOption { + environment = lib.mkOption { description = "Values other than \"production\" adds a banner to each page."; - type = types.enum [ + type = lib.types.enum [ "development" "production" ]; default = "development"; }; - network-key = mkOption { + network-key = lib.mkOption { description = '' An absolute file path (which should be outside the Nix-store) to a secret key to encrypt internal messages with. Use `srht-keygen network` to generate this key. It must be consistent between all services and nodes. ''; - type = types.path; + type = lib.types.path; apply = s: "<" + toString s; }; - owner-email = mkOption { + owner-email = lib.mkOption { description = "Owner's email."; - type = types.str; + type = lib.types.str; default = "contact@example.com"; }; - owner-name = mkOption { + owner-name = lib.mkOption { description = "Owner's name."; - type = types.str; + type = lib.types.str; default = "John Doe"; }; - site-blurb = mkOption { + site-blurb = lib.mkOption { description = "Blurb for your site."; - type = types.str; + type = lib.types.str; default = "the hacker's forge"; }; - site-info = mkOption { + site-info = lib.mkOption { description = "The top-level info page for your site."; - type = types.str; + type = lib.types.str; default = "https://sourcehut.org"; }; - service-key = mkOption { + service-key = lib.mkOption { description = '' An absolute file path (which should be outside the Nix-store) to a key used for encrypting session cookies. Use `srht-keygen service` to @@ -285,37 +253,37 @@ in different keys. If you configure all of your services with the same config.ini, you may use the same service-key for all of them. ''; - type = types.path; + type = lib.types.path; apply = s: "<" + toString s; }; - site-name = mkOption { + site-name = lib.mkOption { description = "The name of your network of sr.ht-based sites."; - type = types.str; + type = lib.types.str; default = "sourcehut"; }; - source-url = mkOption { + source-url = lib.mkOption { description = "The source code for your fork of sr.ht."; - type = types.str; + type = lib.types.str; default = "https://git.sr.ht/~sircmpwn/srht"; }; }; options.mail = { - smtp-host = mkOptionNullOrStr "Outgoing SMTP host."; - smtp-port = mkOption { + smtp-host = lib.mkOptionNullOrStr "Outgoing SMTP host."; + smtp-port = lib.mkOption { description = "Outgoing SMTP port."; - type = with types; nullOr port; + type = with lib.types; nullOr port; default = null; }; - smtp-user = mkOptionNullOrStr "Outgoing SMTP user."; - smtp-password = mkOptionNullOrStr "Outgoing SMTP password."; - smtp-from = mkOption { - type = types.str; + smtp-user = lib.mkOptionNullOrStr "Outgoing SMTP user."; + smtp-password = lib.mkOptionNullOrStr "Outgoing SMTP password."; + smtp-from = lib.mkOption { + type = lib.types.str; description = "Outgoing SMTP FROM."; }; - error-to = mkOptionNullOrStr "Address receiving application exceptions"; - error-from = mkOptionNullOrStr "Address sending application exceptions"; - pgp-privkey = mkOption { - type = types.str; + error-to = lib.mkOptionNullOrStr "Address receiving application exceptions"; + error-from = lib.mkOptionNullOrStr "Address sending application exceptions"; + pgp-privkey = lib.mkOption { + type = lib.types.str; description = '' An absolute file path (which should be outside the Nix-store) to an OpenPGP private key. @@ -326,38 +294,38 @@ in then use the `passwd` command and do not enter a new password. ''; }; - pgp-pubkey = mkOption { - type = with types; either path str; + pgp-pubkey = lib.mkOption { + type = with lib.types; either path str; description = "OpenPGP public key."; }; - pgp-key-id = mkOption { - type = types.str; + pgp-key-id = lib.mkOption { + type = lib.types.str; description = "OpenPGP key identifier."; }; }; options.objects = { - s3-upstream = mkOption { + s3-upstream = lib.mkOption { description = "Configure the S3-compatible object storage service."; - type = with types; nullOr str; + type = with lib.types; nullOr str; default = null; }; - s3-access-key = mkOption { + s3-access-key = lib.mkOption { description = "Access key to the S3-compatible object storage service"; - type = with types; nullOr str; + type = with lib.types; nullOr str; default = null; }; - s3-secret-key = mkOption { + s3-secret-key = lib.mkOption { description = '' An absolute file path (which should be outside the Nix-store) to the secret key of the S3-compatible object storage service. ''; - type = with types; nullOr path; + type = with lib.types; nullOr path; default = null; - apply = mapNullable (s: "<" + toString s); + apply = lib.mapNullable (s: "<" + toString s); }; }; options.webhooks = { - private-key = mkOption { + private-key = lib.mkOption { description = '' An absolute file path (which should be outside the Nix-store) to a base64-encoded Ed25519 key for signing webhook payloads. @@ -366,19 +334,19 @@ in from other sites in your network. Use the `srht-keygen webhook` command to generate a key. ''; - type = types.path; + type = lib.types.path; apply = s: "<" + toString s; }; }; options."builds.sr.ht" = commonServiceSettings "builds" // { - allow-free = mkEnableOption "nonpaying users to submit builds"; - redis = mkOption { + allow-free = lib.mkEnableOption "nonpaying users to submit builds"; + redis = lib.mkOption { description = "The Redis connection used for the Celery worker."; - type = types.str; + type = lib.types.str; default = "redis+socket:///run/redis-sourcehut-buildsrht/redis.sock?virtual_host=2"; }; - shell = mkOption { + shell = lib.mkOption { description = '' Scripts used to launch on SSH connection. `/usr/bin/master-shell` on master, @@ -386,7 +354,7 @@ in If master and worker are on the same system set to `/usr/bin/runner-shell`. ''; - type = types.enum [ + type = lib.types.enum [ "/usr/bin/master-shell" "/usr/bin/runner-shell" ]; @@ -394,75 +362,75 @@ in }; }; options."builds.sr.ht::worker" = { - bind-address = mkOption { + bind-address = lib.mkOption { description = '' HTTP bind address for serving local build information/monitoring. ''; - type = types.str; + type = lib.types.str; default = "localhost:8080"; }; - buildlogs = mkOption { + buildlogs = lib.mkOption { description = "Path to write build logs."; - type = types.str; + type = lib.types.str; default = "/var/log/sourcehut/buildsrht-worker"; }; - name = mkOption { + name = lib.mkOption { description = '' Listening address and listening port of the build runner (with HTTP port if not 80). ''; - type = types.str; + type = lib.types.str; default = "localhost:5020"; }; - timeout = mkOption { + timeout = lib.mkOption { description = '' Max build duration. See . ''; - type = types.str; + type = lib.types.str; default = "3m"; }; }; options."git.sr.ht" = commonServiceSettings "git" // { - outgoing-domain = mkOption { + outgoing-domain = lib.mkOption { description = "Outgoing domain."; - type = types.str; + type = lib.types.str; default = "https://git.localhost.localdomain"; }; - post-update-script = mkOption { + post-update-script = lib.mkOption { description = '' A post-update script which is installed in every git repo. This setting is propagated to newer and existing repositories. ''; - type = types.path; + type = lib.types.path; default = "${pkgs.sourcehut.gitsrht}/bin/gitsrht-update-hook"; defaultText = "\${pkgs.sourcehut.gitsrht}/bin/gitsrht-update-hook"; }; - repos = mkOption { + repos = lib.mkOption { description = '' Path to git repositories on disk. If changing the default, you must ensure that the gitsrht's user as read and write access to it. ''; - type = types.str; + type = lib.types.str; default = "/var/lib/sourcehut/gitsrht/repos"; }; - webhooks = mkOption { + webhooks = lib.mkOption { description = "The Redis connection used for the webhooks worker."; - type = types.str; + type = lib.types.str; default = "redis+socket:///run/redis-sourcehut-gitsrht/redis.sock?virtual_host=1"; }; }; options."git.sr.ht::api" = { - internal-ipnet = mkOption { + internal-ipnet = lib.mkOption { description = '' Set of IP subnets which are permitted to utilize internal API authentication. This should be limited to the subnets from which your *.sr.ht services are running. See [](#opt-services.sourcehut.listenAddress). ''; - type = with types; listOf str; + type = with lib.types; listOf str; default = [ "127.0.0.0/8" "::1/128" @@ -471,42 +439,42 @@ in }; options."hg.sr.ht" = commonServiceSettings "hg" // { - changegroup-script = mkOption { + changegroup-script = lib.mkOption { description = '' A changegroup script which is installed in every mercurial repo. This setting is propagated to newer and existing repositories. ''; - type = types.str; + type = lib.types.str; default = "${pkgs.sourcehut.hgsrht}/bin/hgsrht-hook-changegroup"; defaultText = "\${pkgs.sourcehut.hgsrht}/bin/hgsrht-hook-changegroup"; }; - repos = mkOption { + repos = lib.mkOption { description = '' Path to mercurial repositories on disk. If changing the default, you must ensure that the hgsrht's user as read and write access to it. ''; - type = types.str; + type = lib.types.str; default = "/var/lib/sourcehut/hgsrht/repos"; }; - srhtext = mkOptionNullOrStr '' + srhtext = lib.mkOptionNullOrStr '' Path to the srht mercurial extension (defaults to where the hgsrht code is) ''; - clone_bundle_threshold = mkOption { + clone_bundle_threshold = lib.mkOption { description = ".hg/store size (in MB) past which the nightly job generates clone bundles."; - type = types.ints.unsigned; + type = lib.types.ints.unsigned; default = 50; }; - hg_ssh = mkOption { + hg_ssh = lib.mkOption { description = "Path to hg-ssh (if not in $PATH)."; - type = types.str; + type = lib.types.str; default = "${pkgs.mercurial}/bin/hg-ssh"; defaultText = "\${pkgs.mercurial}/bin/hg-ssh"; }; - webhooks = mkOption { + webhooks = lib.mkOption { description = "The Redis connection used for the webhooks worker."; - type = types.str; + type = lib.types.str; default = "redis+socket:///run/redis-sourcehut-hgsrht/redis.sock?virtual_host=1"; }; }; @@ -515,30 +483,30 @@ in }; options."lists.sr.ht" = commonServiceSettings "lists" // { - allow-new-lists = mkEnableOption "creation of new lists"; - notify-from = mkOption { + allow-new-lists = lib.mkEnableOption "creation of new lists"; + notify-from = lib.mkOption { description = "Outgoing email for notifications generated by users."; - type = types.str; + type = lib.types.str; default = "lists-notify@localhost.localdomain"; }; - posting-domain = mkOption { + posting-domain = lib.mkOption { description = "Posting domain."; - type = types.str; + type = lib.types.str; default = "lists.localhost.localdomain"; }; - redis = mkOption { + redis = lib.mkOption { description = "The Redis connection used for the Celery worker."; - type = types.str; + type = lib.types.str; default = "redis+socket:///run/redis-sourcehut-listssrht/redis.sock?virtual_host=2"; }; - webhooks = mkOption { + webhooks = lib.mkOption { description = "The Redis connection used for the webhooks worker."; - type = types.str; + type = lib.types.str; default = "redis+socket:///run/redis-sourcehut-listssrht/redis.sock?virtual_host=1"; }; }; options."lists.sr.ht::worker" = { - reject-mimetypes = mkOption { + reject-mimetypes = lib.mkOption { description = '' Comma-delimited list of Content-Types to reject. Messages with Content-Types included in this list are rejected. Multipart messages are always supported, @@ -546,28 +514,28 @@ in Uses fnmatch for wildcard expansion. ''; - type = with types; listOf str; + type = with lib.types; listOf str; default = [ "text/html" ]; }; - reject-url = mkOption { + reject-url = lib.mkOption { description = "Reject URL."; - type = types.str; + type = lib.types.str; default = "https://man.sr.ht/lists.sr.ht/etiquette.md"; }; - sock = mkOption { + sock = lib.mkOption { description = '' Path for the lmtp daemon's unix socket. Direct incoming mail to this socket. Alternatively, specify IP:PORT and an SMTP server will be run instead. ''; - type = types.str; + type = lib.types.str; default = "/tmp/lists.sr.ht-lmtp.sock"; }; - sock-group = mkOption { + sock-group = lib.mkOption { description = '' The lmtp daemon will make the unix socket group-read/write for users in this group. ''; - type = types.str; + type = lib.types.str; default = "postfix"; }; }; @@ -581,97 +549,97 @@ in "oauth-client-secret" ] // { - webhooks = mkOption { + webhooks = lib.mkOption { description = "The Redis connection used for the webhooks worker."; - type = types.str; + type = lib.types.str; default = "redis+socket:///run/redis-sourcehut-metasrht/redis.sock?virtual_host=1"; }; - welcome-emails = mkEnableOption "sending stock sourcehut welcome emails after signup"; + welcome-emails = lib.mkEnableOption "sending stock sourcehut welcome emails after signup"; }; options."meta.sr.ht::api" = { - internal-ipnet = mkOption { + internal-ipnet = lib.mkOption { description = '' Set of IP subnets which are permitted to utilize internal API authentication. This should be limited to the subnets from which your *.sr.ht services are running. See [](#opt-services.sourcehut.listenAddress). ''; - type = with types; listOf str; + type = with lib.types; listOf str; default = [ "127.0.0.0/8" "::1/128" ]; }; }; - options."meta.sr.ht::aliases" = mkOption { + options."meta.sr.ht::aliases" = lib.mkOption { description = "Aliases for the client IDs of commonly used OAuth clients."; - type = with types; attrsOf int; + type = with lib.types; attrsOf int; default = { }; example = { "git.sr.ht" = 12345; }; }; options."meta.sr.ht::billing" = { - enabled = mkEnableOption "the billing system"; - stripe-public-key = mkOptionNullOrStr "Public key for Stripe. Get your keys at https://dashboard.stripe.com/account/apikeys"; + enabled = lib.mkEnableOption "the billing system"; + stripe-public-key = lib.mkOptionNullOrStr "Public key for Stripe. Get your keys at https://dashboard.stripe.com/account/apikeys"; stripe-secret-key = - mkOptionNullOrStr '' + lib.mkOptionNullOrStr '' An absolute file path (which should be outside the Nix-store) to a secret key for Stripe. Get your keys at https://dashboard.stripe.com/account/apikeys '' // { - apply = mapNullable (s: "<" + toString s); + apply = lib.mapNullable (s: "<" + toString s); }; }; options."meta.sr.ht::settings" = { - registration = mkEnableOption "public registration"; - onboarding-redirect = mkOption { + registration = lib.mkEnableOption "public registration"; + onboarding-redirect = lib.mkOption { description = "Where to redirect new users upon registration."; - type = types.str; + type = lib.types.str; default = "https://meta.localhost.localdomain"; }; - user-invites = mkOption { + user-invites = lib.mkOption { description = '' How many invites each user is issued upon registration (only applicable if open registration is disabled). ''; - type = types.ints.unsigned; + type = lib.types.ints.unsigned; default = 5; }; }; options."pages.sr.ht" = commonServiceSettings "pages" // { - gemini-certs = mkOption { + gemini-certs = lib.mkOption { description = '' An absolute file path (which should be outside the Nix-store) to Gemini certificates. ''; - type = with types; nullOr path; + type = with lib.types; nullOr path; default = null; }; - max-site-size = mkOption { + max-site-size = lib.mkOption { description = "Maximum size of any given site (post-gunzip), in MiB."; - type = types.int; + type = lib.types.int; default = 1024; }; - user-domain = mkOption { + user-domain = lib.mkOption { description = '' Configures the user domain, if enabled. All users are given \.this.domain. ''; - type = with types; nullOr str; + type = with lib.types; nullOr str; default = null; }; }; options."pages.sr.ht::api" = { - internal-ipnet = mkOption { + internal-ipnet = lib.mkOption { description = '' Set of IP subnets which are permitted to utilize internal API authentication. This should be limited to the subnets from which your *.sr.ht services are running. See [](#opt-services.sourcehut.listenAddress). ''; - type = with types; listOf str; + type = with lib.types; listOf str; default = [ "127.0.0.0/8" "::1/128" @@ -683,37 +651,37 @@ in }; options."todo.sr.ht" = commonServiceSettings "todo" // { - notify-from = mkOption { + notify-from = lib.mkOption { description = "Outgoing email for notifications generated by users."; - type = types.str; + type = lib.types.str; default = "todo-notify@localhost.localdomain"; }; - webhooks = mkOption { + webhooks = lib.mkOption { description = "The Redis connection used for the webhooks worker."; - type = types.str; + type = lib.types.str; default = "redis+socket:///run/redis-sourcehut-todosrht/redis.sock?virtual_host=1"; }; }; options."todo.sr.ht::mail" = { - posting-domain = mkOption { + posting-domain = lib.mkOption { description = "Posting domain."; - type = types.str; + type = lib.types.str; default = "todo.localhost.localdomain"; }; - sock = mkOption { + sock = lib.mkOption { description = '' Path for the lmtp daemon's unix socket. Direct incoming mail to this socket. Alternatively, specify IP:PORT and an SMTP server will be run instead. ''; - type = types.str; + type = lib.types.str; default = "/tmp/todo.sr.ht-lmtp.sock"; }; - sock-group = mkOption { + sock-group = lib.mkOption { description = '' The lmtp daemon will make the unix socket group-read/write for users in this group. ''; - type = types.str; + type = lib.types.str; default = "postfix"; }; }; @@ -725,7 +693,7 @@ in }; builds = { - enableWorker = mkEnableOption '' + enableWorker = lib.mkEnableOption '' worker for builds.sr.ht ::: {.warning} @@ -737,8 +705,8 @@ in ::: ''; - images = mkOption { - type = with types; attrsOf (attrsOf (attrsOf package)); + images = lib.mkOption { + type = with lib.types; attrsOf (attrsOf (attrsOf package)); default = { }; example = lib.literalExpression '' (let @@ -763,20 +731,20 @@ in }; git = { - package = mkPackageOption pkgs "git" { + package = lib.mkPackageOption pkgs "git" { example = "gitFull"; }; - fcgiwrap.preforkProcess = mkOption { + fcgiwrap.preforkProcess = lib.mkOption { description = "Number of fcgiwrap processes to prefork."; - type = types.int; + type = lib.types.int; default = 4; }; }; hg = { - package = mkPackageOption pkgs "mercurial" { }; - cloneBundles = mkOption { - type = types.bool; + package = lib.mkPackageOption pkgs "mercurial" { }; + cloneBundles = lib.mkOption { + type = lib.types.bool; default = false; description = '' Generate clonebundles (which require more disk space but dramatically speed up cloning large repositories). @@ -786,8 +754,8 @@ in lists = { process = { - extraArgs = mkOption { - type = with types; listOf str; + extraArgs = lib.mkOption { + type = with lib.types; listOf str; default = [ "--loglevel DEBUG" "--pool eventlet" @@ -795,8 +763,8 @@ in ]; description = "Extra arguments passed to the Celery responsible for processing mails."; }; - celeryConfig = mkOption { - type = types.lines; + celeryConfig = lib.mkOption { + type = lib.types.lines; default = ""; description = "Content of the `celeryconfig.py` used by the Celery of `listssrht-process`."; }; @@ -804,20 +772,20 @@ in }; }; - config = mkIf cfg.enable (mkMerge [ + config = lib.mkIf cfg.enable (lib.mkMerge [ { environment.systemPackages = [ pkgs.sourcehut.coresrht ]; services.sourcehut.settings = { - "git.sr.ht".outgoing-domain = mkDefault "https://git.${domain}"; - "lists.sr.ht".notify-from = mkDefault "lists-notify@${domain}"; - "lists.sr.ht".posting-domain = mkDefault "lists.${domain}"; - "meta.sr.ht::settings".onboarding-redirect = mkDefault "https://meta.${domain}"; - "todo.sr.ht".notify-from = mkDefault "todo-notify@${domain}"; - "todo.sr.ht::mail".posting-domain = mkDefault "todo.${domain}"; + "git.sr.ht".outgoing-domain = lib.mkDefault "https://git.${domain}"; + "lists.sr.ht".notify-from = lib.mkDefault "lists-notify@${domain}"; + "lists.sr.ht".posting-domain = lib.mkDefault "lists.${domain}"; + "meta.sr.ht::settings".onboarding-redirect = lib.mkDefault "https://meta.${domain}"; + "todo.sr.ht".notify-from = lib.mkDefault "todo-notify@${domain}"; + "todo.sr.ht::mail".posting-domain = lib.mkDefault "todo.${domain}"; }; } - (mkIf cfg.postgresql.enable { + (lib.mkIf cfg.postgresql.enable { assertions = [ { assertion = postgresql.enable; @@ -825,7 +793,7 @@ in } ]; }) - (mkIf cfg.postfix.enable { + (lib.mkIf cfg.postfix.enable { assertions = [ { assertion = postfix.enable; @@ -835,10 +803,10 @@ in # Needed for sharing the LMTP sockets with JoinsNamespaceOf= systemd.services.postfix.serviceConfig.PrivateTmp = true; }) - (mkIf cfg.redis.enable { - services.redis.vmOverCommit = mkDefault true; + (lib.mkIf cfg.redis.enable { + services.redis.vmOverCommit = lib.mkDefault true; }) - (mkIf cfg.nginx.enable { + (lib.mkIf cfg.nginx.enable { assertions = [ { assertion = nginx.enable; @@ -846,9 +814,9 @@ in } ]; # For proxyPass= in virtual-hosts for Sourcehut services. - services.nginx.recommendedProxySettings = mkDefault true; + services.nginx.recommendedProxySettings = lib.mkDefault true; }) - (mkIf (cfg.builds.enable || cfg.git.enable || cfg.hg.enable) { + (lib.mkIf (cfg.builds.enable || cfg.git.enable || cfg.hg.enable) { services.openssh = { # Note that sshd will continue to honor AuthorizedKeysFile. # Note that you may want automatically rotate @@ -867,7 +835,7 @@ in }; environment.etc."ssh/sourcehut/config.ini".source = settingsFormat.generate "sourcehut-dispatch-config.ini" - (filterAttrs (k: v: k == "git.sr.ht::dispatch") cfg.settings); + (lib.filterAttrs (k: v: k == "git.sr.ht::dispatch") cfg.settings); environment.etc."ssh/sourcehut/subdir/srht-dispatch" = { # sshd_config(5): The program must be owned by root, not writable by group or others mode = "0755"; @@ -878,7 +846,7 @@ in ${pkgs.sourcehut.gitsrht}/bin/gitsrht-dispatch "$@" ''; }; - systemd.tmpfiles.settings."10-sourcehut-gitsrht" = mkIf cfg.git.enable (mkMerge [ + systemd.tmpfiles.settings."10-sourcehut-gitsrht" = lib.mkIf cfg.git.enable (lib.mkMerge [ (builtins.listToAttrs ( map (name: { @@ -902,7 +870,7 @@ in } ]); systemd.services.sshd = { - preStart = mkIf cfg.hg.enable '' + preStart = lib.mkIf cfg.hg.enable '' chown ${cfg.hg.user}:${cfg.hg.group} /var/log/sourcehut/hgsrht-keys ''; serviceConfig = { @@ -915,7 +883,7 @@ in # - access the PostgreSQL server in [*.sr.ht] connection-string, # - query metasrht-api (through the HTTP API). # Using this has the side effect of creating empty files in /usr/bin/ - optionals cfg.builds.enable [ + lib.optionals cfg.builds.enable [ "${pkgs.writeShellScript "buildsrht-keys-wrapper" '' set -e cd /run/sourcehut/buildsrht/subdir @@ -924,7 +892,7 @@ in "${pkgs.sourcehut.buildsrht}/bin/master-shell:/usr/bin/master-shell" "${pkgs.sourcehut.buildsrht}/bin/runner-shell:/usr/bin/runner-shell" ] - ++ optionals cfg.git.enable [ + ++ lib.optionals cfg.git.enable [ # /path/to/gitsrht-keys calls /path/to/gitsrht-shell, # or [git.sr.ht] shell= if set. "${pkgs.writeShellScript "gitsrht-keys-wrapper" '' @@ -954,7 +922,7 @@ in fi ''}:/usr/bin/gitsrht-update-hook" ] - ++ optionals cfg.hg.enable [ + ++ lib.optionals cfg.hg.enable [ # /path/to/hgsrht-keys calls /path/to/hgsrht-shell, # or [hg.sr.ht] shell= if set. "${pkgs.writeShellScript "hgsrht-keys-wrapper" '' @@ -1001,7 +969,7 @@ in serviceName = "buildsrht-worker"; statePath = "/var/lib/sourcehut/${serviceName}"; in - mkIf cfg.builds.enableWorker { + lib.mkIf cfg.builds.enableWorker { path = [ pkgs.openssh pkgs.docker @@ -1036,12 +1004,12 @@ in }; extraConfig = let - image_dirs = flatten ( - mapAttrsToList ( + image_dirs = lib.flatten ( + lib.mapAttrsToList ( distro: revs: - mapAttrsToList ( + lib.mapAttrsToList ( rev: archs: - mapAttrsToList ( + lib.mapAttrsToList ( arch: image: pkgs.runCommand "buildsrht-images" { } '' mkdir -p $out/${distro}/${rev}/${arch} @@ -1062,38 +1030,38 @@ in cp -Lr ${image_dir_pre}/* $out/images ''; in - mkMerge [ + lib.mkMerge [ { users.users.${cfg.builds.user}.shell = pkgs.bash; virtualisation.docker.enable = true; - services.sourcehut.settings = mkMerge [ + services.sourcehut.settings = lib.mkMerge [ { # Note that git.sr.ht::dispatch is not a typo, # gitsrht-dispatch always use this section "git.sr.ht::dispatch"."/usr/bin/buildsrht-keys" = - mkDefault "${cfg.builds.user}:${cfg.builds.group}"; + lib.mkDefault "${cfg.builds.user}:${cfg.builds.group}"; } - (mkIf cfg.builds.enableWorker { + (lib.mkIf cfg.builds.enableWorker { "builds.sr.ht::worker".shell = "/usr/bin/runner-shell"; - "builds.sr.ht::worker".images = mkDefault "${image_dir}/images"; - "builds.sr.ht::worker".controlcmd = mkDefault "${image_dir}/images/control"; + "builds.sr.ht::worker".images = lib.mkDefault "${image_dir}/images"; + "builds.sr.ht::worker".controlcmd = lib.mkDefault "${image_dir}/images/control"; }) ]; } - (mkIf cfg.builds.enableWorker { + (lib.mkIf cfg.builds.enableWorker { users.groups = { docker.members = [ cfg.builds.user ]; }; }) - (mkIf (cfg.builds.enableWorker && cfg.nginx.enable) { + (lib.mkIf (cfg.builds.enableWorker && cfg.nginx.enable) { # Allow nginx access to buildlogs users.users.${nginx.user}.extraGroups = [ cfg.builds.group ]; systemd.services.nginx = { serviceConfig.BindReadOnlyPaths = [ cfg.settings."builds.sr.ht::worker".buildlogs ]; }; - services.nginx.virtualHosts."logs.${domain}" = mkMerge [ + services.nginx.virtualHosts."logs.${domain}" = lib.mkMerge [ { /* FIXME: is a listen needed? @@ -1119,14 +1087,14 @@ in in { inherit configIniOfService; - mainService = mkMerge [ + mainService = lib.mkMerge [ baseService { serviceConfig.StateDirectory = [ "sourcehut/gitsrht" "sourcehut/gitsrht/repos" ]; - preStart = mkIf (versionOlder config.system.stateVersion "22.05") (mkBefore '' + preStart = lib.mkIf (lib.versionOlder config.system.stateVersion "22.05") (lib.mkBefore '' # Fix Git hooks of repositories pre-dating https://github.com/NixOS/nixpkgs/pull/133984 ( set +f @@ -1143,17 +1111,17 @@ in service = baseService; timerConfig.OnCalendar = [ "*:0/20" ]; }; - extraConfig = mkMerge [ + extraConfig = lib.mkMerge [ { # https://stackoverflow.com/questions/22314298/git-push-results-in-fatal-protocol-error-bad-line-length-character-this # Probably could use gitsrht-shell if output is restricted to just parameters... users.users.${cfg.git.user}.shell = pkgs.bash; services.sourcehut.settings = { - "git.sr.ht::dispatch"."/usr/bin/gitsrht-keys" = mkDefault "${cfg.git.user}:${cfg.git.group}"; + "git.sr.ht::dispatch"."/usr/bin/gitsrht-keys" = lib.mkDefault "${cfg.git.user}:${cfg.git.group}"; }; systemd.services.sshd = baseService; } - (mkIf cfg.nginx.enable { + (lib.mkIf cfg.nginx.enable { services.nginx.virtualHosts."git.${domain}" = { locations."/authorize" = { proxyPass = "http://${cfg.listenAddress}:${toString cfg.git.port}"; @@ -1198,12 +1166,12 @@ in ExecStart = "${pkgs.sourcehut.gitsrht}/bin/gitsrht-api -b ${cfg.listenAddress}:${toString (cfg.git.port + 100)}"; BindPaths = [ "${cfg.settings."git.sr.ht".repos}:/var/lib/sourcehut/gitsrht/repos" ]; }; - extraServices.gitsrht-fcgiwrap = mkIf cfg.nginx.enable { + extraServices.gitsrht-fcgiwrap = lib.mkIf cfg.nginx.enable { serviceConfig = { # Socket is passed by gitsrht-fcgiwrap.socket ExecStart = "${pkgs.fcgiwrap}/sbin/fcgiwrap -c ${toString cfg.git.fcgiwrap.preforkProcess}"; # No need for config.ini - ExecStartPre = mkForce [ ]; + ExecStartPre = lib.mkForce [ ]; User = null; DynamicUser = true; BindReadOnlyPaths = [ "${cfg.settings."git.sr.ht".repos}:/var/lib/sourcehut/gitsrht/repos" ]; @@ -1213,8 +1181,8 @@ in "-+/run/redis-sourcehut" ]; PrivateNetwork = true; - RestrictAddressFamilies = mkForce [ "none" ]; - SystemCallFilter = mkForce [ + RestrictAddressFamilies = lib.mkForce [ "none" ]; + SystemCallFilter = lib.mkForce [ "@system-service" "~@aio" "~@keyring" @@ -1238,7 +1206,7 @@ in in { inherit configIniOfService; - mainService = mkMerge [ + mainService = lib.mkMerge [ baseService { serviceConfig.StateDirectory = [ @@ -1253,7 +1221,7 @@ in service = baseService; timerConfig.OnCalendar = [ "*:0/20" ]; }; - extraTimers.hgsrht-clonebundles = mkIf cfg.hg.cloneBundles { + extraTimers.hgsrht-clonebundles = lib.mkIf cfg.hg.cloneBundles { service = baseService; timerConfig.OnCalendar = [ "daily" ]; timerConfig.AccuracySec = "1h"; @@ -1263,17 +1231,17 @@ in serviceConfig.RestartSec = "5s"; serviceConfig.ExecStart = "${pkgs.sourcehut.hgsrht}/bin/hgsrht-api -b ${cfg.listenAddress}:${toString (cfg.hg.port + 100)}"; }; - extraConfig = mkMerge [ + extraConfig = lib.mkMerge [ { users.users.${cfg.hg.user}.shell = pkgs.bash; services.sourcehut.settings = { # Note that git.sr.ht::dispatch is not a typo, # gitsrht-dispatch always uses this section. - "git.sr.ht::dispatch"."/usr/bin/hgsrht-keys" = mkDefault "${cfg.hg.user}:${cfg.hg.group}"; + "git.sr.ht::dispatch"."/usr/bin/hgsrht-keys" = lib.mkDefault "${cfg.hg.user}:${cfg.hg.group}"; }; systemd.services.sshd = baseService; } - (mkIf cfg.nginx.enable { + (lib.mkIf cfg.nginx.enable { # Allow nginx access to repositories users.users.${nginx.user}.extraGroups = [ cfg.hg.group ]; services.nginx.virtualHosts."hg.${domain}" = { @@ -1311,8 +1279,8 @@ in inherit configIniOfService; port = 5014; extraConfig = { - services.nginx = mkIf cfg.nginx.enable { - virtualHosts."hub.${domain}" = mkMerge [ + services.nginx = lib.mkIf cfg.nginx.enable { + virtualHosts."hub.${domain}" = lib.mkMerge [ { serverAliases = [ domain ]; } @@ -1340,10 +1308,10 @@ in # Receive the mail from Postfix and enqueue them into Redis and PostgreSQL extraServices.listssrht-lmtp = { wants = [ "postfix.service" ]; - unitConfig.JoinsNamespaceOf = optional cfg.postfix.enable "postfix.service"; + unitConfig.JoinsNamespaceOf = lib.optional cfg.postfix.enable "postfix.service"; serviceConfig.ExecStart = "${pkgs.sourcehut.listssrht}/bin/listssrht-lmtp"; # Avoid crashing: os.chown(sock, os.getuid(), sock_gid) - serviceConfig.PrivateUsers = mkForce false; + serviceConfig.PrivateUsers = lib.mkForce false; }; # Dequeue the mails from Redis and dispatch them extraServices.listssrht-process = { @@ -1354,12 +1322,12 @@ in ''; ExecStart = "${cfg.python}/bin/celery --app listssrht.process worker --hostname listssrht-process@%%h " - + concatStringsSep " " cfg.lists.process.extraArgs; + + lib.concatStringsSep " " cfg.lists.process.extraArgs; # Avoid crashing: os.getloadavg() - ProcSubset = mkForce "all"; + ProcSubset = lib.mkForce "all"; }; }; - extraConfig = mkIf cfg.postfix.enable { + extraConfig = lib.mkIf cfg.postfix.enable { users.groups.${postfix.group}.members = [ cfg.lists.user ]; services.sourcehut.settings."lists.sr.ht::mail".sock-group = postfix.group; services.postfix = { @@ -1397,16 +1365,16 @@ in serviceConfig.RestartSec = "5s"; preStart = "set -x\n" - + concatStringsSep "\n\n" ( - attrValues ( - mapAttrs ( + + lib.concatStringsSep "\n\n" ( + lib.attrValues ( + lib.mapAttrs ( k: s: let srvMatch = builtins.match "^([a-z]*)\\.sr\\.ht$" k; - srv = head srvMatch; + srv = lib.head srvMatch; in # Configure client(s) as "preauthorized" - optionalString (srvMatch != null && cfg.${srv}.enable && ((s.oauth-client-id or null) != null)) '' + lib.optionalString (srvMatch != null && cfg.${srv}.enable && ((s.oauth-client-id or null) != null)) '' # Configure ${srv}'s OAuth client as "preauthorized" ${postgresql.package}/bin/psql '${cfg.settings."meta.sr.ht".connection-string}' \ -c "UPDATE oauthclient SET preauthorized = true WHERE client_id = '${s.oauth-client-id}'" @@ -1427,7 +1395,7 @@ in message = "If meta.sr.ht::billing is enabled, the keys must be defined."; } ]; - environment.systemPackages = optional cfg.meta.enable ( + environment.systemPackages = lib.optional cfg.meta.enable ( pkgs.writeShellScriptBin "metasrht-manageuser" '' set -eux if test "$(${pkgs.coreutils}/bin/id -n -u)" != '${cfg.meta.user}' @@ -1458,7 +1426,7 @@ in iniKey = "pages.sr.ht"; in { - preStart = mkBefore '' + preStart = lib.mkBefore '' set -x # Use the /run/sourcehut/${srvsrht}/config.ini # installed by a previous ExecStartPre= in baseService @@ -1471,7 +1439,7 @@ in echo ${version} >${stateDir}/db fi - ${optionalString cfg.settings.${iniKey}.migrate-on-upgrade '' + ${lib.optionalString cfg.settings.${iniKey}.migrate-on-upgrade '' # Just try all the migrations because they're not linked to the version for sql in ${pkgs.sourcehut.pagessrht}/share/sql/migrations/*.sql; do ${postgresql.package}/bin/psql '${cfg.settings.${iniKey}.connection-string}' -f "$sql" || true @@ -1482,7 +1450,7 @@ in touch ${stateDir}/webhook ''; serviceConfig = { - ExecStart = mkForce "${pkgs.sourcehut.pagessrht}/bin/pages.sr.ht -b ${cfg.listenAddress}:${toString cfg.pages.port}"; + ExecStart = lib.mkForce "${pkgs.sourcehut.pagessrht}/bin/pages.sr.ht -b ${cfg.listenAddress}:${toString cfg.pages.port}"; }; }; }) @@ -1510,12 +1478,12 @@ in }; extraServices.todosrht-lmtp = { wants = [ "postfix.service" ]; - unitConfig.JoinsNamespaceOf = optional cfg.postfix.enable "postfix.service"; + unitConfig.JoinsNamespaceOf = lib.optional cfg.postfix.enable "postfix.service"; serviceConfig.ExecStart = "${pkgs.sourcehut.todosrht}/bin/todosrht-lmtp"; # Avoid crashing: os.chown(sock, os.getuid(), sock_gid) - serviceConfig.PrivateUsers = mkForce false; + serviceConfig.PrivateUsers = lib.mkForce false; }; - extraConfig = mkIf cfg.postfix.enable { + extraConfig = lib.mkIf cfg.postfix.enable { users.groups.${postfix.group}.members = [ cfg.todo.user ]; services.sourcehut.settings."todo.sr.ht::mail".sock-group = postfix.group; services.postfix = { @@ -1534,27 +1502,27 @@ in }; }) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "sourcehut" "originBase" ] [ "services" "sourcehut" "settings" "sr.ht" "global-domain" ] ) - (mkRenamedOptionModule + (lib.mkRenamedOptionModule [ "services" "sourcehut" "address" ] [ "services" "sourcehut" "listenAddress" ] ) - (mkRemovedOptionModule [ "services" "sourcehut" "dispatch" ] '' + (lib.mkRemovedOptionModule [ "services" "sourcehut" "dispatch" ] '' dispatch is deprecated. See https://sourcehut.org/blog/2022-08-01-dispatch-deprecation-plans/ for more information. '') - (mkRemovedOptionModule [ "services" "sourcehut" "services" ] '' + (lib.mkRemovedOptionModule [ "services" "sourcehut" "services" ] '' This option was removed in favor of individual .enable flags. '') ]; meta.doc = ./default.md; - meta.maintainers = with maintainers; [ + meta.maintainers = with lib.maintainers; [ tomberek nessdoor christoph-heiss diff --git a/nixos/modules/services/misc/sourcehut/service.nix b/nixos/modules/services/misc/sourcehut/service.nix index 37040c5e8661b..b20e23423665e 100644 --- a/nixos/modules/services/misc/sourcehut/service.nix +++ b/nixos/modules/services/misc/sourcehut/service.nix @@ -18,18 +18,6 @@ srv: }: let - inherit (lib) types; - inherit (lib.attrsets) mapAttrs optionalAttrs; - inherit (lib.lists) optional; - inherit (lib.modules) - mkBefore - mkDefault - mkForce - mkIf - mkMerge - ; - inherit (lib.options) mkEnableOption mkOption; - inherit (lib.strings) concatStringsSep hasSuffix optionalString; inherit (config.services) postgresql; redis = config.services.redis.servers."sourcehut-${srvsrht}"; inherit (config.users) users; @@ -46,21 +34,21 @@ let runDir = "/run/sourcehut/${serviceName}"; rootDir = "/run/sourcehut/chroots/${serviceName}"; in - mkMerge [ + lib.mkMerge [ extraService { after = [ "network.target" ] - ++ optional cfg.postgresql.enable "postgresql.service" - ++ optional cfg.redis.enable "redis-sourcehut-${srvsrht}.service"; + ++ lib.optional cfg.postgresql.enable "postgresql.service" + ++ lib.optional cfg.redis.enable "redis-sourcehut-${srvsrht}.service"; requires = - optional cfg.postgresql.enable "postgresql.service" - ++ optional cfg.redis.enable "redis-sourcehut-${srvsrht}.service"; + lib.optional cfg.postgresql.enable "postgresql.service" + ++ lib.optional cfg.redis.enable "redis-sourcehut-${srvsrht}.service"; path = [ pkgs.gawk ]; environment.HOME = runDir; serviceConfig = { - User = mkDefault srvCfg.user; - Group = mkDefault srvCfg.group; + User = lib.mkDefault srvCfg.user; + Group = lib.mkDefault srvCfg.group; RuntimeDirectory = [ "sourcehut/${serviceName}" # Used by *srht-keys which reads ../config.ini @@ -81,7 +69,7 @@ let MountAPIVFS = true; # config.ini is looked up in there, before /etc/srht/config.ini # Note that it fails to be set in ExecStartPre= - WorkingDirectory = mkDefault ("-" + runDir); + WorkingDirectory = lib.mkDefault ("-" + runDir); BindReadOnlyPaths = [ builtins.storeDir @@ -90,20 +78,20 @@ let "/run/current-system" "/run/systemd" ] - ++ optional cfg.postgresql.enable "/run/postgresql" - ++ optional cfg.redis.enable "/run/redis-sourcehut-${srvsrht}"; + ++ lib.optional cfg.postgresql.enable "/run/postgresql" + ++ lib.optional cfg.redis.enable "/run/redis-sourcehut-${srvsrht}"; # LoadCredential= are unfortunately not available in ExecStartPre= # Hence this one is run as root (the +) with RootDirectoryStartOnly= # to reach credentials wherever they are. # Note that each systemd service gets its own ${runDir}/config.ini file. - ExecStartPre = mkBefore [ + ExecStartPre = lib.mkBefore [ ( "+" + pkgs.writeShellScript "${serviceName}-credentials" '' set -x # Replace values beginning with a '<' by the content of the file whose name is after. gawk '{ if (match($0,/^([^=]+=)<(.+)/,m)) { getline f < m[2]; print m[1] f } else print $0 }' ${configIni} | - ${optionalString (!allowStripe) "gawk '!/^stripe-secret-key=/' |"} + ${lib.optionalString (!allowStripe) "gawk '!/^stripe-secret-key=/' |"} install -o ${srvCfg.user} -g root -m 400 /dev/stdin ${runDir}/config.ini '' ) @@ -119,7 +107,7 @@ let NoNewPrivileges = true; PrivateDevices = true; PrivateMounts = true; - PrivateNetwork = mkDefault false; + PrivateNetwork = lib.mkDefault false; PrivateUsers = true; ProcSubset = "pid"; ProtectClock = true; @@ -160,18 +148,18 @@ in { options.services.sourcehut.${srv} = { - enable = mkEnableOption "${srv} service"; + enable = lib.mkEnableOption "${srv} service"; - user = mkOption { - type = types.str; + user = lib.mkOption { + type = lib.types.str; default = srvsrht; description = '' User for ${srv}.sr.ht. ''; }; - group = mkOption { - type = types.str; + group = lib.mkOption { + type = lib.types.str; default = srvsrht; description = '' Group for ${srv}.sr.ht. @@ -180,8 +168,8 @@ in ''; }; - port = mkOption { - type = types.port; + port = lib.mkOption { + type = lib.types.port; default = port; description = '' Port on which the "${srv}" backend should listen. @@ -189,8 +177,8 @@ in }; redis = { - host = mkOption { - type = types.str; + host = lib.mkOption { + type = lib.types.str; default = "unix:///run/redis-sourcehut-${srvsrht}/redis.sock?db=0"; example = "redis://shared.wireguard:6379/0"; description = '' @@ -203,8 +191,8 @@ in }; postgresql = { - database = mkOption { - type = types.str; + database = lib.mkOption { + type = lib.types.str; default = "${srv}.sr.ht"; description = '' PostgreSQL database name for the ${srv}.sr.ht service, @@ -214,8 +202,8 @@ in }; gunicorn = { - extraArgs = mkOption { - type = with types; listOf str; + extraArgs = lib.mkOption { + type = with lib.types; listOf str; default = [ "--timeout 120" "--workers 1" @@ -225,10 +213,10 @@ in }; }; } - // optionalAttrs webhooks { + // lib.optionalAttrs webhooks { webhooks = { - extraArgs = mkOption { - type = with types; listOf str; + extraArgs = lib.mkOption { + type = with lib.types; listOf str; default = [ "--loglevel DEBUG" "--pool eventlet" @@ -236,23 +224,23 @@ in ]; description = "Extra arguments passed to the Celery responsible for webhooks."; }; - celeryConfig = mkOption { - type = types.lines; + celeryConfig = lib.mkOption { + type = lib.types.lines; default = ""; description = "Content of the `celeryconfig.py` used by the Celery responsible for webhooks."; }; }; }; - config = lib.mkIf (cfg.enable && srvCfg.enable) (mkMerge [ + config = lib.mkIf (cfg.enable && srvCfg.enable) (lib.mkMerge [ extraConfig { users = { users = { "${srvCfg.user}" = { isSystemUser = true; - group = mkDefault srvCfg.group; - description = mkDefault "sourcehut user for ${srv}.sr.ht"; + group = lib.mkDefault srvCfg.group; + description = lib.mkDefault "sourcehut user for ${srv}.sr.ht"; }; }; groups = @@ -260,28 +248,28 @@ in "${srvCfg.group}" = { }; } // - optionalAttrs - (cfg.postgresql.enable && hasSuffix "0" (postgresql.settings.unix_socket_permissions or "")) + lib.optionalAttrs + (cfg.postgresql.enable && lib.hasSuffix "0" (postgresql.settings.unix_socket_permissions or "")) { "postgres".members = [ srvCfg.user ]; } - // optionalAttrs (cfg.redis.enable && hasSuffix "0" (redis.settings.unixsocketperm or "")) { + // lib.optionalAttrs (cfg.redis.enable && lib.hasSuffix "0" (redis.settings.unixsocketperm or "")) { "redis-sourcehut-${srvsrht}".members = [ srvCfg.user ]; }; }; - services.nginx = mkIf cfg.nginx.enable { - virtualHosts."${srv}.${cfg.settings."sr.ht".global-domain}" = mkMerge [ + services.nginx = lib.mkIf cfg.nginx.enable { + virtualHosts."${srv}.${cfg.settings."sr.ht".global-domain}" = lib.mkMerge [ { - forceSSL = mkDefault true; + forceSSL = lib.mkDefault true; locations."/".proxyPass = "http://${cfg.listenAddress}:${toString srvCfg.port}"; locations."/static" = { root = "${pkgs.sourcehut.${srvsrht}}/${pkgs.sourcehut.python.sitePackages}/${srvsrht}"; - extraConfig = mkDefault '' + extraConfig = lib.mkDefault '' expires 30d; ''; }; - locations."/query" = mkIf (cfg.settings.${iniKey} ? api-origin) { + locations."/query" = lib.mkIf (cfg.settings.${iniKey} ? api-origin) { proxyPass = cfg.settings.${iniKey}.api-origin; extraConfig = '' add_header 'Access-Control-Allow-Origin' '*'; @@ -303,7 +291,7 @@ in ]; }; - services.postgresql = mkIf cfg.postgresql.enable { + services.postgresql = lib.mkIf cfg.postgresql.enable { authentication = '' local ${srvCfg.postgresql.database} ${srvCfg.user} trust ''; @@ -316,23 +304,23 @@ in }) [ srvCfg.user ]; }; - services.sourcehut.settings = mkMerge [ + services.sourcehut.settings = lib.mkMerge [ { - "${srv}.sr.ht".origin = mkDefault "https://${srv}.${cfg.settings."sr.ht".global-domain}"; + "${srv}.sr.ht".origin = lib.mkDefault "https://${srv}.${cfg.settings."sr.ht".global-domain}"; } - (mkIf cfg.postgresql.enable { + (lib.mkIf cfg.postgresql.enable { "${srv}.sr.ht".connection-string = - mkDefault "postgresql:///${srvCfg.postgresql.database}?user=${srvCfg.user}&host=/run/postgresql"; + lib.mkDefault "postgresql:///${srvCfg.postgresql.database}?user=${srvCfg.user}&host=/run/postgresql"; }) ]; - services.redis.servers."sourcehut-${srvsrht}" = mkIf cfg.redis.enable { + services.redis.servers."sourcehut-${srvsrht}" = lib.mkIf cfg.redis.enable { enable = true; databases = 3; syslog = true; # TODO: set a more informed value - save = mkDefault [ + save = lib.mkDefault [ [ 1800 10 @@ -349,26 +337,26 @@ in }; }; - systemd.services = mkMerge [ + systemd.services = lib.mkMerge [ { - "${srvsrht}" = baseService srvsrht { allowStripe = srv == "meta"; } (mkMerge [ + "${srvsrht}" = baseService srvsrht { allowStripe = srv == "meta"; } (lib.mkMerge [ { description = "sourcehut ${srv}.sr.ht website service"; - before = optional cfg.nginx.enable "nginx.service"; - wants = optional cfg.nginx.enable "nginx.service"; + before = lib.optional cfg.nginx.enable "nginx.service"; + wants = lib.optional cfg.nginx.enable "nginx.service"; wantedBy = [ "multi-user.target" ]; - path = optional cfg.postgresql.enable postgresql.package; + path = lib.optional cfg.postgresql.enable postgresql.package; # Beware: change in credentials' content will not trigger restart. restartTriggers = [ configIni ]; serviceConfig = { Type = "simple"; - Restart = mkDefault "always"; - #RestartSec = mkDefault "2min"; + Restart = lib.mkDefault "always"; + #RestartSec = lib.mkDefault "2min"; StateDirectory = [ "sourcehut/${srvsrht}" ]; StateDirectoryMode = "2750"; ExecStart = "${cfg.python}/bin/gunicorn ${srvsrht}.app:app --name ${srvsrht} --bind ${cfg.listenAddress}:${toString srvCfg.port} " - + concatStringsSep " " srvCfg.gunicorn.extraArgs; + + lib.concatStringsSep " " srvCfg.gunicorn.extraArgs; }; preStart = let @@ -376,7 +364,7 @@ in version = package.version; stateDir = "/var/lib/sourcehut/${srvsrht}"; in - mkBefore '' + lib.mkBefore '' set -x # Use the /run/sourcehut/${srvsrht}/config.ini # installed by a previous ExecStartPre= in baseService @@ -389,7 +377,7 @@ in echo ${version} >${stateDir}/db fi - ${optionalString cfg.settings.${iniKey}.migrate-on-upgrade '' + ${lib.optionalString cfg.settings.${iniKey}.migrate-on-upgrade '' if [ "$(cat ${stateDir}/db)" != "${version}" ]; then # Manage schema migrations using alembic ${package}/bin/${srvsrht}-migrate -a upgrade head @@ -410,7 +398,7 @@ in ]); } - (mkIf webhooks { + (lib.mkIf webhooks { "${srvsrht}-webhooks" = baseService "${srvsrht}-webhooks" { } { description = "sourcehut ${srv}.sr.ht webhooks service"; after = [ "${srvsrht}.service" ]; @@ -425,16 +413,16 @@ in Restart = "always"; ExecStart = "${cfg.python}/bin/celery --app ${srvsrht}.webhooks worker --hostname ${srvsrht}-webhooks@%%h " - + concatStringsSep " " srvCfg.webhooks.extraArgs; + + lib.concatStringsSep " " srvCfg.webhooks.extraArgs; # Avoid crashing: os.getloadavg() - ProcSubset = mkForce "all"; + ProcSubset = lib.mkForce "all"; }; }; }) - (mapAttrs ( + (lib.mapAttrs ( timerName: timer: - (baseService timerName { } (mkMerge [ + (baseService timerName { } (lib.mkMerge [ { description = "sourcehut ${timerName} service"; after = [ @@ -450,9 +438,9 @@ in ])) ) extraTimers) - (mapAttrs ( + (lib.mapAttrs ( serviceName: extraService: - baseService serviceName { } (mkMerge [ + baseService serviceName { } (lib.mkMerge [ { description = "sourcehut ${serviceName} service"; # So that extraServices have the PostgreSQL database initialized. @@ -461,7 +449,7 @@ in partOf = [ "${srvsrht}.service" ]; serviceConfig = { Type = "simple"; - Restart = mkDefault "always"; + Restart = lib.mkDefault "always"; }; } extraService @@ -488,7 +476,7 @@ in ) ]; - systemd.timers = mapAttrs (timerName: timer: { + systemd.timers = lib.mapAttrs (timerName: timer: { description = "sourcehut timer for ${timerName}"; wantedBy = [ "timers.target" ]; inherit (timer) timerConfig; diff --git a/nixos/modules/services/misc/tabby.nix b/nixos/modules/services/misc/tabby.nix index 169d058d59b76..9bf21948a5671 100644 --- a/nixos/modules/services/misc/tabby.nix +++ b/nixos/modules/services/misc/tabby.nix @@ -15,7 +15,7 @@ let in { imports = [ - (mkRemovedOptionModule [ + (lib.mkRemovedOptionModule [ "settings" "indexInterval" ] "These options are now managed within the tabby WebGUI") @@ -27,7 +27,7 @@ in package = lib.mkPackageOption pkgs "tabby" { }; host = lib.mkOption { - type = types.str; + type = lib.types.str; default = "127.0.0.1"; description = '' Specifies the hostname on which the tabby server HTTP interface listens. @@ -35,7 +35,7 @@ in }; port = lib.mkOption { - type = types.port; + type = lib.types.port; default = 11029; description = '' Specifies the bind port on which the tabby server HTTP interface listens. @@ -43,7 +43,7 @@ in }; model = lib.mkOption { - type = types.str; + type = lib.types.str; default = "TabbyML/StarCoder-1B"; description = '' Specify the model that tabby will use to generate completions. @@ -74,7 +74,7 @@ in }; acceleration = lib.mkOption { - type = types.nullOr ( + type = lib.types.nullOr ( types.enum [ "cpu" "rocm" @@ -107,7 +107,7 @@ in }; usageCollection = lib.mkOption { - type = types.bool; + type = lib.types.bool; default = false; description = '' Enable sending anonymous usage data. diff --git a/nixos/modules/services/misc/taskchampion-sync-server.nix b/nixos/modules/services/misc/taskchampion-sync-server.nix index 04037dee576b1..14db88aeadb99 100644 --- a/nixos/modules/services/misc/taskchampion-sync-server.nix +++ b/nixos/modules/services/misc/taskchampion-sync-server.nix @@ -14,34 +14,34 @@ in package = lib.mkPackageOption pkgs "taskchampion-sync-server" { }; user = lib.mkOption { description = "Unix User to run the server under"; - type = types.str; + type = lib.types.str; default = "taskchampion"; }; group = lib.mkOption { description = "Unix Group to run the server under"; - type = types.str; + type = lib.types.str; default = "taskchampion"; }; port = lib.mkOption { description = "Port on which to serve"; - type = types.port; + type = lib.types.port; default = 10222; }; openFirewall = lib.mkEnableOption "Open firewall port for taskchampion-sync-server"; dataDir = lib.mkOption { description = "Directory in which to store data"; - type = types.path; + type = lib.types.path; default = "/var/lib/taskchampion-sync-server"; }; snapshot = { versions = lib.mkOption { description = "Target number of versions between snapshots"; - type = types.ints.positive; + type = lib.types.ints.positive; default = 100; }; days = lib.mkOption { description = "Target number of days between snapshots"; - type = types.ints.positive; + type = lib.types.ints.positive; default = 14; }; }; diff --git a/nixos/modules/services/misc/transfer-sh.nix b/nixos/modules/services/misc/transfer-sh.nix index 0433f8971507d..692f96b517e2e 100644 --- a/nixos/modules/services/misc/transfer-sh.nix +++ b/nixos/modules/services/misc/transfer-sh.nix @@ -7,30 +7,17 @@ let cfg = config.services.transfer-sh; - inherit (lib) - mkDefault - mkEnableOption - mkPackageOption - mkIf - mkOption - types - mapAttrs - isBool - getExe - boolToString - optionalAttrs - ; in { options.services.transfer-sh = { - enable = mkEnableOption "Easy and fast file sharing from the command-line"; + enable = lib.mkEnableOption "Easy and fast file sharing from the command-line"; - package = mkPackageOption pkgs "transfer-sh" { }; + package = lib.mkPackageOption pkgs "transfer-sh" { }; - settings = mkOption { - type = types.submodule { + settings = lib.mkOption { + type = lib.types.submodule { freeformType = - with types; + with lib.types; attrsOf (oneOf [ bool int @@ -52,8 +39,8 @@ in ''; }; - provider = mkOption { - type = types.enum [ + provider = lib.mkOption { + type = lib.types.enum [ "local" "s3" "storj" @@ -63,8 +50,8 @@ in description = "Storage providers to use"; }; - secretFile = mkOption { - type = types.nullOr types.path; + secretFile = lib.mkOption { + type = lib.types.nullOr lib.types.path; default = null; example = "/run/secrets/transfer-sh.env"; description = '' @@ -84,24 +71,24 @@ in localProvider = (cfg.provider == "local"); stateDirectory = "/var/lib/transfer.sh"; in - mkIf cfg.enable { + lib.mkIf cfg.enable { services.transfer-sh.settings = { - LISTENER = mkDefault ":8080"; + LISTENER = lib.mkDefault ":8080"; } - // optionalAttrs localProvider { - BASEDIR = mkDefault stateDirectory; + // lib.optionalAttrs localProvider { + BASEDIR = lib.mkDefault stateDirectory; }; systemd.services.transfer-sh = { after = [ "network.target" ]; wantedBy = [ "multi-user.target" ]; - environment = mapAttrs (_: v: if isBool v then boolToString v else toString v) cfg.settings; + environment = lib.mapAttrs (_: v: if lib.isBool v then lib.boolToString v else toString v) cfg.settings; serviceConfig = { DevicePolicy = "closed"; DynamicUser = true; - ExecStart = "${getExe cfg.package} --provider ${cfg.provider}"; + ExecStart = "${lib.getExe cfg.package} --provider ${cfg.provider}"; LockPersonality = true; MemoryDenyWriteExecute = true; PrivateDevices = true; @@ -123,10 +110,10 @@ in SystemCallFilter = [ "@system-service" ]; StateDirectory = baseNameOf stateDirectory; } - // optionalAttrs (cfg.secretFile != null) { + // lib.optionalAttrs (cfg.secretFile != null) { EnvironmentFile = cfg.secretFile; } - // optionalAttrs localProvider { + // lib.optionalAttrs localProvider { ReadWritePaths = cfg.settings.BASEDIR; }; }; diff --git a/nixos/modules/services/misc/uhub.nix b/nixos/modules/services/misc/uhub.nix index befebdc20cdbd..3678b7f13eaeb 100644 --- a/nixos/modules/services/misc/uhub.nix +++ b/nixos/modules/services/misc/uhub.nix @@ -71,7 +71,7 @@ in }; settings = lib.mkOption { description = "Settings specific to this plugin."; - type = with types; attrsOf str; + type = with lib.types; attrsOf str; example = { file = "/etc/uhub/users.db"; }; diff --git a/nixos/modules/services/misc/wastebin.nix b/nixos/modules/services/misc/wastebin.nix index 499b071e4f3e6..edc693c0a6857 100644 --- a/nixos/modules/services/misc/wastebin.nix +++ b/nixos/modules/services/misc/wastebin.nix @@ -7,35 +7,23 @@ let cfg = config.services.wastebin; - inherit (lib) - mkEnableOption - mkPackageOption - mkIf - mkOption - types - mapAttrs - isBool - getExe - boolToString - optionalAttrs - ; in { options.services.wastebin = { - enable = mkEnableOption "Wastebin, a pastebin service"; + enable = lib.mkEnableOption "Wastebin, a pastebin service"; - package = mkPackageOption pkgs "wastebin" { }; + package = lib.mkPackageOption pkgs "wastebin" { }; - stateDir = mkOption { - type = types.path; + stateDir = lib.mkOption { + type = lib.types.path; default = "/var/lib/wastebin"; description = "State directory of the daemon."; }; - secretFile = mkOption { - type = types.nullOr types.path; + secretFile = lib.mkOption { + type = lib.types.nullOr lib.types.path; default = null; example = "/run/secrets/wastebin.env"; description = '' @@ -52,7 +40,7 @@ in ''; }; - settings = mkOption { + settings = lib.mkOption { description = '' Additional configuration for wastebin, see @@ -60,10 +48,10 @@ in For secrets use secretFile option instead. ''; - type = types.submodule { + type = lib.types.submodule { freeformType = - with types; + with lib.types; attrsOf (oneOf [ bool int @@ -72,55 +60,55 @@ in options = { - WASTEBIN_ADDRESS_PORT = mkOption { - type = types.str; + WASTEBIN_ADDRESS_PORT = lib.mkOption { + type = lib.types.str; default = "0.0.0.0:8088"; description = "Address and port to bind to"; }; - WASTEBIN_BASE_URL = mkOption { + WASTEBIN_BASE_URL = lib.mkOption { default = "http://localhost"; example = "https://myhost.tld"; - type = types.str; + type = lib.types.str; description = '' Base URL for the QR code display. If not set, the user agent's Host header field is used as an approximation. ''; }; - WASTEBIN_CACHE_SIZE = mkOption { + WASTEBIN_CACHE_SIZE = lib.mkOption { default = 128; - type = types.int; + type = lib.types.int; description = "Number of rendered syntax highlight items to cache. Can be disabled by setting to 0."; }; - WASTEBIN_DATABASE_PATH = mkOption { + WASTEBIN_DATABASE_PATH = lib.mkOption { default = "/var/lib/wastebin/sqlite3.db"; # TODO make this default to stateDir/sqlite3.db - type = types.str; + type = lib.types.str; description = "Path to the sqlite3 database file. If not set, an in-memory database is used."; }; - WASTEBIN_HTTP_TIMEOUT = mkOption { + WASTEBIN_HTTP_TIMEOUT = lib.mkOption { default = 5; - type = types.int; + type = lib.types.int; description = "Maximum number of seconds a request can be processed until wastebin responds with 408"; }; - WASTEBIN_MAX_BODY_SIZE = mkOption { + WASTEBIN_MAX_BODY_SIZE = lib.mkOption { default = 1024; - type = types.int; + type = lib.types.int; description = "Number of bytes to accept for POST requests"; }; - WASTEBIN_TITLE = mkOption { + WASTEBIN_TITLE = lib.mkOption { default = "wastebin"; - type = types.str; + type = lib.types.str; description = "Overrides the HTML page title"; }; - RUST_LOG = mkOption { + RUST_LOG = lib.mkOption { default = "info"; - type = types.str; + type = lib.types.str; description = '' Influences logging. Besides the typical trace, debug, info etc. keys, you can also set the tower_http key to some log level to get @@ -138,16 +126,16 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { systemd.services.wastebin = { after = [ "network.target" ]; wantedBy = [ "multi-user.target" ]; - environment = mapAttrs (_: v: if isBool v then boolToString v else toString v) cfg.settings; + environment = lib.mapAttrs (_: v: if lib.isBool v then lib.boolToString v else toString v) cfg.settings; serviceConfig = { DevicePolicy = "closed"; DynamicUser = true; - ExecStart = "${getExe cfg.package}"; + ExecStart = "${lib.getExe cfg.package}"; LockPersonality = true; MemoryDenyWriteExecute = true; PrivateDevices = true; @@ -170,7 +158,7 @@ in StateDirectory = baseNameOf cfg.stateDir; ReadWritePaths = cfg.stateDir; } - // optionalAttrs (cfg.secretFile != null) { + // lib.optionalAttrs (cfg.secretFile != null) { EnvironmentFile = cfg.secretFile; }; }; diff --git a/nixos/modules/services/misc/workout-tracker.nix b/nixos/modules/services/misc/workout-tracker.nix index 13555504be302..ab02fcd28c16d 100644 --- a/nixos/modules/services/misc/workout-tracker.nix +++ b/nixos/modules/services/misc/workout-tracker.nix @@ -19,19 +19,19 @@ in package = lib.mkPackageOption pkgs "workout-tracker" { }; address = lib.mkOption { - type = types.str; + type = lib.types.str; default = "127.0.0.1"; description = "Web interface address."; }; port = lib.mkOption { - type = types.port; + type = lib.types.port; default = 8080; description = "Web interface port."; }; environmentFile = lib.mkOption { - type = types.nullOr types.path; + type = lib.types.nullOr lib.types.path; default = null; example = "/run/keys/workout-tracker.env"; description = '' @@ -43,7 +43,7 @@ in }; settings = lib.mkOption { - type = types.attrsOf types.str; + type = lib.types.attrsOf lib.types.str; default = { }; description = '' diff --git a/nixos/modules/services/misc/xmrig.nix b/nixos/modules/services/misc/xmrig.nix index 1d1c0724a892c..4db262e7c4be1 100644 --- a/nixos/modules/services/misc/xmrig.nix +++ b/nixos/modules/services/misc/xmrig.nix @@ -65,7 +65,7 @@ in }; }; - meta = with lib; { - maintainers = with maintainers; [ ratsclub ]; + meta = { + maintainers = [ lib.maintainers.ratsclub ]; }; } diff --git a/nixos/modules/services/misc/zoneminder.nix b/nixos/modules/services/misc/zoneminder.nix index c6299d654e288..a0ffb825d1972 100644 --- a/nixos/modules/services/misc/zoneminder.nix +++ b/nixos/modules/services/misc/zoneminder.nix @@ -76,7 +76,7 @@ let in { options = { - services.zoneminder = with lib; { + services.zoneminder = { enable = lib.mkEnableOption '' ZoneMinder. @@ -88,8 +88,8 @@ in upgrading to a newer version ''; - webserver = mkOption { - type = types.enum [ + webserver = lib.mkOption { + type = lib.types.enum [ "nginx" "none" ]; @@ -102,24 +102,24 @@ in ''; }; - hostname = mkOption { - type = types.str; + hostname = lib.mkOption { + type = lib.types.str; default = "localhost"; description = '' The hostname on which to listen. ''; }; - port = mkOption { - type = types.port; + port = lib.mkOption { + type = lib.types.port; default = 8095; description = '' The port on which to listen. ''; }; - openFirewall = mkOption { - type = types.bool; + openFirewall = lib.mkOption { + type = lib.types.bool; default = false; description = '' Open the firewall port(s). @@ -127,40 +127,40 @@ in }; database = { - createLocally = mkOption { - type = types.bool; + createLocally = lib.mkOption { + type = lib.types.bool; default = false; description = '' Create the database and database user locally. ''; }; - host = mkOption { - type = types.str; + host = lib.mkOption { + type = lib.types.str; default = "localhost"; description = '' Hostname hosting the database. ''; }; - name = mkOption { - type = types.str; + name = lib.mkOption { + type = lib.types.str; default = "zm"; description = '' Name of database. ''; }; - username = mkOption { - type = types.str; + username = lib.mkOption { + type = lib.types.str; default = "zmuser"; description = '' Username for accessing the database. ''; }; - password = mkOption { - type = types.str; + password = lib.mkOption { + type = lib.types.str; default = "zmpass"; description = '' Username for accessing the database. @@ -169,16 +169,16 @@ in }; }; - cameras = mkOption { - type = types.int; + cameras = lib.mkOption { + type = lib.types.int; default = 1; description = '' Set this to the number of cameras you expect to support. ''; }; - storageDir = mkOption { - type = types.nullOr types.str; + storageDir = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; example = "/storage/tank"; description = '' @@ -187,8 +187,8 @@ in ''; }; - extraConfig = mkOption { - type = types.lines; + extraConfig = lib.mkOption { + type = lib.types.lines; default = ""; description = '' Additional configuration added verbatim to the configuration file. diff --git a/nixos/modules/services/monitoring/below.nix b/nixos/modules/services/monitoring/below.nix index 79f9badf65fe7..d2c091db88d3f 100644 --- a/nixos/modules/services/monitoring/below.nix +++ b/nixos/modules/services/monitoring/below.nix @@ -23,7 +23,7 @@ let default = true; description = "Whether to enable ${n}."; }; - optionalType = + lib.optionalType = ty: x: lib.mkOption ( x @@ -33,16 +33,16 @@ let default = null; } ); - optionalPath = optionalType lib.types.path; - optionalStr = optionalType lib.types.str; - optionalInt = optionalType lib.types.int; + lib.optionalPath = lib.optionalType lib.types.path; + lib.optionalStr = lib.optionalType lib.types.str; + lib.optionalInt = lib.optionalType lib.types.int; in { options = { services.below = { enable = lib.mkEnableOption "'below' resource monitor"; - cgroupFilterOut = optionalStr { + cgroupFilterOut = lib.optionalStr { description = "A regexp matching the full paths of cgroups whose data shouldn't be collected"; example = "user.slice.*"; }; @@ -53,7 +53,7 @@ in }; compression.enable = lib.mkEnableOption "data compression"; retention = { - size = optionalInt { + size = lib.optionalInt { description = '' Size limit for below's data, in bytes. Data is deleted oldest-first, in 24h 'shards'. @@ -64,7 +64,7 @@ in ::: ''; }; - time = optionalInt { + time = lib.optionalInt { description = '' Retention time, in seconds. @@ -80,8 +80,8 @@ in }; }; dirs = { - log = optionalPath { description = "Where to store below's logs"; }; - store = optionalPath { + log = lib.optionalPath { description = "Where to store below's logs"; }; + store = lib.optionalPath { description = "Where to store below's data"; example = "/var/lib/below"; }; diff --git a/nixos/modules/services/monitoring/cockpit.nix b/nixos/modules/services/monitoring/cockpit.nix index 31620b31eb315..6c6e0752871c2 100644 --- a/nixos/modules/services/monitoring/cockpit.nix +++ b/nixos/modules/services/monitoring/cockpit.nix @@ -2,14 +2,13 @@ let cfg = config.services.cockpit; - inherit (lib) types mkEnableOption mkOption mkIf literalMD mkPackageOption; settingsFormat = pkgs.formats.ini {}; in { options = { services.cockpit = { - enable = mkEnableOption "Cockpit"; + enable = lib.mkEnableOption "Cockpit"; - package = mkPackageOption pkgs "Cockpit" { + package = lib.mkPackageOption pkgs "Cockpit" { default = [ "cockpit" ]; }; @@ -25,20 +24,20 @@ in { ''; }; - port = mkOption { + port = lib.mkOption { description = "Port where cockpit will listen."; - type = types.port; + type = lib.types.port; default = 9090; }; - openFirewall = mkOption { + openFirewall = lib.mkOption { description = "Open port for cockpit."; - type = types.bool; + type = lib.types.bool; default = false; }; }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { # expose cockpit-bridge system-wide environment.systemPackages = [ cfg.package ]; @@ -51,7 +50,7 @@ in { security.pam.services.cockpit = {}; - networking.firewall.allowedTCPPorts = mkIf cfg.openFirewall [ cfg.port ]; + networking.firewall.allowedTCPPorts = lib.mkIf cfg.openFirewall [ cfg.port ]; systemd.packages = [ cfg.package ]; systemd.sockets.cockpit.wantedBy = [ "multi-user.target" ]; diff --git a/nixos/modules/services/monitoring/collectd.nix b/nixos/modules/services/monitoring/collectd.nix index fc97d4f63e6c4..3387e82cb8065 100644 --- a/nixos/modules/services/monitoring/collectd.nix +++ b/nixos/modules/services/monitoring/collectd.nix @@ -41,7 +41,7 @@ in Disable this if you use the Include directive on files unavailable in the build sandbox, or when cross-compiling. ''; - type = types.bool; + type = lib.types.bool; }; package = lib.mkPackageOption pkgs "collectd" { }; diff --git a/nixos/modules/services/monitoring/gatus.nix b/nixos/modules/services/monitoring/gatus.nix index 408115f5d5145..dc3a4fd2a3319 100644 --- a/nixos/modules/services/monitoring/gatus.nix +++ b/nixos/modules/services/monitoring/gatus.nix @@ -8,35 +8,17 @@ let cfg = config.services.gatus; settingsFormat = pkgs.formats.yaml { }; - - inherit (lib) - getExe - literalExpression - maintainers - mkEnableOption - mkIf - mkOption - mkPackageOption - ; - - inherit (lib.types) - bool - int - nullOr - path - submodule - ; in { options.services.gatus = { - enable = mkEnableOption "Gatus"; + enable = lib.mkEnableOption "Gatus"; - package = mkPackageOption pkgs "gatus" { }; + package = lib.mkPackageOption pkgs "gatus" { }; - configFile = mkOption { - type = path; + configFile = lib.mkOption { + type = lib.types.path; default = settingsFormat.generate "gatus.yaml" cfg.settings; - defaultText = literalExpression '' + defaultText = lib.literalExpression '' let settingsFormat = pkgs.formats.yaml { }; in settingsFormat.generate "gatus.yaml" cfg.settings; ''; description = '' @@ -45,8 +27,8 @@ in ''; }; - environmentFile = mkOption { - type = nullOr path; + environmentFile = lib.mkOption { + type = lib.types.nullOr lib.types.path; default = null; description = '' File to load as environment file. @@ -55,12 +37,12 @@ in ''; }; - settings = mkOption { - type = submodule { + settings = lib.mkOption { + type = lib.types.submodule { freeformType = settingsFormat.type; options = { - web.port = mkOption { - type = int; + web.port = lib.mkOption { + type = lib.types.int; default = 8080; description = '' The TCP port to serve the Gatus service at. @@ -71,7 +53,7 @@ in default = { }; - example = literalExpression '' + example = lib.literalExpression '' { web.port = 8080; endpoints = [{ @@ -93,8 +75,8 @@ in ''; }; - openFirewall = mkOption { - type = bool; + openFirewall = lib.mkOption { + type = lib.types.bool; default = false; description = '' Whether to open the firewall for the Gatus web interface. @@ -102,7 +84,7 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { systemd.services.gatus = { description = "Automated developer-oriented status page"; after = [ "network.target" ]; @@ -114,7 +96,7 @@ in Group = "gatus"; Type = "simple"; Restart = "on-failure"; - ExecStart = getExe cfg.package; + ExecStart = lib.getExe cfg.package; StateDirectory = "gatus"; SyslogIdentifier = "gatus"; EnvironmentFile = lib.optional (cfg.environmentFile != null) cfg.environmentFile; @@ -128,5 +110,5 @@ in networking.firewall.allowedTCPPorts = lib.optionals cfg.openFirewall [ cfg.settings.web.port ]; }; - meta.maintainers = with maintainers; [ pizzapim ]; + meta.maintainers = with lib.maintainers; [ pizzapim ]; } diff --git a/nixos/modules/services/monitoring/gitwatch.nix b/nixos/modules/services/monitoring/gitwatch.nix index 076114a6ef113..bb4c39de72778 100644 --- a/nixos/modules/services/monitoring/gitwatch.nix +++ b/nixos/modules/services/monitoring/gitwatch.nix @@ -5,20 +5,11 @@ ... }: let - inherit (lib) - maintainers - mapAttrs' - mkEnableOption - mkOption - nameValuePair - optionalString - types - ; mkSystemdService = name: cfg: - nameValuePair "gitwatch-${name}" ( + lib.nameValuePair "gitwatch-${name}" ( let - getvar = flag: var: optionalString (cfg."${var}" != null) "${flag} ${cfg."${var}"}"; + getvar = flag: var: lib.optionalString (cfg."${var}" != null) "${flag} ${cfg."${var}"}"; branch = getvar "-b" "branch"; remote = getvar "-r" "remote"; in @@ -44,7 +35,7 @@ let ); in { - options.services.gitwatch = mkOption { + options.services.gitwatch = lib.mkOption { description = '' A set of git repositories to watch for. See [gitwatch](https://github.com/gitwatch/gitwatch) for more. @@ -66,32 +57,31 @@ in }; }; type = - with types; - attrsOf (submodule { + lib.types.attrsOf (lib.types.submodule { options = { - enable = mkEnableOption "watching for repo"; - path = mkOption { + enable = lib.mkEnableOption "watching for repo"; + path = lib.mkOption { description = "The path to repo in local machine"; - type = str; + type = lib.types.str; }; - user = mkOption { + user = lib.mkOption { description = "The name of services's user"; - type = str; + type = lib.types.str; default = "root"; }; - remote = mkOption { + remote = lib.mkOption { description = "Optional url of remote repository"; - type = nullOr str; + type = lib.types.nullOr lib.types.str; default = null; }; - branch = mkOption { + branch = lib.mkOption { description = "Optional branch in remote repository"; - type = nullOr str; + type = lib.types.nullOr lib.types.str; default = null; }; }; }); }; - config.systemd.services = mapAttrs' mkSystemdService config.services.gitwatch; - meta.maintainers = with maintainers; [ shved ]; + config.systemd.services = lib.mapAttrs' mkSystemdService config.services.gitwatch; + meta.maintainers = with lib.maintainers; [ shved ]; } diff --git a/nixos/modules/services/monitoring/glances.nix b/nixos/modules/services/monitoring/glances.nix index fd976ce2f0600..a40a404cb2fbc 100644 --- a/nixos/modules/services/monitoring/glances.nix +++ b/nixos/modules/services/monitoring/glances.nix @@ -8,15 +8,6 @@ let cfg = config.services.glances; - inherit (lib) - getExe - maintainers - mkEnableOption - mkOption - mkIf - mkPackageOption - ; - inherit (lib.types) bool listOf @@ -31,23 +22,23 @@ let in { options.services.glances = { - enable = mkEnableOption "Glances"; + enable = lib.mkEnableOption "Glances"; - package = mkPackageOption pkgs "glances" { }; + package = lib.mkPackageOption pkgs "glances" { }; - port = mkOption { + port = lib.mkOption { description = "Port the server will isten on."; type = port; default = 61208; }; - openFirewall = mkOption { + openFirewall = lib.mkOption { description = "Open port in the firewall for glances."; type = bool; default = false; }; - extraArgs = mkOption { + extraArgs = lib.mkOption { type = listOf str; default = [ "--webserver" ]; example = [ @@ -62,7 +53,7 @@ in }; }; - config = mkIf cfg.enable { + config = lib.mkIf cfg.enable { environment.systemPackages = [ cfg.package ]; @@ -74,7 +65,7 @@ in serviceConfig = { Type = "simple"; DynamicUser = true; - ExecStart = "${getExe cfg.package} --port ${toString cfg.port} ${escapeSystemdExecArgs cfg.extraArgs}"; + ExecStart = "${lib.getExe cfg.package} --port ${toString cfg.port} ${escapeSystemdExecArgs cfg.extraArgs}"; Restart = "on-failure"; NoNewPrivileges = true; @@ -103,8 +94,8 @@ in }; }; - networking.firewall.allowedTCPPorts = mkIf cfg.openFirewall [ cfg.port ]; + networking.firewall.allowedTCPPorts = lib.mkIf cfg.openFirewall [ cfg.port ]; }; - meta.maintainers = with maintainers; [ claha ]; + meta.maintainers = with lib.maintainers; [ claha ]; } diff --git a/nixos/modules/services/monitoring/grafana.nix b/nixos/modules/services/monitoring/grafana.nix index dbbec443bf42d..5e4b062ca29c4 100644 --- a/nixos/modules/services/monitoring/grafana.nix +++ b/nixos/modules/services/monitoring/grafana.nix @@ -1,7 +1,5 @@ { options, config, lib, pkgs, ... }: -with lib; - let cfg = config.services.grafana; opt = options.services.grafana; @@ -14,19 +12,19 @@ let # people reading the NixOS manual can see them without cross-referencing the # official documentation. # - # However, if there is no default entry or if the setting is optional, use + # However, if there is no default entry or if the setting is lib.optional, use # `null` as the default value. It will be turned into the empty string. # # If a setting is a list, always allow setting it as a plain string as well. # # [0]: https://github.com/grafana/grafana/blob/main/conf/defaults.ini settingsFormatIni = pkgs.formats.ini { - listToValue = concatMapStringsSep " " (generators.mkValueStringDefault { }); - mkKeyValue = generators.mkKeyValueDefault + listToValue = lib.concatMapStringsSep " " (lib.generators.mkValueStringDefault { }); + mkKeyValue = lib.generators.mkKeyValueDefault { mkValueString = v: if v == null then "" - else generators.mkValueStringDefault { } v; + else lib.generators.mkValueStringDefault { } v; } "="; }; @@ -78,48 +76,48 @@ let ''; # Get a submodule without any embedded metadata: - _filter = x: filterAttrs (k: v: k != "_module") x; + _filter = x: lib.filterAttrs (k: v: k != "_module") x; # https://grafana.com/docs/grafana/latest/administration/provisioning/#datasources - grafanaTypes.datasourceConfig = types.submodule { + grafanaTypes.datasourceConfig = lib.types.submodule { freeformType = provisioningSettingsFormat.type; options = { - name = mkOption { - type = types.str; + name = lib.mkOption { + type = lib.types.str; description = "Name of the datasource. Required."; }; - type = mkOption { - type = types.str; + type = lib.mkOption { + type = lib.types.str; description = "Datasource type. Required."; }; - access = mkOption { - type = types.enum [ "proxy" "direct" ]; + access = lib.mkOption { + type = lib.types.enum [ "proxy" "direct" ]; default = "proxy"; description = "Access mode. proxy or direct (Server or Browser in the UI). Required."; }; - uid = mkOption { - type = types.nullOr types.str; + uid = lib.mkOption { + type = lib.types.nullOr lib.types.str; default = null; description = "Custom UID which can be used to reference this datasource in other parts of the configuration, if not specified will be generated automatically."; }; - url = mkOption { - type = types.str; + url = lib.mkOption { + type = lib.types.str; default = ""; description = "Url of the datasource."; }; - editable = mkOption { - type = types.bool; + editable = lib.mkOption { + type = lib.types.bool; default = false; description = "Allow users to edit datasources from the UI."; }; - jsonData = mkOption { - type = types.nullOr types.attrs; + jsonData = lib.mkOption { + type = lib.types.nullOr lib.types.attrs; default = null; description = "Extra data for datasource plugins."; }; - secureJsonData = mkOption { - type = types.nullOr types.attrs; + secureJsonData = lib.mkOption { + type = lib.types.nullOr lib.types.attrs; default = null; description = '' Datasource specific secure configuration. Please note that the contents of this option @@ -133,22 +131,22 @@ let }; # https://grafana.com/docs/grafana/latest/administration/provisioning/#dashboards - grafanaTypes.dashboardConfig = types.submodule { + grafanaTypes.dashboardConfig = lib.types.submodule { freeformType = provisioningSettingsFormat.type; options = { - name = mkOption { - type = types.str; + name = lib.mkOption { + type = lib.types.str; default = "default"; description = "A unique provider name."; }; - type = mkOption { - type = types.str; + type = lib.mkOption { + type = lib.types.str; default = "file"; description = "Dashboard provider type."; }; - options.path = mkOption { - type = types.path; + options.path = lib.mkOption { + type = lib.types.path; description = "Path grafana will watch for dashboards. Required when using the 'file' type."; }; }; @@ -156,138 +154,138 @@ let in { imports = [ - (mkRemovedOptionModule [ "services" "grafana" "provision" "notifiers" ] '' + (lib.mkRemovedOptionModule [ "services" "grafana" "provision" "notifiers" ] '' Notifiers (services.grafana.provision.notifiers) were removed in Grafana 11. '') - (mkRenamedOptionModule [ "services" "grafana" "protocol" ] [ "services" "grafana" "settings" "server" "protocol" ]) - (mkRenamedOptionModule [ "services" "grafana" "addr" ] [ "services" "grafana" "settings" "server" "http_addr" ]) - (mkRenamedOptionModule [ "services" "grafana" "port" ] [ "services" "grafana" "settings" "server" "http_port" ]) - (mkRenamedOptionModule [ "services" "grafana" "domain" ] [ "services" "grafana" "settings" "server" "domain" ]) - (mkRenamedOptionModule [ "services" "grafana" "rootUrl" ] [ "services" "grafana" "settings" "server" "root_url" ]) - (mkRenamedOptionModule [ "services" "grafana" "staticRootPath" ] [ "services" "grafana" "settings" "server" "static_root_path" ]) - (mkRenamedOptionModule [ "services" "grafana" "certFile" ] [ "services" "grafana" "settings" "server" "cert_file" ]) - (mkRenamedOptionModule [ "services" "grafana" "certKey" ] [ "services" "grafana" "settings" "server" "cert_key" ]) - (mkRenamedOptionModule [ "services" "grafana" "socket" ] [ "services" "grafana" "settings" "server" "socket" ]) - (mkRenamedOptionModule [ "services" "grafana" "database" "type" ] [ "services" "grafana" "settings" "database" "type" ]) - (mkRenamedOptionModule [ "services" "grafana" "database" "host" ] [ "services" "grafana" "settings" "database" "host" ]) - (mkRenamedOptionModule [ "services" "grafana" "database" "name" ] [ "services" "grafana" "settings" "database" "name" ]) - (mkRenamedOptionModule [ "services" "grafana" "database" "user" ] [ "services" "grafana" "settings" "database" "user" ]) - (mkRenamedOptionModule [ "services" "grafana" "database" "password" ] [ "services" "grafana" "settings" "database" "password" ]) - (mkRenamedOptionModule [ "services" "grafana" "database" "path" ] [ "services" "grafana" "settings" "database" "path" ]) - (mkRenamedOptionModule [ "services" "grafana" "database" "connMaxLifetime" ] [ "services" "grafana" "settings" "database" "conn_max_lifetime" ]) - (mkRenamedOptionModule [ "services" "grafana" "security" "adminUser" ] [ "services" "grafana" "settings" "security" "admin_user" ]) - (mkRenamedOptionModule [ "services" "grafana" "security" "adminPassword" ] [ "services" "grafana" "settings" "security" "admin_password" ]) - (mkRenamedOptionModule [ "services" "grafana" "security" "secretKey" ] [ "services" "grafana" "settings" "security" "secret_key" ]) - (mkRenamedOptionModule [ "services" "grafana" "server" "serveFromSubPath" ] [ "services" "grafana" "settings" "server" "serve_from_sub_path" ]) - (mkRenamedOptionModule [ "services" "grafana" "smtp" "enable" ] [ "services" "grafana" "settings" "smtp" "enabled" ]) - (mkRenamedOptionModule [ "services" "grafana" "smtp" "user" ] [ "services" "grafana" "settings" "smtp" "user" ]) - (mkRenamedOptionModule [ "services" "grafana" "smtp" "password" ] [ "services" "grafana" "settings" "smtp" "password" ]) - (mkRenamedOptionModule [ "services" "grafana" "smtp" "fromAddress" ] [ "services" "grafana" "settings" "smtp" "from_address" ]) - (mkRenamedOptionModule [ "services" "grafana" "users" "allowSignUp" ] [ "services" "grafana" "settings" "users" "allow_sign_up" ]) - (mkRenamedOptionModule [ "services" "grafana" "users" "allowOrgCreate" ] [ "services" "grafana" "settings" "users" "allow_org_create" ]) - (mkRenamedOptionModule [ "services" "grafana" "users" "autoAssignOrg" ] [ "services" "grafana" "settings" "users" "auto_assign_org" ]) - (mkRenamedOptionModule [ "services" "grafana" "users" "autoAssignOrgRole" ] [ "services" "grafana" "settings" "users" "auto_assign_org_role" ]) - (mkRenamedOptionModule [ "services" "grafana" "auth" "disableLoginForm" ] [ "services" "grafana" "settings" "auth" "disable_login_form" ]) - (mkRenamedOptionModule [ "services" "grafana" "auth" "anonymous" "enable" ] [ "services" "grafana" "settings" "auth.anonymous" "enabled" ]) - (mkRenamedOptionModule [ "services" "grafana" "auth" "anonymous" "org_name" ] [ "services" "grafana" "settings" "auth.anonymous" "org_name" ]) - (mkRenamedOptionModule [ "services" "grafana" "auth" "anonymous" "org_role" ] [ "services" "grafana" "settings" "auth.anonymous" "org_role" ]) - (mkRenamedOptionModule [ "services" "grafana" "auth" "azuread" "enable" ] [ "services" "grafana" "settings" "auth.azuread" "enabled" ]) - (mkRenamedOptionModule [ "services" "grafana" "auth" "azuread" "allowSignUp" ] [ "services" "grafana" "settings" "auth.azuread" "allow_sign_up" ]) - (mkRenamedOptionModule [ "services" "grafana" "auth" "azuread" "clientId" ] [ "services" "grafana" "settings" "auth.azuread" "client_id" ]) - (mkRenamedOptionModule [ "services" "grafana" "auth" "azuread" "allowedDomains" ] [ "services" "grafana" "settings" "auth.azuread" "allowed_domains" ]) - (mkRenamedOptionModule [ "services" "grafana" "auth" "azuread" "allowedGroups" ] [ "services" "grafana" "settings" "auth.azuread" "allowed_groups" ]) - (mkRenamedOptionModule [ "services" "grafana" "auth" "google" "enable" ] [ "services" "grafana" "settings" "auth.google" "enabled" ]) - (mkRenamedOptionModule [ "services" "grafana" "auth" "google" "allowSignUp" ] [ "services" "grafana" "settings" "auth.google" "allow_sign_up" ]) - (mkRenamedOptionModule [ "services" "grafana" "auth" "google" "clientId" ] [ "services" "grafana" "settings" "auth.google" "client_id" ]) - (mkRenamedOptionModule [ "services" "grafana" "analytics" "reporting" "enable" ] [ "services" "grafana" "settings" "analytics" "reporting_enabled" ]) - - (mkRemovedOptionModule [ "services" "grafana" "database" "passwordFile" ] '' + (lib.mkRenamedOptionModule [ "services" "grafana" "protocol" ] [ "services" "grafana" "settings" "server" "protocol" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "addr" ] [ "services" "grafana" "settings" "server" "http_addr" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "port" ] [ "services" "grafana" "settings" "server" "http_port" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "domain" ] [ "services" "grafana" "settings" "server" "domain" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "rootUrl" ] [ "services" "grafana" "settings" "server" "root_url" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "staticRootPath" ] [ "services" "grafana" "settings" "server" "static_root_path" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "certFile" ] [ "services" "grafana" "settings" "server" "cert_file" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "certKey" ] [ "services" "grafana" "settings" "server" "cert_key" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "socket" ] [ "services" "grafana" "settings" "server" "socket" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "database" "type" ] [ "services" "grafana" "settings" "database" "type" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "database" "host" ] [ "services" "grafana" "settings" "database" "host" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "database" "name" ] [ "services" "grafana" "settings" "database" "name" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "database" "user" ] [ "services" "grafana" "settings" "database" "user" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "database" "password" ] [ "services" "grafana" "settings" "database" "password" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "database" "path" ] [ "services" "grafana" "settings" "database" "path" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "database" "connMaxLifetime" ] [ "services" "grafana" "settings" "database" "conn_max_lifetime" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "security" "adminUser" ] [ "services" "grafana" "settings" "security" "admin_user" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "security" "adminPassword" ] [ "services" "grafana" "settings" "security" "admin_password" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "security" "secretKey" ] [ "services" "grafana" "settings" "security" "secret_key" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "server" "serveFromSubPath" ] [ "services" "grafana" "settings" "server" "serve_from_sub_path" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "smtp" "enable" ] [ "services" "grafana" "settings" "smtp" "enabled" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "smtp" "user" ] [ "services" "grafana" "settings" "smtp" "user" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "smtp" "password" ] [ "services" "grafana" "settings" "smtp" "password" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "smtp" "fromAddress" ] [ "services" "grafana" "settings" "smtp" "from_address" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "users" "allowSignUp" ] [ "services" "grafana" "settings" "users" "allow_sign_up" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "users" "allowOrgCreate" ] [ "services" "grafana" "settings" "users" "allow_org_create" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "users" "autoAssignOrg" ] [ "services" "grafana" "settings" "users" "auto_assign_org" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "users" "autoAssignOrgRole" ] [ "services" "grafana" "settings" "users" "auto_assign_org_role" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "auth" "disableLoginForm" ] [ "services" "grafana" "settings" "auth" "disable_login_form" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "auth" "anonymous" "enable" ] [ "services" "grafana" "settings" "auth.anonymous" "enabled" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "auth" "anonymous" "org_name" ] [ "services" "grafana" "settings" "auth.anonymous" "org_name" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "auth" "anonymous" "org_role" ] [ "services" "grafana" "settings" "auth.anonymous" "org_role" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "auth" "azuread" "enable" ] [ "services" "grafana" "settings" "auth.azuread" "enabled" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "auth" "azuread" "allowSignUp" ] [ "services" "grafana" "settings" "auth.azuread" "allow_sign_up" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "auth" "azuread" "clientId" ] [ "services" "grafana" "settings" "auth.azuread" "client_id" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "auth" "azuread" "allowedDomains" ] [ "services" "grafana" "settings" "auth.azuread" "allowed_domains" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "auth" "azuread" "allowedGroups" ] [ "services" "grafana" "settings" "auth.azuread" "allowed_groups" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "auth" "google" "enable" ] [ "services" "grafana" "settings" "auth.google" "enabled" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "auth" "google" "allowSignUp" ] [ "services" "grafana" "settings" "auth.google" "allow_sign_up" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "auth" "google" "clientId" ] [ "services" "grafana" "settings" "auth.google" "client_id" ]) + (lib.mkRenamedOptionModule [ "services" "grafana" "analytics" "reporting" "enable" ] [ "services" "grafana" "settings" "analytics" "reporting_enabled" ]) + + (lib.mkRemovedOptionModule [ "services" "grafana" "database" "passwordFile" ] '' This option has been removed. Use 'services.grafana.settings.database.password' with file provider instead. '') - (mkRemovedOptionModule [ "services" "grafana" "security" "adminPasswordFile" ] '' + (lib.mkRemovedOptionModule [ "services" "grafana" "security" "adminPasswordFile" ] '' This option has been removed. Use 'services.grafana.settings.security.admin_password' with file provider instead. '') - (mkRemovedOptionModule [ "services" "grafana" "security" "secretKeyFile" ] '' + (lib.mkRemovedOptionModule [ "services" "grafana" "security" "secretKeyFile" ] '' This option has been removed. Use 'services.grafana.settings.security.secret_key' with file provider instead. '') - (mkRemovedOptionModule [ "services" "grafana" "smtp" "passwordFile" ] '' + (lib.mkRemovedOptionModule [ "services" "grafana" "smtp" "passwordFile" ] '' This option has been removed. Use 'services.grafana.settings.smtp.password' with file provider instead. '') - (mkRemovedOptionModule [ "services" "grafana" "auth" "azuread" "clientSecretFile" ] '' + (lib.mkRemovedOptionModule [ "services" "grafana" "auth" "azuread" "clientSecretFile" ] '' This option has been removed. Use 'services.grafana.settings.azuread.client_secret' with file provider instead. '') - (mkRemovedOptionModule [ "services" "grafana" "auth" "google" "clientSecretFile" ] '' + (lib.mkRemovedOptionModule [ "services" "grafana" "auth" "google" "clientSecretFile" ] '' This option has been removed. Use 'services.grafana.settings.google.client_secret' with file provider instead. '') - (mkRemovedOptionModule [ "services" "grafana" "extraOptions" ] '' + (lib.mkRemovedOptionModule [ "services" "grafana" "extraOptions" ] '' This option has been removed. Use 'services.grafana.settings' instead. For a detailed migration guide, please review the release notes of NixOS 22.11. '') - (mkRemovedOptionModule [ "services" "grafana" "auth" "azuread" "tenantId" ] "This option has been deprecated upstream.") + (lib.mkRemovedOptionModule [ "services" "grafana" "auth" "azuread" "tenantId" ] "This option has been deprecated upstream.") ]; options.services.grafana = { - enable = mkEnableOption "grafana"; + enable = lib.mkEnableOption "grafana"; - declarativePlugins = mkOption { - type = with types; nullOr (listOf path); + declarativePlugins = lib.mkOption { + type = with lib.types; nullOr (listOf path); default = null; description = "If non-null, then a list of packages containing Grafana plugins to install. If set, plugins cannot be manually installed."; - example = literalExpression "with pkgs.grafanaPlugins; [ grafana-piechart-panel ]"; + example = lib.literalExpression "with pkgs.grafanaPlugins; [ grafana-piechart-panel ]"; # Make sure each plugin is added only once; otherwise building # the link farm fails, since the same path is added multiple # times. - apply = x: if isList x then lib.unique x else x; + apply = x: if lib.isList x then lib.unique x else x; }; - package = mkPackageOption pkgs "grafana" { }; + package = lib.mkPackageOption pkgs "grafana" { }; - dataDir = mkOption { + dataDir = lib.mkOption { description = "Data directory."; default = "/var/lib/grafana"; - type = types.path; + type = lib.types.path; }; - settings = mkOption { + settings = lib.mkOption { description = '' Grafana settings. See for available options. INI format is used. ''; default = { }; - type = types.submodule { + type = lib.types.submodule { freeformType = settingsFormatIni.type; options = { paths = { - plugins = mkOption { + plugins = lib.mkOption { description = "Directory where grafana will automatically scan and look for plugins"; default = if (cfg.declarativePlugins == null) then "${cfg.dataDir}/plugins" else declarativePlugins; - defaultText = literalExpression "if (cfg.declarativePlugins == null) then \"\${cfg.dataDir}/plugins\" else declarativePlugins"; - type = types.path; + defaultText = lib.literalExpression "if (cfg.declarativePlugins == null) then \"\${cfg.dataDir}/plugins\" else declarativePlugins"; + type = lib.types.path; }; - provisioning = mkOption { + provisioning = lib.mkOption { description = '' Folder that contains provisioning config files that grafana will apply on startup and while running. Don't change the value of this option if you are planning to use `services.grafana.provision` options. ''; default = provisionConfDir; defaultText = "directory with links to files generated from services.grafana.provision"; - type = types.path; + type = lib.types.path; }; }; server = { - protocol = mkOption { + protocol = lib.mkOption { description = "Which protocol to listen."; default = "http"; - type = types.enum [ "http" "https" "h2" "socket" ]; + type = lib.types.enum [ "http" "https" "h2" "socket" ]; }; - http_addr = mkOption { - type = types.str; + http_addr = lib.mkOption { + type = lib.types.str; default = "127.0.0.1"; description = '' Listening address. @@ -298,13 +296,13 @@ in ''; }; - http_port = mkOption { + http_port = lib.mkOption { description = "Listening port."; default = 3000; - type = types.port; + type = lib.types.port; }; - domain = mkOption { + domain = lib.mkOption { description = '' The public facing domain name used to access grafana from a browser. @@ -312,19 +310,19 @@ in If you set the latter manually, this option does not have to be specified. ''; default = "localhost"; - type = types.str; + type = lib.types.str; }; - enforce_domain = mkOption { + enforce_domain = lib.mkOption { description = '' Redirect to correct domain if the host header does not match the domain. Prevents DNS rebinding attacks. ''; default = false; - type = types.bool; + type = lib.types.bool; }; - root_url = mkOption { + root_url = lib.mkOption { description = '' This is the full URL used to access Grafana from a web browser. This is important if you use Google or GitHub OAuth authentication (for the callback URL to be correct). @@ -333,10 +331,10 @@ in In that case add the subpath to the end of this URL setting. ''; default = "%(protocol)s://%(domain)s:%(http_port)s/"; - type = types.str; + type = lib.types.str; }; - serve_from_sub_path = mkOption { + serve_from_sub_path = lib.mkOption { description = '' Serve Grafana from subpath specified in the `root_url` setting. By default it is set to `false` for compatibility reasons. @@ -347,51 +345,51 @@ in If accessed without subpath, Grafana will redirect to an URL with the subpath. ''; default = false; - type = types.bool; + type = lib.types.bool; }; - router_logging = mkOption { + router_logging = lib.mkOption { description = '' Set to `true` for Grafana to log all HTTP requests (not just errors). These are logged as Info level events to the Grafana log. ''; default = false; - type = types.bool; + type = lib.types.bool; }; - static_root_path = mkOption { + static_root_path = lib.mkOption { description = "Root path for static assets."; default = "${cfg.package}/share/grafana/public"; - defaultText = literalExpression ''"''${package}/share/grafana/public"''; - type = types.str; + defaultText = lib.literalExpression ''"''${package}/share/grafana/public"''; + type = lib.types.str; }; - enable_gzip = mkOption { + enable_gzip = lib.mkOption { description = '' Set this option to `true` to enable HTTP compression, this can improve transfer speed and bandwidth utilization. It is recommended that most users set it to `true`. By default it is set to `false` for compatibility reasons. ''; default = false; - type = types.bool; + type = lib.types.bool; }; - cert_file = mkOption { + cert_file = lib.mkOption { description = '' Path to the certificate file (if `protocol` is set to `https` or `h2`). ''; default = null; - type = types.nullOr types.str; + type = lib.types.nullOr lib.types.str; }; - cert_key = mkOption { + cert_key = lib.mkOption { description = '' Path to the certificate key file (if `protocol` is set to `https` or `h2`). ''; default = null; - type = types.nullOr types.str; + type = lib.types.nullOr lib.types.str; }; - socket_gid = mkOption { + socket_gid = lib.mkOption { description = '' GID where the socket should be set when `protocol=socket`. Make sure that the target group is in the group of Grafana process and that Grafana process is the file owner before you change this setting. @@ -399,10 +397,10 @@ in Not set when the value is -1. ''; default = -1; - type = types.int; + type = lib.types.int; }; - socket_mode = mkOption { + socket_mode = lib.mkOption { description = '' Mode where the socket should be set when `protocol=socket`. Make sure that Grafana process is the file owner before you change this setting. @@ -411,19 +409,19 @@ in # If this was an int, people following tutorials or porting their # old config could stumble across nix not having octal literals. default = "0660"; - type = types.str; + type = lib.types.str; }; - socket = mkOption { + socket = lib.mkOption { description = '' Path where the socket should be created when `protocol=socket`. Make sure that Grafana has appropriate permissions before you change this setting. ''; default = "/run/grafana/grafana.sock"; - type = types.str; + type = lib.types.str; }; - cdn_url = mkOption { + cdn_url = lib.mkOption { description = '' Specify a full HTTP URL address to the root of your Grafana CDN assets. Grafana will add edition and version paths. @@ -432,28 +430,28 @@ in grafana will try to load a javascript file from `http://cdn.myserver.com/grafana-oss/7.4.0/public/build/app..js`. ''; default = null; - type = types.nullOr types.str; + type = lib.types.nullOr lib.types.str; }; - read_timeout = mkOption { + read_timeout = lib.mkOption { description = '' Sets the maximum time using a duration format (5s/5m/5ms) before timing out read of an incoming request and closing idle connections. 0 means there is no timeout for reading the request. ''; default = "0"; - type = types.str; + type = lib.types.str; }; }; database = { - type = mkOption { + type = lib.mkOption { description = "Database type."; default = "sqlite3"; - type = types.enum [ "mysql" "sqlite3" "postgres" ]; + type = lib.types.enum [ "mysql" "sqlite3" "postgres" ]; }; - host = mkOption { + host = lib.mkOption { description = '' Only applicable to MySQL or Postgres. Includes IP or hostname and port or in case of Unix sockets the path to it. @@ -461,22 +459,22 @@ in or with Unix sockets: `host = "/var/run/mysqld/mysqld.sock"` ''; default = "127.0.0.1:3306"; - type = types.str; + type = lib.types.str; }; - name = mkOption { + name = lib.mkOption { description = "The name of the Grafana database."; default = "grafana"; - type = types.str; + type = lib.types.str; }; - user = mkOption { + user = lib.mkOption { description = "The database user (not applicable for `sqlite3`)."; default = "root"; - type = types.str; + type = lib.types.str; }; - password = mkOption { + password = lib.mkOption { description = '' The database user's password (not applicable for `sqlite3`). @@ -487,154 +485,154 @@ in ''; default = ""; - type = types.str; + type = lib.types.str; }; - max_idle_conn = mkOption { + max_idle_conn = lib.mkOption { description = "The maximum number of connections in the idle connection pool."; default = 2; - type = types.int; + type = lib.types.int; }; - max_open_conn = mkOption { + max_open_conn = lib.mkOption { description = "The maximum number of open connections to the database."; default = 0; - type = types.int; + type = lib.types.int; }; - conn_max_lifetime = mkOption { + conn_max_lifetime = lib.mkOption { description = '' Sets the maximum amount of time a connection may be reused. The default is 14400 (which means 14400 seconds or 4 hours). For MySQL, this setting should be shorter than the `wait_timeout` variable. ''; default = 14400; - type = types.int; + type = lib.types.int; }; - locking_attempt_timeout_sec = mkOption { + locking_attempt_timeout_sec = lib.mkOption { description = '' For `mysql`, if the `migrationLocking` feature toggle is set, specify the time (in seconds) to wait before failing to lock the database for the migrations. ''; default = 0; - type = types.int; + type = lib.types.int; }; - log_queries = mkOption { + log_queries = lib.mkOption { description = "Set to `true` to log the sql calls and execution times"; default = false; - type = types.bool; + type = lib.types.bool; }; - ssl_mode = mkOption { + ssl_mode = lib.mkOption { description = '' For Postgres, use either `disable`, `require` or `verify-full`. For MySQL, use either `true`, `false`, or `skip-verify`. ''; default = "disable"; - type = types.enum [ "disable" "require" "verify-full" "true" "false" "skip-verify" ]; + type = lib.types.enum [ "disable" "require" "verify-full" "true" "false" "skip-verify" ]; }; - isolation_level = mkOption { + isolation_level = lib.mkOption { description = '' Only the MySQL driver supports isolation levels in Grafana. In case the value is empty, the driver's default isolation level is applied. ''; default = null; - type = types.nullOr (types.enum [ "READ-UNCOMMITTED" "READ-COMMITTED" "REPEATABLE-READ" "SERIALIZABLE" ]); + type = lib.types.nullOr (lib.types.enum [ "READ-UNCOMMITTED" "READ-COMMITTED" "REPEATABLE-READ" "SERIALIZABLE" ]); }; - ca_cert_path = mkOption { + ca_cert_path = lib.mkOption { description = "The path to the CA certificate to use."; default = null; - type = types.nullOr types.str; + type = lib.types.nullOr lib.types.str; }; - client_key_path = mkOption { + client_key_path = lib.mkOption { description = "The path to the client key. Only if server requires client authentication."; default = null; - type = types.nullOr types.str; + type = lib.types.nullOr lib.types.str; }; - client_cert_path = mkOption { + client_cert_path = lib.mkOption { description = "The path to the client cert. Only if server requires client authentication."; default = null; - type = types.nullOr types.str; + type = lib.types.nullOr lib.types.str; }; - server_cert_name = mkOption { + server_cert_name = lib.mkOption { description = '' The common name field of the certificate used by the `mysql` or `postgres` server. Not necessary if `ssl_mode` is set to `skip-verify`. ''; default = null; - type = types.nullOr types.str; + type = lib.types.nullOr lib.types.str; }; - path = mkOption { + path = lib.mkOption { description = "Only applicable to `sqlite3` database. The file path where the database will be stored."; default = "${cfg.dataDir}/data/grafana.db"; - defaultText = literalExpression ''"''${config.${opt.dataDir}}/data/grafana.db"''; - type = types.path; + defaultText = lib.literalExpression ''"''${config.${opt.dataDir}}/data/grafana.db"''; + type = lib.types.path; }; - cache_mode = mkOption { + cache_mode = lib.mkOption { description = '' For `sqlite3` only. [Shared cache](https://www.sqlite.org/sharedcache.html) setting used for connecting to the database. ''; default = "private"; - type = types.enum [ "private" "shared" ]; + type = lib.types.enum [ "private" "shared" ]; }; - wal = mkOption { + wal = lib.mkOption { description = '' For `sqlite3` only. Setting to enable/disable [Write-Ahead Logging](https://sqlite.org/wal.html). ''; default = false; - type = types.bool; + type = lib.types.bool; }; - query_retries = mkOption { + query_retries = lib.mkOption { description = '' This setting applies to `sqlite3` only and controls the number of times the system retries a query when the database is locked. ''; default = 0; - type = types.int; + type = lib.types.int; }; - transaction_retries = mkOption { + transaction_retries = lib.mkOption { description = '' This setting applies to `sqlite3` only and controls the number of times the system retries a transaction when the database is locked. ''; default = 5; - type = types.int; + type = lib.types.int; }; # TODO Add "instrument_queries" option when upgrading to grafana 10.0 - # instrument_queries = mkOption { + # instrument_queries = lib.mkOption { # description = "Set to `true` to add metrics and tracing for database queries."; # default = false; - # type = types.bool; + # type = lib.types.bool; # }; }; security = { - disable_initial_admin_creation = mkOption { + disable_initial_admin_creation = lib.mkOption { description = "Disable creation of admin user on first start of Grafana."; default = false; - type = types.bool; + type = lib.types.bool; }; - admin_user = mkOption { + admin_user = lib.mkOption { description = "Default admin username."; default = "admin"; - type = types.str; + type = lib.types.str; }; - admin_password = mkOption { + admin_password = lib.mkOption { description = '' Default admin password. Please note that the contents of this option will end up in a world-readable Nix store. Use the file provider @@ -643,16 +641,16 @@ in ''; default = "admin"; - type = types.str; + type = lib.types.str; }; - admin_email = mkOption { + admin_email = lib.mkOption { description = "The email of the default Grafana Admin, created on startup."; default = "admin@localhost"; - type = types.str; + type = lib.types.str; }; - secret_key = mkOption { + secret_key = lib.mkOption { description = '' Secret key used for signing. Please note that the contents of this option will end up in a world-readable Nix store. Use the file provider @@ -661,16 +659,16 @@ in ''; default = "SW2YcwTIb9zpOOhoPsMm"; - type = types.str; + type = lib.types.str; }; - disable_gravatar = mkOption { + disable_gravatar = lib.mkOption { description = "Set to `true` to disable the use of Gravatar for user profile images."; default = false; - type = types.bool; + type = lib.types.bool; }; - data_source_proxy_whitelist = mkOption { + data_source_proxy_whitelist = lib.mkOption { description = '' Define a whitelist of allowed IP addresses or domains, with ports, to be used in data source URLs with the Grafana data source proxy. @@ -678,22 +676,22 @@ in PostgreSQL, MySQL, and MSSQL data sources do not use the proxy and are therefore unaffected by this setting. ''; default = [ ]; - type = types.oneOf [ types.str (types.listOf types.str) ]; + type = lib.types.oneOf [ lib.types.str (lib.types.listOf lib.types.str) ]; }; - disable_brute_force_login_protection = mkOption { + disable_brute_force_login_protection = lib.mkOption { description = "Set to `true` to disable [brute force login protection](https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html#account-lockout)."; default = false; - type = types.bool; + type = lib.types.bool; }; - cookie_secure = mkOption { + cookie_secure = lib.mkOption { description = "Set to `true` if you host Grafana behind HTTPS."; default = false; - type = types.bool; + type = lib.types.bool; }; - cookie_samesite = mkOption { + cookie_samesite = lib.mkOption { description = '' Sets the `SameSite` cookie attribute and prevents the browser from sending this cookie along with cross-site requests. The main goal is to mitigate the risk of cross-origin information leakage. @@ -702,20 +700,20 @@ in Using value `disabled` does not add any `SameSite` attribute to cookies. ''; default = "lax"; - type = types.enum [ "lax" "strict" "none" "disabled" ]; + type = lib.types.enum [ "lax" "strict" "none" "disabled" ]; }; - allow_embedding = mkOption { + allow_embedding = lib.mkOption { description = '' When `false`, the HTTP header `X-Frame-Options: deny` will be set in Grafana HTTP responses which will instruct browsers to not allow rendering Grafana in a ``, `