Search code examples
c#tfsteam-project-collection

How do I get a branches parent from a path in TFS


Lets say the following is my TFS structure:

  • Branches (Folder)
    • Module1 (Folder)
      • Branch1 (Branch with parent Dev)
      • Branch2 (Branch with parent Branch1)
      • Branch3 (Branch with parent Branch1)
  • Dev (Branch)

In code, I have access to my local workspace, as well as a VersionControlServer object.

I want a method such as string GetParentPath(string path) that would act like the following:

GetParentPath("$/Branches/Module1/Branch1"); // $/Dev
GetParentPath("$/Branches/Module1/Branch2"); // $/Branches/Module1/Branch1
GetParentPath("$/Branches/Module1/Branch3"); // $/Branches/Module1/Branch1
GetParentPath("$/Dev"); // throws an exception since there is no parent

I currently have the following, thought it worked, but it doesn't (and I didn't honestly expect it to work either)

private string GetParentPath(string path)
{
    return versionControlServer.QueryMergeRelationships(path)?.LastOrDefault()?.Item;
}

Solution

  • Figured it out (Thanks to Andy Li-MSFT for poking my brain with the BranchObject class):

    string GetParentPath(string path)
    {
        BranchObject branchObject = versionControlServer.QueryBranchObjects(new ItemIdentifier(path), RecursionType.None).Single();
        if (branchObject.Properties.ParentBranch != null)
            return branchObject.Properties.ParentBranch.Item;
        else
            throw new Exception($"Branch '{path}' does not have a parent");
    }
    

    In addition, if you want to get the parent branch of a file/folder located within that branch, you could use the following code to get that functionality:

    private string GetParentPath(string path)
    {
        string modifyingPath = path;
        BranchObject branchObject = versionControlServer.QueryBranchObjects(new ItemIdentifier(modifyingPath), RecursionType.None).FirstOrDefault();
        while (branchObject == null && !string.IsNullOrWhiteSpace(modifyingPath))
        {
            modifyingPath = modifyingPath.Substring(0, modifyingPath.LastIndexOf("/"));
            branchObject = versionControlServer.QueryBranchObjects(new ItemIdentifier(modifyingPath), RecursionType.None).FirstOrDefault();
        }
    
        string root = branchObject?.Properties?.ParentBranch?.Item;
        return root == null ? null : $"{root}{path.Replace(modifyingPath, "")}";
    }