Go It's a great tool. It allows you to not only track changes to a file through hooks but also collaborate seamlessly with other people. In this respect, Git is one of the tools that has pushed free and open source software development forward. However, one of the biggest problems with Git is that managing your repositories takes time and effort. For example, committing and synchronizing these repositories can take two to three git commands. This makes managing them not only tedious but also prone to user error. Here, we'll show you some simple and effective Git hooks to better manage your repositories.
What are Git Hooks?
git-hook is essentially a flexible subcommand that you can use to create custom scripts that run when Git performs an action on a repository. For example, you can use a hook to automatically check your repository for style errors before committing it.
The hook subcommand works by reading the "hooks" folder in the ".git" directory of the repository. This folder contains a number of pre-configured files that provide a script for each Git action you can automate.
For the most part, you can write a git hook in any scripting language you like. This makes it incredibly flexible and friendly to any developer.
1. Prevent Pushing to Master
One of the most common mistakes users make with Git is pushing a commit from the development branch directly to master. This can be incredibly frustrating if you use GitHub to track and maintain your projects.
You can prevent this problem by creating a pre-push which will check and confirm whenever you try to push a repository from the master branch.
- Go to Git repository Who you want to protect.
- Create Git hook file Using your script auditing program. Since this hook must be run before "to push" , you need to create a hook file. “Prepayment”:
touch .git/hooks/pre-push
- Open hook file New in Text editor.
nano .git/hooks/pre-push
- Inside, write New hook "before payment". For example, the following is a script that will ask you for confirmation when you push from the master branch:
#!/bin/sh protect='master' current=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,') if [ $protect = $current ] then read -p "Confirm push to master? Y/n." -n 1 -r < /dev/tty echo if echo $REPLY | grep -E '^[Yy]$' > /dev/null then exit 0 fi exit 1 else exit 0 fi
- Save New hook. in a nano Do this by pressing Ctrl + O , Then Ctrl + X.
- Run the following command to ensure that Git can run the new hook.
chmod +x .git/hooks/pre-push
2. Reject Pushes to the Master Branch
In addition to preventing yourself from pushing to the master, you can also create a server-side hook that will reject any pushes to its master branch. This is incredibly useful if you share a repository with multiple developers.
Fix this by creating a “pre-receive” hook that will automatically prevent any restricted user from pushing to the master branch.
- Create Git hook file for "pre-receipt" In your remote warehouse.
touch .git/hooks/pre-receive
- open this file.
nano .git/hooks/pre-receive
- Add rejection text in hook "pre-receipt"For example, the following lines of code should work out of the box:
#!/bin/sh branch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,') blacklist=(alice bob) if [[ ${blacklist[*]} =~ $USER ]]; then if [ "$branch" == "master" ]; then echo "You are not allowed to commit changes in this branch" exit 1 fi fi
- Save your new hook file. In my case, I need to press Ctrl+O, then Ctrl+X to save the file.
- Save hook text Make it your own and make it actionable.
chmod +x .git/hooks/pre-receive
Tip: You can also use a Git alias to make using Git more efficient.
3. Lock the Repository from Rebasing
Another common mistake users make with Git is rebasing the currently active branch. This can be frustrating if you're working on a repository with multiple contributors, as rebasing will remove commits made by other users.
You can prevent this problem by creating a “pre-rebase” hook that will check whether the current branch is closed or not.
- created pre-rebase file In the guide “.git/hooks”:
touch .git/hooks/pre-rebase
- open this File for editing.
nano .git/hooks/pre-rebase
- Add script pass inside New hook file.
#!/bin/sh branch="$2" [ -n "$branch" ] || branch=$(git rev-parse --abbrev-ref HEAD) lock="branch.${branch}.rebaselock" if [ "$(git config --bool "$lock")" = true ]; then echo "pre-rebase hook: “$lock” is set to true. Refusing to rebase." exit 1 fi
- Save hook file New and make it actionable.
chmod +x .git/hooks/pre-rebase
4. Force a Style and Syntax Check on Your Code
One of the most useful uses of a Git hook is to attach it to a code linter. This is a simple program that checks whether your code follows the style and format of the project.
- To connect linter With your Git repository, first create a binding file. "Pre-commitment".
touch .git/hooks/pre-commit
- install linter appropriate for your project language. In this case, I use “shellcheck” To analyze my Bash code:
sudo apt install shellcheck
- Open hook file New and add the following script.
#!/bin/bash for file in $(git diff --cached --name-only --diff-filter=AM | grep -E '\.sh$') do shellcheck "$file" # Run the linter for every new file. if [$? -ne 0 ]; then exit 1 # Terminate the commit if the linter fails. fi done
- Save hook file New and make it executable:
chmod +x .git/hooks/pre-commit
5. Automatically Notify Users with Repository Changes
Finally, you can also create a Git hook that will automatically send an email whenever your repository receives a new commit. This is useful if you want to create a simple notification system for your repository.
- Create “post-Receiver” hooks file In the guide .git/hooks In your warehouse:
touch .git/hooks/post-receive
- Open Git hook file New and enter the following script:
#!/bin/sh commit_message=$(git log -1 --pretty=%B) users=("[email protected]""[email protected]""[email protected]") for user in "${users[@]}"; do mail -s "New Commit: $commit_message" $user < /dev/null done
- Save hook file New and make it actionable.
chmod +x .git/hooks/post-receive
Frequently Asked Questions
Q1. Can I write Git hooks in a compiled language, such as C?
answer. One of the biggest limitations of Git hooks is that they require you to use a language that you can run directly from the terminal. This means that Git hooks do not support any compiled language for their scripts. For example, you can create new Git hooks using Python or the shell, but not C or C++.
Q2. Is it possible to run multiple hooks in the same Git repository?
answer. Yes. While the examples above show hooks as separate individual features, you can easily combine them to create your own unique workflow, making Git hooks incredibly flexible and adaptable to any coding situation. For example, you can use both the "Prevent Push to Master" hook and the "Syntax Check" precommit hook in your repository.
Q3. Why don't Git hooks send emails to users?
answer. This issue is most likely caused by your remote server not being able to send any outgoing emails correctly. To fix this, ensure that your remote server is secure and has a mail delivery agent working in conjunction with the SMTP domain.