From 6b2bed05a2dd0844b3cc12a2d0adf41abf40633e Mon Sep 17 00:00:00 2001 From: Sander Date: Sat, 9 Mar 2024 23:43:20 +0000 Subject: [PATCH] Add assertions and warnings to the pre-commit module --- modules/pre-commit.nix | 78 +++++++++++++++++++++++++++++++++--------- 1 file changed, 61 insertions(+), 17 deletions(-) diff --git a/modules/pre-commit.nix b/modules/pre-commit.nix index ab65bb3f..1c58447f 100644 --- a/modules/pre-commit.nix +++ b/modules/pre-commit.nix @@ -33,23 +33,25 @@ let mapAttrsToList (id: value: value.raw // { inherit id; }) enabledHooks; configFile = - runCommand "pre-commit-config.json" - { - buildInputs = [ - pkgs.jq - # needs to be an input so we regenerate the config and reinstall the hooks - # when the package changes - cfg.package - ]; - passAsFile = [ "rawJSON" ]; - rawJSON = builtins.toJSON cfg.rawConfig; - } '' - { - echo '# DO NOT MODIFY'; - echo '# This file was generated by pre-commit-hooks.nix'; - jq . <"$rawJSONPath" - } >$out - ''; + performAssertions ( + runCommand "pre-commit-config.json" + { + buildInputs = [ + pkgs.jq + # needs to be an input so we regenerate the config and reinstall the hooks + # when the package changes + cfg.package + ]; + passAsFile = [ "rawJSON" ]; + rawJSON = builtins.toJSON cfg.rawConfig; + } '' + { + echo '# DO NOT MODIFY'; + echo '# This file was generated by pre-commit-hooks.nix'; + jq . <"$rawJSONPath" + } >$out + '' + ); run = runCommand "pre-commit-run" { buildInputs = [ git ]; } '' @@ -80,6 +82,24 @@ let touch $out [ $? -eq 0 ] && exit $exitcode ''; + + failedAssertions = builtins.map (x: x.message) (builtins.filter (x: !x.assertion) config.assertions); + + performAssertions = + let + formatAssertionMessage = message: + let + lines = lib.splitString "\n" message; + in + "- ${lib.concatStringsSep "\n " lines}"; + in + if failedAssertions != [ ] + then + throw '' + Failed assertions: + ${lib.concatStringsSep "\n" (builtins.map formatAssertionMessage failedAssertions)} + '' + else lib.trivial.showWarnings config.warnings; in { options = @@ -243,6 +263,30 @@ in ''; internal = true; }; + + assertions = lib.mkOption { + type = types.listOf types.unspecified; + internal = true; + default = [ ]; + example = [{ assertion = false; message = "you can't enable this for that reason"; }]; + description = '' + This option allows modules to express conditions that must + hold for the evaluation of the configuration to succeed, + along with associated error messages for the user. + ''; + }; + + warnings = lib.mkOption { + type = types.listOf types.str; + internal = true; + default = [ ]; + example = [ "you should fix this or that" ]; + description = '' + This option allows modules to express warnings about the + configuration. For example, `lib.mkRenamedOptionModule` uses this to + display a warning message when a renamed option is used. + ''; + }; }; config =