Skip to content

Commit 772f8ff

Browse files
sunshinecogitster
authored andcommitted
githooks: discuss Git operations in foreign repositories
Hook authors are periodically caught off-guard by difficult-to-diagnose errors when their hook invokes Git commands in a repository other than the local one. In particular, Git environment variables, such as GIT_DIR and GIT_WORK_TREE, which reference the local repository cause the Git commands to operate on the local repository rather than on the repository which the author intended. This is true whether the environment variables have been set manually by the user or automatically by Git itself. The same problem crops up when a hook invokes Git commands in a different worktree of the same repository, as well. Recommended best-practice[1,2,3,4,5,6] for avoiding this problem is for the hook to ensure that Git variables are unset before invoking Git commands in foreign repositories or other worktrees: unset $(git rev-parse --local-env-vars) However, this advice is not documented anywhere. Rectify this shortcoming by mentioning it in githooks.txt documentation. [1]: https://lore.kernel.org/git/[email protected]/ [2]: https://lore.kernel.org/git/[email protected]/ [3]: https://lore.kernel.org/git/[email protected]/ [4]: https://lore.kernel.org/git/[email protected]/ [5]: https://lore.kernel.org/git/[email protected]/ [6]: https://lore.kernel.org/git/[email protected]/ Signed-off-by: Eric Sunshine <[email protected]> Acked-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent c48035d commit 772f8ff

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

Documentation/githooks.txt

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,18 @@ repository. An exception are hooks triggered during a push ('pre-receive',
2727
'update', 'post-receive', 'post-update', 'push-to-checkout') which are always
2828
executed in $GIT_DIR.
2929

30+
Environment variables, such as `GIT_DIR`, `GIT_WORK_TREE`, etc., are exported
31+
so that Git commands run by the hook can correctly locate the repository. If
32+
your hook needs to invoke Git commands in a foreign repository or in a
33+
different working tree of the same repository, then it should clear these
34+
environment variables so they do not interfere with Git operations at the
35+
foreign location. For example:
36+
37+
------------
38+
local_desc=$(git describe)
39+
foreign_desc=$(unset $(git rev-parse --local-env-vars); git -C ../foreign-repo describe)
40+
------------
41+
3042
Hooks can get their arguments via the environment, command-line
3143
arguments, and stdin. See the documentation for each hook below for
3244
details.

0 commit comments

Comments
 (0)