简体   繁体   English

如何在git中的先前提交中回滚文件中的更改

[英]how to roll back changes in a file in a previous commit in git

I made 3 'git commit' but I have not done a 'git push'. 我做了3个'git commit',但是我没有做过'git push'。

1. commit 1
2. commit 2
   touches fileA
   touches fileB
   touches fileC
3. commit 3

So How can I 那我该怎么办

  1. roll back changes I made in file b for commit 2? 回退我对提交2在文件b中所做的更改? (I can't do a 'git checkout -- fileB' anymore since I already 'git commit', how can i roll back my changes? (由于我已经执行了“ git commit”,因此我无法再执行“ git checkout-fileB”操作,如何回滚更改?
  2. make changes in fileC and make it like part of commit 2? 在fileC中进行更改,使其像提交2的一部分? I think I can go and change the file now and then run a 'git rebase -i HEAD~2' Correct? 我想我可以立即更改文件,然后运行'git rebase -i HEAD〜2'对吗?

This should work: 这应该工作:

1. git rebase -i HEAD~2
2. in your editor, select the following:

edit 9b86592 commit 2
pick f3907cb commit 3

3. at this point roll back the changes you made in fileB, for example with
   `git checkout <version_you_want>` or by manually editing the file
4. make the changes in fileC you want to be part of commit 2
5. `git add fileB fileC`
6. `git commit --amend`
7. `git rebase --continue`

You may need to resolve merging issues if there are conflicts when git tries to apply commit 3. After you resolve those, run git rebase --continue again. 如果git尝试应用提交3时发生冲突,则可能需要解决合并问题。解决这些问题后, git rebase --continue再次运行git rebase --continue

使用git rebase -i HEAD~2并编辑第二个提交。

Assuming that you are on branch master and have a clean tree: 假设您在分支主服务器上并且有一棵干净的树:

# checkout incorrect commit
git checkout <sha1_of_commit2>

# revert the changes to fileB by checking out the parent version
git checkout HEAD^ -- fileB

# make an amended commit
git commit --amend

# go back to master
git checkout master

# transplant the changes since the bad commit onto the amended commit
git rebase --onto HEAD@{1} <sha1_of_commit2>

This is how I would do it. 这就是我要做的。

Checkout the old version of fileB and commit it 检出旧版本的fileB并提交

git checkout HEAD~3 -- fileB
git commit -m"fix fileB" fileB

Now rebase to squash in your fix with the old commit 现在使用旧的提交重新定位到您的修复程序中

git rebase -i HEAD~3

now move your most recent commit "fix fileB" to be after commit 2, and change the "pick" instruction to "squash", joining the commit changing fileB with the commit resetting it. 现在将您最近的提交“ fix fileB”移到提交2之后,并将“ pick”指令更改为“ squash”,将提交更改的fileB与重新设置的提交一起加入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM