devroom.io/content/post/2012-09-04-git-interactive-revert.md

63 lines
1.8 KiB
Markdown
Raw Normal View History

2017-03-20 15:35:19 +00:00
+++
date = "2012-09-04"
title = "Git: Interactive Revert"
tags = ["git", "protip"]
slug = "git-interactive-revert"
+++
2015-03-26 11:28:08 +00:00
I recently made a commit in a project that, mistakenly, included changes to `db/schema.rb`. My local schema was out of date and this could cause trouble for the others in my team.
Luckily we use [a successful git branching model][1] so my changes were still up for review by the team.
The change I made was part of larger commit. But all I wanted was to revert serveral chunks from `db/schema.rb` that would cause trouble.
## Interactive add
Now, there's `git add -i` which allows you to selectively stage chunks for the next commit. Unfortunately, the process for reversing interactively is a bit more complicated, but not much.
## Interactive revert
Well, let's say you want to revert changes you made in commit `f1e11c`. Go to your feature branch and revert your changes for that commit <em>but do not commit them yet</em>, hence the `-n` option:
2017-03-20 15:35:19 +00:00
``` shell
git revert -n f1e11c
```
2015-03-26 11:28:08 +00:00
Your working copy now contains staged changes to revert the entire `f1e11c` commit. You don't want to revert everything, so unstage all those changes.
2017-03-20 15:35:19 +00:00
``` shell
git reset
```
2015-03-26 11:28:08 +00:00
The key now is to interactively <em>stage the changes you want to revert</em>. You can do this like this:
2017-03-20 15:35:19 +00:00
``` shell
git add -p
```
2015-03-26 11:28:08 +00:00
or
2017-03-20 15:35:19 +00:00
``` shell
git add -i
```
2015-03-26 11:28:08 +00:00
Choose whichever suits you.
In my case I staged only the chunks that related to the changes in `db/schema.rb` that I wanted to revert.
With your reverting changes staged, commit them.
2017-03-20 15:35:19 +00:00
``` shell
git commit
```
2015-03-26 11:28:08 +00:00
You're now left with reverting changes you didn't want to make. Just throw them away.
2017-03-20 15:35:19 +00:00
``` shell
git reset --hard
```
2015-03-26 11:28:08 +00:00
And that's all. You have now selectively reverted a commit.
2017-03-20 15:35:19 +00:00
[1]: http://nvie.com/posts/a-successful-git-branching-model/