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

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



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


shelljs



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


.git/hooks/pre-commit


git add dist





Is the hook actually executed? It needs the executable bit set, and might be ignored if it is not there. Also check without the shelljs, calling git add dist directly
– Dmitriy Smirnov
Aug 10 at 7:30


git add dist





Possible duplicate of Can a Git hook automatically add files to the commit?
– Dmitriy Smirnov
Aug 10 at 7:32





The hook is definitely executed yeah, and I did try just running git add dist but it still didn't work
– Heather Roberts
Aug 12 at 23:26


git add dist




1 Answer
1



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.


git add



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





Adding files via pre-commit hooks actually works. consider the simplest hook echo text > test.file && git add test.file - worked for me.
– Dmitriy Smirnov
Aug 10 at 7:28


echo text > test.file && git add test.file





@DmitriySmirnov OK, still seems "wrong" to me ;)
– VonC
Aug 10 at 7:30





What about pre-push? You can commit always, but when trying to push, you can actually generate other files, add them, commit them programmatically, and issue a exit(0) so the push will happen. But yes, "seems wrong" as @VonC said.
– Lovato
Aug 10 at 13:20






Thanks @VonC using that other question's solution did help me, but I would have liked to be able to add an extra file in the pre-commit hook...
– Heather Roberts
Aug 12 at 23:31






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS