Skip to content

Commit

Permalink
v0.252.0 (#9477)
Browse files Browse the repository at this point in the history
Release notes: https://github.com/dependabot/dependabot-core/releases/tag/v0.252.0

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
  • Loading branch information
2 people authored and brettfo committed Apr 12, 2024
1 parent 37d86e4 commit 08d2d5b
Show file tree
Hide file tree
Showing 6 changed files with 69 additions and 93 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;

using NuGetUpdater.Core.Discover;
Expand Down Expand Up @@ -29,7 +30,7 @@ protected static async Task TestDiscoveryAsync(
protected static void ValidateWorkspaceResult(ExpectedWorkspaceDiscoveryResult expectedResult, WorkspaceDiscoveryResult actualResult)
{
Assert.NotNull(actualResult);
Assert.Equal(expectedResult.FilePath, actualResult.FilePath);
Assert.Equal(expectedResult.FilePath.NormalizePathToUnix(), actualResult.FilePath.NormalizePathToUnix());
ValidateDirectoryPackagesProps(expectedResult.DirectoryPackagesProps, actualResult.DirectoryPackagesProps);
ValidateResultWithDependencies(expectedResult.GlobalJson, actualResult.GlobalJson);
ValidateResultWithDependencies(expectedResult.DotNetToolsJson, actualResult.DotNetToolsJson);
Expand All @@ -50,7 +51,7 @@ void ValidateResultWithDependencies(ExpectedDependencyDiscoveryResult? expectedR
Assert.NotNull(actualResult);
}

Assert.Equal(expectedResult.FilePath, actualResult.FilePath);
Assert.Equal(expectedResult.FilePath.NormalizePathToUnix(), actualResult.FilePath.NormalizePathToUnix());
ValidateDependencies(expectedResult.Dependencies, actualResult.Dependencies);
Assert.Equal(expectedResult.ExpectedDependencyCount ?? expectedResult.Dependencies.Length, actualResult.Dependencies.Length);
}
Expand All @@ -64,12 +65,12 @@ void ValidateProjectResults(ImmutableArray<ExpectedSdkProjectDiscoveryResult> ex

foreach (var expectedProject in expectedProjects)
{
var actualProject = actualProjects.Single(p => p.FilePath == expectedProject.FilePath);
var actualProject = actualProjects.Single(p => p.FilePath.NormalizePathToUnix() == expectedProject.FilePath.NormalizePathToUnix());

Assert.Equal(expectedProject.FilePath, actualProject.FilePath);
AssertEx.Equal(expectedProject.Properties, actualProject.Properties);
Assert.Equal(expectedProject.FilePath.NormalizePathToUnix(), actualProject.FilePath.NormalizePathToUnix());
AssertEx.Equal(expectedProject.Properties, actualProject.Properties, PropertyComparer.Instance);
AssertEx.Equal(expectedProject.TargetFrameworks, actualProject.TargetFrameworks);
AssertEx.Equal(expectedProject.ReferencedProjectPaths, actualProject.ReferencedProjectPaths);
AssertEx.Equal(expectedProject.ReferencedProjectPaths.Select(PathHelper.NormalizePathToUnix), actualProject.ReferencedProjectPaths.Select(PathHelper.NormalizePathToUnix));
ValidateDependencies(expectedProject.Dependencies, actualProject.Dependencies);
Assert.Equal(expectedProject.ExpectedDependencyCount ?? expectedProject.Dependencies.Length, actualProject.Dependencies.Length);
}
Expand Down Expand Up @@ -114,4 +115,21 @@ protected static async Task<WorkspaceDiscoveryResult> RunDiscoveryAsync(TestFile
var resultJson = await File.ReadAllTextAsync(resultPath);
return JsonSerializer.Deserialize<WorkspaceDiscoveryResult>(resultJson, DiscoveryWorker.SerializerOptions)!;
}

internal class PropertyComparer : IEqualityComparer<Property>
{
public static PropertyComparer Instance { get; } = new();

public bool Equals(Property? x, Property? y)
{
return x?.Name == y?.Name &&
x?.Value == y?.Value &&
x?.SourceFilePath.NormalizePathToUnix() == y?.SourceFilePath.NormalizePathToUnix();
}

public int GetHashCode([DisallowNull] Property obj)
{
throw new NotImplementedException();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -110,15 +110,15 @@ public void ProjectPathsCanBeParsedFromSolutionFiles(string solutionContent, str
[InlineData("<Project><PropertyGroup><TargetFrameworks>netstandard2.0</TargetFrameworks></PropertyGroup></Project>", "netstandard2.0", null)]
[InlineData("<Project><PropertyGroup><TargetFrameworks> ; netstandard2.0 ; </TargetFrameworks></PropertyGroup></Project>", "netstandard2.0", null)]
[InlineData("<Project><PropertyGroup><TargetFrameworks>netstandard2.0 ; netstandard2.1 ; </TargetFrameworks></PropertyGroup></Project>", "netstandard2.0", "netstandard2.1")]
public void TfmsCanBeDeterminedFromProjectContents(string projectContents, string? expectedTfm1, string? expectedTfm2)
[InlineData("<Project><PropertyGroup><TargetFramework>netstandard2.0</TargetFramework><TargetFrameworkVersion Condition='False'>v4.7.2</TargetFrameworkVersion></PropertyGroup></Project>", "netstandard2.0", null)]
public async Task TfmsCanBeDeterminedFromProjectContents(string projectContents, string? expectedTfm1, string? expectedTfm2)
{
var projectPath = Path.GetTempFileName();
try
{
File.WriteAllText(projectPath, projectContents);
var expectedTfms = new[] { expectedTfm1, expectedTfm2 }.Where(tfm => tfm is not null).ToArray();
var buildFile = ProjectBuildFile.Open(Path.GetDirectoryName(projectPath)!, projectPath);
var actualTfms = MSBuildHelper.GetTargetFrameworkMonikers(ImmutableArray.Create(buildFile));
var (_buildFiles, actualTfms) = await MSBuildHelper.LoadBuildFilesAndTargetFrameworksAsync(Path.GetDirectoryName(projectPath)!, projectPath);
AssertEx.Equal(expectedTfms, actualTfms);
}
finally
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ public async Task BuildFileEnumerationWithGlobalJsonWithComments()

private static async Task<string[]> LoadBuildFilesFromTemp(TemporaryDirectory temporaryDirectory, string relativeProjectPath)
{
var buildFiles = await MSBuildHelper.LoadBuildFilesAsync(temporaryDirectory.DirectoryPath, $"{temporaryDirectory.DirectoryPath}/{relativeProjectPath}");
var (buildFiles, _tfms) = await MSBuildHelper.LoadBuildFilesAndTargetFrameworksAsync(temporaryDirectory.DirectoryPath, $"{temporaryDirectory.DirectoryPath}/{relativeProjectPath}");
var buildFilePaths = buildFiles.Select(f => f.RelativePath.NormalizePathToUnix()).ToArray();
return buildFilePaths;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ internal static class SdkProjectDiscovery
public static async Task<ImmutableArray<ProjectDiscoveryResult>> DiscoverAsync(string repoRootPath, string workspacePath, string projectPath, Logger logger)
{
// Determine which targets and props files contribute to the build.
var buildFiles = await MSBuildHelper.LoadBuildFilesAsync(repoRootPath, projectPath, includeSdkPropsAndTargets: true);
var (buildFiles, projectTargetFrameworks) = await MSBuildHelper.LoadBuildFilesAndTargetFrameworksAsync(repoRootPath, projectPath);

// Get all the dependencies which are directly referenced from the project file or indirectly referenced from
// targets and props files.
Expand Down Expand Up @@ -49,9 +49,7 @@ public static async Task<ImmutableArray<ProjectDiscoveryResult>> DiscoverAsync(s
if (buildFile.GetFileType() == ProjectBuildFileType.Project)
{
// Collect information that is specific to the project file.
var tfms = MSBuildHelper.GetTargetFrameworkMonikers(buildFiles)
.OrderBy(tfm => tfm)
.ToImmutableArray();
var tfms = projectTargetFrameworks.Order().ToImmutableArray();
var properties = MSBuildHelper.GetProperties(buildFiles).Values
.Where(p => !p.SourceFilePath.StartsWith(".."))
.OrderBy(p => p.Name)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@ public static async Task UpdateDependencyAsync(
// SDK-style project, modify the XML directly
logger.Log(" Running for SDK-style project");

var buildFiles = await MSBuildHelper.LoadBuildFilesAsync(repoRootPath, projectPath);
var tfms = MSBuildHelper.GetTargetFrameworkMonikers(buildFiles);
var (buildFiles, tfms) = await MSBuildHelper.LoadBuildFilesAndTargetFrameworksAsync(repoRootPath, projectPath);

// Get the set of all top-level dependencies in the current project
var topLevelDependencies = MSBuildHelper.GetTopLevelPackageDependencyInfos(buildFiles).ToArray();
Expand Down Expand Up @@ -226,10 +225,10 @@ private static async Task AddTransitiveDependencyAsync(string projectPath, strin
logger.Log($" Adding [{dependencyName}/{newDependencyVersion}] as a top-level package reference.");

// see https://learn.microsoft.com/nuget/consume-packages/install-use-packages-dotnet-cli
var (exitCode, _, _) = await ProcessEx.RunAsync("dotnet", $"add {projectPath} package {dependencyName} --version {newDependencyVersion}", workingDirectory: Path.GetDirectoryName(projectPath));
var (exitCode, stdout, stderr) = await ProcessEx.RunAsync("dotnet", $"add {projectPath} package {dependencyName} --version {newDependencyVersion}", workingDirectory: Path.GetDirectoryName(projectPath));
if (exitCode != 0)
{
logger.Log($" Transitive dependency [{dependencyName}/{newDependencyVersion}] was not added.");
logger.Log($" Transitive dependency [{dependencyName}/{newDependencyVersion}] was not added.\nSTDOUT:\n{stdout}\nSTDERR:\n{stderr}");
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,72 +60,6 @@ public static void RegisterMSBuild()
}
}

public static string[] GetTargetFrameworkMonikers(ImmutableArray<ProjectBuildFile> buildFiles)
{
HashSet<string> targetFrameworkValues = new(StringComparer.OrdinalIgnoreCase);
Dictionary<string, Property> propertyInfo = new(StringComparer.OrdinalIgnoreCase);

foreach (var buildFile in buildFiles)
{
var projectRoot = CreateProjectRootElement(buildFile);

foreach (var property in projectRoot.Properties)
{
if (property.Name.Equals("TargetFramework", StringComparison.OrdinalIgnoreCase) ||
property.Name.Equals("TargetFrameworks", StringComparison.OrdinalIgnoreCase))
{
if (buildFile.IsOutsideBasePath)
{
continue;
}

foreach (var tfm in property.Value.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
targetFrameworkValues.Add(tfm);
}
}
else if (property.Name.Equals("TargetFrameworkVersion", StringComparison.OrdinalIgnoreCase))
{
if (buildFile.IsOutsideBasePath)
{
continue;
}

// For packages.config projects that use TargetFrameworkVersion, we need to convert it to TargetFramework
targetFrameworkValues.Add($"net{property.Value.TrimStart('v').Replace(".", "")}");
}
else
{
propertyInfo[property.Name] = new(property.Name, property.Value, buildFile.RelativePath);
}
}
}

HashSet<string> targetFrameworks = new(StringComparer.OrdinalIgnoreCase);

foreach (var targetFrameworkValue in targetFrameworkValues)
{
var (resultType, _, tfms, _, errorMessage) =
GetEvaluatedValue(targetFrameworkValue, propertyInfo, propertiesToIgnore: ["TargetFramework", "TargetFrameworks"]);
if (resultType != EvaluationResultType.Success)
{
continue;
}

if (string.IsNullOrEmpty(tfms))
{
continue;
}

foreach (var tfm in tfms.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
targetFrameworks.Add(tfm);
}
}

return targetFrameworks.ToArray();
}

public static IEnumerable<string> GetProjectPathsFromSolution(string solutionPath)
{
var solution = SolutionFile.Parse(solutionPath);
Expand Down Expand Up @@ -569,7 +503,7 @@ internal static bool TryGetDirectoryPackagesPropsPath(string repoRootPath, strin
return directoryPackagesPropsPath is not null;
}

internal static async Task<ImmutableArray<ProjectBuildFile>> LoadBuildFilesAsync(string repoRootPath, string projectPath, bool includeSdkPropsAndTargets = false)
internal static async Task<(ImmutableArray<ProjectBuildFile> ProjectBuildFiles, string[] TargetFrameworks)> LoadBuildFilesAndTargetFrameworksAsync(string repoRootPath, string projectPath)
{
var buildFileList = new List<string>
{
Expand All @@ -579,6 +513,7 @@ internal static async Task<ImmutableArray<ProjectBuildFile>> LoadBuildFilesAsync
// a global.json file might cause problems with the dotnet msbuild command; create a safe version temporarily
TryGetGlobalJsonPath(repoRootPath, projectPath, out var globalJsonPath);
var safeGlobalJsonName = $"{globalJsonPath}{Guid.NewGuid()}";
HashSet<string> targetFrameworks = new(StringComparer.OrdinalIgnoreCase);

try
{
Expand Down Expand Up @@ -607,16 +542,44 @@ internal static async Task<ImmutableArray<ProjectBuildFile>> LoadBuildFilesAsync
// load the project even if it imports a file that doesn't exist (e.g. a file that's generated at restore
// or build time).
using var projectCollection = new ProjectCollection(); // do this in a one-off instance and don't pollute the global collection
var project = Project.FromFile(projectPath, new ProjectOptions
Project project = Project.FromFile(projectPath, new ProjectOptions
{
LoadSettings = ProjectLoadSettings.IgnoreMissingImports,
ProjectCollection = projectCollection,
});
buildFileList.AddRange(project.Imports.Select(i => i.ImportedProject.FullPath.NormalizePathToUnix()));

// use the MSBuild-evaluated value so we don't have to try to manually parse XML
IEnumerable<ProjectProperty> targetFrameworkProperties = project.Properties.Where(p => p.Name.Equals("TargetFramework", StringComparison.OrdinalIgnoreCase)).ToList();
IEnumerable<ProjectProperty> targetFrameworksProperties = project.Properties.Where(p => p.Name.Equals("TargetFrameworks", StringComparison.OrdinalIgnoreCase)).ToList();
IEnumerable<ProjectProperty> targetFrameworkVersionProperties = project.Properties.Where(p => p.Name.Equals("TargetFrameworkVersion", StringComparison.OrdinalIgnoreCase)).ToList();
foreach (ProjectProperty tfm in targetFrameworkProperties)
{
targetFrameworks.Add(tfm.EvaluatedValue);
}

foreach (ProjectProperty tfms in targetFrameworksProperties)
{
foreach (string tfmValue in tfms.EvaluatedValue.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
targetFrameworks.Add(tfmValue);
}
}

if (targetFrameworks.Count == 0)
{
// Only try this if we haven't been able to resolve anything yet. This is because deep in the SDK, a
// `TargetFramework` of `netstandard2.0` (eventually) gets turned into `v2.0` and we don't want to
// interpret that as a .NET Framework 2.0 project.
foreach (ProjectProperty tfvm in targetFrameworkVersionProperties)
{
targetFrameworks.Add($"net{tfvm.EvaluatedValue.TrimStart('v').Replace(".", "")}");
}
}
}
catch (InvalidProjectFileException)
{
return [];
return ([], []);
}
finally
{
Expand All @@ -627,16 +590,14 @@ internal static async Task<ImmutableArray<ProjectBuildFile>> LoadBuildFilesAsync
}

var repoRootPathPrefix = repoRootPath.NormalizePathToUnix() + "/";
var buildFiles = includeSdkPropsAndTargets
? buildFileList.Distinct()
: buildFileList
.Where(f => f.StartsWith(repoRootPathPrefix, StringComparison.OrdinalIgnoreCase))
.Distinct();
var buildFiles = buildFileList
.Where(f => f.StartsWith(repoRootPathPrefix, StringComparison.OrdinalIgnoreCase))
.Distinct();
var result = buildFiles
.Where(File.Exists)
.Select(path => ProjectBuildFile.Open(repoRootPath, path))
.ToImmutableArray();
return result;
return (result, targetFrameworks.ToArray());
}

[GeneratedRegex("^\\s*NuGetData::Package=(?<PackageName>[^,]+), Version=(?<PackageVersion>.+)$")]
Expand Down

0 comments on commit 08d2d5b

Please sign in to comment.