Git恢复到以前的提交,并继续向master提交新的更改



我在master分支上,head指向我在master上的最后一次提交A,我想知道以下是否可能:

  1. 恢复到之前的提交b
  2. 移动所有从B到A的提交(B除外)到一个新的"实验"分支。在这个master的最后一次提交应该是B,而"experimental"的最后一次提交应该是a。
  3. 在master分支下的B之后做一个新的提交C。在这个主服务器最后一次提交之后应该是C

我所有的提交都已经被推送到原点,并且我的工作目录是干净的(没有阶段性或非阶段性的更改)。

请指教。

如果您没有将从BA的提交推送到远程存储库,这是可能的,并且没有副作用。

你应该这样做,但顺序与列表不同:

  • 将所有从B到A的提交(B除外)移动到一个新的分支"experimental"
  • git branch experimental
    

    git branch创建指向当前HEAD(在commit A上)的分支experimental。当前分支仍然是master

    1. 恢复到之前的提交b
    2. 这个master的最后一次提交应该是B,而"experimental"的最后一次提交应该是a。
    git reset --hard B
    

    git reset将当前分支(master)移动到提交B--hard选项告诉它也更新索引和工作树以匹配提交B(因此git status将报告"无提交,工作目录清理")。

  • 在master分支下的B之后做一个新的提交C。在这个主服务器最后一次提交之后应该是C
  • 当前分支为master。做你想做的修改,把它们添加到索引中,然后像往常一样提交。

    恭喜你!你的master刚刚偏离了experimental

    评论

    在启动前必须清理工作树。这意味着git status必须报告"没有什么要提交,工作目录清理"。(它还必须报告没有添加到索引的未跟踪文件;你不必担心,只要文件没有在commit B或任何以后的提交中被跟踪)。

    如果工作树不干净,那么您可以使用git stash将更改放在一边以便稍后恢复。当您到达步骤3时,您可以使用git stash apply恢复存储的更改。

    git checkout -b experimental    // Will Create and Switch your branch to "experimental" with the existing changes from master.
    git push origin experimental    // Will Push "experimental" to remote origin.
    git checkout master             // Will Switch branch back to "master"
    git reset --hard <commit>       // Will bring the head to the <commit> mentioned. Also, will remove uncommitted changes from "master"
    git add <files>                 // Add files to be committed to "master"
    git commit -m "new commit C"    // Now you can do the new commit "C" to master which is your current branch.
    git push origin master          // Will Push master to remote
    

    希望这能解决问题。

    最新更新