【问题标题】:GIT : edit staged files in old commit but keep changesGIT:编辑旧提交中的暂存文件但保留更改
【发布时间】:2020-10-15 02:05:43
【问题描述】:

我查看了所有内容,但找不到解决我正在尝试做的事情的方法。也许我只是错过了。

说我有:

Commit A: 
- file 1
- file 2
- file 3
Commit B:
- file 4
Commit C:
- file 5
- file 6
HEAD: has files 1-6. 

有没有办法以交互方式返回到提交 A 以取消提交文件 2 和文件 3,然后重播剩余的提交? 这样我就剩下了

Commit A: 
- file 1
Commit B:
- file 4
Commit C:
- file 5
- file 6
HEAD: has files 1-6, with file2 and file3 as unstaged.

我找到了不完整的解决方案:

- git reset --soft <commit A>
- make changes
- git commit

但这让我没有剩余的提交(B,C)。

- git rebase -i HEAD~n
- edit <commit>
- make changes
- git commit --amend
- git rebase --continue

但此处的更改是在该提交时提交的文件之上,我不想撤消文件更改,只需取消提交/取消暂存它们。

- git revert -n <commit> 

但这会撤消更改。

- git rebase drop <commit> 

但这会丢弃整个提交。

我正在寻找 rebase 的回放/--continue,但是软重置的可编辑性。有没有办法做到这一点?

谢谢

【问题讨论】:

    标签: git commit rebase history revert


    【解决方案1】:

    我会推荐:

    git rm -- file_2 file_3
    git commit
    

    这会创建一个删除这两个文件的新提交。历史没有改变。

    要恢复工作树中的两个文件:

    git checkout HEAD^ -- file_2 file_3
    git reset HEAD -- file_2 file_3
    

    git checkout 恢复文件,git reset 将它们从暂存区域中删除,这样您就不会提交它们。

    或者,如果您尚未将这些提交推送到共享存储库,并希望更改历史记录,请使用 git rebase -i

    git rebase -i HEAD~n #n should be one more than the number of commits to change
    #mark commit A to edit 
    git reset -- file_2 file_3 # remove file_2 and file_3 from staging so they won't be committed
    git commit --amend
    git rebase --continue
    

    我相信这会将 file_1 和 file_2 留在您的工作树中。如果没有,它们可以使用上面的 git checkout 从你的 pre-rebase 提交中恢复。

    【讨论】:

    • 谢谢,我明白这是在做什么。但就我而言,我有 50 个文件要取消提交。我想在提交给提交 A 之前“及时返回”查看提交 A 的所有暂存文件。然后我可以选择性地(重新)提交我想要的文件。这是可能的还是对 git 的要求太高了?
    • 这是可能的。执行git reset -- . 取消暂存所有内容,然后执行git add -- &lt;files to add&gt;,然后执行git commit --amendgit rebase --continue
    • 感谢您的快速回复,@DavidSugar!我刚试过git rebase -i HEAD~n -> 编辑提交。我收到消息:You can amend the commit now, with git commit --amend Once you are satisfied with your changes, run git rebase --continue,然后运行git reset -- .,但没有未暂存的文件。这是我在发布之前尝试过的事情之一,但我不确定我在做什么。我错过了一步吗?我做错了吗?
    • 对不起..应该是git reset HEAD^ --. 您想将文件重置为上一次提交——而不是当前提交(这将导致暂存区域中的这些文件没有更改)。
    • 完美,非常感谢! :) 这创建了新的暂存文件,这些文件撤消了已提交的文件,同时保留了未暂存文件中的原始更改。我能够git commit --amend 并保留更改的文件。
    猜你喜欢
    • 2012-04-28
    • 2021-09-17
    • 2012-08-26
    • 2018-10-04
    • 2016-07-05
    • 2014-07-12
    • 2020-12-15
    • 2018-12-07
    相关资源
    最近更新 更多