如何在Bitbucket中禁止Git cherry-pick操作以遵循标准分支策略?
Hey there! I totally get where you’re coming from—you want your team to stick strictly to your company’s branch strategy and avoid git cherry-pick entirely, without sinking time into building complex Git hooks. Let’s break down the most practical options for your Bitbucket setup:
1. Use Bitbucket’s Built-in Branch Protections (The Easiest First Step)
Bitbucket doesn’t have a direct "block cherry-pick" toggle, but you can use its built-in tools to make cherry-pick effectively useless for your protected branches:
- Lock down protected branches: Mark your main branches (like
main,develop) as protected, and disable direct pushes—only allow merges via Pull Requests. This way, even if someone runs a cherry-pick locally, they can’t push that commit directly to your critical branches; they have to go through PR review. - Enforce linear history: Enable the "Require linear history" merge check for your protected branches. Cherry-picked commits almost always create non-linear history, so this check will block PRs that include cherry-picked changes until the contributor rebases their branch to fix the history. This indirectly forces your team to avoid cherry-pick in favor of rebasing or merging from the main branch.
2. A Super Lightweight Server-Side Hook (No Complexity Required)
If you need a hard block on cherry-picked commits being pushed at all, you don’t need a fancy hook. Cherry-picked commits automatically include the phrase cherry picked from commit <HASH> in their message (unless the user manually edits it). You can use a simple pre-receive hook to scan for this phrase and reject the push.
Here’s a minimal bash script you can use:
#!/bin/bash # Reject pushes containing cherry-picked commits while read oldrev newrev refname; do # Check all new commits in the push for cherry-pick markers git log --format=%B "$oldrev..$newrev" | grep -q "cherry picked from commit" if [ $? -eq 0 ]; then echo "❌ ERROR: Cherry-picked commits are not allowed. Please follow the company's standard branch strategy." exit 1 fi done exit 0
To set this up:
- Save the script as
block-cherry-pick.shin your Bitbucket repo’shooks/pre-receive.d/directory - Give it execute permissions with
chmod +x block-cherry-pick.sh
This is way simpler than building a full custom hook, and it covers 99% of cases where someone uses cherry-pick without editing the commit message.
3. Combine Tech Restrictions with Team Alignment
Don’t forget the human side! Make sure your team understands why cherry-pick is off-limits (e.g., to keep commit history clean, avoid hidden conflicts, or align with your CI/CD pipeline). Pair that with the above technical safeguards, and you’ll have a much smoother enforcement process.
内容的提问来源于stack exchange,提问作者Azi

