Ogen Ogen -4 years ago 127
Git Question

What are the git commands to iterate through files being pushed?

I am trying to implement a

pre-push
git hook in python to validate files before they are pushed to the remote repo.

I have previously written a
pre-commit
git hook to validate files before they are committed to the local repo and to get a list of the files in the commit, I ran
git diff-index --cached --name-status HEAD
.

For the
pre-push
script, what git commands can I run to iterate through all of the commits about to be pushed, and then iterate through all of the files in the individual commits so that I can validate them?

So far I am using the command:
git diff --name-status @{u}..


EDIT: I think it's also important to note that the same files could be modified across multiple commits that are about to be pushed - so it would be good to not end up validating the same file multiple times.

FINAL_SOLUTION:

Here is the code I ended up using thanks to @Vampire's answer...

# read from stdin
# <local ref> SP <local sha1> SP <remote ref> SP <remote sha1> LF
pre_push_info = sys.stdin.read().split()

# get changed files
changed_files = subprocess.check_output(["git", "diff", "--name-status", pre_push_info[1], pre_push_info[3]])

# changed files now looks something like this...
# D Test/foo.py
# M Test/bar.py

Answer Source

Using @{u}.. is little helful, as it will diff the the upstream of HEAD against HEAD if there is an upstream defined at all. But this does not necessarily have anything to do with what is pushed, as you can push any branch or actually any commit-ish, regardless of what is checked out currently and to any remote branch you wish, regardless of the upstream setting.

As per the documentation of githooks, you get the remote name and location as parameters to your script and on stdin you get one line per pushed "thing" with the local and remote ref and local and remote sha. So you need to iterate over stdin and diff the remote sha that is pushed to against the local sha you push to get the files that are different.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download