DEV Community

cerico
cerico

Posted on • Updated on

Blocking commits on main with the pre-commit hook

Blocking commits on main with the pre-commit hook

While you can edit the settings on github to block commits on main, it's also possible to do it locally so you can prevent it from happening in the first place by using the pre-commit hook.

# ~/.config/git/hooks/pre-commit
branch="$(git branch --show-current)"
commits="$(git rev-list --all)"

if [ "$branch" = "main" ] && [ "$commits" != "" ]; then
  echo "Commit on main branch is blocked, there are already existing commits."
  exit 1
fi
Enter fullscreen mode Exit fullscreen mode

Any newly created repo will automatically have this hook in place. If you want to add it to an existing repo, you can copy the file to the .git/hooks directory. Typically in a newly created repo we will want the initial commit to be on main, so the hook also checks there are any existing commits before blocking the commit.

☁  brew@kelso:asda ➜ (main) ✗ git add README.md
☁  brew@kelso:asda ➜ (main) ✗ git commit -m "adding initial documentation"
main branch commit is blocked
Enter fullscreen mode Exit fullscreen mode

Top comments (0)