Git Hooks are small scripts that run automatically at specific points during the Git workflow. They allow you to customize and automate various tasks, such as:
1. **Validation**: Verify code changes before committing them.
2. **Formatting**: Enforce coding standards or formatting rules.
3. **Backup**: Create a backup of your repository or files.
4. **Notification**: Send notifications about specific events (e.g., new commit, branch creation).
**Types of Git Hooks:**
-------------------------
There are several types of Git Hooks:
1. **Client-Side Hooks**: Run on the client-side (your local machine) before committing changes.
2. **Server-Side Hooks**: Run on the server-side when pushing or pulling changes to/from a remote repository.
3. **Pre-Commit Hooks**: Run before committing changes, allowing you to validate and format code.
4. **Post-Commit Hooks**: Run after committing changes, allowing you to perform tasks like backing up your repository.
**How to Create a Git Hook:**
--------------------------------
To create a Git Hook:
1. **Create a new file**: In the `.git/hooks` directory of your repository, create a new file with a name starting with `hook_`, followed by an underscore and the event you want to hook (e.g., `pre-commit`).
2. **Write the script**: Write a Bash script (or other language) that performs the desired action.
3. **Make it executable**: Run `chmod +x <hook_file>` to make the file executable.
**Examples of Git Hooks:**
-----------------------------
Here are some examples:
1. **Pre-Commit Hook**: Validate code formatting using tools like ESLint or Prettier before committing changes.
```bash
#!/bin/bash
eslint .
```
2. **Post-Commit Hook**: Send a notification to your team when a new commit is made:
```bash
#!/bin/bash
curl -X POST \
https://example.com/new-commit-notification \
-H 'Content-Type: application/json' \
-d '{"commit_hash": "$COMMIT_HASH", "author": "'$AUTHOR'"}'
```
3. **Pre-Push Hook**: Check for outstanding changes before pushing to a remote repository:
```bash
#!/bin/bash
if [ $(git status --porcelain | wc -l) -gt 0 ]; then
echo "Error: Uncommitted changes detected!"
exit 1
fi
```
**Tips and Variations:**
-------------------------
1. **Customize your hooks**: Tailor Git Hooks to your specific needs or project requirements.
2. **Use existing scripts**: Leverage existing tools and scripts, such as ESLint or Prettier, in your Git Hooks.
3. **Integrate with CI/CD**: Use Git Hooks to trigger CI/CD pipelines or automate deployment processes.
By leveraging Git Hooks, you can create a customized workflow that automates repetitive tasks, enforces coding standards, and enhances collaboration within your team!
# References
```dataview
Table title as Title, authors as Authors
where contains(subject, "Git hooks")
sort title, authors, modified, desc
```