在 git 钩子中,当前的工作目录是否保证在 git 存储库中?

从实验上看,git 钩子似乎是在将工作目录设置为存储库的根的情况下运行的。但是,我在 git 文档中看不到任何关于这一点的保证。我应该依靠当前的工作目录来定位 git 存储库,还是有更好的方法来找到与钩子相关的 git 存储库?

31573 次浏览

You can use the environment variable $GIT_DIR. $GIT_DIR points at the .git directory.

It is based on the value set for environment variable GIT_DIR. It is set to the root of the repository when the hook starts running. Many hooks, especially those doing a pull from another repo, unset ( and reset) this environment variable as needed.

The current answers appear to be outdated. As of 2.9.0, the docs state the following:

Before Git invokes a hook, it changes its working directory to either the root of the working tree in a non-bare repository, or to the $GIT_DIR in a bare repository.

https://git-scm.com/docs/githooks/2.9.0