如何在以前的提交中将更改还原为 1 个文件



最好使用SourceTree或简单的git命令,我将如何在以前的提交中撤消对1个文件的更改。换句话说,如何撤消提交,但仅适用于已提交的许多文件中的一个?

希望避免必须撤消整个提交,然后重新提交除 1 个文件之外的所有更改。

编辑:我最终只是通过编辑手动"还原"1 文件。但是得到了 2 个好看的答案,我会选择似乎在更多情况下有效的答案。

做:

git revert <commit> --no-commit     #reverts the whole commit, putting changes in index and working dir
git reset HEAD .                    #clears index of changes
git add <fileyouwanttorevert>       #adds changes to that one file to index
git commit -m "Reverting the file"  #commits that one file's changes
git checkout .                      #gets rid of all the changes in working directory

如果您希望撤消最新的提交并且尚未推送,则可以发出以下命令:

git checkout HEAD^ -- <file_path>  # revert and stage the problematic file
git commit --amend                 # edit the latest commmit

要在任意提交中还原对文件的更改,

git revert $thecommit              # revert the whole commit
git reset --hard @{1}              # in what turns out to have been a throwaway commit
git checkout @{1} $thatfile        # take what you want

但是,如果不需要的更改在最近的提交中,则可以直接使用

git checkout @^ $thatfile          # restore mainline-parent content

最新更新