Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 542
Heather Roberts Avatar asked Aug 12 '26 20:08

Heather Roberts


1 Answers

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.

like image 90
VonC Avatar answered Aug 14 '26 15:08

VonC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!