diff --git a/lib/default.nix b/lib/default.nix index 599f74de..ea2c143d 100644 --- a/lib/default.nix +++ b/lib/default.nix @@ -82,6 +82,7 @@ lib.makeExtensible ( ifNonNull' listToUnkeyedAttrs literalLua + mkAssertions mkIfNonNull mkIfNonNull' mkRaw diff --git a/lib/utils.nix b/lib/utils.nix index d2e240c5..7bbcd696 100644 --- a/lib/utils.nix +++ b/lib/utils.nix @@ -173,6 +173,37 @@ rec { in lib.literalExpression exp; + __messagePrefix = scope: "Nixvim (${scope}):"; + /** + Process one or several assertions by prepending the common 'Nixvim (): ' prefix to messages. + The second argument can either be a list of assertions or a single one. + + # Example + + ```nix + warnings = mkAssertions "plugins.foo" { + assertion = plugins.foo.settings.barIntegration && (!plugins.bar.enable); + message = "`barIntegration` is enabled but the `bar` plugin is not." + } + ``` + + # Type + + ``` + mkAssertions :: String -> List -> List + ``` + */ + mkAssertions = + scope: assertions: + let + prefix = __messagePrefix scope; + processAssertion = a: { + inherit (a) assertion; + message = "${prefix} ${lib.trim a.message}"; + }; + in + builtins.map processAssertion (lib.toList assertions); + /** Convert one or several conditional warnings to a final warning list. The second argument can either be a list of _conditional warnings_ or a single one. @@ -195,9 +226,9 @@ rec { mkWarnings = scope: warnings: let + prefix = __messagePrefix scope; processWarning = - warning: - lib.optional (warning.when or true) "Nixvim (${scope}): ${lib.trim (warning.message or warning)}"; + warning: lib.optional (warning.when or true) "${prefix} ${lib.trim (warning.message or warning)}"; in builtins.concatMap processWarning (lib.toList warnings); diff --git a/tests/lib-tests.nix b/tests/lib-tests.nix index c3c61458..694e2f5a 100644 --- a/tests/lib-tests.nix +++ b/tests/lib-tests.nix @@ -491,6 +491,38 @@ let }; }; + testMkAssertions = { + expr = + (lib.nixvim.mkAssertions "foo-bar" [ + { + assertion = true; + message = "This is the message"; + } + { + assertion = false; + message = "Another assertion"; + } + ]) + ++ (lib.nixvim.mkAssertions "single-element") { + assertion = true; + message = " Trailing whitespaces "; + }; + expected = [ + { + assertion = true; + message = "Nixvim (foo-bar): This is the message"; + } + { + assertion = false; + message = "Nixvim (foo-bar): Another assertion"; + } + { + assertion = true; + message = "Nixvim (single-element): Trailing whitespaces"; + } + ]; + }; + testMkWarnings = { expr = (lib.nixvim.mkWarnings "foo-bar" [ @@ -506,12 +538,12 @@ let ]) ++ (lib.nixvim.mkWarnings "single-element") { when = true; - message = "Hello"; + message = " Trailing whitespaces "; }; expected = [ "Nixvim (foo-bar): This is the message" "Nixvim (foo-bar): This is an unconditional warning" - "Nixvim (single-element): Hello" + "Nixvim (single-element): Trailing whitespaces" ]; }; };