Search code examples
gitversion-controlgit-fetch

git remove single line from file in git history


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?


Solution

  • 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.