Skip to content

Commit

Permalink
fix: unhandled exception when package reference without version
Browse files Browse the repository at this point in the history
First() will throw exception if the Version or Include attributes are not found
  • Loading branch information
cslong committed Feb 23, 2024
1 parent 3eaab8c commit b894d39
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
16 changes: 13 additions & 3 deletions src/CTA.Rules.ProjectFile/ProjectFileCreator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -291,9 +291,19 @@ private void UpdatePackageReferences()
//Select existing packages and deduplicate them by package name:
var existingPackages = _projectFileXml.Descendants()
.Where(d => d.Name == "PackageReference")
.Select(d => new { Name = d.Attributes("Include").First().Value, Version = d.Attributes("Version").First().Value })
.GroupBy(d => d.Name).Select(d => d.FirstOrDefault())
.ToDictionary(p => p.Name, p => p.Version);
.Select(d => new
{
Name = d.Attributes("Include")
.FirstOrDefault()?
.Value ?? "",
Version = d.Attributes("Version")
.FirstOrDefault()?
.Value ?? ""
})
.GroupBy(d => d.Name)
.Select(d => d.FirstOrDefault())
.ToDictionary(p => p.Name,
p => p.Version);

_packages = _packages.Where(p => existingPackages.Keys?.Contains(p.Key) == false).ToDictionary(d => d.Key, d => d.Value);

Expand Down
27 changes: 27 additions & 0 deletions tst/CTA.Rules.Test/Actions/ProjectFileActionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,33 @@ public void ProjectFileCreationHandlesNoExistingPackages()
StringAssert.Contains("<PackageReference Include=\"Newtonsoft.Json\" Version=\"2.2.6\" />", result);
}

[Test]
public void ProjectFileCreationHandlePackageReferenceNoVersion()
{
const string projectFile = @"
<Project Sdk=""Microsoft.NET.Sdk"">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include=""Microsoft.EntityFrameworkCore.Design""/>
</ItemGroup>
</Project>";

var result = CreateNewFile(
ProjectType.CoreMvc,
new List<string>() { SupportedFrameworks.Net8 },
new Dictionary<string, string>()
{
{"Newtonsoft.Json", "2.2.6"}
}, new List<string>(),
newContent: projectFile);
StringAssert.Contains(SupportedFrameworks.Net8, result);
//verify both new and old package reference remain
StringAssert.Contains("<PackageReference Include=\"Newtonsoft.Json\" Version=\"2.2.6\" />", result);
StringAssert.Contains("<PackageReference Include=\"Microsoft.EntityFrameworkCore.Design\" />", result);
}

private string CreateNewFile(ProjectType projectType, List<string> targetVersions, Dictionary<string, string> packageReferences, List<string> projectReferences, bool isNetCore = false, string newContent="")
{
ResetProjectFile(newContent: newContent, isNetCore: isNetCore);
Expand Down

0 comments on commit b894d39

Please sign in to comment.