Tallboy
Tallboy

Reputation: 13417

How to "undo" a commit as a new commit?

I've searched to find many answers relating to my question but they don't do exactly what I want, and I'm not sure how else to describe it.

Lets say I make a commit called remove tracking and I remove 10 lines of code.

I want to essentially "undo" this commit but leaving the branch untouched, and leaving the old commit exactly as it is. Almost as if I said "oh I need to undo those changes" and I manually copy and paste from the red parts of the diff and paste them where they need to go, and have those changes be unstaged.

Often times I make lots of undo/redo related to split tests, and this workflow would be much more favorable than actually TRULY "undoing" the commit. I want to really just take the last commit and do the inverse of it and put that into unstaged, and nothing more.

The reason I want it unstaged is because usually after undoing it I need to make further changes to the undo, which is why I dont want an 'actual' undo

Upvotes: 0

Views: 245

Answers (2)

1615903
1615903

Reputation: 34733

This is exactly what git revert does:

Given one or more existing commits, revert the changes that the related patches introduce, and record some new commits that record them.

Use --no-commit flag and use git reset to remove the changes from staging area.

The answer by @eftshift0 works if the commit you want to undo is the previous one. git revert works even if the commit you want to undo is done earlier in the history.

Upvotes: 1

eftshift0
eftshift0

Reputation: 30212

Like "I want to get this file back to how it was on HEAD~"?

git checkout HEAD~ -- the-file
git reset the-file # so that it is out of the index

This is the new approach, if I recall correctly:

git restore --worktree HEAD~ -- the-file

If you need to take the whole thing back instead of a single file, use . instead of the-file in the recipes.

Upvotes: 1

Related Questions