Search code examples
tfsazure-devops-rest-apitfs-workitemtfs-sdktfs-aggregator

How access message of git commits from Microsoft.TeamFoundation.WorkItemTracking.Client?


I'm using TFS 2017 update 1 on premises. I'm using #ID in log comments of commits in order to associate workitem ID (of User Story, Task etc.) with GIT commits of source code. It properly works (I can see links to commit from workitem interface).

I'd like to use TFS SDK API with tfs aggregator in order to better manage GIT commits (e.g. automatic transition to custom state of workitem when a specific custom git commit message is done by programmers).

How can access message/log of git commits from Microsoft.TeamFoundation.WorkItemTracking.Client in order be able to parser custom message in addition to those described here (e.g. "Fixes #123" or "Close #123")?


Solution

  • You can't get the commit comment only with WorkItemHttpClient, you can get it along with GitHttpClient. first of all get the work item links with WorkItemHttpClient, than get the commit id and get the comment with GitHttpClient.

    A working example:

    VssClientCredentials cred = new VssClientCredentials();
    VssConnection tfs = new VssConnection(new Uri("http://tfs-server:8080/tfs/collection"), cred);
    var workItemClient = tfs.GetClient<WorkItemTrackingHttpClient>();
    var gitClient = tfs.GetClient<GitHttpClient>();
    int workItemId = 1213;
    
    var workItem = workItemClient.GetWorkItemAsync("Project-Name", workItemId, expand: WorkItemExpand.Relations).Result;
    // We need to retrieve the commit id from the links, debug the following line to understand what I did
    var commitId = wit.Relations.Where(r => r.Url.Contains("Git")).FirstOrDefault().Url.Split('%')[2].Remove(0,2);
    var commit = gitClient.GetCommitAsync("Project-Name", commitId, "Repo-Name").Result;
    string comment = commit.comment;
    

    By the way, you can't use the Fixes #123 syntax because is not supported in TFS 2017.