Prevent committing to a branch in IntelliJ IDEA
Question
Is there a way to get IntelliJ IDEA to warn or prevent committing directly to a branch like main?
Answer
IntelliJ IDEA does not have a built-in option to warn before committing to the main branch. However, there are several ways to achieve similar behavior:
Use Git hooks:
- Add a
pre-commithook to your repository to prevent commits directly to themainbranch. For example, create a file in your hooks directory (.git/hooks/pre-commitor as set bycore.hooksPathgit configuration) with the following content:
#!/bin/sh
branch="$(git rev-parse --abbrev-ref HEAD)"
if [ "$branch" = "main" ]; then
echo "Refusing to commit directly on main. Create a feature branch instead."
exit 1
fi- Make the hook file executable (not required on Windows) using
chmod +x .git/hooks/pre-commitcommand. - IntelliJ IDEA respects Git hooks, so this script will block and warn against committing to the
mainbranch, even when committing from within the IDE.
Use protected branches in the IDE:
- In File | Settings | Version Control | Git | Protected branches, add
mainor any other branch name you want to protect. - When a branch is marked as protected, IntelliJ IDEA disables the Push button for that branch, preventing accidental pushes from the IDE.
Remote repository protections:
- Configure your remote repository to require pull requests or reviews for changes to the protected branch. If push restrictions are set up, IntelliJ IDEA will show push errors when you attempt to push directly.
Please sign in to leave a comment.