A ‘pre-commit’ Hook
Learn about the "pre-commit hook."
We'll cover the following
Create repositories#
To understand Git hooks properly, you’re going to create a bare repository with nothing in it and then clone from that bare repo. You looked at bare repositories earlier in this (advanced) part.
1 mkdir lgthw_hooks
2 cd lgthw_hooks
3 mkdir git_origin
4 cd git_origin
5 git init --bare
6 cd ..
7 git clone git_origin git_clone
You have two repositories: git_origin
(which is the bare repository you will push to) and git_clone
(which is the repository you will work in). You can think of them as part of a client-server Git workflow where users treat the git_origin
folder as the server and clones as the client.
Next, add some content to the cloned repository, and push it:
8 cd git_clone
9 echo 'first commit' > file1
10 git add file1
11 git commit -m 'adding file1'
12 git push
Nothing surprising should have happened there. The content was added, committed, and pushed to the origin repo.
Adding a “pre-commit” hook#
Now imagine that you’ve set a rule for yourself that you shouldn’t work on weekends. To try and enforce this, you can use a Git hook in your clone.
Add a second change, and take a look at the .git/hooks
folder:
13 echo 'second change in clone' >> file1
14 ls .git/hooks
In the .git/hooks
folder, there are various examples of scripts that can be run at various points in the Git content lifecycle. If you want to, take a look at them now to see what they might do, but this can be somewhat bewildering.
What you’re going to do now is create a script that is run before any commit is accepted into your local Git repository:
15 cat > .git/hooks/pre-commit << EOF
16 > echo NO WORKING AT WEEKENDS!
17 > exit 1
18 > EOF
19 chmod +x .git/hooks/pre-commit
You have created a pre-commit
script in the hooks
folder of the repository’s local .git
folder and made it executable. The script prints a message about not working on weekends and exit
s with a code of 1
, which is a generic error code in a shell script (exit 0
would mean “OK”).
See what happens when you try to commit:
20 git commit -am 'Second change'
You should have seen that the commit did not work. If you’re still not sure whether it got in, run a log command in the terminal above and check that the diff is still there:
21 git log
22 git diff
This should confirm that no commit has taken place.
To show a reverse example that lets the commit through, replace the script with this content:
23 cat > .git/hooks/pre-commit << EOF
24 > echo OK
25 > exit 0
26 > EOF
This time you’ve added an OK message and exited with a 0
(success) code rather than a 1
for error.
Now your commit should work, and you should see an OK message as you commit.
27 git commit -am 'Second change'