git回放提交
方案 1:使用 git checkout 和 git restore
这是一个更简单的方案,可以直接将指定 commit 的改动提取到目标分支的工作区。
步骤:
切换到目标分支
bash$ git checkout <target-branch>将指定 commit 的改动提取到工作区 使用
git checkout提取某个 commit 的改动到当前工作区:bash$ git checkout <commit-hash> -- .<commit-hash>是你想要重放的 commit 的哈希值。-- .表示将该 commit 的所有改动提取到当前分支的工作区。
检查工作区改动
bash$ git status此时,改动已被提取到目标分支的工作区,并处于未暂存状态。
方案 2:使用 git cherry-pick 和 git reset
这是一个更常见的方法,通过 git cherry-pick 应用 commit 的改动,然后通过 git reset 将改动变为未提交状态。
步骤:
切换到目标分支
bash$ git checkout <target-branch>应用指定 commit 的改动 使用
git cherry-pick将指定 commit 的改动应用到当前分支:bash$ git cherry-pick <commit-hash>- 这会将该 commit 的改动应用到当前分支,并生成一个新的 commit。
撤销 commit,但保留改动 为了达到
git stash pop的效果,我们需要撤销这个新的 commit,但保留改动在工作区:bash$ git reset HEAD~1- 这会撤销最近的一个 commit,同时将改动保留在工作区。
检查工作区改动
bash$ git status此时,改动已被应用到工作区,但未提交。
方案 3:使用 git format-patch 和 git am
这种方法通过生成补丁文件来实现改动的重放,适合需要跨多个分支应用相同改动的场景。
步骤:
生成指定 commit 的补丁 切换到包含该 commit 的分支,运行以下命令生成补丁文件:
bash$ git format-patch -1 <commit-hash>-1表示生成一个补丁文件。- 这会生成一个
.patch文件,例如0001-commit-message.patch。
切换到目标分支
bash$ git checkout <target-branch>应用补丁到工作区 使用
git am应用补丁,但不生成新的 commit:$ git am --keep-cr <patch-file>--keep-cr会保留补丁的内容,但不会生成新的 commit。
检查工作区改动
bash$ git status
方案 4:手动创建 stash,然后应用
如果你愿意,实际上也可以将目标 commit 的改动存入 stash,然后切换到目标分支后再 git stash pop。
步骤:
将指定 commit 的改动存入 stash 使用
git stash push提取某个 commit 的改动到 stash:bash$ git stash push -m "Temporary stash" $(git diff <commit-hash>^ <commit-hash>)切换到目标分支
bash$ git checkout <target-branch>应用 stash 使用
git stash pop将改动应用到目标分支的工作区:bash$ git stash pop
方案 5:使用 git diff 和 git apply
这种方法会提取 commit 的改动,然后将改动直接应用到目标分支的工作区。
步骤:
切换到目标分支 首先切换到目标分支(你希望将改动应用到的分支):
bash$ git checkout <target-branch>生成改动的补丁 使用
git diff提取指定commit的改动,并保存为补丁文件,或者直接将其输出到命令管道:bash$ git diff <commit-hash>^ <commit-hash> > changes.patch<commit-hash>是你要重放的 commit 的哈希值。^表示上一版本(即该 commit 的父 commit)。changes.patch是生成的补丁文件(你也可以跳过保存为文件,直接管道到下一个命令)。
将改动应用到目标分支 在目标分支上应用改动(将补丁应用到工作区):
bash$ git apply changes.patch或者,如果你跳过了保存补丁文件,可以直接将
git diff的输出管道到git apply:bash$ git diff <commit-hash>^ <commit-hash> | git apply检查工作区改动 运行以下命令查看改动是否正确应用到工作区:
bash$ git status你会看到改动已被应用到工作区,但未被提交。
引用
AI