-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
DiscoverCommand.cs
219 lines (179 loc) · 7.88 KB
/
DiscoverCommand.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
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Security.Cryptography;
using Microsoft.AspNetCore.Razor.Language;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Razor;
using Microsoft.CodeAnalysis.Razor.Serialization;
using Microsoft.NET.Sdk.Razor.Tool.CommandLineUtils;
using Newtonsoft.Json;
namespace Microsoft.NET.Sdk.Razor.Tool
{
internal class DiscoverCommand : CommandBase
{
public DiscoverCommand(Application parent)
: base(parent, "discover")
{
Assemblies = Argument("assemblies", "assemblies to search for tag helpers", multipleValues: true);
TagHelperManifest = Option("-o", "output file", CommandOptionType.SingleValue);
ProjectDirectory = Option("-p", "project root directory", CommandOptionType.SingleValue);
Version = Option("-v|--version", "Razor language version", CommandOptionType.SingleValue);
Configuration = Option("-c", "Razor configuration name", CommandOptionType.SingleValue);
ExtensionNames = Option("-n", "extension name", CommandOptionType.MultipleValue);
ExtensionFilePaths = Option("-e", "extension file path", CommandOptionType.MultipleValue);
}
public CommandArgument Assemblies { get; }
public CommandOption TagHelperManifest { get; }
public CommandOption ProjectDirectory { get; }
public CommandOption Version { get; }
public CommandOption Configuration { get; }
public CommandOption ExtensionNames { get; }
public CommandOption ExtensionFilePaths { get; }
protected override bool ValidateArguments()
{
if (string.IsNullOrEmpty(TagHelperManifest.Value()))
{
Error.WriteLine($"{TagHelperManifest.Description} must be specified.");
return false;
}
if (Assemblies.Values.Count == 0)
{
Error.WriteLine($"{Assemblies.Name} must have at least one value.");
return false;
}
if (string.IsNullOrEmpty(ProjectDirectory.Value()))
{
ProjectDirectory.Values.Add(Environment.CurrentDirectory);
}
if (string.IsNullOrEmpty(Version.Value()))
{
Error.WriteLine($"{Version.Description} must be specified.");
return false;
}
else if (!RazorLanguageVersion.TryParse(Version.Value(), out _))
{
Error.WriteLine($"Invalid option {Version.Value()} for Razor language version --version; must be Latest or a valid version in range {RazorLanguageVersion.Version_1_0} to {RazorLanguageVersion.Latest}.");
return false;
}
if (string.IsNullOrEmpty(Configuration.Value()))
{
Error.WriteLine($"{Configuration.Description} must be specified.");
return false;
}
if (ExtensionNames.Values.Count != ExtensionFilePaths.Values.Count)
{
Error.WriteLine($"{ExtensionNames.Description} and {ExtensionFilePaths.Description} should have the same number of values.");
}
foreach (var filePath in ExtensionFilePaths.Values)
{
if (!Path.IsPathRooted(filePath))
{
Error.WriteLine($"Extension file paths must be fully-qualified, absolute paths.");
return false;
}
}
return true;
}
protected override Task<int> ExecuteCoreAsync()
{
if (!Parent.Checker.Check(ExtensionFilePaths.Values))
{
Error.WriteLine($"Extenions could not be loaded. See output for details.");
return Task.FromResult(ExitCodeFailure);
}
// Loading all of the extensions should succeed as the dependency checker will have already
// loaded them.
var extensions = new RazorExtension[ExtensionNames.Values.Count];
for (var i = 0; i < ExtensionNames.Values.Count; i++)
{
extensions[i] = new AssemblyExtension(ExtensionNames.Values[i], Parent.Loader.LoadFromPath(ExtensionFilePaths.Values[i]));
}
var version = RazorLanguageVersion.Parse(Version.Value());
var configuration = RazorConfiguration.Create(version, Configuration.Value(), extensions);
var result = ExecuteCore(
configuration: configuration,
projectDirectory: ProjectDirectory.Value(),
outputFilePath: TagHelperManifest.Value(),
assemblies: Assemblies.Values.ToArray());
return Task.FromResult(result);
}
private int ExecuteCore(RazorConfiguration configuration, string projectDirectory, string outputFilePath, string[] assemblies)
{
outputFilePath = Path.Combine(projectDirectory, outputFilePath);
var metadataReferences = new MetadataReference[assemblies.Length];
for (var i = 0; i < assemblies.Length; i++)
{
metadataReferences[i] = Parent.AssemblyReferenceProvider(assemblies[i], default(MetadataReferenceProperties));
}
var engine = RazorProjectEngine.Create(configuration, RazorProjectFileSystem.Empty, b =>
{
b.Features.Add(new DefaultMetadataReferenceFeature() { References = metadataReferences });
b.Features.Add(new CompilationTagHelperFeature());
b.Features.Add(new DefaultTagHelperDescriptorProvider());
CompilerFeatures.Register(b);
});
var feature = engine.Engine.Features.OfType<ITagHelperFeature>().Single();
var tagHelpers = feature.GetDescriptors();
using (var stream = new MemoryStream())
{
Serialize(stream, tagHelpers);
stream.Position = 0;
var newHash = Hash(stream);
var existingHash = Hash(outputFilePath);
if (!HashesEqual(newHash, existingHash))
{
stream.Position = 0;
using (var output = File.Open(outputFilePath, FileMode.Create))
{
stream.CopyTo(output);
}
}
}
return ExitCodeSuccess;
}
private static byte[] Hash(string path)
{
if (!File.Exists(path))
{
return Array.Empty<byte>();
}
using (var stream = File.OpenRead(path))
{
return Hash(stream);
}
}
private static byte[] Hash(Stream stream)
{
using (var sha = SHA256.Create())
{
sha.ComputeHash(stream);
return sha.Hash;
}
}
private bool HashesEqual(byte[] x, byte[] y)
{
if (x.Length != y.Length)
{
return false;
}
for (var i = 0; i < x.Length; i++)
{
if (x[i] != y[i])
{
return false;
}
}
return true;
}
private static void Serialize(Stream stream, IReadOnlyList<TagHelperDescriptor> tagHelpers)
{
using (var writer = new StreamWriter(stream, Encoding.UTF8, bufferSize: 4096, leaveOpen: true))
{
var serializer = new JsonSerializer();
serializer.Converters.Add(new TagHelperDescriptorJsonConverter());
serializer.Converters.Add(new RazorDiagnosticJsonConverter());
serializer.Serialize(writer, tagHelpers);
}
}
}
}