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-commit hook to your repository to prevent commits directly to the main branch. For example, create a file in your hooks directory (.git/hooks/pre-commit or as set by core.hooksPath git 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-commit command.
  • IntelliJ IDEA respects Git hooks, so this script will block and warn against committing to the main branch, even when committing from within the IDE.

Use protected branches in the IDE:

  • In File | Settings | Version Control | Git | Protected branches, add main or 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.
0 out of 0 found this helpful

Please sign in to leave a comment.

Have more questions?

Submit a request