如何在上一次提交中恢复对 1 个文件的更改

How to revert changes to 1 file in previous commit

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

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

编辑: 我最终只是手动 "reverting" 通过编辑 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