You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何合并Git因--strategy=ours合并标记为已有的变更?

解决Git合并方向切换后无法将A全部内容合并到B的问题

核心思路

由于之前使用git merge --strategy=ours让B标记为已包含A的所有提交,Git默认不会再处理重复合并。要强制将A的全部内容同步到B,有以下几种可行方案:

方案1:快速强制合并(直接覆盖内容)

这个方法能一次性将A的当前状态同步到B,同时保留合并历史:

# 切换到目标分支B
git checkout B

# 执行空的ours合并(不提交,仅更新合并记录)
git merge --no-ff -s ours --no-commit A

# 将A的所有内容覆盖到B的工作区
git checkout A .

# 提交所有变更
git add .
git commit -m "Force sync all content from branch A to B"

方案2:遍历提交重新应用(处理合并提交)

如果需要保留A的每一条提交历史,可以写脚本批量cherry-pick,合并提交需用-m 1指定父分支(假设A的合并提交中第一个父提交是主分支方向):

  1. 先确定切换合并方向前的A分支最后一个提交哈希(记为<last-before-switch>)
  2. 从A的初始提交到<last-before-switch>遍历所有提交:
git checkout B
# 获取A分支从初始到目标提交的所有哈希(按顺序)
git log --reverse --pretty=format:"%H" <initial-commit>..<last-before-switch> | while read commit_hash; do
    # 判断是否为合并提交
    if [ $(git rev-list --count --merges $commit_hash^..$commit_hash) -eq 1 ]; then
        # 合并提交用-m 1指定父分支
        git cherry-pick -m 1 $commit_hash
    else
        git cherry-pick $commit_hash
    fi
    # 若有冲突,处理后继续,可根据需求自动跳过或停止
    if [ $? -ne 0 ]; then
        echo "Conflict at commit $commit_hash, resolve manually and press enter to continue"
        read
        git cherry-pick --continue
    fi
done

方案3:基于标签批量同步

针对A上的111个标签,可按标签顺序逐个将标签对应的内容合并到B:

  1. 列出所有需要同步的标签(按创建时间排序):
git tag --sort=creatordate | grep "<tag-pattern>" > tag_list.txt
  1. 遍历标签列表,逐个合并:
git checkout B
cat tag_list.txt | while read tag; do
    # 强制将标签对应的内容合并到B
    git merge --no-ff -s ours --no-commit $tag
    git checkout $tag .
    git add .
    git commit -m "Sync content from tag $tag to B"
done

内容的提问来源于stack exchange,提问作者tanager

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 03:03:17