0

I accidentally committed a line of code that was not meant to be part of the commit.

class Engine {
    x: X
    protected _events: Event // <-- this line was accidentally included
    y: Y

the committed version needs to instead be

class Engine {
    x: X
    y: Y

I have already made more commits afterwards, so doing git reset and manually re-staging is not tenable.

Following another post, I attempted this command

git filter-branch --tree-filter 'sed -i "/protected _events: Event/ d" src/engine/Engine.ts' -- --all

but receive the following error

WARNING: git-filter-branch has a glut of gotchas generating mangled history
         rewrites.  Hit Ctrl-C before proceeding to abort, then use an
         alternative filtering tool such as 'git filter-repo'
         (https://github.com/newren/git-filter-repo/) instead.  See the
         filter-branch manual page for more details; to squelch this warning,
         set FILTER_BRANCH_SQUELCH_WARNING=1.
Proceeding with filter-branch...

fatal: bad revision '_events:'

What is going wrong?

Michael Moreno
  • 947
  • 1
  • 7
  • 24
  • Why not just do another commit with the line removed? – Andy Preston Apr 17 '23 at 08:37
  • @AndyPreston because that still leaves the original commit with the unrelated line. I'm a proponent of [semantic commits](https://nitayneeman.com/posts/understanding-semantic-commit-messages-using-git-and-angular/); If I make a commit labeled `refactor`, then only changes involved in that refactor should be included in the commit- that's what the commit conceptually represented, so allowing unrelated changes to be included is disorganized/misleading/impure. When I `checkout` or review commits, the only changes that I should see are changes that were part of that commit's identity. – Michael Moreno Apr 17 '23 at 09:05

1 Answers1

3

filter-branch for removing a line from a file on a commit? That's more than an overkill (not to bring up that upstream recommends to use git filter-repo instead of filter-branch these days... still a big overkill)

Just run git rebase -i the-commit-i-want-to-change~ (make sure to use the pigtail!!!). Set the action for the first commit (which should be the one you want to modify) to edit. Save an exit. Git will stop on that commit. Modify the file and leave it the way you want it to be.

git add the-file
git commit --amend --no-edit
git rebase --continue

And now you have history the way you wanted. Disclaimer: I am assuming the branch you are working on a straight-line branch, at least past the commit you want to modify.

eftshift0
  • 26,375
  • 3
  • 36
  • 60