17 ## Simple (higher order) functions
21 For when you need a function that does “nothing”.
41 Ignores the second argument. If called with only one argument,
42 constructs a function that always returns a static value.
63 ## `lib.trivial.const` usage example
66 let f = const 5; in f 10
77 Pipes a value through a list of functions, left to right.
83 : Value to start piping.
87 : List of functions to apply sequentially.
92 pipe :: a -> [<functions>] -> <return type of last function>
97 ## `lib.trivial.pipe` usage example
101 (x: x + 2) # 2 + 2 = 4
102 (x: x * 2) # 4 * 2 = 8
106 # ideal to do text transformations
107 pipe [ "a/b" "a/c" ] [
109 # create the cp command
110 (map (file: ''cp "${src}/${file}" $out\n''))
112 # concatenate all commands into one string
115 # make that string into a nix derivation
116 (pkgs.runCommand "copy-to-out" {})
119 => <drv which copies all files to $out>
121 The output type of each function has to be the input type
122 of the next function, and the last function returns the
128 pipe = builtins.foldl' (x: f: f x);
130 # note please don’t add a function like `compose = flip pipe`.
131 # This would confuse users, because the order of the functions
132 # in the list is not clear. With pipe, it’s obvious that it
133 # goes first-to-last. With `compose`, not so much.
135 ## Named versions corresponding to some builtin operators.
138 Concatenate two lists
145 : 1\. Function argument
149 : 2\. Function argument
154 concat :: [a] -> [a] -> [a]
159 ## `lib.trivial.concat` usage example
162 concat [ 1 2 ] [ 3 4 ]
168 concat = x: y: x ++ y;
178 : 1\. Function argument
182 : 2\. Function argument
194 : 1\. Function argument
198 : 2\. Function argument
203 boolean “exclusive or”
210 : 1\. Function argument
214 : 2\. Function argument
216 # We explicitly invert the arguments purely as a type assertion.
217 # This is invariant under XOR, so it does not affect the result.
218 xor = x: y: (!x) != (!y);
223 bitNot = builtins.sub (-1);
226 Convert a boolean to a string.
228 This function uses the strings "true" and "false" to represent
229 boolean values. Calling `toString` on a bool instead returns "1"
237 : 1\. Function argument
242 boolToString :: bool -> string
245 boolToString = b: if b then "true" else "false";
248 Merge two attribute sets shallowly, right side trumps left
250 mergeAttrs :: attrs -> attrs -> attrs
261 : Right attribute set (higher precedence for equal keys)
266 ## `lib.trivial.mergeAttrs` usage example
269 mergeAttrs { a = 1; b = 2; } { b = 3; c = 4; }
270 => { a = 1; b = 3; c = 4; }
280 Flip the order of the arguments of a binary function.
287 : 1\. Function argument
291 : 2\. Function argument
295 : 3\. Function argument
300 flip :: (a -> b -> c) -> (b -> a -> c)
305 ## `lib.trivial.flip` usage example
314 flip = f: a: b: f b a;
317 Apply function if the supplied argument is non-null.
328 : Argument to check for null before passing it to `f`
333 ## `lib.trivial.mapNullable` usage example
336 mapNullable (x: x+1) null
338 mapNullable (x: x+1) 22
346 a: if a == null then a else f a;
348 # Pull in some builtins not included elsewhere.
350 pathExists readFile isBool
351 isInt isFloat add sub lessThan
352 seq deepSeq genericClosure
355 ## nixpkgs version strings
358 Returns the current full nixpkgs version number.
360 version = release + versionSuffix;
363 Returns the current nixpkgs release number as string.
365 release = lib.strings.fileContents ./.version;
368 The latest release that is supported, at the time of release branch-off,
371 Ideally, out-of-tree modules should be able to evaluate cleanly with all
372 supported Nixpkgs versions (master, release and old release until EOL).
373 So if possible, deprecation warnings should take effect only when all
374 out-of-tree expressions/libs/modules can upgrade to the new way without
375 losing support for supported Nixpkgs versions.
377 This release number allows deprecation warnings to be implemented such that
378 they take effect as soon as the oldest release reaches end of life.
380 oldestSupportedRelease =
381 # Update on master only. Do not backport.
385 Whether a feature is supported in all supported releases (at the time of
386 release branch-off, if applicable). See `oldestSupportedRelease`.
393 : Release number of feature introduction as an integer, e.g. 2111 for 21.11.
394 Set it to the upcoming release, matching the nixpkgs/.version file.
398 release <= lib.trivial.oldestSupportedRelease;
401 Returns the current nixpkgs release code name.
403 On each release the first letter is bumped and a new animal is chosen
404 starting with that new letter.
409 Returns the current nixpkgs version suffix as string.
412 let suffixFile = ../.version-suffix;
413 in if pathExists suffixFile
414 then lib.strings.fileContents suffixFile
418 Attempts to return the the current revision of nixpkgs and
419 returns the supplied default value otherwise.
426 : Default value to return if revision can not be determined
431 revisionWithDefault :: string -> string
434 revisionWithDefault =
437 revisionFile = "${toString ./..}/.git-revision";
438 gitRepo = "${toString ./..}/.git";
439 in if lib.pathIsGitRepo gitRepo
440 then lib.commitIdFromGitRepo gitRepo
441 else if lib.pathExists revisionFile then lib.fileContents revisionFile
444 nixpkgsVersion = warn "lib.nixpkgsVersion is a deprecated alias of lib.version." version;
447 Determine whether the function is being called from inside a Nix
456 inNixShell = builtins.getEnv "IN_NIX_SHELL" != "";
459 Determine whether the function is being called from inside pure-eval mode
460 by seeing whether `builtins` contains `currentSystem`. If not, we must be in
466 inPureEvalMode :: bool
469 inPureEvalMode = ! builtins ? currentSystem;
471 ## Integer operations
474 Return minimum of two numbers.
481 : 1\. Function argument
485 : 2\. Function argument
487 min = x: y: if x < y then x else y;
490 Return maximum of two numbers.
497 : 1\. Function argument
501 : 2\. Function argument
503 max = x: y: if x > y then x else y;
513 : 1\. Function argument
517 : 2\. Function argument
522 ## `lib.trivial.mod` usage example
533 mod = base: int: base - (int * (builtins.div base int));
541 a < b, compare a b => -1
542 a == b, compare a b => 0
543 a > b, compare a b => 1
550 : 1\. Function argument
554 : 2\. Function argument
564 Split type into two subtypes by predicate `p`, take all elements
565 of the first subtype to be less than all the elements of the
566 second subtype, compare elements of a single subtype with `yes`
567 and `no` respectively.
578 : Comparison function if predicate holds for both values
582 : Comparison function if predicate holds for neither value
586 : First value to compare
590 : Second value to compare
595 (a -> bool) -> (a -> a -> int) -> (a -> a -> int) -> (a -> a -> int)
600 ## `lib.trivial.splitByAndCompare` usage example
603 let cmp = splitByAndCompare (hasPrefix "foo") compare compare; in
606 cmp "fooa" "fooz" => -1
611 compare "fooa" "a" => 1
619 then if p b then yes a b else -1
620 else if p b then 1 else no a b;
631 : 1\. Function argument
636 importJSON :: path -> any
640 builtins.fromJSON (builtins.readFile path);
650 : 1\. Function argument
655 importTOML :: path -> any
659 builtins.fromTOML (builtins.readFile path);
663 # See https://github.com/NixOS/nix/issues/749. Eventually we'd like these
664 # to expand to Nix builtins that carry metadata so that Nix can filter out
665 # the INFO messages without parsing the message string.
669 # foo = lib.warn "foo is deprecated" oldFoo;
670 # bar = lib.warnIf (bar == "") "Empty bar is deprecated" bar;
673 # TODO: figure out a clever way to integrate location information from
674 # something like __unsafeGetAttrPos.
677 Print a warning before returning the second argument. This function behaves
678 like `builtins.trace`, but requires a string message and formats it as a
679 warning, including the `warning: ` prefix.
681 To get a call stack trace and abort evaluation, set the environment variable
682 `NIX_ABORT_ON_WARN=true` and set the Nix options `--option pure-eval false --show-trace`
688 : Warning message to print.
692 : Value to return as-is.
701 if lib.elem (builtins.getEnv "NIX_ABORT_ON_WARN") ["1" "true" "yes"]
702 then msg: builtins.trace "
\e[1;31mwarning: ${msg}
\e[0m" (abort "NIX_ABORT_ON_WARN=true; warnings are treated as unrecoverable errors.")
703 else msg: builtins.trace "
\e[1;31mwarning: ${msg}
\e[0m";
706 Like warn, but only warn when the first argument is `true`.
713 : 1\. Function argument
717 : 2\. Function argument
721 : Value to return as-is.
726 bool -> string -> a -> a
729 warnIf = cond: msg: if cond then warn msg else x: x;
732 Like warnIf, but negated (warn if the first argument is `false`).
739 : 1\. Function argument
743 : 2\. Function argument
747 : Value to return as-is.
752 bool -> string -> a -> a
755 warnIfNot = cond: msg: if cond then x: x else warn msg;
758 Like the `assert b; e` expression, but with a custom error message and
759 without the semicolon.
761 If true, return the identity function, `r: r`.
763 If false, throw the error message.
765 Calls can be juxtaposed using function application, as `(r: r) a = a`, so
766 `(r: r) (r: r) a = a`, and so forth.
773 : 1\. Function argument
777 : 2\. Function argument
782 bool -> string -> a -> a
787 ## `lib.trivial.throwIfNot` usage example
790 throwIfNot (lib.isList overlays) "The overlays argument to nixpkgs must be a list."
791 lib.foldr (x: throwIfNot (lib.isFunction x) "All overlays passed to nixpkgs must be functions.") (r: r) overlays
797 throwIfNot = cond: msg: if cond then x: x else throw msg;
800 Like throwIfNot, but negated (throw if the first argument is `true`).
807 : 1\. Function argument
811 : 2\. Function argument
816 bool -> string -> a -> a
819 throwIf = cond: msg: if cond then throw msg else x: x;
822 Check if the elements in a list are valid values from a enum, returning the identity function, or throwing an error message otherwise.
829 : 1\. Function argument
833 : 2\. Function argument
837 : 3\. Function argument
842 String -> List ComparableVal -> List ComparableVal -> a -> a
847 ## `lib.trivial.checkListOfEnum` usage example
850 let colorVariants = ["bright" "dark" "black"]
851 in checkListOfEnum "color variants" [ "standard" "light" "dark" ] colorVariants;
853 error: color variants: bright, black unexpected; valid ones: standard, light, dark
858 checkListOfEnum = msg: valid: given:
860 unexpected = lib.subtractLists valid given;
862 lib.throwIfNot (unexpected == [])
863 "${msg}: ${builtins.concatStringsSep ", " (builtins.map builtins.toString unexpected)} unexpected; valid ones: ${builtins.concatStringsSep ", " (builtins.map builtins.toString valid)}";
865 info = msg: builtins.trace "INFO: ${msg}";
867 showWarnings = warnings: res: lib.foldr (w: x: warn w x) res warnings;
869 ## Function annotations
872 Add metadata about expected function arguments to a function.
873 The metadata should match the format given by
874 builtins.functionArgs, i.e. a set from expected argument to a bool
875 representing whether that argument has a default or not.
876 setFunctionArgs : (a → b) → Map String Bool → (a → b)
878 This function is necessary because you can't dynamically create a
879 function of the { a, b ? foo, ... }: format, but some facilities
880 like callPackage expect to be able to query expected arguments.
887 : 1\. Function argument
891 : 2\. Function argument
893 setFunctionArgs = f: args:
894 { # TODO: Should we add call-time "type" checking like built in?
896 __functionArgs = args;
900 Extract the expected function arguments from a function.
901 This works both with nix-native { a, b ? foo, ... }: style
902 functions and functions with args set with 'setFunctionArgs'. It
903 has the same return type and semantics as builtins.functionArgs.
904 setFunctionArgs : (a → b) → Map String Bool.
911 : 1\. Function argument
915 then f.__functionArgs or (functionArgs (f.__functor f))
916 else builtins.functionArgs f;
919 Check whether something is a function or something
920 annotated with function args.
927 : 1\. Function argument
929 isFunction = f: builtins.isFunction f ||
930 (f ? __functor && isFunction (f.__functor f));
933 `mirrorFunctionArgs f g` creates a new function `g'` with the same behavior as `g` (`g' x == g x`)
934 but its function arguments mirroring `f` (`lib.functionArgs g' == lib.functionArgs f`).
941 : Function to provide the argument metadata
945 : Function to set the argument metadata to
950 mirrorFunctionArgs :: (a -> b) -> (a -> c) -> (a -> c)
955 ## `lib.trivial.mirrorFunctionArgs` usage example
958 addab = {a, b}: a + b
959 addab { a = 2; b = 4; }
961 lib.functionArgs addab
962 => { a = false; b = false; }
963 addab1 = attrs: addab attrs + 1
964 addab1 { a = 2; b = 4; }
966 lib.functionArgs addab1
968 addab1' = lib.mirrorFunctionArgs addab addab1
969 addab1' { a = 2; b = 4; }
971 lib.functionArgs addab1'
972 => { a = false; b = false; }
980 fArgs = functionArgs f;
983 setFunctionArgs g fArgs;
986 Turns any non-callable values into constant functions.
987 Returns callable values as is.
999 ## `lib.trivial.toFunction` usage example
1002 nix-repl> lib.toFunction 1 2
1005 nix-repl> lib.toFunction (x: x + 1) 2
1018 Convert the given positive integer to a string of its hexadecimal
1019 representation. For example:
1021 toHexString 0 => "0"
1023 toHexString 16 => "10"
1025 toHexString 250 => "FA"
1039 else hexDigits.${toString d};
1040 in i: lib.concatMapStrings toHexDigit (toBaseDigits 16 i);
1043 `toBaseDigits base i` converts the positive integer i to a list of its
1044 digits in the given base. For example:
1046 toBaseDigits 10 123 => [ 1 2 3 ]
1048 toBaseDigits 2 6 => [ 1 1 0 ]
1050 toBaseDigits 16 250 => [ 15 10 ]
1057 : 1\. Function argument
1061 : 2\. Function argument
1063 toBaseDigits = base: i:
1070 r = i - ((i / base) * base);
1075 assert (isInt base);
1079 lib.reverseList (go i);