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.
401 release <= lib.trivial.oldestSupportedRelease;
404 Returns the current nixpkgs release code name.
406 On each release the first letter is bumped and a new animal is chosen
407 starting with that new letter.
412 Returns the current nixpkgs version suffix as string.
415 let suffixFile = ../.version-suffix;
416 in if pathExists suffixFile
417 then lib.strings.fileContents suffixFile
421 Attempts to return the the current revision of nixpkgs and
422 returns the supplied default value otherwise.
429 : Default value to return if revision can not be determined
434 revisionWithDefault :: string -> string
437 revisionWithDefault =
440 revisionFile = "${toString ./..}/.git-revision";
441 gitRepo = "${toString ./..}/.git";
442 in if lib.pathIsGitRepo gitRepo
443 then lib.commitIdFromGitRepo gitRepo
444 else if lib.pathExists revisionFile then lib.fileContents revisionFile
447 nixpkgsVersion = warn "lib.nixpkgsVersion is a deprecated alias of lib.version." version;
450 Determine whether the function is being called from inside a Nix
459 inNixShell = builtins.getEnv "IN_NIX_SHELL" != "";
462 Determine whether the function is being called from inside pure-eval mode
463 by seeing whether `builtins` contains `currentSystem`. If not, we must be in
469 inPureEvalMode :: bool
472 inPureEvalMode = ! builtins ? currentSystem;
474 ## Integer operations
477 Return minimum of two numbers.
484 : 1\. Function argument
488 : 2\. Function argument
490 min = x: y: if x < y then x else y;
493 Return maximum of two numbers.
500 : 1\. Function argument
504 : 2\. Function argument
506 max = x: y: if x > y then x else y;
516 : 1\. Function argument
520 : 2\. Function argument
525 ## `lib.trivial.mod` usage example
536 mod = base: int: base - (int * (builtins.div base int));
544 a < b, compare a b => -1
545 a == b, compare a b => 0
546 a > b, compare a b => 1
553 : 1\. Function argument
557 : 2\. Function argument
567 Split type into two subtypes by predicate `p`, take all elements
568 of the first subtype to be less than all the elements of the
569 second subtype, compare elements of a single subtype with `yes`
570 and `no` respectively.
581 : Comparison function if predicate holds for both values
585 : Comparison function if predicate holds for neither value
589 : First value to compare
593 : Second value to compare
598 (a -> bool) -> (a -> a -> int) -> (a -> a -> int) -> (a -> a -> int)
603 ## `lib.trivial.splitByAndCompare` usage example
606 let cmp = splitByAndCompare (hasPrefix "foo") compare compare; in
609 cmp "fooa" "fooz" => -1
614 compare "fooa" "a" => 1
622 then if p b then yes a b else -1
623 else if p b then 1 else no a b;
631 ## `lib.trivial.importJSON` usage example
636 "title": "Example JSON",
647 importJSON ./example.json
649 title = "Example JSON";
665 : 1\. Function argument
670 importJSON :: path -> any
674 builtins.fromJSON (builtins.readFile path);
681 ## `lib.trivial.importTOML` usage example
685 title = "TOML Example"
695 importTOML ./example.toml
697 title = "TOML Example";
713 : 1\. Function argument
718 importTOML :: path -> any
722 builtins.fromTOML (builtins.readFile path);
726 `warn` *`message`* *`value`*
728 Print a warning before returning the second argument.
730 See [`builtins.warn`](https://nix.dev/manual/nix/latest/language/builtins.html#builtins-warn) (Nix >= 2.23).
731 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.
737 : Warning message to print before evaluating *`value`*.
739 *`value`* (any value)
741 : Value to return as-is.
750 # Since Nix 2.23, https://github.com/NixOS/nix/pull/10592
752 let mustAbort = lib.elem (builtins.getEnv "NIX_ABORT_ON_WARN") ["1" "true" "yes"];
754 # Do not eta reduce v, so that we have the same strictness as `builtins.warn`.
756 # `builtins.warn` requires a string message, so we enforce that in our implementation, so that callers aren't accidentally incompatible with newer Nix versions.
759 then builtins.trace "
\e[1;31mevaluation warning:
\e[0m ${msg}" (abort "NIX_ABORT_ON_WARN=true; warnings are treated as unrecoverable errors.")
760 else builtins.trace "
\e[1;35mevaluation warning:
\e[0m ${msg}" v
765 `warnIf` *`condition`* *`message`* *`value`*
767 Like `warn`, but only warn when the first argument is `true`.
771 *`condition`* (Boolean)
773 : `true` to trigger the warning before continuing with *`value`*.
777 : Warning message to print before evaluating
779 *`value`* (any value)
781 : Value to return as-is.
786 Bool -> String -> a -> a
789 warnIf = cond: msg: if cond then warn msg else x: x;
793 `warnIfNot` *`condition`* *`message`* *`value`*
795 Like `warnIf`, but negated: warn if the first argument is `false`.
801 : `false` to trigger the warning before continuing with `val`.
805 : Warning message to print before evaluating *`value`*.
809 : Value to return as-is.
814 Boolean -> String -> a -> a
817 warnIfNot = cond: msg: if cond then x: x else warn msg;
820 Like the `assert b; e` expression, but with a custom error message and
821 without the semicolon.
823 If true, return the identity function, `r: r`.
825 If false, throw the error message.
827 Calls can be juxtaposed using function application, as `(r: r) a = a`, so
828 `(r: r) (r: r) a = a`, and so forth.
835 : 1\. Function argument
839 : 2\. Function argument
844 bool -> string -> a -> a
849 ## `lib.trivial.throwIfNot` usage example
852 throwIfNot (lib.isList overlays) "The overlays argument to nixpkgs must be a list."
853 lib.foldr (x: throwIfNot (lib.isFunction x) "All overlays passed to nixpkgs must be functions.") (r: r) overlays
859 throwIfNot = cond: msg: if cond then x: x else throw msg;
862 Like throwIfNot, but negated (throw if the first argument is `true`).
869 : 1\. Function argument
873 : 2\. Function argument
878 bool -> string -> a -> a
881 throwIf = cond: msg: if cond then throw msg else x: x;
884 Check if the elements in a list are valid values from a enum, returning the identity function, or throwing an error message otherwise.
891 : 1\. Function argument
895 : 2\. Function argument
899 : 3\. Function argument
904 String -> List ComparableVal -> List ComparableVal -> a -> a
909 ## `lib.trivial.checkListOfEnum` usage example
912 let colorVariants = ["bright" "dark" "black"]
913 in checkListOfEnum "color variants" [ "standard" "light" "dark" ] colorVariants;
915 error: color variants: bright, black unexpected; valid ones: standard, light, dark
920 checkListOfEnum = msg: valid: given:
922 unexpected = lib.subtractLists valid given;
924 lib.throwIfNot (unexpected == [])
925 "${msg}: ${builtins.concatStringsSep ", " (builtins.map builtins.toString unexpected)} unexpected; valid ones: ${builtins.concatStringsSep ", " (builtins.map builtins.toString valid)}";
927 info = msg: builtins.trace "INFO: ${msg}";
929 showWarnings = warnings: res: lib.foldr (w: x: warn w x) res warnings;
931 ## Function annotations
934 Add metadata about expected function arguments to a function.
935 The metadata should match the format given by
936 builtins.functionArgs, i.e. a set from expected argument to a bool
937 representing whether that argument has a default or not.
938 setFunctionArgs : (a → b) → Map String Bool → (a → b)
940 This function is necessary because you can't dynamically create a
941 function of the { a, b ? foo, ... }: format, but some facilities
942 like callPackage expect to be able to query expected arguments.
949 : 1\. Function argument
953 : 2\. Function argument
955 setFunctionArgs = f: args:
956 { # TODO: Should we add call-time "type" checking like built in?
958 __functionArgs = args;
962 Extract the expected function arguments from a function.
963 This works both with nix-native { a, b ? foo, ... }: style
964 functions and functions with args set with 'setFunctionArgs'. It
965 has the same return type and semantics as builtins.functionArgs.
966 setFunctionArgs : (a → b) → Map String Bool.
973 : 1\. Function argument
977 then f.__functionArgs or (functionArgs (f.__functor f))
978 else builtins.functionArgs f;
981 Check whether something is a function or something
982 annotated with function args.
989 : 1\. Function argument
991 isFunction = f: builtins.isFunction f ||
992 (f ? __functor && isFunction (f.__functor f));
995 `mirrorFunctionArgs f g` creates a new function `g'` with the same behavior as `g` (`g' x == g x`)
996 but its function arguments mirroring `f` (`lib.functionArgs g' == lib.functionArgs f`).
1003 : Function to provide the argument metadata
1007 : Function to set the argument metadata to
1012 mirrorFunctionArgs :: (a -> b) -> (a -> c) -> (a -> c)
1017 ## `lib.trivial.mirrorFunctionArgs` usage example
1020 addab = {a, b}: a + b
1021 addab { a = 2; b = 4; }
1023 lib.functionArgs addab
1024 => { a = false; b = false; }
1025 addab1 = attrs: addab attrs + 1
1026 addab1 { a = 2; b = 4; }
1028 lib.functionArgs addab1
1030 addab1' = lib.mirrorFunctionArgs addab addab1
1031 addab1' { a = 2; b = 4; }
1033 lib.functionArgs addab1'
1034 => { a = false; b = false; }
1039 mirrorFunctionArgs =
1042 fArgs = functionArgs f;
1045 setFunctionArgs g fArgs;
1048 Turns any non-callable values into constant functions.
1049 Returns callable values as is.
1061 ## `lib.trivial.toFunction` usage example
1064 nix-repl> lib.toFunction 1 2
1067 nix-repl> lib.toFunction (x: x + 1) 2
1080 Convert a hexadecimal string to it's integer representation.
1085 fromHexString :: String -> [ String ]
1094 fromHexString (builtins.hashString "sha256" "test")
1095 => 9223372036854775807
1098 fromHexString = value:
1100 noPrefix = lib.strings.removePrefix "0x" (lib.strings.toLower value);
1102 parsed = builtins.fromTOML "v=0x${noPrefix}";
1106 Convert the given positive integer to a string of its hexadecimal
1107 representation. For example:
1109 toHexString 0 => "0"
1111 toHexString 16 => "10"
1113 toHexString 250 => "FA"
1127 else hexDigits.${toString d};
1128 in i: lib.concatMapStrings toHexDigit (toBaseDigits 16 i);
1131 `toBaseDigits base i` converts the positive integer i to a list of its
1132 digits in the given base. For example:
1134 toBaseDigits 10 123 => [ 1 2 3 ]
1136 toBaseDigits 2 6 => [ 1 1 0 ]
1138 toBaseDigits 16 250 => [ 15 10 ]
1145 : 1\. Function argument
1149 : 2\. Function argument
1151 toBaseDigits = base: i:
1158 r = i - ((i / base) * base);
1163 assert (isInt base);
1167 lib.reverseList (go i);