Skip to content Skip to sidebar Skip to footer

Git Diff Call In Pre-commit Throws "fatal: Unable To Read [sha1]"

I am working in windows and attempting to run a git diff command in the pre-commit script (Python) of a repository. My Python call looks like this: repo_dir = 'D:/git/current_uic/s

Solution 1:

The Problem:

Upon running a hook, Git sets some environment variables that are accessible by the hook script. The problem is that Git itself uses these environment variables, and the normal way in which Git sets/uses them seems to be overridden by the values set when the hook gets fired off. In this particular instance, the environment variable GIT_INDEX_FILE has been set to the path to the index file corresponding to the repository which had called the hook (D:/git/current_uic/src/.git/modules/gtc/index), causing a mismatch between the (incorrect) index and the (correct) change tree.

The Fix:

In the hook script, set the environment variable GIT_INDEX_FILE to the correct value before making any git calls. In this case, you could do the following:

set GIT_INDEX_FILE=D:/git/current_uic/src/.git/modules/gtc/modules/resource/index
git --git-dir=D:/git/current_uic/src/gtc/resource/.git 
    --work-tree=D:/git/current_uic/src/gtc/resource diff --name-only

Additional Info

More information about these Git environment variables and which hooks set them can be found here.

Solution 2:

Got exactly same issue but using gitpython. I solved it like this:

repo = git.Repo()
for submodule in repo.submodules:
    back_index = os.getenv('GIT_INDEX_FILE')
    os.environ['GIT_INDEX_FILE'] = submodule.module().index.path
    commit = submodule.module().head.commit
    print([item.a_path for item in commit.diff(None)])
    os.environ['GIT_INDEX_FILE'] = back_index

Post a Comment for "Git Diff Call In Pre-commit Throws "fatal: Unable To Read [sha1]""