2

Let's say that I have 2 files:

  • App.js
  • Home.js

They are already tracked and exist in first commit. And I add a new feature to App.js on second commit which is maybe a new function and have more commits afterwards and let's say I'm in 10th commit now.

What I would like to do is just remove that function in a new commit without rebasing only in App.js; what should I do in order to achieve this?

Edit

Function is a simple example it's pretty easy to delete those lines and have a new commit. What I want is something more smart and does not need a manual effort. I use VS Code and the GitLens extension; it would be great if there is feature on these tools.

Alexander Nied
  • 12,804
  • 4
  • 25
  • 45
suchcodemuchwow
  • 848
  • 2
  • 9
  • 27
  • Are you looking for `git revert ` ? This creates a new commit, which basically applies the reverse patch of `` – LeGEC Jul 21 '22 at 12:55
  • If you want to revert only **part** of a commit, maybe take a look at [this possible duplicate](https://stackoverflow.com/questions/69677716/how-to-reopen-an-ancient-commit-into-worktree-that-was-reverted-in-a-recent-co). – Romain Valeri Jul 21 '22 at 13:12

1 Answers1

1

One way you could achieve this in the command line:

  1. git revert <commit_number_with_lines_you_want_to_revert>
  2. git reset --soft HEAD~1 to take the reversion commit you just created out of history but keep the changes in your local filesystem
  3. git reset to unstage the reversion changes
  4. Use git add -i to do an interactive staging
    • Choose to patch on the files which have the lines you wish to revert
    • Walk through the patching dialog, selecting "yes" for those you wish to revert and skipping all others
    • If a patch is too large (meaning it contains both lines you want to revert and lines you do not wish to revert) you can "split" or "edit manually" (this is rarely needed, in my experience)
    • When you are done adding the lines you wish to revert, quit the interactive session
  5. Make a new commit with your staged reversion lines
  6. git reset --hard to undo all other local changes

This looks like a lot of steps, but once you get used to the interactive session interface it tends to go pretty smoothly. While it is not as friendly a GUI as GitLens, since it walks you through each local change and allows you to add or skip changes with a single keystroke I would say it counts for relatively low "manual effort".

This is not the only approach; you could probably generate and manually edit a patch from a diff, and I'm sure other users might think up other recipes to accomplish this that may be more elegant or faster. But this should work for your needs.

Alexander Nied
  • 12,804
  • 4
  • 25
  • 45