-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathProgram.cs
More file actions
348 lines (293 loc) · 15.1 KB
/
Program.cs
File metadata and controls
348 lines (293 loc) · 15.1 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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.Loader;
using System.Text;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi;
using Microsoft.OpenApi.Writers;
using Swashbuckle.AspNetCore.Swagger;
namespace Swashbuckle.AspNetCore.Cli
{
internal class Program
{
private const string OpenApiVersionOption = "--openapiversion";
private const string SerializeAsV2Flag = "--serializeasv2";
public static int Main(string[] args)
{
// Helper to simplify command line parsing etc.
var runner = new CommandRunner("dotnet swagger", "Swashbuckle (Swagger) Command Line Tools", Console.Out);
// NOTE: The "dotnet swagger tofile" command does not serve the request directly. Instead, it invokes a corresponding
// command (called _tofile) via "dotnet exec" so that the runtime configuration (*.runtimeconfig & *.deps.json) of the
// provided startupassembly can be used instead of the tool's. This is neccessary to successfully load the
// startupassembly and it's transitive dependencies. See https://github.com/dotnet/coreclr/issues/13277 for more.
// > dotnet swagger tofile ...
runner.SubCommand("tofile", "retrieves Swagger from a startup assembly, and writes to file", c =>
{
c.Argument("startupassembly", "relative path to the application's startup assembly");
c.Argument("swaggerdoc", "name of the swagger doc you want to retrieve, as configured in your startup class");
c.Option("--output", "relative path where the Swagger will be output, defaults to stdout");
c.Option("--host", "a specific host to include in the Swagger output");
c.Option("--basepath", "a specific basePath to include in the Swagger output");
c.Option(OpenApiVersionOption, "output Swagger in the specified version, defaults to 3.0");
c.Option("--yaml", "exports swagger in a yaml format", true);
// TODO Remove this option in the major version that adds support for OpenAPI 3.1
c.Option(SerializeAsV2Flag, "output Swagger in the V2 format rather than V3 [deprecated]", true);
c.OnRun((namedArgs) =>
{
string subProcessCommandLine = PrepareCommandLine(args, namedArgs);
using var child = Process.Start("dotnet", subProcessCommandLine);
child.WaitForExit();
return child.ExitCode;
});
});
// > dotnet swagger _tofile ... (* should only be invoked via "dotnet exec")
runner.SubCommand("_tofile", "", c =>
{
c.Argument("startupassembly", "");
c.Argument("swaggerdoc", "");
c.Option("--output", "");
c.Option("--host", "");
c.Option("--basepath", "");
c.Option(OpenApiVersionOption, "");
c.Option("--yaml", "", true);
// TODO Remove this option in the major version that adds support for OpenAPI 3.1
c.Option(SerializeAsV2Flag, "", true);
c.OnRun((namedArgs) =>
{
SetupAndRetrieveSwaggerProviderAndOptions(namedArgs, out var swaggerProvider, out var swaggerOptions);
var swaggerDocumentSerializer = swaggerOptions?.Value?.CustomDocumentSerializer;
var swagger = swaggerProvider.GetSwagger(
namedArgs["swaggerdoc"],
namedArgs.TryGetValue("--host", out var arg) ? arg : null,
namedArgs.TryGetValue("--basepath", out var namedArg) ? namedArg : null);
// 4) Serialize to specified output location or stdout
var outputPath = namedArgs.TryGetValue("--output", out var arg1)
? Path.Combine(Directory.GetCurrentDirectory(), arg1)
: null;
if (!string.IsNullOrEmpty(outputPath))
{
string directoryPath = Path.GetDirectoryName(outputPath);
if (!string.IsNullOrEmpty(directoryPath) && !Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
}
using Stream stream = outputPath != null ? File.Create(outputPath) : Console.OpenStandardOutput();
using var streamWriter = new FormattingStreamWriter(stream, CultureInfo.InvariantCulture);
IOpenApiWriter writer;
if (namedArgs.ContainsKey("--yaml"))
{
writer = new OpenApiYamlWriter(streamWriter);
}
else
{
writer = new OpenApiJsonWriter(streamWriter);
}
OpenApiSpecVersion specVersion = OpenApiSpecVersion.OpenApi3_0;
if (namedArgs.TryGetValue(OpenApiVersionOption, out var versionArg))
{
specVersion = versionArg switch
{
"2.0" => OpenApiSpecVersion.OpenApi2_0,
"3.0" => OpenApiSpecVersion.OpenApi3_0,
_ => throw new NotSupportedException($"The specified OpenAPI version \"{versionArg}\" is not supported."),
};
}
else if (namedArgs.ContainsKey(SerializeAsV2Flag))
{
specVersion = OpenApiSpecVersion.OpenApi2_0;
WriteSerializeAsV2DeprecationWarning();
}
if (swaggerDocumentSerializer != null)
{
swaggerDocumentSerializer.SerializeDocument(swagger, writer, specVersion);
}
else
{
switch (specVersion)
{
case OpenApiSpecVersion.OpenApi2_0:
swagger.SerializeAsV2(writer);
break;
case OpenApiSpecVersion.OpenApi3_0:
default:
swagger.SerializeAsV3(writer);
break;
}
}
if (outputPath != null)
{
Console.WriteLine($"Swagger JSON/YAML successfully written to {outputPath}");
}
return 0;
});
});
// > dotnet swagger list
runner.SubCommand("list", "retrieves the list of Swagger document names from a startup assembly", c =>
{
c.Argument("startupassembly", "relative path to the application's startup assembly");
c.Option("--output", "relative path where the document names will be output, defaults to stdout");
c.OnRun((namedArgs) =>
{
string subProcessCommandLine = PrepareCommandLine(args, namedArgs);
using var child = Process.Start("dotnet", subProcessCommandLine);
child.WaitForExit();
return child.ExitCode;
});
});
// > dotnet swagger _list ... (* should only be invoked via "dotnet exec")
runner.SubCommand("_list", "", c =>
{
c.Argument("startupassembly", "");
c.Option("--output", "");
c.OnRun((namedArgs) =>
{
SetupAndRetrieveSwaggerProviderAndOptions(namedArgs, out var swaggerProvider, out var swaggerOptions);
IList<string> docNames = [];
string outputPath = namedArgs.TryGetValue("--output", out var arg1)
? Path.Combine(Directory.GetCurrentDirectory(), arg1)
: null;
bool outputViaConsole = outputPath == null;
if (!string.IsNullOrEmpty(outputPath))
{
string directoryPath = Path.GetDirectoryName(outputPath);
if (!string.IsNullOrEmpty(directoryPath) && !Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
}
using Stream stream = outputViaConsole ? Console.OpenStandardOutput() : File.Create(outputPath);
using StreamWriter writer = new(stream, outputViaConsole ? Console.OutputEncoding : Encoding.UTF8);
if (swaggerProvider is not ISwaggerDocumentMetadataProvider docMetaProvider)
{
writer.WriteLine($"The registered {nameof(ISwaggerProvider)} instance does not implement {nameof(ISwaggerDocumentMetadataProvider)}; unable to list the Swagger document names.");
return -1;
}
docNames = docMetaProvider.GetDocumentNames();
foreach (var name in docNames)
{
writer.WriteLine($"\"{name}\"");
}
return 0;
});
});
return runner.Run(args);
}
private static void SetupAndRetrieveSwaggerProviderAndOptions(IDictionary<string, string> namedArgs, out ISwaggerProvider swaggerProvider, out IOptions<SwaggerOptions> swaggerOptions)
{
// 1) Configure host with provided startupassembly
var startupAssembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(
Path.Combine(Directory.GetCurrentDirectory(), namedArgs["startupassembly"]));
// 2) Build a service container that's based on the startup assembly
var serviceProvider = GetServiceProvider(startupAssembly);
// 3) Retrieve Swagger via configured provider
swaggerProvider = serviceProvider.GetRequiredService<ISwaggerProvider>();
swaggerOptions = serviceProvider.GetService<IOptions<SwaggerOptions>>();
}
private static string PrepareCommandLine(string[] args, IDictionary<string, string> namedArgs)
{
if (!File.Exists(namedArgs["startupassembly"]))
{
throw new FileNotFoundException(namedArgs["startupassembly"]);
}
var depsFile = namedArgs["startupassembly"].Replace(".dll", ".deps.json");
var runtimeConfig = namedArgs["startupassembly"].Replace(".dll", ".runtimeconfig.json");
var commandName = args[0];
var subProcessArguments = new string[args.Length - 1];
if (subProcessArguments.Length > 0)
{
Array.Copy(args, 1, subProcessArguments, 0, subProcessArguments.Length);
}
var subProcessCommandLine = string.Format(
"exec --depsfile {0} --runtimeconfig {1} {2} _{3} {4}", // note the underscore prepended to the command name
EscapePath(depsFile),
EscapePath(runtimeConfig),
EscapePath(typeof(Program).GetTypeInfo().Assembly.Location),
commandName,
string.Join(" ", subProcessArguments.Select(EscapePath))
);
return subProcessCommandLine;
}
private static string EscapePath(string path)
{
return path.Contains(' ')
? "\"" + path + "\""
: path;
}
private static IServiceProvider GetServiceProvider(Assembly startupAssembly)
{
if (TryGetCustomHost(startupAssembly, "SwaggerHostFactory", "CreateHost", out IHost host))
{
return host.Services;
}
if (TryGetCustomHost(startupAssembly, "SwaggerWebHostFactory", "CreateWebHost", out IWebHost webHost))
{
return webHost.Services;
}
try
{
return WebHost.CreateDefaultBuilder()
.UseStartup(startupAssembly.GetName().Name)
.Build()
.Services;
}
catch
{
var serviceProvider = HostingApplication.GetServiceProvider(startupAssembly);
if (serviceProvider != null)
{
return serviceProvider;
}
throw;
}
}
private static bool TryGetCustomHost<THost>(
Assembly startupAssembly,
string factoryClassName,
string factoryMethodName,
out THost host)
{
// Scan the assembly for any types that match the provided naming convention
var factoryTypes = startupAssembly.DefinedTypes
.Where(t => t.Name == factoryClassName)
.ToList();
if (factoryTypes.Count == 0)
{
host = default;
return false;
}
else if (factoryTypes.Count > 1)
{
throw new InvalidOperationException($"Multiple {factoryClassName} classes detected");
}
var factoryMethod = factoryTypes
.Single()
.GetMethod(factoryMethodName, BindingFlags.Public | BindingFlags.Static);
if (factoryMethod == null || factoryMethod.ReturnType != typeof(THost))
{
throw new InvalidOperationException(
$"{factoryClassName} class detected but does not contain a public static method " +
$"called {factoryMethodName} with return type {typeof(THost).Name}");
}
host = (THost)factoryMethod.Invoke(null, null);
return true;
}
private static void WriteSerializeAsV2DeprecationWarning()
{
const string AppName = "Swashbuckle.AspNetCore.Cli";
string message = $"The {SerializeAsV2Flag} flag will be removed in a future version of {AppName}. Use the {OpenApiVersionOption} option instead.";
Console.WriteLine(message);
// See https://docs.github.com/actions/writing-workflows/choosing-what-your-workflow-does/workflow-commands-for-github-actions#setting-a-warning-message
// and https://docs.github.com/actions/writing-workflows/choosing-what-your-workflow-does/store-information-in-variables#default-environment-variables
if (Environment.GetEnvironmentVariable("GITHUB_ACTIONS") is "true")
{
Console.WriteLine($"::warning title={AppName}::{message}");
}
}
}
}