GIT-返回上一次提交并进行修改

时间:2019-06-20 08:03:19

标签: git

我有一个项目,其中有以下提交顺序:

* 800cedc (HEAD, origin/master, origin/HEAD, master) Commit 6
* 1d51716 Commit 5
* 5232f4b Commit 4
* 01838a5 Commit 3
* 3aeb34d Commit 2
* 9b75b72 Commit 1

出于开发原因,我需要执行以下操作: 1.转到提交5。 2.进行一些小的更改。 3.将更改发布到生产中。 4.将更改添加到提交中。

问题来了,当我看到更改的文件也已在提交6中更改时。

我该怎么做才能在提交5中更改文件,并将更改与提交6合并以保持对所有内容的良好跟踪?

谢谢!

3 个答案:

答案 0 :(得分:4)

正如@NilsWerner的评论所说,重写已发布的历史记录不是一个好主意。但是如果您真的想,

git reset 1d51716 --hard
# modify the file and
git add path/to/file
git commit --amend

# apply Commit 6 again
git cherry-pick 800cedc 

# there might be conflicts and if any,
# resolve the conflicts, and then
git add path/to/file
git cherry-pick --continue

# force push "master"
git push origin -f master

强制推送后,请务必告知其他贡献者您已重写master,他们应强制更新其本地master并将未推送的提交应用于其新的本地master,这是一个很麻烦的任务。

答案 1 :(得分:1)

您可以执行以下步骤。

  1. 使用commit5创建新分支。

    git branch branchname <sha1-of-commit5>
    git checkout branchname 
    
  2. 您不能对单个文件进行自动选择。您只能在提交级别执行cherrypick。 对要从commit6合并的Commit5特定文件(例如file_a)进行本地复制。之后,从commit6中检出特定文件。

    git checkout <sha1-ofcommit6> path/to/file_a

  3. 现在,手动将commit5文件(本地副本)与commit6文件(在git分支中)合并

  4. 完成更改后,暂存并推送到远程。

    git add .
    git commit -m "manual merge for file_a"
    git push origin branchname```
    

答案 2 :(得分:0)

尝试:

git revert 1d51716
git revert --no-commit HEAD

然后,进行更改。

不确定,请小心进行验证。

顺便说一句:我认为最好的方法就是重新提交:-)