Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add RemoveDependency method to DependencyFileManager #4405

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 82 additions & 2 deletions src/Microsoft.DotNet.Darc/DarcLib/Helpers/DependencyFileManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,86 @@ public async Task AddDependencyAsync(
await AddDependencyToVersionDetailsAsync(repoUri, branch, dependency);
}

public async Task RemoveDependencyAsync(DependencyDetail dependency, string repoUri, string branch, bool repoIsVmr = false)
{
var updatedDependencyVersionFile =
new GitFile(VersionFiles.VersionDetailsXml, await RemoveDependencyFromVersionDetailsAsync(dependency, repoUri, branch));
var updatedVersionPropsFile =
new GitFile(VersionFiles.VersionProps, await RemoveDependencyFromVersionPropsAsync(dependency, repoUri, branch));
List<GitFile> gitFiles = [updatedDependencyVersionFile, updatedVersionPropsFile];

var updatedDotnetTools = await RemoveDotnetToolsDependencyAsync(dependency, repoUri, branch, repoIsVmr);
if (updatedDotnetTools != null)
{
gitFiles.Add(new(VersionFiles.DotnetToolsConfigJson, updatedDotnetTools));
}

await GetGitClient(repoUri).CommitFilesAsync(
gitFiles,
repoUri,
branch,
$"Remove {dependency.Name} from Version.Details.xml and Version.props'");

_logger.LogInformation($"Dependency '{dependency.Name}' successfully removed from '{VersionFiles.VersionDetailsXml}'");
}

private async Task<JObject> RemoveDotnetToolsDependencyAsync(DependencyDetail dependency, string repoUri, string branch, bool repoIsVmr)
{
var dotnetTools = await ReadDotNetToolsConfigJsonAsync(repoUri, branch, repoIsVmr);

if (dotnetTools == null)
{
return null;
}

if (dotnetTools["tools"] is not JObject tools)
{
return null;
}

// we have to do this because JObject is case sensitive
var toolProperty = tools.Properties().FirstOrDefault(p => p.Name.Equals(dependency.Name, StringComparison.OrdinalIgnoreCase));
if (toolProperty != null)
{
tools.Remove(toolProperty.Name);
}

return dotnetTools;
}

private async Task<XmlDocument> RemoveDependencyFromVersionPropsAsync(DependencyDetail dependency, string repoUri, string branch)
{
var versionProps = await ReadVersionPropsAsync(repoUri, branch);
string nodeName = VersionFiles.GetVersionPropsPackageVersionElementName(dependency.Name);
XmlNode element = versionProps.SelectSingleNode($"//{nodeName}");
if (element == null)
{
string alternateNodeName = VersionFiles.GetVersionPropsAlternatePackageVersionElementName(dependency.Name);
element = versionProps.SelectSingleNode($"//{alternateNodeName}");
if (element == null)
{
throw new DependencyException($"Couldn't find dependency {dependency.Name} in Version.props");
}
}
element.ParentNode.RemoveChild(element);

return versionProps;
}

private async Task<XmlDocument> RemoveDependencyFromVersionDetailsAsync(DependencyDetail dependency, string repoUri, string branch)
{
var versionDetails = await ReadVersionDetailsXmlAsync(repoUri, branch);
XmlNode dependencyNode = versionDetails.SelectSingleNode($"//{VersionDetailsParser.DependencyElementName}[@Name='{dependency.Name}']");

if (dependencyNode == null)
{
throw new DependencyException($"Dependency {dependency.Name} not found in Version.Details.xml");
}

dependencyNode.ParentNode.RemoveChild(dependencyNode);
return versionDetails;
}

private static void SetAttribute(XmlDocument document, XmlNode node, string name, string value)
{
XmlAttribute attribute = node.Attributes[name];
Expand Down Expand Up @@ -805,8 +885,8 @@ private async Task AddDependencyToVersionsPropsAsync(string repo, string branch,

// Attempt to find the element name or alternate element name under
// the property group nodes
XmlNode existingVersionNode = versionProps.DocumentElement.SelectSingleNode($"//*[local-name()='{packageVersionElementName}' and parent::PropertyGroup]");
existingVersionNode ??= versionProps.DocumentElement.SelectSingleNode($"//*[local-name()='{packageVersionAlternateElementName}' and parent::PropertyGroup]");
XmlNode existingVersionNode = versionProps.DocumentElement.SelectSingleNode($"//*[local-name()='{packageVersionElementName}' and parent::PropertyGroup]")
?? versionProps.DocumentElement.SelectSingleNode($"//*[local-name()='{packageVersionAlternateElementName}' and parent::PropertyGroup]");

if (existingVersionNode != null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ public interface IDependencyFileManager
{
Task AddDependencyAsync(DependencyDetail dependency, string repoUri, string branch);

Task RemoveDependencyAsync(DependencyDetail dependency, string repoUri, string branch, bool repoIsVmr = false);

Dictionary<string, HashSet<string>> FlattenLocationsAndSplitIntoGroups(Dictionary<string, HashSet<string>> assetLocationMap);

List<(string key, string feed)> GetPackageSources(XmlDocument nugetConfig, Func<string, bool>? filter = null);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,238 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.DotNet.DarcLib.Helpers;
using Microsoft.DotNet.DarcLib.Models.Darc;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.VisualStudio.Services.Profile;
using Moq;
using NUnit.Framework;

namespace Microsoft.DotNet.DarcLib.Tests.Helpers;

[TestFixture]
public class DependencyFileManagerTests
{
private const string VersionDetails = """
<?xml version="1.0" encoding="utf-8"?>
<Dependencies>
<!-- Elements contains all product dependencies -->
<ProductDependencies>
<Dependency Name="Foo" Version="1.0.0">
<Uri>https://github.com/dotnet/foo</Uri>
<Sha>sha1</Sha>
</Dependency>
<Dependency Name="Bar" Version="1.0.0">
<Uri>https://github.com/dotnet/bar</Uri>
<Sha>sha1</Sha>
</Dependency>
</ProductDependencies>
<ToolsetDependencies>
</ToolsetDependencies>
</Dependencies>
""";

private const string VersionProps = """
<?xml version="1.0" encoding="utf-8"?>
<Project>
<PropertyGroup>
</PropertyGroup>
<!--Package versions-->
<PropertyGroup>
<FooPackageVersion>1.0.0</FooPackageVersion>
<BarPackageVersion>1.0.0</BarPackageVersion>
</PropertyGroup>
</Project>
""";

private const string DotnetTools = """
{
"version": 1,
"isRoot": true,
"tools": {
"microsoft.dnceng.secretmanager": {
"version": "1.1.0-beta.25071.2",
"commands": [
"secret-manager"
]
},
"foo": {
"version": "8.0.0",
"commands": [
"foo"
]
},
"microsoft.dnceng.configuration.bootstrap": {
"version": "1.1.0-beta.25071.2",
"commands": [
"bootstrap-dnceng-configuration"
]
}
}
}
""";

[Test]
[TestCase(true)]
[TestCase(false)]
public async Task RemoveDependencyShouldRemoveDependency(bool dotnetToolsExists)
{
var expectedVersionDetails = """
<?xml version="1.0" encoding="utf-8"?>
<Dependencies>
<!-- Elements contains all product dependencies -->
<ProductDependencies>
<Dependency Name="Bar" Version="1.0.0">
<Uri>https://github.com/dotnet/bar</Uri>
<Sha>sha1</Sha>
</Dependency>
</ProductDependencies>
<ToolsetDependencies>
</ToolsetDependencies>
</Dependencies>
""";
var expectedVersionProps = """
<?xml version="1.0" encoding="utf-8"?>
<Project>
<PropertyGroup>
</PropertyGroup>
<!--Package versions-->
<PropertyGroup>
<BarPackageVersion>1.0.0</BarPackageVersion>
</PropertyGroup>
</Project>
""";
var expectedDotNetTools = """
{
"version": 1,
"isRoot": true,
"tools": {
"microsoft.dnceng.secretmanager": {
"version": "1.1.0-beta.25071.2",
"commands": [
"secret-manager"
]
},
"microsoft.dnceng.configuration.bootstrap": {
"version": "1.1.0-beta.25071.2",
"commands": [
"bootstrap-dnceng-configuration"
]
}
}
}
""";

var tmpVersionDetailsPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
var tmpVersionPropsPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
var tmpDotnetToolsPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
DependencyDetail dependency = new()
{
Name = "Foo"
};

Mock<IGitRepo> repo = new();
Mock<IGitRepoFactory> repoFactory = new();

repo.Setup(r => r.GetFileContentsAsync(VersionFiles.VersionDetailsXml, It.IsAny<string>(), It.IsAny<string>()))
.ReturnsAsync(VersionDetails);
repo.Setup(r => r.GetFileContentsAsync(VersionFiles.VersionProps, It.IsAny<string>(), It.IsAny<string>()))
.ReturnsAsync(VersionProps);
if (!dotnetToolsExists)
{
repo.Setup(r => r.GetFileContentsAsync(VersionFiles.DotnetToolsConfigJson, It.IsAny<string>(), It.IsAny<string>()))
.Throws<DependencyFileNotFoundException>();
}
else
{
repo.Setup(r => r.GetFileContentsAsync(VersionFiles.DotnetToolsConfigJson, It.IsAny<string>(), It.IsAny<string>()))
.ReturnsAsync(DotnetTools);
}

repo.Setup(r => r.CommitFilesAsync(
It.Is<List<GitFile>>(files =>
files.Count == (dotnetToolsExists ? 3 : 2) &&
files.Any(f => f.FilePath == VersionFiles.VersionDetailsXml) && files.Any(f => f.FilePath == VersionFiles.VersionProps)),
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<string>()))
.Callback<List<GitFile>, string, string, string>((files, repoUri, branch, commitMessage) =>
{
File.WriteAllText(tmpVersionDetailsPath, files[0].Content);
File.WriteAllText(tmpVersionPropsPath, files[1].Content);
if (dotnetToolsExists)
{
File.WriteAllText(tmpDotnetToolsPath, files[2].Content);
}
});

repoFactory.Setup(repoFactory => repoFactory.CreateClient(It.IsAny<string>())).Returns(repo.Object);

DependencyFileManager manager = new(
repoFactory.Object,
new VersionDetailsParser(),
NullLogger.Instance);

try
{
await manager.RemoveDependencyAsync(dependency, string.Empty, string.Empty);

File.ReadAllText(tmpVersionDetailsPath).Replace("\r\n", "\n").TrimEnd().Should()
.Be(expectedVersionDetails.Replace("\r\n", "\n").TrimEnd());
File.ReadAllText(tmpVersionPropsPath).Replace("\r\n", "\n").TrimEnd().Should()
.Be(expectedVersionProps.Replace("\r\n", "\n").TrimEnd());
if (dotnetToolsExists)
{
File.ReadAllText(tmpDotnetToolsPath).Replace("\r\n", "\n").TrimEnd().Should()
.Be(expectedDotNetTools.Replace("\r\n", "\n").TrimEnd());
}
}
finally
{
if (File.Exists(tmpVersionDetailsPath))
{
File.Delete(tmpVersionDetailsPath);
}
if (File.Exists(tmpVersionPropsPath))
{
File.Delete(tmpVersionPropsPath);
}
if (File.Exists(tmpDotnetToolsPath))
{
File.Delete(tmpDotnetToolsPath);
}
}
}

[Test]
public async Task RemoveDependencyShouldThrowWhenDependencyDoesNotExist()
{
DependencyDetail dependency = new()
{
Name = "gaa"
};

Mock<IGitRepo> repo = new();
Mock<IGitRepoFactory> repoFactory = new();

repo.Setup(r => r.GetFileContentsAsync(VersionFiles.VersionDetailsXml, It.IsAny<string>(), It.IsAny<string>()))
.ReturnsAsync(VersionDetails);
repo.Setup(r => r.GetFileContentsAsync(VersionFiles.VersionProps, It.IsAny<string>(), It.IsAny<string>()))
.ReturnsAsync(VersionProps);
repoFactory.Setup(repoFactory => repoFactory.CreateClient(It.IsAny<string>())).Returns(repo.Object);

DependencyFileManager manager = new(
repoFactory.Object,
new VersionDetailsParser(),
NullLogger.Instance);

Func<Task> act = async () => await manager.RemoveDependencyAsync(dependency, string.Empty, string.Empty);
await act.Should().ThrowAsync<DependencyException>();
}
}