20 ## Simple (higher order) functions
24 For when you need a function that does “nothing”.
44 Ignores the second argument. If called with only one argument,
45 constructs a function that always returns a static value.
66 ## `lib.trivial.const` usage example
69 let f = const 5; in f 10
80 Pipes a value through a list of functions, left to right.
86 : Value to start piping.
90 : List of functions to apply sequentially.
95 pipe :: a -> [<functions>] -> <return type of last function>
100 ## `lib.trivial.pipe` usage example
104 (x: x + 2) # 2 + 2 = 4
105 (x: x * 2) # 4 * 2 = 8
109 # ideal to do text transformations
110 pipe [ "a/b" "a/c" ] [
112 # create the cp command
113 (map (file: ''cp "${src}/${file}" $out\n''))
115 # concatenate all commands into one string
118 # make that string into a nix derivation
119 (pkgs.runCommand "copy-to-out" {})
122 => <drv which copies all files to $out>
124 The output type of each function has to be the input type
125 of the next function, and the last function returns the
131 pipe = builtins.foldl' (x: f: f x);
133 # note please don’t add a function like `compose = flip pipe`.
134 # This would confuse users, because the order of the functions
135 # in the list is not clear. With pipe, it’s obvious that it
136 # goes first-to-last. With `compose`, not so much.
138 ## Named versions corresponding to some builtin operators.
141 Concatenate two lists
148 : 1\. Function argument
152 : 2\. Function argument
157 concat :: [a] -> [a] -> [a]
162 ## `lib.trivial.concat` usage example
165 concat [ 1 2 ] [ 3 4 ]
171 concat = x: y: x ++ y;
181 : 1\. Function argument
185 : 2\. Function argument
197 : 1\. Function argument
201 : 2\. Function argument
206 boolean “exclusive or”
213 : 1\. Function argument
217 : 2\. Function argument
219 # We explicitly invert the arguments purely as a type assertion.
220 # This is invariant under XOR, so it does not affect the result.
221 xor = x: y: (!x) != (!y);
226 bitNot = builtins.sub (-1);
229 Convert a boolean to a string.
231 This function uses the strings "true" and "false" to represent
232 boolean values. Calling `toString` on a bool instead returns "1"
240 : 1\. Function argument
245 boolToString :: bool -> string
248 boolToString = b: if b then "true" else "false";
251 Merge two attribute sets shallowly, right side trumps left
253 mergeAttrs :: attrs -> attrs -> attrs
264 : Right attribute set (higher precedence for equal keys)
269 ## `lib.trivial.mergeAttrs` usage example
272 mergeAttrs { a = 1; b = 2; } { b = 3; c = 4; }
273 => { a = 1; b = 3; c = 4; }
283 Flip the order of the arguments of a binary function.
290 : 1\. Function argument
294 : 2\. Function argument
298 : 3\. Function argument
303 flip :: (a -> b -> c) -> (b -> a -> c)
308 ## `lib.trivial.flip` usage example
317 flip = f: a: b: f b a;
320 Apply function if the supplied argument is non-null.
331 : Argument to check for null before passing it to `f`
336 ## `lib.trivial.mapNullable` usage example
339 mapNullable (x: x+1) null
341 mapNullable (x: x+1) 22
349 a: if a == null then a else f a;
351 # Pull in some builtins not included elsewhere.
353 pathExists readFile isBool
354 isInt isFloat add sub lessThan
355 seq deepSeq genericClosure
358 ## nixpkgs version strings
361 Returns the current full nixpkgs version number.
363 version = release + versionSuffix;
366 Returns the current nixpkgs release number as string.
368 release = lib.strings.fileContents ./.version;
371 The latest release that is supported, at the time of release branch-off,
374 Ideally, out-of-tree modules should be able to evaluate cleanly with all
375 supported Nixpkgs versions (master, release and old release until EOL).
376 So if possible, deprecation warnings should take effect only when all
377 out-of-tree expressions/libs/modules can upgrade to the new way without
378 losing support for supported Nixpkgs versions.
380 This release number allows deprecation warnings to be implemented such that
381 they take effect as soon as the oldest release reaches end of life.
383 oldestSupportedRelease =
384 # Update on master only. Do not backport.
388 Whether a feature is supported in all supported releases (at the time of
389 release branch-off, if applicable). See `oldestSupportedRelease`.
396 : Release number of feature introduction as an integer, e.g. 2111 for 21.11.
397 Set it to the upcoming release, matching the nixpkgs/.version file.
400 lib.warnIf (lib.oldestSupportedReleaseIsAtLeast 2411)
401 "lib.isInOldestRelease is deprecated. Use lib.oldestSupportedReleaseIsAtLeast instead."
402 lib.oldestSupportedReleaseIsAtLeast;
405 Alias for `isInOldestRelease` introduced in 24.11.
406 Use `isInOldestRelease` in expressions outside of Nixpkgs for greater compatibility.
408 oldestSupportedReleaseIsAtLeast =
410 release <= lib.trivial.oldestSupportedRelease;
413 Returns the current nixpkgs release code name.
415 On each release the first letter is bumped and a new animal is chosen
416 starting with that new letter.
421 Returns the current nixpkgs version suffix as string.
424 let suffixFile = ../.version-suffix;
425 in if pathExists suffixFile
426 then lib.strings.fileContents suffixFile
430 Attempts to return the the current revision of nixpkgs and
431 returns the supplied default value otherwise.
438 : Default value to return if revision can not be determined
443 revisionWithDefault :: string -> string
446 revisionWithDefault =
449 revisionFile = "${toString ./..}/.git-revision";
450 gitRepo = "${toString ./..}/.git";
451 in if lib.pathIsGitRepo gitRepo
452 then lib.commitIdFromGitRepo gitRepo
453 else if lib.pathExists revisionFile then lib.fileContents revisionFile
456 nixpkgsVersion = warn "lib.nixpkgsVersion is a deprecated alias of lib.version." version;
459 Determine whether the function is being called from inside a Nix
468 inNixShell = builtins.getEnv "IN_NIX_SHELL" != "";
471 Determine whether the function is being called from inside pure-eval mode
472 by seeing whether `builtins` contains `currentSystem`. If not, we must be in
478 inPureEvalMode :: bool
481 inPureEvalMode = ! builtins ? currentSystem;
483 ## Integer operations
486 Return minimum of two numbers.
493 : 1\. Function argument
497 : 2\. Function argument
499 min = x: y: if x < y then x else y;
502 Return maximum of two numbers.
509 : 1\. Function argument
513 : 2\. Function argument
515 max = x: y: if x > y then x else y;
525 : 1\. Function argument
529 : 2\. Function argument
534 ## `lib.trivial.mod` usage example
545 mod = base: int: base - (int * (builtins.div base int));
553 a < b, compare a b => -1
554 a == b, compare a b => 0
555 a > b, compare a b => 1
562 : 1\. Function argument
566 : 2\. Function argument
576 Split type into two subtypes by predicate `p`, take all elements
577 of the first subtype to be less than all the elements of the
578 second subtype, compare elements of a single subtype with `yes`
579 and `no` respectively.
590 : Comparison function if predicate holds for both values
594 : Comparison function if predicate holds for neither value
598 : First value to compare
602 : Second value to compare
607 (a -> bool) -> (a -> a -> int) -> (a -> a -> int) -> (a -> a -> int)
612 ## `lib.trivial.splitByAndCompare` usage example
615 let cmp = splitByAndCompare (hasPrefix "foo") compare compare; in
618 cmp "fooa" "fooz" => -1
623 compare "fooa" "a" => 1
631 then if p b then yes a b else -1
632 else if p b then 1 else no a b;
640 ## `lib.trivial.importJSON` usage example
645 "title": "Example JSON",
656 importJSON ./example.json
658 title = "Example JSON";
674 : 1\. Function argument
679 importJSON :: path -> any
683 builtins.fromJSON (builtins.readFile path);
690 ## `lib.trivial.importTOML` usage example
694 title = "TOML Example"
704 importTOML ./example.toml
706 title = "TOML Example";
722 : 1\. Function argument
727 importTOML :: path -> any
731 builtins.fromTOML (builtins.readFile path);
735 `warn` *`message`* *`value`*
737 Print a warning before returning the second argument.
739 See [`builtins.warn`](https://nix.dev/manual/nix/latest/language/builtins.html#builtins-warn) (Nix >= 2.23).
740 On older versions, the Nix 2.23 behavior is emulated with [`builtins.trace`](https://nix.dev/manual/nix/latest/language/builtins.html#builtins-warn), including the [`NIX_ABORT_ON_WARN`](https://nix.dev/manual/nix/latest/command-ref/conf-file#conf-abort-on-warn) behavior, but not the `nix.conf` setting or command line option.
746 : Warning message to print before evaluating *`value`*.
748 *`value`* (any value)
750 : Value to return as-is.
759 # Since Nix 2.23, https://github.com/NixOS/nix/pull/10592
761 let mustAbort = lib.elem (builtins.getEnv "NIX_ABORT_ON_WARN") ["1" "true" "yes"];
763 # Do not eta reduce v, so that we have the same strictness as `builtins.warn`.
765 # `builtins.warn` requires a string message, so we enforce that in our implementation, so that callers aren't accidentally incompatible with newer Nix versions.
768 then builtins.trace "
\e[1;31mevaluation warning:
\e[0m ${msg}" (abort "NIX_ABORT_ON_WARN=true; warnings are treated as unrecoverable errors.")
769 else builtins.trace "
\e[1;35mevaluation warning:
\e[0m ${msg}" v
774 `warnIf` *`condition`* *`message`* *`value`*
776 Like `warn`, but only warn when the first argument is `true`.
780 *`condition`* (Boolean)
782 : `true` to trigger the warning before continuing with *`value`*.
786 : Warning message to print before evaluating
788 *`value`* (any value)
790 : Value to return as-is.
795 Bool -> String -> a -> a
798 warnIf = cond: msg: if cond then warn msg else x: x;
802 `warnIfNot` *`condition`* *`message`* *`value`*
804 Like `warnIf`, but negated: warn if the first argument is `false`.
810 : `false` to trigger the warning before continuing with `val`.
814 : Warning message to print before evaluating *`value`*.
818 : Value to return as-is.
823 Boolean -> String -> a -> a
826 warnIfNot = cond: msg: if cond then x: x else warn msg;
829 Like the `assert b; e` expression, but with a custom error message and
830 without the semicolon.
832 If true, return the identity function, `r: r`.
834 If false, throw the error message.
836 Calls can be juxtaposed using function application, as `(r: r) a = a`, so
837 `(r: r) (r: r) a = a`, and so forth.
844 : 1\. Function argument
848 : 2\. Function argument
853 bool -> string -> a -> a
858 ## `lib.trivial.throwIfNot` usage example
861 throwIfNot (lib.isList overlays) "The overlays argument to nixpkgs must be a list."
862 lib.foldr (x: throwIfNot (lib.isFunction x) "All overlays passed to nixpkgs must be functions.") (r: r) overlays
868 throwIfNot = cond: msg: if cond then x: x else throw msg;
871 Like throwIfNot, but negated (throw if the first argument is `true`).
878 : 1\. Function argument
882 : 2\. Function argument
887 bool -> string -> a -> a
890 throwIf = cond: msg: if cond then throw msg else x: x;
893 Check if the elements in a list are valid values from a enum, returning the identity function, or throwing an error message otherwise.
900 : 1\. Function argument
904 : 2\. Function argument
908 : 3\. Function argument
913 String -> List ComparableVal -> List ComparableVal -> a -> a
918 ## `lib.trivial.checkListOfEnum` usage example
921 let colorVariants = ["bright" "dark" "black"]
922 in checkListOfEnum "color variants" [ "standard" "light" "dark" ] colorVariants;
924 error: color variants: bright, black unexpected; valid ones: standard, light, dark
929 checkListOfEnum = msg: valid: given:
931 unexpected = lib.subtractLists valid given;
933 lib.throwIfNot (unexpected == [])
934 "${msg}: ${builtins.concatStringsSep ", " (builtins.map builtins.toString unexpected)} unexpected; valid ones: ${builtins.concatStringsSep ", " (builtins.map builtins.toString valid)}";
936 info = msg: builtins.trace "INFO: ${msg}";
938 showWarnings = warnings: res: lib.foldr (w: x: warn w x) res warnings;
940 ## Function annotations
943 Add metadata about expected function arguments to a function.
944 The metadata should match the format given by
945 builtins.functionArgs, i.e. a set from expected argument to a bool
946 representing whether that argument has a default or not.
947 setFunctionArgs : (a → b) → Map String Bool → (a → b)
949 This function is necessary because you can't dynamically create a
950 function of the { a, b ? foo, ... }: format, but some facilities
951 like callPackage expect to be able to query expected arguments.
958 : 1\. Function argument
962 : 2\. Function argument
964 setFunctionArgs = f: args:
965 { # TODO: Should we add call-time "type" checking like built in?
967 __functionArgs = args;
971 Extract the expected function arguments from a function.
972 This works both with nix-native { a, b ? foo, ... }: style
973 functions and functions with args set with 'setFunctionArgs'. It
974 has the same return type and semantics as builtins.functionArgs.
975 setFunctionArgs : (a → b) → Map String Bool.
982 : 1\. Function argument
986 then f.__functionArgs or (functionArgs (f.__functor f))
987 else builtins.functionArgs f;
990 Check whether something is a function or something
991 annotated with function args.
998 : 1\. Function argument
1000 isFunction = f: builtins.isFunction f ||
1001 (f ? __functor && isFunction (f.__functor f));
1004 `mirrorFunctionArgs f g` creates a new function `g'` with the same behavior as `g` (`g' x == g x`)
1005 but its function arguments mirroring `f` (`lib.functionArgs g' == lib.functionArgs f`).
1012 : Function to provide the argument metadata
1016 : Function to set the argument metadata to
1021 mirrorFunctionArgs :: (a -> b) -> (a -> c) -> (a -> c)
1026 ## `lib.trivial.mirrorFunctionArgs` usage example
1029 addab = {a, b}: a + b
1030 addab { a = 2; b = 4; }
1032 lib.functionArgs addab
1033 => { a = false; b = false; }
1034 addab1 = attrs: addab attrs + 1
1035 addab1 { a = 2; b = 4; }
1037 lib.functionArgs addab1
1039 addab1' = lib.mirrorFunctionArgs addab addab1
1040 addab1' { a = 2; b = 4; }
1042 lib.functionArgs addab1'
1043 => { a = false; b = false; }
1048 mirrorFunctionArgs =
1051 fArgs = functionArgs f;
1054 setFunctionArgs g fArgs;
1057 Turns any non-callable values into constant functions.
1058 Returns callable values as is.
1070 ## `lib.trivial.toFunction` usage example
1073 nix-repl> lib.toFunction 1 2
1076 nix-repl> lib.toFunction (x: x + 1) 2
1089 Convert a hexadecimal string to it's integer representation.
1094 fromHexString :: String -> [ String ]
1103 fromHexString (builtins.hashString "sha256" "test")
1104 => 9223372036854775807
1107 fromHexString = value:
1109 noPrefix = lib.strings.removePrefix "0x" (lib.strings.toLower value);
1111 parsed = builtins.fromTOML "v=0x${noPrefix}";
1115 Convert the given positive integer to a string of its hexadecimal
1116 representation. For example:
1118 toHexString 0 => "0"
1120 toHexString 16 => "10"
1122 toHexString 250 => "FA"
1136 else hexDigits.${toString d};
1137 in i: lib.concatMapStrings toHexDigit (toBaseDigits 16 i);
1140 `toBaseDigits base i` converts the positive integer i to a list of its
1141 digits in the given base. For example:
1143 toBaseDigits 10 123 => [ 1 2 3 ]
1145 toBaseDigits 2 6 => [ 1 1 0 ]
1147 toBaseDigits 16 250 => [ 15 10 ]
1154 : 1\. Function argument
1158 : 2\. Function argument
1160 toBaseDigits = base: i:
1167 r = i - ((i / base) * base);
1172 assert (isInt base);
1176 lib.reverseList (go i);