1

I have several commits C1 -> C2 -> C3 -> C4 (the last)

The features added to C4 are aborted for my project.

I got C3 by typing

git checkout <commit_id> 

and made some changes on it

I'm now in a DETACHED mode.

I would like to commit and push C3 modified on top of history

C1 -> C2 -> C3 -> C4 -> C5 (= C3 modified)

What's the best way to do that ?

buddemat
  • 4,552
  • 14
  • 29
  • 49
  • 1
    You should never `git checkout ` unless you know what you're doing; that (as you rightly say) is a detached head. If you wanted to "undo" C4, you should have done a `git revert` of C4, or even a `git reset` back to C3. – matt Nov 09 '20 at 19:34
  • See also - https://stackoverflow.com/questions/8824971/how-to-amend-older-git-commit, https://stackoverflow.com/questions/1186535/how-to-modify-a-specified-commit – RJFalconer Nov 10 '20 at 00:44

1 Answers1

1

From your current detached HEAD state, you could create a branch, then reset the original feature branch to that new branch:

# from detached HEAD
git branch new_feature
git checkout feature
git reset --hard new_feature
git push --force origin feature

Note that we have to force push your feature branch, because we have rewritten its history.

However, you also could have completely avoided even going to a detached HEAD state by just nuking the C4 commit, modifying the C3 commit, and adding the other commits:

# from feature
git reset --hard HEAD~1
# make changes to C3
git commit --amend
# make commits C4 and C5
git push --force origin feature
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • Thx for answer. In your example "feature" is equal to C4 in my example ? Right ? –  Nov 09 '20 at 16:05
  • No. `feature` is the name of your current branch. – Tim Biegeleisen Nov 09 '20 at 16:05
  • But all the commit (C1 to C4) are already on the same branch. Sorry for my question but I'm a newbee ! –  Nov 09 '20 at 16:26
  • 1
    I can't explain any more clearly than I have above without including diagrams for each step, and I don't have time for that now (and it would be too much information for a basic Git question). – Tim Biegeleisen Nov 09 '20 at 16:54