libgit2sharp
libgit2sharp copied to clipboard
How to find if a branch is merged into another branch?
Is this sort of feature already implemented into libgit2sharp?
This is basically git branch --merged
Hi below is my solution it seems to work:
using (var repo = new Repository(@"repoPath"))
{
//Get reference of head
var headRef = repo.Refs.Where(r => r.CanonicalName == repo.Head.CanonicalName);
//get only local branches
foreach (var branch in repo.Branches.Where(d => !d.IsRemote))
{
//check if local branch tip is rechable from HEAD
var refs = repo.Refs.ReachableFrom(headRef, new[] { branch.Tip });
if (refs.Any())
{
//This branch was merged
}
}
}
Can anyone can look at it? Maybe i should create PR for documentation update?
how about to find the source branch tip.sha in target branch commits ?
string sourceSha = sourceBranch.Tip.Sha; var commit = targetBranch.Commits.Where(p => p.Sha.Equals(sourceSha, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); if (commit != null) { return true; } return false;
@norek I found this really slow to execute until I added ToList()
onto the end of the line that gets the ref of the head.
var headRef = repo.Refs.Where(r => r.CanonicalName == repo.Head.CanonicalName).ToList();
To check if, for example, a feature was merged to main
, do this:
var repo = new Repository(@"YOUR REPO PATH");
var main = repo.Branches["origin/main"];
var feat = repo.Branches["YOUR FEATURE BRANCH NAME"];
var isMerged = repo.Refs
.ReachableFrom(new[] { main.Reference }, new[] { feat.Tip })
.Any();
⚠️ Don't use:
var isMerged = main.Commits.Any(commit => commit == feat.Tip);
because even though it also works, it's much less efficient, and the efficiency will get even slower with growing number of commits in main
. For example, in my repository with 525 commits .Any()
was already 50 times (!) slower than .ReachableFrom()
.
Hi below is my solution it seems to work:
using (var repo = new Repository(@"repoPath")) { //Get reference of head var headRef = repo.Refs.Where(r => r.CanonicalName == repo.Head.CanonicalName); //get only local branches foreach (var branch in repo.Branches.Where(d => !d.IsRemote)) { //check if local branch tip is rechable from HEAD var refs = repo.Refs.ReachableFrom(headRef, new[] { branch.Tip }); if (refs.Any()) { //This branch was merged } } }
Can anyone can look at it? Maybe i should create PR for documentation update?
this worked for me and Ok.