Skip to content

合并问题

回滚代码

1. 合并还没提交(正在冲突或合并中)

如果你执行了 git merge xxx,但还没 commit,可以直接放弃合并:

shell
git merge --abort

👉 这会恢复到合并前的状态。 如果 --abort 不行,可以用:

git reset --merge

2. 合并已经提交了(git commit 完成)

如果你合并后已经提交了,但又后悔了,可以用 回退

shell
git reset --hard HEAD~1

👉 回到合并前的版本(会丢掉合并提交和修改)。

🔹 方法二:保留历史(安全,团队常用)

git revert 撤销那个合并提交,这样不会丢历史,只是“反做”合并:

shell
git revert -m 1 <merge_commit_id>
git push origin HEAD

解释:

  • <merge_commit_id> 就是你想撤销的合并提交的哈希值(用 git log 查)。
  • -m 1 表示以合并提交的 第一个父分支 为主,撤销掉另一个分支的更改。

这样做的效果是:远程历史还在,但合并的内容被撤销。

操作步骤

  1. 先找到你要撤销的合并提交 ID

    shell
    git log --oneline

    找到那个合并的哈希值,例如:

    shell
    c92ecb08 (origin/refine-0.0.2, refine-0.0.2) Merge branch 'refine-0.0.2' into n_master
  2. 撤销这个合并提交

    shell
    git revert -m 1 c92ecb08
    • -m 参数的作用 -m <parent-number> 主要用于 撤销合并提交(merge commit)。

    • -m 1 表示保留第一个父分支(通常是你所在的主分支),撤销掉被合并进来的分支改动。

    • 这会生成一个新的提交,用来反向抵消合并带来的修改。

  3. 推送到远程

    shell
    git push origin HEAD

最终效果

  • 提交历史里,原来的合并记录还在。
  • 但它的更改被新提交抵消。
  • 所有人同步后不会遇到历史冲突。

撤销掉刚才的撤销(推荐)

相当于 revert 的 revert

  1. 找到刚才生成的 revert 提交 的哈希:

    git log --oneline

    比如你会看到:

    4e69d042 (origin/n_master, n_master) Revert "Merge branch 'refine-0.0.2' into n_master"
  2. 直接再做一次 revert:

    git revert 4e69d042

    ✅ 这样 Git 会再生成一个新提交,把原来被撤销的代码恢复回来。

E325: ATTENTION
Found a swap file by the name "~/code/hc-project/web/admin-web/.git/.COMMIT_EDITMSG.swp"
          owned by: admin   dated: 二 10 21 17:10:12 2025
         file name: ~admin/code/hc-project/web/admin-web/.git/COMMIT_EDITMSG
          modified: no
         user name: admin   host name: admindeMac-mini.local
        process ID: 71417 (STILL RUNNING)
While opening file "/Users/admin/code/hc-project/web/admin-web/.git/COMMIT_EDITMSG"
             dated: 二 10 21 17:22:50 2025
      NEWER than swap file!

(1) Another program may be editing the same file.  If this is the case,
    be careful not to end up with two different instances of the same
    file when making changes.  Quit, or continue with caution.
(2) An edit session for this file crashed.
    If this is the case, use ":recover" or "vim -r /Users/admin/code/hc-project/web/admin-web/.git/COMMIT_EDITMSG"
    to recover the changes (see ":help recovery").
    If you did this already, delete the swap file "/Users/admin/code/hc-project/web/admin-web/.git/.COMMIT_EDITMSG.swp"
    to avoid this message.

Swap file "~/code/hc-project/web/admin-web/.git/.COMMIT_EDITMSG.swp" already exists!
[O]pen Read-Only, (E)dit anyway, (R)ecover, (Q)uit, (A)bort:

[O]pen Read-Only, (E)dit anyway, (R)ecover, (Q)uit, (A)bort: 选哪个?

ChatGPT 说:

推荐选: E (Edit anyway)

这会忽略旧的 .swp 文件,直接编辑提交信息,不会影响你的代码或仓库。

进入 Vim 后:

  1. 编辑你的提交说明;
  2. 保存退出(:wq)。

Lucking