Skip to content

[Feature] Allow injecting custom environ variables in the pre-commit flake check #698

Description

@sunziping2016

Background

I'm using the flakeModule in my own homelab repo. I turned on pre-commit.check.enable.

https://github.com/tillycode/homelab-v2/blob/5562ca44dbb97e295d361728b93f7c709608ea9b/flake/pre-commit.nix#L46-L59

In the example above, I wrote a custom commit hook flat-flake in Python. Its source code is placed within the repo. To prevent devshell from rebuilding whenever there's a change in the source code, I use editable mode, which relies on an environment variable pointing to the root of the source code. You can see I use PRJ_ROOT, which follows the convention of numtide/devshell.

However, when running nix flake check, the PRJ_ROOT environment variable is unset, causing error. I set the environment in the pre-commit.settings.package to circumvent the issue, which is quite ugly.

Feature Request

I hope there is an option, such as pre-commit.check.preRunScript, for me to prepare some environment variables in the buildPhase of run derivation

run =
mkDerivation {
name = "pre-commit-run";
src = cfg.rootSrc;
buildInputs = [ cfg.gitPackage cfg.package ];
nativeBuildInputs = enabledExtraPackages
++ lib.optional (config.settings.rust.check.cargoDeps != null) cargoSetupHook;
cargoDeps = config.settings.rust.check.cargoDeps;
buildPhase = ''
set +e
# Set HOME to a temporary directory for pre-commit to create its cache files in.
HOME=$(mktemp -d)
ln -fs ${cfg.configFile} ${cfg.configPath}
git init -q
git add .
git config --global user.email "you@example.com"
git config --global user.name "Your Name"
git commit -m "init" -q
if [[ ${toString (compare cfg.installStages [ "manual" ])} -eq 0 ]]
then
echo "Running: $ pre-commit run --hook-stage manual --all-files"
${lib.getExe cfg.package} run -c ${cfg.configPath} --hook-stage manual --all-files
else
echo "Running: $ pre-commit run --all-files"
${lib.getExe cfg.package} run -c ${cfg.configPath} --all-files
fi
exitcode=$?
git --no-pager diff --color
# Derivations must produce an output
mkdir $out
[ $? -eq 0 ] && exit $exitcode
'';
};

If it is available, I can just set

{
  pre-commit.check.preRunScript = ''
    export PRJ_ROOT="$PWD"
  '';
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions