获取解决方案中的所有 nuget 包 [英] Get all nuget packages in solution
问题描述
我正在尝试编写一个单元测试来强制合并 Nuget 包(我们有一个构建要求,所有单元测试都通过,因此这将阻止未合并的 PR 通过)并且我试图使用 Nuget.Core
来做到这一点.但是,我似乎无法通过他们的图书馆找到自己的方式,而且还没有人问过这个问题.那么,如何以编程方式获取给定解决方案引用的所有 Nuget 包?
I'm trying to write a unit test to enforce consolidation of Nuget packages (we have a build requirement that all unit tests pass so this would keep PRs that aren't consolidating from passing) and I was attempting to use Nuget.Core
to do that. However, I cannot seem to find my way through their libraries and no one has asked this question yet. So, how can I get all the Nuget packages a given solution references programmatically?
推荐答案
这是最终的解决方案(连同单元测试).关键是使用Directory
库遍历解决方案中的所有项目,然后使用NuGet.Core
分析每个项目中的NuGet 包.
This is the final solution (along with unit test). The key is to use the Directory
library to iterate over all the projects in the solution and then use NuGet.Core
to analyze the NuGet packages in each project.
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();
}
}
}
这篇关于获取解决方案中的所有 nuget 包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!