Katie
Katie

Reputation: 907

How can I use a pre-push git hook to check whether certain files or directories different between the local and the remote branch?

... and more specifically, why can't I programmatically fetch a file?

I am new to writing git hooks. I want to be able to perform action X if a configuration file is changed since the last push. I have thought of two approaches:

1) get the relevant file from github and run diff.

2) scan the commit history since the last push for the presence of the file, using the information you get for free in a pre-push git hook (looks like this when I log it):

Name of the remote to which the push is being done: origin
URL to which the push is being done: [email protected]:<me>/<myrepo>.git
local ref: refs/heads/<mybranch>
local sha1: c83288a9e0b2a5c9f7b1940360e052b2d4468222
remote ref: refs/heads/<mybranch>
remote sha1: 164c55a9af0abee06bc03e91e162301ebf2bb097

Right now I'm trying (1) because it feels more obvious to me. I'm not sure how to use that information to inspect all the commits for changes to the relevant file. But I'm stuck because curl https://raw.githubusercontent.com/<repo-owner>/<repo>/docs-and-config/config/config.ymlas well as trying a GET command in Postman both return 404s -- I would understand not authorized, but I get not found. If I visit the same url in my browser, I can reach it (and GitHub attaches some kind of token to it).

So I have two questions:

(1) why is this happening and can you tell me how I can fetch the remote file? (2) do you have better ideas for how I can approach this task?

Upvotes: 0

Views: 2335

Answers (1)

bk2204
bk2204

Reputation: 76884

When the pre-push hook runs, your data hasn't been pushed to the remote system yet. So trying to fetch the data you haven't pushed from GitHub, which doesn't have it, won't work. GitHub gives you a 404 because it's not there yet.

Approach 2, which checks the commit history, is going to be the best approach here. You could try something like the following:

#!/bin/sh

while read lref loid rref roid
do
    if echo $roid | grep -qsE '^0+$'
    then
        # Do whatever you want with a new branch.
    elif echo $loid | grep -qsE '^0+$'
    then
        # Do whatever you want with a deleted branch.
    elif git diff --name-only $loid $roid | grep -qsF "MY-FILENAME-HERE"
    then
        # Do whatever you want to do if MY-FILENAME-HERE is present in the diff.
    else
        # Do whatever you want if the file is absent.
    fi
done

Upvotes: 3

Related Questions