Celebrate Bisexuality Day

As of the May 2022 release of Visual Studio Code, it's possible to configure git branch protection directly within VS Code:

With the new git.branchProtection setting, you can configure specific branches to be protected. VS Code will avoid committing directly on protected branches and will offer you the chance to create a new branch to commit to instead. You can fine tune this behavior with the git.branchProtectionPrompt setting.

Configure branch protection

I think this is most useful inside your workspace settings instead of your global user settings. To open your workspace settings, press ctrl + shift + p (Windows/Linux) or cmd + shift + p (Mac). Search for Preferences: Open Workspace Settings (JSON). Selecting this option will open a settings.json file where you can add an array of protected branches:

{
"git.branchProtection": ["main"]
}

Now when you try to commit to a protected branch using the source control view, VS Code will show a warning:

You are trying to commit to a protected branch and you might not have permission to push your commits to the remote. How would you like to proceed?
VS Code shows a warning when you try to commit to a protected branch.

Note that this protection only works inside the source control view. It doesn't affect the command line.

Customise branch protection

You can customise this behaviour with the git.branchProtectionPrompt setting. You have three options:

"alwaysPrompt" (default)
Always prompt before changes are committed to a protected branch.
"alwaysCommitToNewBranch"
Always commit changes to a new branch.
"alwaysCommit"
Always commit changes to the protected branch.

For example, here's the default setting (which can be omitted):

{
"git.branchProtection": ["main"],
"git.branchProtectionPrompt": "alwaysPrompt"
}