Richard Haven
Richard Haven

Reputation: 143

git: How to get more information (when, sha) about a branch merging into another?

I found git branch -r --merged master to see all the branches ever merged into master

Our flow is pretty standard: develop == feature branch --> develop == release branch --> master ("==" create a branch from; "-->" PR into)

I want to find out when the branch merged (or the latest sha) in order to generate a list of branches merged since the last PR into master

Ideally, we would have an inventory of each release branch

Cheers

Upvotes: 1

Views: 85

Answers (2)

Richard Haven
Richard Haven

Reputation: 143

I found a good solution for me:

I compare the release branches against each other

import sys
from subprocess import run, PIPE, CompletedProcess

if len(sys.argv) > 1:
    branch1 = sys.argv[1]
else:
    branch1 = "master"

if len(sys.argv) > 2:
    branch2 = sys.argv[2]
else:
    branch2 = "develop"


base_command = ["git", "branch", "-r", "--merged"]

branch2_command = base_command + [branch2]
process_result : CompletedProcess = run(branch2_command, stdout=PIPE, check=True)
branch2_result = process_result.stdout.decode("utf-8")
branch2_list = branch2_result.split()

branch1_command = base_command + [branch1]

process_result : CompletedProcess = run(branch1_command, stdout=PIPE, check=True)
branch1_result = process_result.stdout.decode("utf-8")
branch1_list = branch1_result.split()


result = [item for item in branch2_list if item not in set(branch1_list)]

print(branch2 + " minus " + branch1 + " is\n" + "\n".join(result))

if I compare origin/release/1 to origin/release/2, I get the new stuff in release/2

Cheers

Upvotes: 0

IMSoP
IMSoP

Reputation: 97996

"git branch" is probably the wrong tool for this job: it will only tell you about branches that still exist, and merged feature branches aren't something you particularly need lying around.

Its definition of "merged" also can't tell you "when" - it just means there's at least one path working backwards from "master" that gets you to the current tip of that branch. (A commit is never really "on" a branch in git; a branch only exists as a pointer to a single commit, and from there to its entire history.)

A different approach to the problem is this:

git log --first-parent master..develop

As long as the only commits that get into develop are merge commits - no fast-forward merges or direct commits to that branch - this will give you a list of them.

  • The --first-parent stops it listing out the individual commits from each feature merged in.
  • The master..develop notation means roughly "everything on develop that's not also on master". (Again, "on" actually means "reachable from the current tip of".)

You can use the --pretty option to customise exactly what gets shown here. I frequently use it with --pretty='format:%s' which just shows the commit message on the merge commit.

Upvotes: 1

Related Questions