Подтвердить что ты не робот

Как программно получить информацию о ветких в TFS?

Мне нужно программно узнать информацию о ветвях в TFS. Например, главное, что мне интересно, это указать корневую папку $/MyProject/Project1. Мне нужно выяснить, какие из других папок были разветвлены. Я сразу после правильных методов API.

Скажем, я подключился к серверу TFS и имею доступ к экземплярам класса VersionControlServer и Workspace.

4b9b3361

Ответ 1

Хорошо, это было легче и сложнее, чем я думал. Мне удалось собрать это из нескольких источников, но это, похоже, работает. Я предупрежу вас, здесь нет обработки ошибок, и если itemSpec не существует, он бомбит исключение.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;

static void Main(string[] args)
{
    TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(
                                            new Uri("http://tfs:8080"));    
    string srcFolder = "$/ProjectName";    
    var versionControl = tfs.GetService<VersionControlServer>();    
    ItemSpec[] specs = new ItemSpec[]{new ItemSpec(srcFolder, RecursionType.None)};

    System.Console.WriteLine(string.Format("Source folder {0} was branched to:",
                                           srcFolder));    
    BranchHistoryTreeItem[][] branchHistory =
        versionControl.GetBranchHistory(specs, VersionSpec.Latest);

    foreach (BranchHistoryTreeItem item in branchHistory[0][0].Children)
    {
        ShowChildren(item);
    } 

    System.Console.WriteLine();
    System.Console.WriteLine("Hit Enter to continue");
    System.Console.ReadLine();    
}

static void ShowChildren(BranchHistoryTreeItem parent)
{
    foreach (BranchHistoryTreeItem item in parent.Children)
    {
        System.Console.WriteLine(
            string.Format("Branched to {0}", 
                          item.Relative.BranchToItem.ServerItem));
        if (item.Children.Count > 0)
        {
            foreach(BranchHistoryTreeItem child in item.Children)
            {
                ShowChildren(child);
            }                       
        }
    }
}

Ответ 2

Код первичного ответа не всегда возвращает все ветки цели. В моем тестировании он вернул еще одну ветку, чем диалоговое окно слияния Visual Studio.

Существует более простой и безопасный способ получить список целевых ветвей. Это то же самое, что Visual Studio получает список для диалогового окна "Слияние":

using System;
using System.Collections.Generic;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;

class Program
{
    static void Main(string[] args)
    {
        string tfsUri = "http://tfs:8080/tfs/MyCollection";
        string tfsItemSpec = "$/MyTeamProject/Folder";

        List<string> branches = GetPathsEligibleForMerge(tfsUri, tfsItemSpec);

        foreach (string branch in branches)
        {
            Console.WriteLine(branch);
        }
    }

    public static List<string> GetPathsEligibleForMerge(
        string tfsUri, string tfsBranchPath)
    {
        List<string> tfsEligibleMergePaths = new List<string>();

        using (TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri(tfsUri)))
        {
            VersionControlServer vcs =
                (VersionControlServer)tfs.GetService(typeof(VersionControlServer));

            foreach (ItemIdentifier mergeItem in vcs.QueryMergeRelationships(tfsBranchPath))
            {
                if (!mergeItem.IsDeleted && !string.IsNullOrWhiteSpace(mergeItem.Item))
                {
                    tfsEligibleMergePaths.Add(mergeItem.Item);
                }
            }
        }

        tfsEligibleMergePaths.Sort(StringComparer.OrdinalIgnoreCase);

        return tfsEligibleMergePaths;
    }
}

Этот код всегда возвращает тот же список, что и диалоговое окно "Слияние".