husky: Fatal when trying to call git from hook

I am getting fatal: Not a git repository: '.git' when trying to call git from hook: "precommit": "git status". I think the reason is that my package.json isn’t located in root folder and hook is run from there.

The only way I found is to prepend each git call with cd ../../../.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 2
  • Comments: 27 (1 by maintainers)

Commits related to this issue

Most upvoted comments

For me, an upgrade of git to version 2.23.0 (from 2.17.1) solved this wrong GIT_DIR problem - did not tried versions between. The issue seems to be really a problem in older git versions as @testerez suggested.

Adding unset GIT_DIR at the top of my hook scripts did the trick for me. I’d be interested at understanding the reasoning behind this GIT_DIR though…

GIT_DIR did not work for me. It seems to want to leverage the .git within the same folder…getting this: "precommit": "yarn docs && cross-env GIT_DIR=../../.git git add README.md"

fatal: Unable to create 'subdirectory/stuff/.git/index.lock': No such file or directory

This did:

"precommit": "yarn docs && cd ../../ && git add subdirectory/stuff/README.md"

I used "postcommit": "cross-env GIT_DIR=../.git git update-index --again",

Remember that any NPM script is just a command line that gets executed. There is nothing that says it has to be JavaScript. For instance, it is quite common to invoke make, rm and other standard Unix tools on the path. There is nothing preventing you from having an NPM script called prepush that simply is python ../../my-hooks/lint-python-stuff.

Looks like the issue(?) is in git itself. Pretty easy to reproduce:

mkdir test-precommit
cd test-precommit
git init
mkdir dir
echo "echo GIT_DIR=\$GIT_DIR" >> .git/hooks/pre-commit
echo "cd dir" >> .git/hooks/pre-commit
echo "git status" >> .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit
git commit -m test

Output:

GIT_DIR=.git
fatal: not a git repository: '.git'

Just for documentation purposes, I want to share my experience of this same issue while building a docker image for my project.

Here’s the setup of my directory

Root Dir/

  • .git/
  • server/
  • client/

with server/ and client/ with their own package.json. I have husky installed in server and client folder respectively and got the fatal error while I was building the image.

I took inspiration from @egucciar and changed my precommit script to do cd ../ before my designated precommit command and it seemed to work.

This is how my precommit command looks: "pre-commit": "cd ../ && pretty-quick --staged"

I am running into this issue as well. This happens because the node app is a child directory of the git repository. My guess is that it is caused by lint-staged, so I created an issue there https://github.com/okonet/lint-staged/issues/170