How to rewrite the commit history in Git?
Opened this issue · 0 comments
BensonLiao commented
As the blog #4 mentioned, none of those command are really do rewrite commit history.
And of course we can do with reset <commit-sha-id> --hard
but it only do delete, what if we want to alter it?
Yes! git filter-branch
*Be careful about the so call nuclear-grade option
A general use case are to change committer information like author name or email:
git filter-branch -f --env-filter "if [[ \$GIT_AUTHOR_EMAIL = 'myname@myname-MacBook-Pro.local' ]]; then GIT_AUTHOR_EMAIL=myname@gmail.com; fi" HEAD
or git filter-branch -f --env-filter "if [[ \$GIT_AUTHOR_EMAIL = 'myname@myname-MacBook-Pro.local' ]]; then GIT_AUTHOR_NAME=myname; GIT_AUTHOR_EMAIL=myname@gmail.com; fi" HEAD
or git filter-branch -f --env-filter "if [[ \$GIT_AUTHOR_EMAIL = 'myname@myname-MacBook-Pro.local' ]]; then GIT_COMMITTER_EMAIL=myname@gmail.com; fi" HEAD
or whatever config you want to set.
Then if you run git status
, you'll see the following message:
On branch feature/refactor
Your branch and 'origin/feature/refactor' have diverged,
and have 19 and 19 different commits each, respectively.
(use "git pull" to merge the remote branch into yours)
nothing to commit, working tree clean
So if you want to push to remote branch after one or more command, use git push -f
to force update or you'll see Git rejected:
! [rejected] 1.5.0 -> 1.5.0 (non-fast-forward)
error: failed to push some refs to 'git@github.com:/xxx/.git'
To prevent you from losing history, non-fast-forward updates were rejected
Merge the remote changes (e.g. 'git pull') before pushing again. See the
'Note about fast-forwards' section of 'git push --help' for details.