git: Why is it so difficult to get the parent branch name?

245 Views Asked by At

It is difficult to find the parent-branch in git ...

My current solution:

git show-branch -a 2>/dev/null \
| grep '\*' \
| grep -v `git rev-parse --abbrev-ref HEAD` \
| head -n1 \
| perl -ple 's/\[[A-Za-z]+-\d+\][^\]]+$//; s/^.*\[([^~^\]]+).*$/$1/'

Source: https://stackoverflow.com/a/74314172/633961

Why is it difficult to find the parent-branch in git?

This question is not about "how to solve this?". It is about "why is it not straight forward?"

2

There are 2 best solutions below

1
LeGEC On BEST ANSWER

git doesn't store anything about branches.

A commit is an object which points to its parent, and you will have a relationship between commits, but a branch is just a name that points to a commit -- a shallow reference with no extra data.

In standard git, there is no information stored which keep track of : "branch x was initially created from y, then was merged with branch z on june 16th, then was reset on that day, then ...".

You can only do guess work based on the current commit graph, and the current state of other branches.

This guess work leads to commands such as the one you quoted.

You should also note that depending on the way you manage branches in your own repository, some of these commands may work for someone else but not for you.

1
Adam On

It's worth reading; https://git-scm.com/book/en/v2/Git-Internals-Git-References.

Then take a look at the content of .git/refs/heads/master or any equivalent file in that folder. It's just a file containing a commit hash. That's what a branch is.

The point is that the original commit hash or ref is not stored for a branch. Only the current commit hash is stored for the branch.