Torek's answer is definitely better (and simple!), but for the sake of completeness, I wanted to add a few alternative (some naive) solutions to this problem.
Solution 1: Reverse Patch (naive, compared to Torek's solution)
This is very similar to Torek's solution. To undo the changes to a specific file that were made by a specific commit, just get a reverse diff of that commit by reversing the arguments to git diff
:
git diff <commit> <commit>^ -- <filepath> | git apply
Normally, to get the changes introduced by <commit>
, you use the order
git diff <commit>^ <commit>
but by reversing the order, you end up getting the inverse of those changes, which is a valid diff that can be used as a patch!
Solution 2: Revert All Files, then Only Commit Changes to Specific Files (very naive)
A more naive solution would be to revert the commit that added the changes that you want to undo, but don't commit the revert. Then just remove all the changes to the other files from the index and working copy:
git revert --no-commit <commit>
# Unstage all changes that revert all files
git reset -- .
# Stage and commit just the reversion changes that you want
git add <yourFile>
git commit -m "Revert changes to <yourFile> from <commit>"
# Undo all reversions changes to the other files
git checkout -- .
This is necessary because git revert
doesn't revert changes to individual files, it currently only reverts entire commits.