Search code examples
gitgit-post-receive

How to access to repository file with GIT in post-receive hook


I have this scenario with GIT:

I want to "do something" with a specific file when it is changed in a push. For example a .sql file must be dumped in a db if it's changed.

I'm using 'post-receive' hook in GIT with a statement like this:

DUMP=$(git diff-tree --name-only -r -z master dump.sql);

if [ -n "$DUMP" ]; then
  // using the new dump.sql
fi

How can I access to the new dump.sql just pushed from the hook?


Solution

  • You can retrieve file dump.sql from revision $rev using:

    git cat-file blob $rev:dump.sql
    

    The post-receive hook is also called for things other than pushing master... hopefully you have a check somewhere that you're processing the updated master ref. As a matter of style, I'd use the new-revision value passed to the hook rather than referencing master directly from within the hook.

    Usually I write a post-receive hook like this:

    while read oldrev newrev refname; do
        if [ "$refname" = "refs/heads/master" ]; then
            # definitely updating master; $oldrev and $newrev encompass the changes
            if git diff-tree --name-only -r -z $oldrev $newrev dump.sql; then
                # dump.sql changed...
            fi
        fi
    done
    

    Importantly, this also copes with a single push sending over several commits to master in one go--- the command you showed in the question only looked at the last commit on master.