首页 > 解决方案 > 还原项目 20 多次提交,然后选择性地重新应用其中的一些

问题描述

我有一个 git 项目,其中进行了几次提交,我想恢复其中的大部分。但是,在这段时间内,我想保留几个错误修复和其他提交,所以我想做以下事情:

  1. 将存储库恢复到我要恢复的第一次提交之前的提交
  2. 完成提交并仅重新应用其中一些,而其中一些仅部分重新应用

是否有一些 git 命令序列可以让我实现这一目标?我可以弄清楚如何恢复到某些提交,但如果选择性重新提交甚至是可能的,我一无所知。

标签: gitgithub

解决方案


您不必还原。您可以git rebase在交互模式下使用来编辑您的历史记录。例如,在我当前的主题分支上,如果我运行,git rebase -i master我会在 VIM 中看到这个视图:

pick 23299aa6 improve unit test messages
pick cf1c3c0c move sagas tests to where they'll get run
pick f7ff7fa7 use docker-compose up to rebuild the ui image more quickly
pick 544902ec split definitions file into helpers and given, when, then files
pick 55e94e7b remove canary test
pick 8a4b0862 move expectTitleToBe function to helper file

# Rebase 72b74f26..8a4b0862 onto 72b74f26 (6 commands)
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
# d, drop = remove commit
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out

从这个视图中,我可以删除我不想提交的行,如果我实际上不想删除金丝雀测试,我可以删除或注释掉该行或使用drop命令。我可以在提交时停止变基并更改将通过编辑提交的内容(您可以通过删除更改在此处部分提交)等等列出的其他命令:

edit 23299aa6 improve unit test messages
pick cf1c3c0c move sagas tests to where they'll get run
pick f7ff7fa7 use docker-compose up to rebuild the ui image more quickly
pick 544902ec split definitions file into helpers and given, when, then files
drop 55e94e7b remove canary test
pick 8a4b0862 move expectTitleToBe function to helper file

# Rebase 72b74f26..8a4b0862 onto 72b74f26 (6 commands)
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
# d, drop = remove commit
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out

对于您的情况并针对您自己而不是另一个分支进行重新定位,您可以回顾一下git log以找到您想要恢复到的提交的提交哈希。这通常是您开始工作之前git rebase -i <where to "revert">的一次提交: .


推荐阅读