A Git hook to prevent committing directly to main 0 ▲ alexwlchan 2 hours ago · Tech · hide · 0 comments At work, we use a standard Git workflow: develop on a feature branch, push to GitHub, and open a pull request to main. Once somebody else approves the PR, the changes get merged. At least once a week, I forget to branch and commit changes directly to my local main. I only realise my mistake when I try to push and GitHub blocks me. To untangle myself, I have to create a new branch with my current state, push that instead, and then reset my local main back to origin so I can pull other people’s changes. This isn’t difficult to fix, but it’s annoying – especially when I often forget to clean up my local main until the next time I try to pull. To stop me getting into this state, I’ve written a Git pre-commit hook. I saved the following shell script in .git/hooks/pre-commit and made it executable: #!/usr/bin/env bash set -o errexit set -o nounset branch="$(git rev-parse --abbrev-ref HEAD)" if [ "$branch" = "main" ]; then echo "You can't commit directly to main" exit 1 fi The git rev-parse… No comments yet. Log in to reply on the Fediverse. Comments will appear here.