Heather Roberts
Heather Roberts

Reputation: 2148

Git add in pre-commit hook not staging file for commit

I have written a pre-commit hook that compiles my project and adds the generated file to the commit.

This is a JavaScript project and I am using husky, but I have experimented with editing the .git/hooks/pre-commit as well and the file is not getting added to the commit. If I cancel the commit, I can see the file has been added, but for some reason this is not applying to the current commit.

My pre-commit hook looks something like:

const shell = require('shelljs');

shell.exec('yarn bundle');
shell.exec('git add dist');
shell.exit(0);

shelljs is just a library to execute cross-OS unix commands in node

I edited the .git/hooks/pre-commit to run git add dist and the file is still not added to the commit

Upvotes: 5

Views: 7988

Answers (1)

VonC
VonC

Reputation: 1324148

I don't think a git add can work in a pre-commit hook, made to inspect what is about to be committed, not to modify it.

You can follow an approach similar to "Can a Git hook automatically add files to the commit?" instead, which creates a separate additional commit.

Upvotes: 2

Related Questions