I am trying to enforce some coding rules in my team. To that end, I've written a number of client-side hooks, which work all right, but now I want the same checks to run when a developer pushes their modifications to the central repository. But they don't work.
Here is what I want to do:
I want to traverse the pushed files line by line, check for coding conventions violations and if I find any, reject the push, also showing the line numbers + violations.
In my pre-commit client side hook I was able to do that by calling git diff --cached --name-status --diff-filter=AM
to get the list of modified files, and git cat-file -p :filename
for each of the files retrieved in the first call to get the whole text of the files.
When I try to do the same in my server-side update
hook, I get an empty string (for the list of the files).
I also tried calling git show --pretty="format:" --name-only newrev
(where newrev is the SHA I get as a parameter to the update hook, git diff-tree -r --name-only --no-commit-id <tree-ish>
, and some other things I find on the net, but I can't get a clear understanding of what is going on and what I should call.
Can you help me?
The pre-push hook runs during git push , after the remote refs have been updated but before any objects have been transferred. It receives the name and location of the remote as parameters, and a list of to-be-updated refs through stdin .
Hooks are local to any given Git repository, and they are not copied over to the new repository when you run git clone .
Git hooks let developers automate expectations and workflows–terrific news for supporting ease-of-use and consistency across a development team. Unfortunately, git doesn't automatically synchronize hooks between project contributors.
You have to make changes to your script because there's no working copy on the server side, and git diff --cached
works with a staging area (or index), while your index is empty when the server receives a push.
Simply use git diff --name-status <sha-old> <sha-new>
instead, with sha-old
and sha-new
being the refs sent to the hooks as an argument, and you'll get the same output as running git diff --cached
before a commit.
As for checking file content, you can use git show sha-new:/path/to/file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With