gitgit-branchgit-commitgit-revert

Revert changes in Git "main" to prior commit, after branching out with all changes since in "new-branch"


I erred by working locally on a local repo's "main" branch, instead of branching out with a new branch and modifying code there. I brought more modifications to the code than I thought I would, all without pushing anything to remote "origin". A quick $ git reflog --date=iso | grep pull yielded the hash that corresponds to the pull from "origin/main", from which I should have branched out in the first place (and didn't), say it's "D".

Before restoring my local "main" to the prior state of interest, "D", I created a "new-branch". Now I have:

         E' (new-branch)
        /   
B--D--(E)   (main)

So currently E' reflects all changes locally made to D. What I would like is to end up with all changes reflected in E' to be as if they :

     E'     (new-branch)
    /   
B--D--      (main)

Not sure that the two schematics above are fully correct representation. In any case it's all local. Would doing

$ git checkout main
$ git checkout -b new-branch
$ git checkout main
$ git reset --soft <sha1_for-D>

revert all changes to previous state "D" on my local "main", while preserving changes stored in "new-branch" as "E'". But is this strictly equivalent to

$ git checkout main
$ git switch -c new-branch
$ git checkout main

as suggested here?

Continuing to work on "new-branch" will eventually lead to a merge into "main" after testing. Will that future "merge" unfold any differently from a merge that would have occurred with no soft reset on "main" ?


Solution

  • Your chart is a bit misleading, as there seems to be no commit E'. After git checkout -n new-branch both branches point to the same commit E like this:

    C--D--E (main) (new-branch)
    

    If you then checkout main and reset it to commit D as you proposed this will result in

         E (new-branch)
        /
    C--D   (main)
    

    You might want to consider using git reset --hard or at least switch back to the new-branch immediately after the reset to not have this somewhat confusing state of the repository with lots of uncomitted local changes that git reset --soft leaves behind.