I committed changes that added some code and deleted some code. Now, I want to undo this. There are other changes in the file (along with other files changed in the commit) which I don't want undone, so a standard git revert will not do. What I want is to create a commit that undoes these select changes by providing the line numbers. And preferably a technique which allows me to use my GUI client (Github Desktop) to select the changes / line numbers in the diff. How would I go about this?
Asked
Active
Viewed 1,823 times
4
-
By undo, do you mean to create something similar to a revert commit that only reverts those lines, do you mean you want to get rid of the original commit in the first place, or do you mean you want to change the original commit to not change those lines, but change all the other ones it also does? – Lasse V. Karlsen Jun 07 '17 at 21:12
-
i mean the revert way. created a new commit which undoes those selected changes. – Alex Bollbach Jun 07 '17 at 21:21
-
If the answer help you solve the problem, please mark it. And it will help others who have similar questions. – Marina Liu Jun 21 '17 at 09:26
2 Answers
2
There are probably a number of ways to achieve this but I'd go with something like:
# stage a revision of the given commit without making a commit of this revision
git revert -n <hash-of-commit-to-partially revert>
# Unstage these changes so the revision is only in the working tree
git reset
# Selectively stage only the parts which make the revisions which you want
git add -p <path-of-interest>
# Optional: discard other changes from the working tree for testing
# (you might need to "git clean" if you are discarding the revision
# of a change that originally removed a file)
git checkout -- .
# Commit the selected revision
git commit
-
thanks. this will most likely work for me. especially by allowing me to selectively re-add changes to the index in a GUI client. however, i feel for a difference case, say, where i have many files changed and all i want to do is change one line. i'd have to add all but that one line. seems inefficient. – Alex Bollbach Jun 07 '17 at 21:23
-
@AlexBollbach: Even for this case, I'd probably follow the same procedure. It's only the `add -p` that is expensive (in human time) if you have a lot of changes and you can still restrict it to the one file that you are interested in and quickly skip over the chunks which you are not interested in. – CB Bailey Jun 07 '17 at 21:26
-
i get a merge conflict when i revert the commit btw, presumably because its undoing code on the same lines – Alex Bollbach Jun 07 '17 at 21:29
-
@AlexBollbach: That probably means that some commit between the one which you are reverting and the current commit has touched the same lines as the change which you are reverting. You have to resolve the commit, although if the conflict only affects the parts of the reversion that you are discarding, you wouldn't have to do this "correctly". – CB Bailey Jun 07 '17 at 21:48