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.
>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
abc123is onbranch1" actually means "if you start at the commit referenced bybranch1, and follow "parent" pointers backwards, you will at some point reach commitabc123".
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