📜 ⬆️ ⬇️

An example of using hooks in git

In order to get acquainted with the mechanism of hooks in git, simply start to use them and see how it works, and how it works inside.
Hooks in git are some scripts that are triggered on certain events, in essence they are their handlers. They are located in the directory. Git / hooks.


For example, let's try to make a simple handler. Its task is to place in the edited description to the commit the information we need.

So, we will create a prepare-commit-msg script with the following contents in the .git / hooks directory of our project:
')
#!/bin/sh

# master
last_master=`git log origin/master| head -n 1|cut -f 2 -d ' '`;
#
parent=`git log | head -n 1|cut -f 2 -d ' '`;
# . __
# 1364_restore_xterm_title
ticket=`git branch|grep '* '|cut -f 1 -d '_'|cut -f 2 -d ' '`;

# Ticket #
if [ "$last_master" == "$parent" ]; then
echo "Ticket #$ticket" > "$1".tmp;
fi

# GIT_AUTHOR_IDENT
SOB=$(git var GIT_AUTHOR_IDENT | sed -n "s/^\(.*>\).*$/Signed-off-by: \1/p")
grep -qs "^$SOB""$1"|| echo "$SOB" >> "$1".tmp;

# diff "+++", "---", "@@"
(echo; git diff --cached| grep -e "+++" -e "---" -e "@@"|sed -e 's/.*/# &/')>> "$1".tmp;
#
(echo; sed -e '/^$/d' "$1") >> "$1".tmp
mv "$1".tmp "$1";



The script inserts the signature of the committer and adds a list of changed functions by this commit. In addition, since we have a strictly regulated workflow in our project, according to which the commit should be executed in a certain way, for my convenience I added the insert of the ticket number to the beginning of the commit description, but only if this is the first commit in the branch.

This hook works on the client side, and as the name implies, it works when git commit is called.

Source: https://habr.com/ru/post/75063/


All Articles