From ae057f480f67a856eec6e0b25002946d68099f8d Mon Sep 17 00:00:00 2001 From: Tom Hubrecht Date: Sat, 7 Dec 2024 13:12:16 +0100 Subject: [PATCH] feat(lib): Add warn --- lib/nix-lib/nixpkgs.nix | 46 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/lib/nix-lib/nixpkgs.nix b/lib/nix-lib/nixpkgs.nix index 302a1b9..ff04b2e 100644 --- a/lib/nix-lib/nixpkgs.nix +++ b/lib/nix-lib/nixpkgs.nix @@ -413,4 +413,50 @@ rec { flip = f: a: b: f b a; + + /** + `warn` *`message`* *`value`* + + Print a warning before returning the second argument. + + See [`builtins.warn`](https://nix.dev/manual/nix/latest/language/builtins.html#builtins-warn) (Nix >= 2.23). + 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. + + # Inputs + + *`message`* (String) + + : Warning message to print before evaluating *`value`*. + + *`value`* (any value) + + : Value to return as-is. + + # Type + + ``` + String -> a -> a + ``` + */ + warn = + # Since Nix 2.23, https://github.com/NixOS/nix/pull/10592 + builtins.warn or ( + let + mustAbort = builtins.elem (builtins.getEnv "NIX_ABORT_ON_WARN") [ + "1" + "true" + "yes" + ]; + in + # Do not eta reduce v, so that we have the same strictness as `builtins.warn`. + msg: v: + # `builtins.warn` requires a string message, so we enforce that in our implementation, so that callers aren't accidentally incompatible with newer Nix versions. + assert builtins.isString msg; + if mustAbort then + builtins.trace "␛[1;31mevaluation warning:␛[0m ${msg}" ( + abort "NIX_ABORT_ON_WARN=true; warnings are treated as unrecoverable errors." + ) + else + builtins.trace "␛[1;35mevaluation warning:␛[0m ${msg}" v + ); }