MKPC MKPC - 1 year ago 86
Git Question

Git rebase in detached HEAD state - what to do if I want to correct file in history and replace one in latest commit

I got quite confused with all merging and rebasing commands and got couple of errors. Given project is just for myself. My problem is following:

My commits in master, origin/master branch (from latest, all publicly visible):

Commit 4 - test_data.txt commited, same file as in commit 2
Commit 3 - revert of commit 2, code.txt bug found, state of commit 1
Commit 2 - code.txt test_data.txt changed
Commit 1 - Everything fine

Now, with given history I found out the bug in code.txt. I
git checkout commit 2
and I want to make a commit 5 with corrected code.txt and original test_data.txt(included in both commit 2 and commit 4).

My question:
Is there something what I did wrong in given history/log?
What should I do now? I checked out commit 2, fixed the bug and made a commit, but couldnt push in into master branch (commit 5 was from detached HEAD). Even if I merged commit 5 and commit 4 (successfully), I couldnt puch it to master. But my main question is, what should be the proper way to handle this situation?

Thank you

Answer Source

Because you've pushed commits to the master branch of a publicly available repository, then it's ill advised to rewrite history. You should make commit 5 fix on top of 4 and let 2-4 continue to have the bug in history.

However, to answer your question:

Checkout the branch tip and do an interactive rebase.

git rebase -i <commit 1>

Change pick to edit on commit 2. Make your changes, then continue.

git rebase --continue

Now history has been rewritten and you will need to force push the branch.

git push origin master --force

And because of these shenanigans, others will have to force update.

git fetch origin
git reset --hard origin/master
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download