Home > Blockchain >  Fail to run git command in specific directory in global post-commit hook
Fail to run git command in specific directory in global post-commit hook

Time:10-31

I am trying to use a submodule with a global post-commit hook but find an issue.

Description

Consider we have two git directories A and B. A is the super-project of B.

Here's my script in the global post-commit hook.

#!/bin/sh 
git -C path/to/A remote show origin 

Expected behavior

It supposes to show the remote information about A after committing in B.

Actual behavior

It shows remote information about B after I committed in B.

Questions

  • Did I do anything wrong to cause the unexpected result?
  • If not, Why did this happen? (maybe caused by the limitation of post-commit hooks? doc)
  • How do I get the expected behavior?

CodePudding user response:

Git hooks run because of some Git command, and like any internal Git command, they're run with an environment setup that specifies which particular repository is to be used. This means that in general you're not supposed to do operations on some other repository.

If you know precisely what you're doing, though, you can unset the various Git environment variables that control the specific repository, index, working tree, and/or other Git settings that Git is using. Note that you may need to do this for potentially many (and ever-more in the future) Git variables, so it's not wise to do this without a really good reason.

The one variable in particular that you must always unset here is GIT_DIR. That is:

git -C <path> ...

doesn't work because GIT_DIR is set, but:

unset GIT_DIR
git -C <path> ...

will remove the GIT_DIR setting and the subsequent git -C operation will work. Note that by unsetting GIT_DIR here, you make it difficult to operate on the post-commit's repository, so you might in some cases want to do this in a sub-shell.

  • Related