forked from domaindrivendev/Swashbuckle.AspNetCore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
313 lines (263 loc) · 12.7 KB
/
Program.cs
File metadata and controls
313 lines (263 loc) · 12.7 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
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.Loader;
using System.Text;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi;
using Swashbuckle.AspNetCore.Swagger;
namespace Swashbuckle.AspNetCore.Cli;
internal class Program
{
private const string OpenApiVersionOption = "--openapiversion";
public static async Task<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);
c.OnRun((namedArgs) =>
{
string subProcessCommandLine = PrepareCommandLine(args, namedArgs);
using var child = Process.Start("dotnet", subProcessCommandLine);
child.WaitForExit();
return Task.FromResult(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);
c.OnRun(async (namedArgs) =>
{
SetupAndRetrieveSwaggerProviderAndOptions(namedArgs, out var asyncSwaggerProvider, out var swaggerProvider, out var swaggerOptions);
var swaggerDocumentSerializer = swaggerOptions?.Value?.CustomDocumentSerializer;
var host = namedArgs.TryGetValue("--host", out var arg) ? arg : null;
var basePath = namedArgs.TryGetValue("--basepath", out var namedArg) ? namedArg : null;
var swagger = asyncSwaggerProvider != null
? await asyncSwaggerProvider.GetSwaggerAsync(namedArgs["swaggerdoc"], host, basePath)
: swaggerProvider.GetSwagger(namedArgs["swaggerdoc"], host, basePath);
// 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,
"3.1" => OpenApiSpecVersion.OpenApi3_1,
_ => throw new NotSupportedException($"The specified OpenAPI version \"{versionArg}\" is not supported."),
};
}
if (swaggerDocumentSerializer != null)
{
swaggerDocumentSerializer.SerializeDocument(swagger, writer, specVersion);
}
else
{
swagger.SerializeAs(specVersion, writer);
}
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 Task.FromResult(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 _, 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 Task.FromResult(-1);
}
docNames = docMetaProvider.GetDocumentNames();
foreach (var name in docNames)
{
writer.WriteLine($"\"{name}\"");
}
return Task.FromResult(0);
});
});
return await runner.RunAsync(args);
}
private static void SetupAndRetrieveSwaggerProviderAndOptions(IDictionary<string, string> namedArgs, out IAsyncSwaggerProvider asyncSwaggerProvider, 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
asyncSwaggerProvider = serviceProvider.GetService<IAsyncSwaggerProvider>();
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).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;
}
#pragma warning disable ASPDEPR008
if (TryGetCustomHost(startupAssembly, "SwaggerWebHostFactory", "CreateWebHost", out IWebHost webHost))
{
return webHost.Services;
}
#pragma warning restore ASPDEPR008
try
{
return Host.CreateDefaultBuilder()
.ConfigureWebHostDefaults(builder => builder.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;
}
}