Matthew Blackwind
Matthew Blackwind

Reputation: 159

Creating a git pre-receive hook

Prologue

I want to create a pre-receive hook from my pre-push hook. Now, looking around the 'net and the SO, I have found many questions pertaining to specific problems, and/or focusing on a description of the hook, instead of actually showing it (I'm looking at you, git-scm).

The point

So anyway, as far as I have gathered, pre-receive hook is called with no parameters. How do I get data then? There is very much data that I would see myself wanting to get a hold of in such hook, for example:

but I honestly have no idea how to get the data - and I know that people do it, because I have seen such scripts in action.

Assumptions

I would like to assume that it's bash-doable, because the less configuration the better, amirite?

Actual question

Coding a pre-receive hook, how to gather data about the push that triggered it?

Upvotes: 0

Views: 305

Answers (2)

Johan van Breda
Johan van Breda

Reputation: 593

You need to read from stdin. Each line gives you the old reference, new reference and reference name. An starting example can be found at Git pre-receive hook.

Upvotes: 1

Bruno De Fraine
Bruno De Fraine

Reputation: 47316

This is documented, see https://git-scm.com/docs/githooks#pre-receive :

This hook executes once for the receive operation. It takes no arguments, but for each ref to be updated it receives on standard input a line of the format:

<old-value> SP <new-value> SP <ref-name> LF

where <old-value> is the old object name stored in the ref, <new-value> is the new object name to be stored in the ref and <ref-name> is the full name of the ref. When creating a new ref, <old-value> is 40 0.

Note that you can receive updates to multiple branches. When you write your pre-receive hook in bash, you can start with:

while read old new ref; do
    # do something with each $old $new $ref
done

$ref will be the full name, for example, refs/heads/my-branch. $old and $new are SHA-1 names of commit objects.

To get at the commit message, author, etc. you can invoke git commands with $old and $new, for example, git log $old..$new (note that there may be multiple new commits pushed on one branch).

Upvotes: 1

Related Questions