0

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?"

Pavel Fedotov
  • 748
  • 1
  • 7
  • 29
guettli
  • 25,042
  • 81
  • 346
  • 663
  • 1
    what is a "parent" branch? Is it the branch where a branch is created from? Probably because nothing about that is saved about a branch. A branch is **just** a pointer to a commit. – eftshift0 Nov 04 '22 at 08:55
  • 2
    I think `parent branch` is a false concept. Any ref including branches is a non-persistent reference, as we can rename, delete and recreate it. So, which is the parent and which is the child, is not a fixed relationship. – ElpieKay Nov 04 '22 at 08:55
  • 1
    Because Git is based on the DAG (directed acyclic graph) concept. – Ivan Yuzafatau Nov 04 '22 at 09:53
  • 1
    Because there is no such thing as a parent branch in git. You're asking your car to cook food. – Romain Valeri Nov 04 '22 at 09:58

2 Answers2

2

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.

Adam
  • 4,180
  • 2
  • 27
  • 31
  • As an aside, if the ref was always local then you can use the reflog; https://git-scm.com/docs/git-reflog. This doesn't work for refs that you fetched from remotes. – Adam Nov 04 '22 at 11:54
1

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.

LeGEC
  • 46,477
  • 5
  • 57
  • 104