Home > database >  Git - How to change one line of source code of an old commit and propagate changes to all upstream c
Git - How to change one line of source code of an old commit and propagate changes to all upstream c

Time:01-07

The situation is that I have a repository with .cs file containing a test string equal to a curse word. Like:

string test = "very bad curse word";

and it was added to repository on 5th commit but then 1000s more commits were made.

It's not an option to simply change that word and make a new commit because that bad word will still be in all previous commits.

Maybe there is some sort of special rebase or other git technique where I can go back to that initial problematic commit where that test string was created originally, change only that commit, make a rebase and that word would be gone forever?

CodePudding user response:

This is definitely a bad pratice! .. however, if you really want to do that, then you can edit the concerned commit by running an interactive rebase and rewriting your git history.

First get the SHA1 of the commit right before the concerned one and do: git rebase -i SHA1. Then in the rebase editor, change the first word from pick to edit (or e) on the line indicating the commit you want to change (it should be the very first line). Save and exit.

From there, modify your file and run git add -u to add it to staged changes. Then, run git commit --amend, git rebase --continue to complete the rebase (be aware that, depending on the changes, you may have to resolve conflicts).

Finally, run git push -f origin master (assuming your branch is master) to upload your changes to the remote.

!!! NOTE: the option -f tells git to force push to the remote. Since you rewrote the whole history from the changed commit:

  • your co-workers will no longer be able to push to the remote. I mean, they will have to retrieve the forced changes first.
  • you will lose any tags you made.
  • maybe aome other "cons" ..

This is really a bad practice and not something to go easy with. Think twice before doing such things ..

  • Related