-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
OpenApiToCSharpClientCommand.cs
315 lines (271 loc) · 15.2 KB
/
OpenApiToCSharpClientCommand.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
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
//-----------------------------------------------------------------------
// <copyright file="SwaggerToCSharpClientCommand.cs" company="NSwag">
// Copyright (c) Rico Suter. All rights reserved.
// </copyright>
// <license>https://github.com/RicoSuter/NSwag/blob/master/LICENSE.md</license>
// <author>Rico Suter, mail@rsuter.com</author>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NConsole;
using NSwag.CodeGeneration;
using NSwag.CodeGeneration.CSharp;
#pragma warning disable 1591
namespace NSwag.Commands.CodeGeneration
{
[Command(Name = "openapi2csclient", Description = "Generates CSharp client code from a Swagger/OpenAPI specification.")]
public class OpenApiToCSharpClientCommand : OpenApiToCSharpCommandBase<CSharpClientGeneratorSettings>
{
public OpenApiToCSharpClientCommand() : base(new CSharpClientGeneratorSettings())
{
}
[Argument(Name = "ClientBaseClass", IsRequired = false, Description = "The client base class (empty for no base class).")]
public string ClientBaseClass
{
get { return Settings.ClientBaseClass; }
set { Settings.ClientBaseClass = value; }
}
[Argument(Name = "ConfigurationClass", IsRequired = false, Description = "The configuration class. The setting ClientBaseClass must be set. (empty for no configuration class).")]
public string ConfigurationClass
{
get { return Settings.ConfigurationClass; }
set { Settings.ConfigurationClass = value; }
}
[Argument(Name = "GenerateClientClasses", IsRequired = false, Description = "Specifies whether generate client classes.")]
public bool GenerateClientClasses
{
get { return Settings.GenerateClientClasses; }
set { Settings.GenerateClientClasses = value; }
}
[Argument(Name = "SuppressClientClassesOutput", IsRequired = false, Description = "Specifies whether generate output for client classes.")]
public bool SuppressClientClassesOutput
{
get { return Settings.SuppressClientClassesOutput; }
set { Settings.SuppressClientClassesOutput = value; }
}
[Argument(Name = "GenerateClientInterfaces", IsRequired = false, Description = "Specifies whether generate interfaces for the client classes.")]
public bool GenerateClientInterfaces
{
get { return Settings.GenerateClientInterfaces; }
set { Settings.GenerateClientInterfaces = value; }
}
[Argument(Name = "SuppressClientInterfacesOutput", IsRequired = false, Description = "Specifies whether generate output for interfaces for the client classes.")]
public bool SuppressClientInterfacesOutput
{
get { return Settings.SuppressClientInterfacesOutput; }
set { Settings.SuppressClientInterfacesOutput = value; }
}
[Argument(Name = "ClientBaseInterface", IsRequired = false, Description = "Base interface for client interfaces (empty for no client base interface).")]
public string ClientBaseInterface
{
get { return Settings.ClientBaseInterface; }
set { Settings.ClientBaseInterface = value; }
}
[Argument(Name = "InjectHttpClient", IsRequired = false, Description = "Specifies whether an HttpClient instance is injected (default: true).")]
public bool InjectHttpClient
{
get { return Settings.InjectHttpClient; }
set { Settings.InjectHttpClient = value; }
}
[Argument(Name = "DisposeHttpClient", IsRequired = false, Description = "Specifies whether to dispose the HttpClient (injected HttpClient is never disposed).")]
public bool DisposeHttpClient
{
get { return Settings.DisposeHttpClient; }
set { Settings.DisposeHttpClient = value; }
}
[Argument(Name = "ProtectedMethods", IsRequired = false, Description = "List of methods with a protected access modifier ('classname.methodname').")]
public string[] ProtectedMethods
{
get { return Settings.ProtectedMethods; }
set { Settings.ProtectedMethods = value; }
}
[Argument(Name = "GenerateExceptionClasses", IsRequired = false, Description = "Specifies whether to generate exception classes (default: true).")]
public bool GenerateExceptionClasses
{
get { return Settings.GenerateExceptionClasses; }
set { Settings.GenerateExceptionClasses = value; }
}
[Argument(Name = "ExceptionClass", IsRequired = false, Description = "The exception class (default 'SwaggerException', may use '{controller}' placeholder).")]
public string ExceptionClass
{
get { return Settings.ExceptionClass; }
set { Settings.ExceptionClass = value; }
}
[Argument(Name = "WrapDtoExceptions", IsRequired = false, Description = "Specifies whether DTO exceptions are wrapped in a SwaggerException instance (default: true).")]
public bool WrapDtoExceptions
{
get { return Settings.WrapDtoExceptions; }
set { Settings.WrapDtoExceptions = value; }
}
[Argument(Name = "UseHttpClientCreationMethod", IsRequired = false, Description = "Specifies whether to call CreateHttpClientAsync on the base class to create a new HttpClient.")]
public bool UseHttpClientCreationMethod
{
get { return Settings.UseHttpClientCreationMethod; }
set { Settings.UseHttpClientCreationMethod = value; }
}
[Argument(Name = "HttpClientType", IsRequired = false, Description = "Specifies the HttpClient type. By default the 'System.Net.Http.HttpClient' is used.")]
public string HttpClientType
{
get { return Settings.HttpClientType; }
set { Settings.HttpClientType = value; }
}
[Argument(Name = "UseHttpRequestMessageCreationMethod", IsRequired = false,
Description = "Specifies whether to call CreateHttpRequestMessageAsync on the base class to create a new HttpRequestMethod.")]
public bool UseHttpRequestMessageCreationMethod
{
get { return Settings.UseHttpRequestMessageCreationMethod; }
set { Settings.UseHttpRequestMessageCreationMethod = value; }
}
[Argument(Name = "UseBaseUrl", IsRequired = false,
Description = "Specifies whether to use and expose the base URL (default: true).")]
public bool UseBaseUrl
{
get { return Settings.UseBaseUrl; }
set { Settings.UseBaseUrl = value; }
}
[Argument(Name = nameof(GenerateBaseUrlProperty), IsRequired = false,
Description = "Specifies whether to generate the BaseUrl property, must be defined on the base class otherwise (default: true).")]
public bool GenerateBaseUrlProperty
{
get { return Settings.GenerateBaseUrlProperty; }
set { Settings.GenerateBaseUrlProperty = value; }
}
[Argument(Name = "GenerateSyncMethods", IsRequired = false,
Description = "Specifies whether to generate synchronous methods (not recommended, default: false).")]
public bool GenerateSyncMethods
{
get { return Settings.GenerateSyncMethods; }
set { Settings.GenerateSyncMethods = value; }
}
[Argument(Name = "GeneratePrepareRequestAndProcessResponseAsAsyncMethods", IsRequired = false,
Description = "Specifies whether to generate PrepareRequest and ProcessResponse methods as asynchronous methods (if true, both must be defined in the base class or in the partial class, default: false).")]
public bool GeneratePrepareRequestAndProcessResponseAsAsyncMethods
{
get { return Settings.GeneratePrepareRequestAndProcessResponseAsAsyncMethods; }
set { Settings.GeneratePrepareRequestAndProcessResponseAsAsyncMethods = value; }
}
[Argument(Name = nameof(ExposeJsonSerializerSettings), IsRequired = false,
Description = "Specifies whether to expose the JsonSerializerSettings property (default: false).")]
public bool ExposeJsonSerializerSettings
{
get { return Settings.ExposeJsonSerializerSettings; }
set { Settings.ExposeJsonSerializerSettings = value; }
}
[Argument(Name = "ClientClassAccessModifier", IsRequired = false, Description = "The client class access modifier (default: public).")]
public string ClientClassAccessModifier
{
get { return Settings.ClientClassAccessModifier; }
set { Settings.ClientClassAccessModifier = value; }
}
[Argument(Name = "TypeAccessModifier", IsRequired = false, Description = "The DTO class/enum access modifier (default: public).")]
public string TypeAccessModifier
{
get { return Settings.CSharpGeneratorSettings.TypeAccessModifier; }
set { Settings.CSharpGeneratorSettings.TypeAccessModifier = value; }
}
[Argument(Name = "PropertySetterAccessModifier", IsRequired = false, Description = "The access modifier of property setters (default: '').")]
public string PropertySetterAccessModifier
{
get { return Settings.CSharpGeneratorSettings.PropertySetterAccessModifier; }
set { Settings.CSharpGeneratorSettings.PropertySetterAccessModifier = value; }
}
[Argument(Name = "GenerateNativeRecords", IsRequired = false, Description = "Generate C# 9.0 record types instead of record-like classes (default: false).")]
public bool GenerateNativeRecords
{
get { return Settings.CSharpGeneratorSettings.GenerateNativeRecords; }
set { Settings.CSharpGeneratorSettings.GenerateNativeRecords = value; }
}
[Argument(Name = "GenerateContractsOutput", IsRequired = false,
Description = "Specifies whether to generate contracts output (interface and models in a separate file set with the ContractsOutput parameter).")]
public bool GenerateContractsOutput { get; set; }
[Argument(Name = "ContractsNamespace", IsRequired = false, Description = "The contracts .NET namespace.")]
public string ContractsNamespace { get; set; }
[Argument(Name = "ContractsOutput", IsRequired = false,
Description = "The contracts output file path (optional, if no path is set then a single file with the implementation and contracts is generated).")]
public string ContractsOutputFilePath { get; set; }
[Argument(Name = "ParameterDateTimeFormat", IsRequired = false,
Description = "Specifies the format for DateTime type method parameters (default: s).")]
public string ParameterDateTimeFormat
{
get { return Settings.ParameterDateTimeFormat; }
set { Settings.ParameterDateTimeFormat = value; }
}
[Argument(Name = "ParameterDateFormat", IsRequired = false,
Description = "Specifies the format for Date type method parameters (default: yyyy-MM-dd).")]
public string ParameterDateFormat
{
get { return Settings.ParameterDateFormat; }
set { Settings.ParameterDateFormat = value; }
}
[Argument(Name = "GenerateUpdateJsonSerializerSettingsMethod", IsRequired = false,
Description = "Generate the UpdateJsonSerializerSettings method (must be implemented in the base class otherwise, default: true).")]
public bool GenerateUpdateJsonSerializerSettingsMethod
{
get { return Settings.GenerateUpdateJsonSerializerSettingsMethod; }
set { Settings.GenerateUpdateJsonSerializerSettingsMethod = value; }
}
[Argument(Name = "UseRequestAndResponseSerializationSettings", IsRequired = false,
Description = "Generate different request and response serialization settings (default: false).")]
public bool UseRequestAndResponseSerializationSettings
{
get { return Settings.UseRequestAndResponseSerializationSettings; }
set { Settings.UseRequestAndResponseSerializationSettings = value; }
}
[Argument(Name = "SerializeTypeInformation", IsRequired = false,
Description = "Serialize the type information in a $type property (not recommended, also sets TypeNameHandling = Auto, default: false).")]
public bool SerializeTypeInformation
{
get { return Settings.SerializeTypeInformation; }
set { Settings.SerializeTypeInformation = value; }
}
[Argument(Name = nameof(QueryNullValue), IsRequired = false,
Description = "The null value used for query parameters which are null (default: '').")]
public string QueryNullValue
{
get { return Settings.QueryNullValue; }
set { Settings.QueryNullValue = value; }
}
public override async Task<object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
{
var result = await RunAsync();
foreach (var pair in result)
{
await TryWriteFileOutputAsync(pair.Key, host, () => pair.Value).ConfigureAwait(false);
}
return result;
}
public async Task<Dictionary<string, string>> RunAsync()
{
var document = await GetInputSwaggerDocument().ConfigureAwait(false);
var clientGenerator = new CSharpClientGenerator(document, Settings);
if (GenerateContractsOutput)
{
var result = new Dictionary<string, string>();
GenerateContracts(result, clientGenerator);
GenerateImplementation(result, clientGenerator);
return result;
}
return new Dictionary<string, string>
{
{ OutputFilePath ?? "Full", clientGenerator.GenerateFile(ClientGeneratorOutputType.Full) }
};
}
private void GenerateImplementation(Dictionary<string, string> result, CSharpClientGenerator clientGenerator)
{
var savedAdditionalNamespaceUsages = Settings.AdditionalNamespaceUsages?.ToArray();
Settings.AdditionalNamespaceUsages =
Settings.AdditionalNamespaceUsages?.Concat(new[] { ContractsNamespace }).ToArray() ?? new[] { ContractsNamespace };
result[OutputFilePath ?? "Implementation"] = clientGenerator.GenerateFile(ClientGeneratorOutputType.Implementation);
Settings.AdditionalNamespaceUsages = savedAdditionalNamespaceUsages;
}
private void GenerateContracts(Dictionary<string, string> result, CSharpClientGenerator clientGenerator)
{
var savedNamespace = Settings.CSharpGeneratorSettings.Namespace;
Settings.CSharpGeneratorSettings.Namespace = ContractsNamespace;
result[ContractsOutputFilePath ?? "Contracts"] = clientGenerator.GenerateFile(ClientGeneratorOutputType.Contracts);
Settings.CSharpGeneratorSettings.Namespace = savedNamespace;
}
}
}