Reverse Apply a commit to working copy
Asked Answered
R

3

55

In order to investigate the effect introduced by a previous commit, I want to reverse- apply it to my working copy and fiddle around with the code.

I managed with a workflow around creating and applying a patch, but wonder if this can be done easier.

git checkout -b "tmp-fiddle"
git diff -R -p d9fd2bb^ d9fd2bb > patch_to_examine.patch
# Manually edit the patch a little
git apply patch_to_examine.patch

Note that I am not looking at git revert or git rebase -i since these would either introduce a new commit or change the history: I merely want the changes introduced in d9fd2bb to be un-applied to my current working copy.

Roselane answered 17/4, 2013 at 12:16 Comment(2)
What's the manual editing you're doing?Turcotte
That was the patch not applying cleanly; sending warnings about whitespace.Roselane
F
67

How about git revert -n?

-n
--no-commit

Usually the command automatically creates some commits with commit log messages stating which commits were reverted. This flag applies the changes necessary to revert the named commits to your working tree and the index, but does not make the commits. In addition, when this option is used, your index does not have to match the HEAD commit. The revert is done against the beginning state of your index.

This is useful when reverting more than one commits' effect to your index in a row.

Finbur answered 17/4, 2013 at 12:22 Comment(1)
Unfortunately, this works only as long as your working copy has no modifications to any of the files affected by the commit (it can have changes in other files though). I guess, in such case you need git stash; git revert -n <commit>; git stash pop and resolve the conflicts (if any).Loutitia
A
29

Another way that works is git show | git apply -R. -R stands for reverse the diff.

This works with any diffs, so you can do git diff [...] | git apply -R

Or reverse a stash git stash show -p stash@{0} | git apply -R

Adam answered 16/8, 2019 at 6:22 Comment(2)
Fun fact: there is also git show -RSextodecimo
using git show did not work for me. But using git diff <hash> -R | git apply worked.Papilionaceous
P
1

If you are after previous commit(s). Then the simplest way is

git reset HEAD~ -- .

what it does it leaves your working tree intact but changes index to match the previous commit. Git diff and GUI tools will highlight changes and allow you to go through them to remove, revert or change some of the hunks. Subsequent git -a commit --amend / git -a commit will fix either current commit or create a separate fix commit, while git reset --hard will abandon them.

To pick an arbitrary change and leave tree at HEAD.

git revert -n <changeset> # or changeset range
git reset -s HEAD . # restore worktree to the tip (but leave staging as above)
Pocosin answered 30/11, 2020 at 15:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.