📜  git global hooks - Shell-Bash (1)

📅  最后修改于: 2023-12-03 15:30:55.504000             🧑  作者: Mango

Git Global Hooks - Shell/Bash

Introduction

Git hooks are scripts that Git executes before or after certain events occur in the Git repository, such as commits, push, pull or merge. Git hooks can be used to enforce code quality, run automated tests or perform other custom actions.

Global hooks are hooks that can be attached to any repository on your system, regardless of the repository's location or owner. With global hooks, you can enforce certain policies or practices across all repositories on your machine.

In this guide, we will discuss how to create global hooks using Shell/Bash scripting.

Prerequisites

To create and configure Git global hooks, you need:

  • Git installed on your system
  • Basic knowledge of Shell/Bash scripting
  • Permission to write to the Git hooks directory (usually located in /.git/hooks/)
Creating Global Hooks
  1. To create a global Git hook, write a Shell/Bash script that performs the desired action. For example, here's a simple hook that echoes a message before each commit:
#!/bin/sh

echo "Preparing to commit..."
  1. Save the script with a descriptive name, such as pre-commit-hook.sh.

  2. Make sure the script is executable by running:

chmod +x pre-commit-hook.sh
  1. Move the script to the Git hooks directory on your machine. For global hooks, this directory is usually located in ~/.git-template/hooks/.
mv pre-commit-hook.sh ~/.git-template/hooks/
  1. Configure Git to use the template directory by running:
git config --global init.templateDir ~/.git-template
  1. Finally, initialize any new Git repositories with the git init command. The hook will be automatically installed in each new repository.
Sample Scripts

Here are a few sample global hooks that you can use as a starting point for your own custom hooks:

Enforce Commit Message Format

This hook enforces a specific format for commit messages, such as requiring a specific prefix or suffix.

#!/bin/sh

commit_msg=$(cat "$1")

if ! echo "$commit_msg" | grep -q "^(feat|bug|chore|docs|style|refactor|test|temp)-[a-z0-9]+: .+$"; then
  echo "Invalid commit message format. Please use format: 'type(id): message'" >&2
  exit 1
fi
Run Automated Tests

This hook runs automated tests before each commit to ensure that code quality standards are met.

#!/bin/bash

current_branch=$(git rev-parse --abbrev-ref HEAD)

if [[ $current_branch == "master" ]]; then
  exit 0
fi

echo "Running automated tests..."
python manage.py test
Conclusion

In conclusion, using Git global hooks with Shell/Bash scripting is a powerful way to enforce custom policies or practices across all of your Git repositories. By creating custom hooks and sharing them with your team, you can improve code quality, enforce code review standards, and streamline your development process.