Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

git reset on intermediate commit: is the last commit really lost?

I have a branch2 branching from another branch1 with no additional commits on branch1
so the branch tree is actually linear.

Now I found out that the last commit in branch1 should be actually the first commit of branch2.
So I think it would be save to command git reset --hard HEAD~.
In the documentation, we find, that the commits after are lost,
but I think because we have branch2, this is not true in the given scenario.

To be sure, I would like to get the opinion of the community.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are right, nothing is lost. To understand why, it’s worth knowing a bit about how git works:

  • In git, a "branch" is actually just a named pointer to a single commit.
  • Each commit has a pointer to its "parent" (or, for a merge, more than one) pointing.
  • When we talk about commits being "on a branch", it’s technically more accurate to say they are "reachable from a reference"; e.g. "commit abc123 is on branch1" actually means "if you start at the commit referenced by branch1, and follow "parent" pointers backwards, you will at some point reach commit abc123".

What git reset --hard does (as well as discarding uncommitted changes, which is permanent) is change the named reference to point to a different commit.

The warning is that this might leave the previous commit "unreachable" – that is, not in the history of any named branch or tag. Periodically, unreachable commits are "garbage collected", and deleted from the database. Until then, they can still be accessed if you know their hash, or find it somewhere like git reflog

In your case, all the commits reachable from branch1 are also reachable from branch2, so nothing will become unreachable.

You are changing a history like this:

a <- b <- c <- d <- e <- f
          ^              ^
       branch1        branch2

To one like this:

a <- b <- c <- d <- e <- f
     ^                   ^
   branch1            branch2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading