lib.trivial.warnIf: init

It's a common pattern in Nixpkgs to want to emit a warning in certain
cases, but not actually change behaviours.

This is often expressed as either
	if cond then lib.warn "Don't do that thing" x else x
Or
	(if cond then lib.warn "Don't do that thing" else lib.id) x

Neither of which really expresses the intent here, because it looks
like 'x' is being chosen conditionally.

To make this clearer, I introduce a "warnIf" function, which makes it
clear that the only thing being affected by the condition is whether
the warning is generated, not the value being returned.
master
Alyssa Ross 2021-04-27 10:56:51 +00:00
parent e57815f095
commit 81e1e68eaf
2 changed files with 6 additions and 2 deletions

View File

@ -66,8 +66,9 @@ let
stringLength sub substring tail trace; stringLength sub substring tail trace;
inherit (self.trivial) id const pipe concat or and bitAnd bitOr bitXor inherit (self.trivial) id const pipe concat or and bitAnd bitOr bitXor
bitNot boolToString mergeAttrs flip mapNullable inNixShell isFloat min max bitNot boolToString mergeAttrs flip mapNullable inNixShell isFloat min max
importJSON importTOML warn info showWarnings nixpkgsVersion version mod compare importJSON importTOML warn warnIf info showWarnings nixpkgsVersion version
splitByAndCompare functionArgs setFunctionArgs isFunction toHexString toBaseDigits; mod compare splitByAndCompare functionArgs setFunctionArgs isFunction
toHexString toBaseDigits;
inherit (self.fixedPoints) fix fix' converge extends composeExtensions inherit (self.fixedPoints) fix fix' converge extends composeExtensions
composeManyExtensions makeExtensible makeExtensibleWithCustomName; composeManyExtensions makeExtensible makeExtensibleWithCustomName;
inherit (self.attrsets) attrByPath hasAttrByPath setAttrByPath inherit (self.attrsets) attrByPath hasAttrByPath setAttrByPath

View File

@ -297,12 +297,15 @@ rec {
# Usage: # Usage:
# { # {
# foo = lib.warn "foo is deprecated" oldFoo; # foo = lib.warn "foo is deprecated" oldFoo;
# bar = lib.warnIf (bar == "") "Empty bar is deprecated" bar;
# } # }
# #
# TODO: figure out a clever way to integrate location information from # TODO: figure out a clever way to integrate location information from
# something like __unsafeGetAttrPos. # something like __unsafeGetAttrPos.
warn = msg: builtins.trace "warning: ${msg}"; warn = msg: builtins.trace "warning: ${msg}";
warnIf = cond: msg: if cond then warn msg else id;
info = msg: builtins.trace "INFO: ${msg}"; info = msg: builtins.trace "INFO: ${msg}";
showWarnings = warnings: res: lib.fold (w: x: warn w x) res warnings; showWarnings = warnings: res: lib.fold (w: x: warn w x) res warnings;