Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find first branch on which a git commit was made

How can I find the first branch on which a commit was made? Seems able to do this but I'm not sure how.

It seems like this is not possible in git due to its design which places commits not branches at the center of change tracking.

I can use the following which shows 1st branch + any merges but cannot narrow focus to just 1st commit branch.

git branch --contains --merge <sha1>

returns a list of all branches to which the commit was merged and the 1st branch on which it was merged. --no-merged returns all subsequent branches that include the commit because they branched after the merge point.

So, you can get a list of each merge but not 1st branch on which it was made and any branch deleted prior to command execution is lost (or your looking at reflogs)

Results

git branch --contains <sha1 for "added feature/inital 1">
* develop
  feature/inital
  feature/subsequent1

git branch --contains <sha1 for "added feature/inital 1"> --merged
* develop
  feature/inital

git branch --contains <sha1 for "added feature/inital 1"> --no-merged
  feature/inital

Test Script

function mkbranch {
  git checkout -b $1
  git push --set-upstream origin $1
}

# Develop
mkbranch develop
for f in 1 2 3; do date > file${f}.txt;  git add file${f}.txt; git commit -m "added develop $f"; done
git push

# Initial Feature Branch
mkbranch feature/inital
for f in 1 3; do date > file${f}.txt;  git add file${f}.txt; git commit -m "modified feature/inital $f"; done
git push

# Merge
git checkout -b develop
git merge feature/inital
git push


# Next Feature Branch
mkbranch feature/subsequent1
for f in 1 3; do date > file${f}.txt;  git add file${f}.txt; git commit -m "modified feature/subsequent1 $f"; done
git push
like image 457
Peter Kahn Avatar asked Oct 19 '22 00:10

Peter Kahn


1 Answers

The answer is simply you cannot.
A branch is simply a post-it note that was sticked onto a commit.
You can at any time peel off the post-it and place it somewhere else or throw it away.
So you cannot tell which was the first branch a commit was introduced into.

To be more correct, as long as

  • the branch is not deleted and
  • you are on the system / in the repository where the commit was made
  • and the commit is not longer ago than the reflog timeout (90 days by default)

you can find out, because then you know where the branch post-its where at the time of the commit.

like image 132
Vampire Avatar answered Oct 27 '22 09:10

Vampire