我正在尝试编写一个单元测试以强制整合Nuget软件包(我们有一个构建要求,即所有单元测试都必须通过,这样才能使未合并的PR不能通过),并且我试图使用Nuget.Core来执行那.但是,我似乎无法在他们的图书馆中找到自己的出路,而且还没有人问过这个问题.那么,如何才能以编程方式获取给定解决方案引用的所有Nuget软件包?
解决方法:
这是最终的解决方案(以及单元测试).关键是使用目录库迭代解决方案中的所有项目,然后使用NuGet.Core分析每个项目中的NuGet包.
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NuGet;
using Shouldly;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace UnitTests
{
[TestClass]
public class NugetConsolidationTest
{
private List<string> _ignoredPackages = new List<string>();
[TestMethod]
public void AllNugetPackagesAreConsolidated()
{
var packageVersionMapping = new Dictionary<string, List<string>>();
var parentDir = (Directory.GetParent(Directory.GetCurrentDirectory()).Parent).Parent.FullName;
var files = Directory.GetFiles(parentDir, "packages.config", SearchOption.AllDirectories);
foreach (var packageFile in files)
{
var file = new PackageReferenceFile(packageFile);
var refs = file.GetPackageReferences(true);
foreach (var packageRef in refs)
{
if (_ignoredPackages.Contains(packageRef.Id))
continue;
if (!packageVersionMapping.ContainsKey(packageRef.Id))
packageVersionMapping[packageRef.Id] = new List<string>() { packageRef.Version.ToFullString() };
else
{
if (packageVersionMapping[packageRef.Id].All(x => !x.Equals(packageRef.Version.ToFullString(),
StringComparison.InvariantCultureIgnoreCase)))
packageVersionMapping[packageRef.Id].Add(packageRef.Version.ToFullString());
}
}
}
var errors = packageVersionMapping.Where(x => x.Value.Count > 1)?.
Select(x => $"Package {x.Key} has {x.Value.Count} separate versions installed! Current versions are {string.Join(", ", x.Value)}");
errors.ShouldBeEmpty();
}
}
}