-
Notifications
You must be signed in to change notification settings - Fork 3
/
DotnetNugetHelper.cs
88 lines (77 loc) · 2.97 KB
/
DotnetNugetHelper.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
namespace Atc.DotNet;
public static class DotnetNugetHelper
{
/// <summary>
/// Get all PackageReferences from file.
/// </summary>
/// <param name="fileInfo">The file.</param>
public static List<DotnetNugetPackageMetadataBase> GetAllPackageReferences(FileInfo fileInfo)
{
if (fileInfo is null)
{
throw new ArgumentNullException(nameof(fileInfo));
}
if (!fileInfo.Exists)
{
throw new FileNotFoundException();
}
var fileContent = File.ReadAllText(fileInfo.FullName);
return GetAllPackageReferences(fileContent);
}
/// <summary>
/// Get all PackageReferences from file-content.
/// </summary>
/// <param name="fileContent">The file as text.</param>
public static List<DotnetNugetPackageMetadataBase> GetAllPackageReferences(string fileContent)
{
if (fileContent is null)
{
throw new ArgumentNullException(nameof(fileContent));
}
if (!fileContent.StartsWith('<'))
{
throw new DataException("Expect xml content");
}
var data = new List<DotnetNugetPackageMetadataBase>();
foreach (var line in fileContent.EnsureEnvironmentNewLines().Split(Environment.NewLine))
{
if (!line.Contains("<PackageReference ", StringComparison.Ordinal) ||
!line.Contains("Include=", StringComparison.Ordinal) ||
!line.Contains("Version=", StringComparison.Ordinal))
{
continue;
}
var attributes = line
.Replace("<PackageReference ", string.Empty, StringComparison.Ordinal)
.Replace("/>", string.Empty, StringComparison.Ordinal)
.Replace(">", string.Empty, StringComparison.Ordinal)
.Trim()
.Split(' ');
var packageId = string.Empty;
var version = string.Empty;
foreach (var attribute in attributes)
{
if (attribute.StartsWith("Include=", StringComparison.Ordinal))
{
packageId = attribute
.Replace("Include=", string.Empty, StringComparison.Ordinal)
.Replace("\"", string.Empty, StringComparison.Ordinal);
}
else if (attribute.StartsWith("Version=", StringComparison.Ordinal))
{
version = attribute
.Replace("Version=", string.Empty, StringComparison.Ordinal)
.Replace("\"", string.Empty, StringComparison.Ordinal);
}
}
if (!string.IsNullOrEmpty(packageId) &&
!string.IsNullOrEmpty(version))
{
data.Add(new DotnetNugetPackageMetadataBase(packageId, version));
}
}
return data
.OrderBy(x => x.PackageId, StringComparer.Ordinal)
.ToList();
}
}