-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathAssets.cs
More file actions
248 lines (228 loc) · 8.3 KB
/
Copy pathAssets.cs
File metadata and controls
248 lines (228 loc) · 8.3 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using Newtonsoft.Json.Linq;
using Semmle.Util;
using Semmle.Util.Logging;
namespace Semmle.Extraction.CSharp.DependencyFetching
{
/// <summary>
/// Class for parsing project.assets.json files.
/// </summary>
internal class Assets
{
private readonly ILogger logger;
/// <summary>
/// Contains the dependencies found in the parsed assets files.
/// </summary>
public DependencyContainer Dependencies { get; } = new();
internal Assets(ILogger logger)
{
this.logger = logger;
}
/// <summary>
/// Class needed for deserializing parts of an assets file.
/// It holds information about a reference.
///
/// Type carries the type of the reference.
/// We are only interested in package references.
///
/// Compile holds information about the files needed for compilation.
/// However, if it is a .NET framework reference we assume that all files in the
/// package are needed for compilation.
/// </summary>
private record class ReferenceInfo(string? Type, Dictionary<string, object>? Compile);
/// <summary>
/// Add the package dependencies from the assets file to dependencies.
///
/// Parse a part of the JSon assets file and add the paths
/// to the dependencies required for compilation (and collect
/// information about used packages).
///
/// Example:
/// {
/// "Castle.Core/4.4.1": {
/// "type": "package",
/// "compile": {
/// "lib/netstandard1.5/Castle.Core.dll": {
/// "related": ".xml"
/// }
/// }
/// },
/// "Json.Net/1.0.33": {
/// "type": "package",
/// "compile": {
/// "lib/netstandard2.0/Json.Net.dll": {}
/// },
/// "runtime": {
/// "lib/netstandard2.0/Json.Net.dll": {}
/// }
/// }
/// }
///
/// Adds the following dependencies
/// Paths: {
/// "castle.core/4.4.1/lib/netstandard1.5/Castle.Core.dll",
/// "json.net/1.0.33/lib/netstandard2.0/Json.Net.dll"
/// }
/// Packages: {
/// "castle.core",
/// "json.net"
/// }
/// </summary>
private void AddPackageDependencies(JObject json, string jsonPath)
{
// If there is more than one framework we need to pick just one.
// To ensure stability we pick one based on the lexicographic order of
// the framework names.
var references = json
.GetProperty("targets")?
.Properties()?
.MaxBy(p => p.Name)?
.Value
.ToObject<Dictionary<string, ReferenceInfo>>();
if (references is null)
{
logger.LogDebug($"No references found in the targets section in '{jsonPath}'");
return;
}
// Find all the compile dependencies for each reference and
// create the relative path to the dependency.
references
.ForEach(r =>
{
var info = r.Value;
var name = r.Key.ToLowerInvariant();
if (info.Type != "package")
{
return;
}
if (info.Compile is null || !info.Compile.Any())
{
// If this is a framework reference then include everything.
if (FrameworkPackageNames.AllFrameworks.Any(framework => name.StartsWith(framework)))
{
Dependencies.AddFramework(name);
}
return;
}
info.Compile
.ForEach(r => Dependencies.Add(name, r.Key));
});
}
/// <summary>
/// Add the framework dependencies from the assets file to dependencies.
///
/// Example:
/// "project": {
/// "version": "1.0.0",
/// "frameworks": {
/// "net7.0": {
/// "frameworkReferences": {
/// "Microsoft.AspNetCore.App": {
/// "privateAssets": "none"
/// },
/// "Microsoft.NETCore.App": {
/// "privateAssets": "all"
/// }
/// }
/// }
/// }
/// }
///
/// Adds the following dependencies
/// Paths: {
/// "microsoft.aspnetcore.app.ref",
/// "microsoft.netcore.app.ref"
/// }
/// Packages: {
/// "microsoft.aspnetcore.app.ref",
/// "microsoft.netcore.app.ref"
/// }
/// </summary>
private void AddFrameworkDependencies(JObject json, string jsonPath)
{
var frameworks = json
.GetProperty("project")?
.GetProperty("frameworks");
if (frameworks is null)
{
logger.LogDebug($"No framework section in '{jsonPath}'.");
return;
}
// If there is more than one framework we need to pick just one.
// To ensure stability we pick one based on the lexicographic order of
// the framework names.
var references = frameworks
.Properties()?
.MaxBy(p => p.Name)?
.Value["frameworkReferences"] as JObject;
if (references is null)
{
logger.LogDebug($"No framework references in '{jsonPath}'.");
return;
}
references
.Properties()
.ForEach(f => Dependencies.AddFramework($"{f.Name}.Ref".ToLowerInvariant()));
}
/// <summary>
/// Parse `json` as project.assets.json content and add relative paths to the dependencies
/// (together with used package information) required for compilation.
/// </summary>
/// <returns>True if parsing succeeds, otherwise false.</returns>
public bool TryParse(string json, string jsonPath)
{
try
{
var obj = JObject.Parse(json);
AddPackageDependencies(obj, jsonPath);
AddFrameworkDependencies(obj, jsonPath);
return true;
}
catch (Exception e)
{
logger.LogDebug($"Failed to parse assets file (unexpected error): {e.Message}");
return false;
}
}
private static bool TryReadAllText(string path, ILogger logger, [NotNullWhen(returnValue: true)] out string? content)
{
try
{
content = File.ReadAllText(path);
return true;
}
catch (Exception e)
{
logger.LogInfo($"Failed to read assets file '{path}': {e.Message}");
content = null;
return false;
}
}
/// <summary>
/// Add the dependencies from the assets file to the dependencies.
/// </summary>
/// <param name="asset">Path to an assets file.</param>
public void AddDependencies(string asset)
{
if (TryReadAllText(asset, logger, out var json))
{
TryParse(json, asset);
}
}
/// <summary>
/// Add the dependencies from the assets files to the dependencies.
/// </summary>
/// <param name="assets">Collection of paths to assets files.</param>
public void AddDependenciesRange(IEnumerable<string> assets) =>
assets.ForEach(AddDependencies);
}
internal static class JsonExtensions
{
internal static JObject? GetProperty(this JObject json, string property) =>
json[property] as JObject;
}
}