This question is the continuation of this question, As requested I have raised this as a separate question.
How to check whether a commit is present in a Branch in Azure Dev Ops?
Is there any efficient way to get the latest commit of a particular branch using this package?
The below is a C# demo, it should achieve your requirement:
using Microsoft.TeamFoundation.SourceControl.WebApi;
using Microsoft.VisualStudio.Services.Common;
using Microsoft.VisualStudio.Services.WebApi;
using System;
using System.Collections.Generic;
using System.Linq;
namespace CheckWhetherCommitExistInCurrentBranch
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Uri orgUrl = new Uri("https://dev.azure.com/xxx/"); // Organization URL
string project = "xxx";
string repository = "xxx";
String personalAccessToken = "xxx";
string branch_name = "xxx";
var commitref = GetLastestCommit(orgUrl, personalAccessToken, project, repository, branch_name);
Console.WriteLine("The latest commit id is: "+commitref.CommitId);
}
//get lastest commit
public static GitCommitRef GetLastestCommit(Uri orgUrl, string personalAccessToken, string project, string repoId, string branchName)
{
List<string> branches = new List<string>();
VssConnection connection = new VssConnection(orgUrl, new VssBasicCredential(string.Empty, personalAccessToken));
GitHttpClient gitClient = connection.GetClient<GitHttpClient>();
var commit = gitClient.GetCommitsAsync(project: project, repositoryId: repoId, new GitQueryCommitsCriteria()
{
ItemVersion = new GitVersionDescriptor()
{
Version = branchName,
VersionType = GitVersionType.Branch
},
Top = 1
}).Result.FirstOrDefault();
return commit;
}
}
}
Works Successfully on my side: