Need to run a "hook" on new Git Tag (Git hook for newly pulled tags)

Viewed 230

To begin, I looked at this question which seems to be the only one regarding this topic:

But I do not understand what hook that is or how it is being used. I simply want to run a little script that will update if I git pull and new tag are received.

I tried putting it in: .git/hooks/update, .git/hooks/post-receive

#!/bin/bash
exec < /dev/tty

CURRENT_TAG=$(git tag --contains)
echo Test Test
echo "LATEST_TAG: \"${CURRENT_TAG}"\" > "config/latest_tag.yml"

I would like to use Git hooks if possible. I was thinking of doing alias "git pull"="git pull && ./update_script.sh but I cannot alias a spaced word, n'or can I alias something and enforce the rest of the team to remember it.

1 Answers

As the documentation says, the post-receive and update hooks are "server" side hooks, i.e. they run on the server in reaction to a push from a client. What you want is the opposite, for which there unfortunately is no hook.

Since you mention that aliasing the command wouldn't work, you could use a function as the next best thing. It will receive the arguments that can then be examined.

git() { env git $* && [ "$1" = "fetch" -o "$1" = "pull" ] && ./update_script.sh; }

Care must be taken when shadowing commands like this to not cause infinite recursion. Within the function body, you must never call git directly, as that would re-run the function, not the git command. I've used env to resolve the actual git binary, but using an absolute path would work just as well.

Note that it is actually git fetch that will get the new tags and git pull simply calls git fetch internally. I therefore included handling for both fetch and pull. Also note that it will shadow the git command in all repositories, so it would need to be extended if the special handling should only be applied to specific repositories.

In case your update_script.sh is tracked within the repository itself there are at least two things to be aware of:

  • Anyone who can push changes to that file will essentially be enabled to run arbitrary commands on any machine where pulls happen.
  • As the pull or fetch commands may be run anywhere in the work tree, not just at the top level, the path should first be resolved using [env] git rev-parse --show-toplevel.
Related