Search code examples
githookrepo

Make git hooks run from current directory


Let's say I have a GIT repo "MyRepo" with a subfolder "Code", like:

MyRepo
  |-- .git
        |-- hooks
              |-- pre-commit
        |-- <other stuff>
  |-- Code
        |-- code.java
        |-- <other files>

I do cd MyRepo/Code, then make some changes, do a git commit -m "yada yada", and then the pre-commit hook runs. Only problem is that it runs in MyRepo. I want the pre-commit hook to run in the directory I'm currently in, in this case, Code. How can I achieve that?

And as an extension to this question, is there a way to make all of my git hooks behave this way?


Solution

  • Hooks and aliases are run with your current path inside the work tree passed in as the GIT_PREFIX variable, so your hook can either cd $GIT_PREFIX or append it as desired.

    . . . I see this is not documented except in some release notes from long ago, I found it by reasoning something like it had to be there and putting a declare -p ${!GIT_*} in a hook, running it from a subdir, then checking the Git history for the GIT_ var that had that.