Skip to content

Commit

Permalink
Add assertions and warnings to the pre-commit module
Browse files Browse the repository at this point in the history
  • Loading branch information
sandydoo committed Mar 9, 2024
1 parent 8af5964 commit 6b2bed0
Showing 1 changed file with 61 additions and 17 deletions.
78 changes: 61 additions & 17 deletions modules/pre-commit.nix
Original file line number Diff line number Diff line change
Expand Up @@ -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 ]; } ''
Expand Down Expand Up @@ -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 =
Expand Down Expand Up @@ -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 =
Expand Down

0 comments on commit 6b2bed0

Please sign in to comment.