Skip to content

git回放提交

方案 1:使用 git checkoutgit restore

这是一个更简单的方案,可以直接将指定 commit 的改动提取到目标分支的工作区。

步骤:

  1. 切换到目标分支

    bash
    $ git checkout <target-branch>
  2. 将指定 commit 的改动提取到工作区 使用 git checkout 提取某个 commit 的改动到当前工作区:

    bash
    $ git checkout <commit-hash> -- .
    • <commit-hash> 是你想要重放的 commit 的哈希值。
    • -- . 表示将该 commit 的所有改动提取到当前分支的工作区。
  3. 检查工作区改动

    bash
    $ git status

    此时,改动已被提取到目标分支的工作区,并处于未暂存状态。

方案 2:使用 git cherry-pickgit reset

这是一个更常见的方法,通过 git cherry-pick 应用 commit 的改动,然后通过 git reset 将改动变为未提交状态。

步骤:

  1. 切换到目标分支

    bash
    $ git checkout <target-branch>
  2. 应用指定 commit 的改动 使用 git cherry-pick 将指定 commit 的改动应用到当前分支:

    bash
    $ git cherry-pick <commit-hash>
    • 这会将该 commit 的改动应用到当前分支,并生成一个新的 commit。
  3. 撤销 commit,但保留改动 为了达到 git stash pop 的效果,我们需要撤销这个新的 commit,但保留改动在工作区:

    bash
    $ git reset HEAD~1
    • 这会撤销最近的一个 commit,同时将改动保留在工作区。
  4. 检查工作区改动

    bash
    $ git status

    此时,改动已被应用到工作区,但未提交。

方案 3:使用 git format-patchgit am

这种方法通过生成补丁文件来实现改动的重放,适合需要跨多个分支应用相同改动的场景。

步骤:

  1. 生成指定 commit 的补丁 切换到包含该 commit 的分支,运行以下命令生成补丁文件:

    bash
    $ git format-patch -1 <commit-hash>
    • -1 表示生成一个补丁文件。
    • 这会生成一个 .patch 文件,例如 0001-commit-message.patch
  2. 切换到目标分支

    bash
    $ git checkout <target-branch>
  3. 应用补丁到工作区 使用 git am 应用补丁,但不生成新的 commit:

    $ git am --keep-cr <patch-file>
    • --keep-cr 会保留补丁的内容,但不会生成新的 commit。
  4. 检查工作区改动

    bash
    $ git status

方案 4:手动创建 stash,然后应用

如果你愿意,实际上也可以将目标 commit 的改动存入 stash,然后切换到目标分支后再 git stash pop

步骤:

  1. 将指定 commit 的改动存入 stash 使用 git stash push 提取某个 commit 的改动到 stash:

    bash
    $ git stash push -m "Temporary stash" $(git diff <commit-hash>^ <commit-hash>)
  2. 切换到目标分支

    bash
    $ git checkout <target-branch>
  3. 应用 stash 使用 git stash pop 将改动应用到目标分支的工作区:

    bash
    $ git stash pop

方案 5:使用 git diffgit apply

这种方法会提取 commit 的改动,然后将改动直接应用到目标分支的工作区。

步骤:

  1. 切换到目标分支 首先切换到目标分支(你希望将改动应用到的分支):

    bash
    $ git checkout <target-branch>
  2. 生成改动的补丁 使用 git diff 提取指定 commit 的改动,并保存为补丁文件,或者直接将其输出到命令管道:

    bash
    $ git diff <commit-hash>^ <commit-hash> > changes.patch
    • <commit-hash> 是你要重放的 commit 的哈希值。
    • ^ 表示上一版本(即该 commit 的父 commit)。
    • changes.patch 是生成的补丁文件(你也可以跳过保存为文件,直接管道到下一个命令)。
  3. 将改动应用到目标分支 在目标分支上应用改动(将补丁应用到工作区):

    bash
    $ git apply changes.patch

    或者,如果你跳过了保存补丁文件,可以直接将 git diff 的输出管道到 git apply

    bash
    $ git diff <commit-hash>^ <commit-hash> | git apply
  4. 检查工作区改动 运行以下命令查看改动是否正确应用到工作区:

    bash
    $ git status

    你会看到改动已被应用到工作区,但未被提交。

引用

AI