Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

git selective revert local changes from a file

I believe you can do it most simply with:

git checkout -p <optional filename(s)>

From the manpage:

   −p, −−patch
       Interactively select hunks in the difference between the <tree−ish>
       (or the index, if unspecified) and the working tree. The chosen
       hunks are then applied in reverse to the working tree (and if a
       <tree−ish> was specified, the index).
       This means that you can use git checkout −p to selectively discard
       edits from your current working tree.

You can do that directly with git checkout -p. See Daniel Stutzbach's answer below.


Old answer (before checkout -p was introduced):

You can do it like this:

git add -i

(select the hunks you want to keep)

git commit -m "tmp"

Now you have a commit with only the changes you want to keep, and the rest is unstaged.

git reset --hard HEAD

At this point, uncommitted changes have been discarded, so you have a clean working directory, with the changes you want to keep committed on top.

git reset --mixed HEAD^

This removes the last commit ('tmp'), but keeps the modifications in your working directory, unstaged.

EDIT: replaced --soft with --mixed, to clean up the staging area.


You could run git diff on the file, save the resulting diff, edit it to remove the changes you do want to save, then run it through patch -R to undo the remaining diffs.

git diff file.txt >patch.tmp
# edit patch.tmp to remove the hunks you want to keep
patch -R <patch.tmp

Looks like you want

 git revert --no-commit $REVSISON 

You can then use

 git diff --cached

to see what change will be made before commiting ( as reverting is just a commit in a forwards direction that replicates the inverse of a change in the past )

If you were with a pure Git repository, you could possibly, depending on your goals, utilise interactive rebase (git rebase -i) to go back to the commit you didn't like and edit the commit retroactively so that the changes you don't like never happened, but thats generally only for if you KNOW you'll never want to see it again.