A dangling commit is a commit which is not associated with reference, i.e., there is no way to reach it.
For example, consider the diagram below. Suppose we delete the branch featureX without merging its changes, then commit D will become a dangling commit because there is no reference associated with it. Had it been merged into master, then HEAD and master references would have pointed to commit D and it would not be dangling anymore, even if we deleted featureX. Read the note after the diagram to understand this better.
Git automatically garbage collects i.e. disposes dangling commits. We can use the git reflog
to recover a branch (of dangling commits) which was deleted without merging it. We can recover deleted commits only if it is present in local object store. If it was garbage collected, then we can't recover it.
NOTE that a branch name i.e. a branch label is actually a reference to the latest commit on a branch or the tip of the branch. In the diagram above, featureX, master and HEAD are just references to specific commits. featureX and master labels refer to latest commits on their respective branches. HEAD generally refers to the tip of the currently checked out branch (master in this case). If you checkout an older commit on your current branch, then HEAD will be in a detached state, i.e., it will point to the older commit instead of the latest one. Also note that HEAD is called a symbolic reference because it actually points to the current branch label and any branch label always points to the tip of the branch. So, under normal circumstances, HEAD indirectly points to the latest commit.
As an aside, note that Git represents its commit graph/history as a directed acyclic graph. Each commit has a reference to its parent. Hence, the arrows in a commit diagram point from child commit to parent commit. We need a reference to the latest child commit in order to reach the older commits on a branch.
PS - The above diagram and understanding was obtained from this free course. Even though the course is quite old, the knowledge is still relevant.
git gc
, and 2) I don't need to worry about this at all because these dangling bits are normal and git already handle's them? – Learn