david
david

Reputation: 33627

How do I reverse a specific hunk of a commit in git?

I'm wondering if there is a way to quickly reverse specific hunk of a commit.

I can generate a diff between two commits or HEAD to see the difference.

How do I reverse just one of those hunks (or better yet, a set of specific hunks)?

Upvotes: 48

Views: 15110

Answers (5)

David
David

Reputation: 2930

The way I like to do this is to use:

  1. git rebase -i HEAD~n where 'n' is the number of commits back.
  2. Use 'edit', on the commit you want to remove the hunk from.
  3. Follow this with git add -p or manual edits.
  4. git commit --amend.
  5. git rebase --continue to end the rebase.

Upvotes: 1

kxr
kxr

Reputation: 5548

To revert one or more hunks from specific commit(s) do like this - using add -p in essence:

git revert --no-commit <commit>…​ 
git reset                              # unstage things
git add -p [OPTIONS] [<pathspec>…​]     # choose hunks interactively
git restore .                          # wipe the rest (in root directory)
... maybe further changes ...
git commit [--fixup] ...

Future git versions may support git revert -p directly...

Note: Methods like git checkout/restore -p ... do not consistently revert hunks from a specific commit but go to pick parts from a certain file state - possibly loosing changes in other later commits.

Upvotes: 4

cdhowie
cdhowie

Reputation: 169353

git checkout -p $REF -- path/to/file

e.g.,

git checkout -p HEAD^ myfile

Where $REF is a ref name or commit ID that specifies the commit you want to take the file state from. For example, to selectively revert changes made in the last commit, use HEAD^.

Upvotes: 53

erik
erik

Reputation: 2446

git difftool $REF -- /path/to/file

where $REF is a ref name or commit ID that specifies the commit you want to take the file state from. For example, to selectively revert changes made in the last commit, use HEAD^.

This question was already answered by @cdhowie, but I find it somewhat nicer to use an interactive difftool like meld to selectively restore old hunks/lines of code, especially if there is a newly-introduced, hard-to-find bug in the code.

Upvotes: 2

John Naegle
John Naegle

Reputation: 8257

To recover a deleted file from a previous commit I used the answer here:

Find and restore a deleted file in a Git repository

git checkout <deleting_commit>^ -- <file_path>

Upvotes: 0

Related Questions