Skip to content

Commit

Permalink
Simplify collection initialization (#5044)
Browse files Browse the repository at this point in the history
  • Loading branch information
lahma authored Nov 22, 2024
1 parent 63082af commit 9ce0218
Show file tree
Hide file tree
Showing 27 changed files with 102 additions and 102 deletions.
5 changes: 1 addition & 4 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,6 @@
[IDE0260] Use pattern matching
[IDE0270] Null check can be simplified
[IDE0290] Use primary constructor
[IDE0300] Collection initialization can be simplified
[IDE0301] Collection initialization can be simplified
[IDE0305] Collection initialization can be simplified
[IDE0330] Use 'System.Threading.Lock'
[CA1200] Avoid using cref tags with a prefix
[CA1304] The behavior of 'string.ToUpper()' could vary based on the current user's locale settings
Expand Down Expand Up @@ -108,7 +105,7 @@
[SYSLIB0012] 'Assembly.CodeBase' is obsolete
-->
<NoWarn>$(NoWarn);IDE0005;IDE0008;IDE0011;IDE0017;IDE0019;IDE0021;IDE0022;IDE0025;IDE0027;IDE0028;IDE0029;IDE0032;IDE0039;IDE0045;IDE0046;IDE0055;IDE0056;IDE0057;IDE0059;IDE0060;IDE0061;IDE0074;IDE0078;IDE0083;IDE0090;IDE0130;IDE0160;IDE0200;IDE0260;IDE0270;IDE0290;IDE0300;IDE0305;IDE0301;IDE0330</NoWarn>
<NoWarn>$(NoWarn);IDE0005;IDE0008;IDE0011;IDE0017;IDE0019;IDE0021;IDE0022;IDE0025;IDE0027;IDE0028;IDE0029;IDE0032;IDE0039;IDE0045;IDE0046;IDE0055;IDE0056;IDE0057;IDE0059;IDE0060;IDE0061;IDE0074;IDE0078;IDE0083;IDE0090;IDE0130;IDE0160;IDE0200;IDE0260;IDE0270;IDE0290;IDE0330</NoWarn>
<NoWarn>$(NoWarn);CA1200;CA1304;CA1305;CA1310;CA1311;CA1507;CA1510;CA1514;CA1710;CA1716;CA1720;CA1725;CA1805;CA1834;CA1845;CA1847;CA1861;CA1862;CA1865;CA1866;CA1870;CA2249;CA2263;SYSLIB0012</NoWarn>
</PropertyGroup>

Expand Down
2 changes: 1 addition & 1 deletion src/NSwag.Annotations/OpenApiBodyParameterAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public class OpenApiBodyParameterAttribute : Attribute
/// <summary>Initializes a new instance of the <see cref="OpenApiBodyParameterAttribute"/> class with the 'application/json' mime type.</summary>
public OpenApiBodyParameterAttribute()
{
MimeTypes = new[] { "application/json" };
MimeTypes = ["application/json"];
}

/// <summary>Initializes a new instance of the <see cref="OpenApiBodyParameterAttribute"/> class.</summary>
Expand Down
6 changes: 3 additions & 3 deletions src/NSwag.AspNet.Owin/SwaggerExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public static IAppBuilder UseOpenApi(
Assembly webApiAssembly,
Action<SwaggerSettings<WebApiOpenApiDocumentGeneratorSettings>> configure = null)
{
return app.UseOpenApi(new[] { webApiAssembly }, configure);
return app.UseOpenApi([webApiAssembly], configure);
}

/// <summary>Adds the OpenAPI/Swagger generator to the OWIN pipeline.</summary>
Expand Down Expand Up @@ -81,7 +81,7 @@ public static IAppBuilder UseSwaggerUi(
Assembly webApiAssembly,
Action<SwaggerUiSettings<WebApiOpenApiDocumentGeneratorSettings>> configure = null)
{
return app.UseSwaggerUi(new[] { webApiAssembly }, configure);
return app.UseSwaggerUi([webApiAssembly], configure);
}

/// <summary>Adds the Swagger generator and Swagger UI to the OWIN pipeline.</summary>
Expand Down Expand Up @@ -152,7 +152,7 @@ public static IAppBuilder UseSwaggerReDoc(
Assembly webApiAssembly,
Action<ReDocSettings<WebApiOpenApiDocumentGeneratorSettings>> configure = null)
{
return app.UseSwaggerReDoc(new[] { webApiAssembly }, configure);
return app.UseSwaggerReDoc([webApiAssembly], configure);
}

/// <summary>Adds the Swagger generator and Swagger UI to the OWIN pipeline.</summary>
Expand Down
2 changes: 1 addition & 1 deletion src/NSwag.AspNetCore.Launcher/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ private static int Main(string[] args)

try
{
method.Invoke(null, new[] { commandContent, outputFile, applicationName });
method.Invoke(null, [commandContent, outputFile, applicationName]);
}
catch (Exception ex)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,10 @@ protected CSharpGeneratorBaseSettings()
SchemaType = SchemaType.Swagger2
};

CSharpGeneratorSettings.TemplateFactory = new DefaultTemplateFactory(CSharpGeneratorSettings, new[]
{
CSharpGeneratorSettings.TemplateFactory = new DefaultTemplateFactory(CSharpGeneratorSettings, [
typeof(CSharpGeneratorSettings).GetTypeInfo().Assembly,
typeof(CSharpGeneratorBaseSettings).GetTypeInfo().Assembly,
});
typeof(CSharpGeneratorBaseSettings).GetTypeInfo().Assembly
]);

ResponseArrayType = "System.Collections.Generic.ICollection";
ResponseDictionaryType = "System.Collections.Generic.IDictionary";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ public IEnumerable<string> ResponseClassNames
.Distinct();
}

return new[] { _settings.ResponseClass.Replace("{controller}", string.Empty) };
return [_settings.ResponseClass.Replace("{controller}", string.Empty)];
}
}

Expand All @@ -150,7 +150,7 @@ public IEnumerable<string> ExceptionClassNames
}
else
{
return new[] { settings.ExceptionClass.Replace("{controller}", string.Empty) };
return [settings.ExceptionClass.Replace("{controller}", string.Empty)];
}
}
return [];
Expand Down
23 changes: 11 additions & 12 deletions src/NSwag.CodeGeneration.CSharp/Models/CSharpOperationModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,15 @@ namespace NSwag.CodeGeneration.CSharp.Models
/// <summary>The CSharp operation model.</summary>
public class CSharpOperationModel : OperationModelBase<CSharpParameterModel, CSharpResponseModel>
{
private static readonly string[] ReservedKeywords =
{
private static readonly HashSet<string> ReservedKeywords =
[
"abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue",
"decimal", "default", "delegate", "do", "double", "else", "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float",
"for", "foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object",
"operator", "out", "override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof",
"stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe",
"ushort", "using", "virtual", "void", "volatile", "while"
};
];

private readonly CSharpGeneratorBaseSettings _settings;
private readonly OpenApiOperation _operation;
Expand Down Expand Up @@ -55,17 +55,16 @@ public CSharpOperationModel(
// TODO: Move to CSharpControllerOperationModel
if (generator is CSharpControllerGenerator)
{
parameters = parameters
parameters = [.. parameters
.OrderBy(p => p.Position ?? 0)
.OrderBy(p => !p.IsRequired)
.ThenBy(p => p.Default == null).ToList();
.ThenBy(p => !p.IsRequired)
.ThenBy(p => p.Default == null)];
}
else
{
parameters = parameters
parameters = [.. parameters
.OrderBy(p => p.Position ?? 0)
.OrderBy(p => !p.IsRequired)
.ToList();
.ThenBy(p => !p.IsRequired)];
}
}

Expand Down Expand Up @@ -181,10 +180,10 @@ public IEnumerable<CSharpExceptionDescriptionModel> ExceptionDescriptions
}
else if (r.InheritsExceptionSchema)
{
return new[]
{
return
[
new CSharpExceptionDescriptionModel(r.Type, r.ExceptionDescription, controllerName, settings)
};
];
}
else
{
Expand Down
6 changes: 3 additions & 3 deletions src/NSwag.CodeGeneration.Tests/CodeGenerationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ public void When_generating_CSharp_code_with_SystemTextJson_and_JsonConverters_t
// Act
var settings = new CSharpClientGeneratorSettings();
settings.CSharpGeneratorSettings.JsonLibrary = NJsonSchema.CodeGeneration.CSharp.CSharpJsonLibrary.SystemTextJson;
settings.CSharpGeneratorSettings.JsonConverters = new[] { "CustomConverter1", "CustomConverter2" };
settings.CSharpGeneratorSettings.JsonConverters = ["CustomConverter1", "CustomConverter2"];

var generator = new CSharpClientGenerator(document, settings);
var code = generator.GenerateFile();
Expand Down Expand Up @@ -140,7 +140,7 @@ public static Person FromJson(string data)
// Act
var settings = new CSharpClientGeneratorSettings();
settings.CSharpGeneratorSettings.JsonLibrary = NJsonSchema.CodeGeneration.CSharp.CSharpJsonLibrary.SystemTextJson;
settings.CSharpGeneratorSettings.JsonConverters = new[] { "CustomConverter1", "CustomConverter2" };
settings.CSharpGeneratorSettings.JsonConverters = ["CustomConverter1", "CustomConverter2"];
settings.CSharpGeneratorSettings.GenerateJsonMethods = true;

var generator = new CSharpClientGenerator(document, settings);
Expand Down Expand Up @@ -237,7 +237,7 @@ public void When_using_MultipleClientsFromFirstTagAndOperationName_then_ensure_t
// Arrange
var operation = new OpenApiOperation
{
Tags = tags.ToList()
Tags = [.. tags]
};
var generator = new MultipleClientsFromFirstTagAndOperationNameGenerator();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public IEnumerable<string> ResponseClassNames
.Distinct();
}

return new[] { _settings.ResponseClass.Replace("{controller}", string.Empty) };
return [_settings.ResponseClass.Replace("{controller}", string.Empty)];
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,7 @@ public TypeScriptOperationModel(

if (settings.GenerateOptionalParameters)
{
parameters = parameters
.OrderBy(p => p.Position ?? 0)
.OrderBy(p => !p.IsRequired)
.ToList();
parameters = [.. parameters.OrderBy(p => p.Position ?? 0).ThenBy(p => !p.IsRequired)];
}

Parameters = parameters
Expand Down Expand Up @@ -131,7 +128,7 @@ public override string ExceptionType
return string.Join(" | ", _operation.ActualResponses
.Where(r => !HttpUtilities.IsSuccessStatusCode(r.Key) && r.Value.Schema != null)
.Select(r => _generator.GetTypeName(r.Value.Schema, r.Value.IsNullable(_settings.CodeGeneratorSettings.SchemaType), "Exception"))
.Concat(new[] { "string" }));
.Concat(["string"]));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ public TypeScriptClientGenerator(OpenApiDocument document, TypeScriptClientGener

_extensionCode = new TypeScriptExtensionCode(
Settings.TypeScriptGeneratorSettings.ExtensionCode,
(Settings.TypeScriptGeneratorSettings.ExtendedClasses ?? []).Concat(new[] { Settings.ConfigurationClass }).ToArray(),
new[] { Settings.ClientBaseClass });
[.. (Settings.TypeScriptGeneratorSettings.ExtendedClasses ?? []), Settings.ConfigurationClass],
[Settings.ClientBaseClass]);
}

/// <summary>Gets or sets the generator settings.</summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,10 @@ public TypeScriptClientGeneratorSettings()
TypeScriptVersion = 2.7m
};

TypeScriptGeneratorSettings.TemplateFactory = new DefaultTemplateFactory(TypeScriptGeneratorSettings, new Assembly[]
{
TypeScriptGeneratorSettings.TemplateFactory = new DefaultTemplateFactory(TypeScriptGeneratorSettings, [
typeof(TypeScriptGeneratorSettings).GetTypeInfo().Assembly,
typeof(TypeScriptClientGeneratorSettings).GetTypeInfo().Assembly,
});
typeof(TypeScriptClientGeneratorSettings).GetTypeInfo().Assembly
]);

ProtectedMethods = [];
}
Expand Down
49 changes: 29 additions & 20 deletions src/NSwag.CodeGeneration/ClientGeneratorBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ public abstract class ClientGeneratorBase<TOperationModel, TParameterModel, TRes
/// <param name="document">The document.</param>
/// <param name="settings">The code generator settings.</param>
/// <param name="resolver">The type resolver.</param>
protected ClientGeneratorBase(OpenApiDocument document, CodeGeneratorSettingsBase settings, TypeResolverBase resolver)
protected ClientGeneratorBase(OpenApiDocument document, CodeGeneratorSettingsBase settings,
TypeResolverBase resolver)
{
_document = document;
Resolver = resolver;
Expand Down Expand Up @@ -70,19 +71,21 @@ public string GenerateFile(ClientGeneratorOutputType outputType)
{
var clientTypes = GenerateAllClientTypes();

var dtoTypes = BaseSettings.GenerateDtoTypes ?
GenerateDtoTypes() :
Enumerable.Empty<CodeArtifact>();
var dtoTypes = BaseSettings.GenerateDtoTypes ? GenerateDtoTypes() : [];

clientTypes =
outputType == ClientGeneratorOutputType.Full ? clientTypes :
outputType == ClientGeneratorOutputType.Implementation ? clientTypes.Where(t => t.Category != CodeArtifactCategory.Contract) :
outputType == ClientGeneratorOutputType.Contracts ? clientTypes.Where(t => t.Category == CodeArtifactCategory.Contract) :
Enumerable.Empty<CodeArtifact>();

dtoTypes =
outputType == ClientGeneratorOutputType.Full ||
outputType == ClientGeneratorOutputType.Contracts ? dtoTypes : Enumerable.Empty<CodeArtifact>();
clientTypes = outputType switch
{
ClientGeneratorOutputType.Full => clientTypes,
ClientGeneratorOutputType.Implementation => clientTypes.Where(t =>
t.Category != CodeArtifactCategory.Contract),
ClientGeneratorOutputType.Contracts => clientTypes.Where(t =>
t.Category == CodeArtifactCategory.Contract),
_ => []
};

dtoTypes = outputType is ClientGeneratorOutputType.Full or ClientGeneratorOutputType.Contracts
? dtoTypes
: [];

return GenerateFile(clientTypes, dtoTypes, outputType)
.Replace("\r", string.Empty)
Expand All @@ -95,7 +98,8 @@ public string GenerateFile(ClientGeneratorOutputType outputType)
/// <param name="dtoTypes">The DTO types.</param>
/// <param name="outputType">Type of the output.</param>
/// <returns>The code.</returns>
protected abstract string GenerateFile(IEnumerable<CodeArtifact> clientTypes, IEnumerable<CodeArtifact> dtoTypes, ClientGeneratorOutputType outputType);
protected abstract string GenerateFile(IEnumerable<CodeArtifact> clientTypes,
IEnumerable<CodeArtifact> dtoTypes, ClientGeneratorOutputType outputType);

/// <summary>Generates the client types.</summary>
/// <returns>The code artifact collection.</returns>
Expand All @@ -111,7 +115,7 @@ protected virtual IEnumerable<CodeArtifact> GenerateAllClientTypes()
{
var controllerName = controllerOperations.Key;
var controllerClassName = BaseSettings.GenerateControllerName(controllerOperations.Key);
var clientType = GenerateClientTypes(controllerName, controllerClassName, controllerOperations.ToList());
var clientType = GenerateClientTypes(controllerName, controllerClassName, [.. controllerOperations]);
clientTypes.AddRange(clientType);
}
}
Expand All @@ -131,7 +135,8 @@ protected virtual IEnumerable<CodeArtifact> GenerateAllClientTypes()
/// <param name="controllerClassName">Name of the controller class.</param>
/// <param name="operations">The operations.</param>
/// <returns>The code.</returns>
protected abstract IEnumerable<CodeArtifact> GenerateClientTypes(string controllerName, string controllerClassName, IEnumerable<TOperationModel> operations);
protected abstract IEnumerable<CodeArtifact> GenerateClientTypes(string controllerName,
string controllerClassName, IEnumerable<TOperationModel> operations);

/// <summary>Generates all DTO types.</summary>
/// <returns>The code artifact collection.</returns>
Expand All @@ -141,7 +146,8 @@ protected virtual IEnumerable<CodeArtifact> GenerateAllClientTypes()
/// <param name="operation">The operation.</param>
/// <param name="settings">The settings.</param>
/// <returns>The operation model.</returns>
protected abstract TOperationModel CreateOperationModel(OpenApiOperation operation, ClientGeneratorBaseSettings settings);
protected abstract TOperationModel CreateOperationModel(OpenApiOperation operation,
ClientGeneratorBaseSettings settings);

private List<TOperationModel> GetOperations(OpenApiDocument document)
{
Expand All @@ -156,7 +162,8 @@ private List<TOperationModel> GetOperations(OpenApiDocument document)
var httpMethod = p.Key;
var operation = p.Value;

var operationName = BaseSettings.OperationNameGenerator.GetOperationName(document, path, httpMethod, operation);
var operationName =
BaseSettings.OperationNameGenerator.GetOperationName(document, path, httpMethod, operation);

if (operationName.Contains("."))
{
Expand All @@ -169,15 +176,17 @@ private List<TOperationModel> GetOperations(OpenApiDocument document)
}

var operationModel = CreateOperationModel(operation, BaseSettings);
operationModel.ControllerName = BaseSettings.OperationNameGenerator.GetClientName(document, path, httpMethod, operation);
operationModel.ControllerName =
BaseSettings.OperationNameGenerator.GetClientName(document, path, httpMethod, operation);
operationModel.Path = path;
operationModel.HttpMethod = httpMethod;
operationModel.OperationName = operationName;

result.Add(operationModel);
}
}

return result;
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ private static ReadOnlySpan<char> GetClientName(OpenApiOperation operation)
// no underscore, fast path
if (idxFirst == -1)
{
return ReadOnlySpan<char>.Empty;
return [];
}

int idxLast = operationIdSpan.LastIndexOf(underscoreSeparator);
Expand All @@ -88,7 +88,7 @@ private static ReadOnlySpan<char> GetClientName(OpenApiOperation operation)
// underscore is the first character
if (idxFirst == 0)
{
return ReadOnlySpan<char>.Empty;
return [];
}

return operationIdSpan.Slice(0, idxFirst);
Expand Down
Loading

0 comments on commit 9ce0218

Please sign in to comment.