2

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

Heather Roberts
  • 1,978
  • 1
  • 24
  • 33
  • 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 – Dmitrii Smirnov Aug 10 '18 at 07:30
  • 2
    Possible duplicate of [Can a Git hook automatically add files to the commit?](https://stackoverflow.com/questions/3284292/can-a-git-hook-automatically-add-files-to-the-commit) – Dmitrii Smirnov Aug 10 '18 at 07: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 '18 at 23:26

1 Answers1

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.

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

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • 2
    Adding files via pre-commit hooks actually works. consider the simplest hook `echo text > test.file && git add test.file` - worked for me. – Dmitrii Smirnov Aug 10 '18 at 07:28
  • 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 '18 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 '18 at 23:31