Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add analysis rules and relaxations #5036

Merged
merged 1 commit into from
Nov 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 85 additions & 2 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,10 @@
<RepositoryUrl>https://github.com/RicoSuter/NSwag.git</RepositoryUrl>

<LangVersion>latest</LangVersion>
<!-- TODO -->
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>

<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<!-- suppress NuGet audit checks being errors -->
<WarningsNotAsErrors>NU1901,NU1902,NU1903,NU1904</WarningsNotAsErrors>

<PublishRepositoryUrl>true</PublishRepositoryUrl>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
Expand All @@ -38,4 +40,85 @@
<ItemGroup>
<None Include="..\..\assets\NuGetIcon.png" Pack="true" Visible="false" PackagePath="" />
</ItemGroup>

<PropertyGroup Label="Analyzer settings">
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<AnalysisLevel>latest-Recommended</AnalysisLevel>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
<!--
[IDE0005] Using directive is unnecessary
[IDE0011] Add braces to 'if' statement
[IDE0008] Use explicit type instead of 'var'
[IDE0017] Object initialization can be simplified
[IDE0019] Use pattern matching
[IDE0021] Use block body for constructor
[IDE0022] Use block body for method
[IDE0025] Use expression body for property
[IDE0027] Use expression body for accessor
[IDE0028] Collection initialization can be simplified
[IDE0029] Null check can be simplified
[IDE0032] Use auto property
[IDE0039] Use local function
[IDE0040] Accessibility modifiers required
[IDE0044] Make field readonly
[IDE0045] 'if' statement can be simplified
[IDE0046] 'if' statement can be simplified
[IDE0055] Fix formatting
[IDE0056] Indexing can be simplified
[IDE0057] Substring can be simplified
[IDE0059] Unnecessary assignment of a value
[IDE0060] Remove unused parameter
[IDE0061] Use block body for local function
[IDE0063] 'using' statement can be simplified
[IDE0074] Use compound assignment
[IDE0078] Use pattern matching
[IDE0083] Use pattern matching
[IDE0090] 'new' expression can be simplified
[IDE0100] Remove redundant equality
[IDE0130] Namespace does not match folder structure
[IDE0160] Convert to block scoped namespace
[IDE0200] Lambda expression can be removed
[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'
[IDE1005] Delegate invocation can be simplified
[CA1200] Avoid using cref tags with a prefix
[CA1304] The behavior of 'string.ToUpper()' could vary based on the current user's locale settings
[CA1305] The behavior of 'int.ToString()' could vary based on the current user's locale settings
[CA1310] The behavior of 'string.StartsWith(string)' could vary based on the current user's locale settings
[CA1311] The behavior of 'string.StartsWith(string)' could vary based on the current user's locale settings
[CA1507] Use nameof in place of string literal
[CA1510] Use 'ArgumentNullException.ThrowIfNull' instead of explicitly throwing a new exception instance
[CA1514] 'System.ReadOnlySpan<char>.Slice(int, int)' uses a redundant length calculation that can be removed
[CA1710] Rename to end in either 'Dictionary' or 'Collection'
[CA1716] rename parameter property so that it no longer conflicts with the reserved language keyword
[CA1720] Identifier 'xxx' contains type name
[CA1725] Overriden parameter name mismatch
[CA1805] Member is explicitly initialized to its default value
[CA1822] Member does not access instance data and can be marked as static
[CA1827] Count() is used where Any() could be used instead to improve performance
[CA1834] Use 'StringBuilder.Append(char)' instead of 'StringBuilder.Append(string)' when the input is a constant unit string
[CA1845] Use span-based 'string.Concat' and 'AsSpan' instead of 'Substring'
[CA1847] Use 'string.Contains(char)' instead of 'string.Contains(string)' - needs polyfill
[CA1852] Type can be sealed because it has no subtypes in its containing assembly and is not externally visible
[CA1854] Prefer a 'TryGetValue' call over a Dictionary indexer access
[CA1860] Prefer comparing 'Count' to 0 rather than using 'Any()'
[CA1861] Prefer 'static readonly' fields over constant array arguments
[CA1862] Prefer using 'string.Equals(string, StringComparison)' to perform a case-insensitive comparison
[CA1865] Use 'string.StartsWith(char)' instead of 'string.StartsWith(string)' - needs polyfill
[CA1866] Use 'string.StartsWith(char)' instead of 'string.StartsWith(string)' - needs polyfill
[CA1870] Use a cached 'SearchValues' instance for improved searching performance
[CA2249] Use 'string.Contains' instead of 'string.IndexOf' to improve readability - needs polyfill
[CA2263] Prefer the generic overload 'System.Enum.GetValues<TEnum>()'

[SYSLIB0012] 'Assembly.CodeBase' is obsolete
-->
<NoWarn>$(NoWarn);IDE0005;IDE0008;IDE0011;IDE0017;IDE0019;IDE0021;IDE0022;IDE0025;IDE0027;IDE0028;IDE0029;IDE0032;IDE0039;IDE0040;IDE0044;IDE0045;IDE0046;IDE0055;IDE0056;IDE0057;IDE0059;IDE0060;IDE0061;IDE0063;IDE0074;IDE0078;IDE0083;IDE0090;IDE0100;IDE0130;IDE0160;IDE0200;IDE0260;IDE0270;IDE0290;IDE0300;IDE0305;IDE0301;IDE0330;IDE1005</NoWarn>
<NoWarn>$(NoWarn);CA1200;CA1304;CA1305;CA1310;CA1311;CA1507;CA1510;CA1514;CA1710;CA1716;CA1720;CA1725;CA1805;CA1822;CA1827;CA1834;CA1845;CA1847;CA1852;CA1854;CA1860;CA1861;CA1862;CA1865;CA1866;CA1870;CA2249;CA2263;SYSLIB0012</NoWarn>
</PropertyGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<NoDefaultLaunchSettingsFile>true</NoDefaultLaunchSettingsFile>
<NoWarn>$(NoWarn);CA1707;IDE1006</NoWarn>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,12 @@ public void TestWithEnum([FromUri] MyEnum? myEnum = null)
}
}

public class FromUriAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Parameter)]
public class FromUriAttribute : Attribute;

#pragma warning disable CA1711
public enum MyEnum
#pragma warning restore CA1711
{
One,
Two,
Expand All @@ -42,7 +45,9 @@ public enum MyEnum
}
public class MyClass
{
#pragma warning disable IDE0051
private string MyString { get; set; }
#pragma warning restore IDE0051
public MyEnum? MyEnum { get; set; }
public int MyInt { get; set; }
}
Expand Down
17 changes: 9 additions & 8 deletions src/NSwag.CodeGeneration.CSharp.Tests/ParameterTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Threading.Tasks;
using NJsonSchema;
using Xunit;

Expand Down Expand Up @@ -77,7 +78,7 @@ public void When_parameters_names_have_differences_only_in_case_of_the_first_let
}

[Fact]
public void When_parent_parameters_have_same_kind_then_they_are_included()
public async Task When_parent_parameters_have_same_kind_then_they_are_included()
{
// Arrange
var swagger = @"{
Expand Down Expand Up @@ -140,7 +141,7 @@ public void When_parent_parameters_have_same_kind_then_they_are_included()
""definitions"" : { }
}
";
var document = OpenApiDocument.FromJsonAsync(swagger).Result;
var document = await OpenApiDocument.FromJsonAsync(swagger);

// Act
var generator = new CSharpClientGenerator(document, new CSharpClientGeneratorSettings());
Expand All @@ -151,7 +152,7 @@ public void When_parent_parameters_have_same_kind_then_they_are_included()
}

[Fact]
public void When_swagger_contains_optional_parameters_then_they_are_rendered_in_CSharp()
public async Task When_swagger_contains_optional_parameters_then_they_are_rendered_in_CSharp()
{
// Arrange
var swagger = @"{
Expand Down Expand Up @@ -222,7 +223,7 @@ public void When_swagger_contains_optional_parameters_then_they_are_rendered_in_
}
}";

var document = OpenApiDocument.FromJsonAsync(swagger).Result;
var document = await OpenApiDocument.FromJsonAsync(swagger);

// Act
var generator = new CSharpClientGenerator(document, new CSharpClientGeneratorSettings());
Expand All @@ -234,7 +235,7 @@ public void When_swagger_contains_optional_parameters_then_they_are_rendered_in_
}

[Fact]
public void Deep_object_properties_are_correctly_named()
public async Task Deep_object_properties_are_correctly_named()
{
// Arrange
var swagger = @"{
Expand Down Expand Up @@ -298,7 +299,7 @@ public void Deep_object_properties_are_correctly_named()
}
}";

var document = OpenApiDocument.FromJsonAsync(swagger, "", SchemaType.OpenApi3).Result;
var document = await OpenApiDocument.FromJsonAsync(swagger, "", SchemaType.OpenApi3);

// Act
var generator = new CSharpClientGenerator(document, new CSharpClientGeneratorSettings());
Expand All @@ -310,7 +311,7 @@ public void Deep_object_properties_are_correctly_named()
}

[Fact]
public void Date_and_DateTimeFormat_Parameters_are_correctly_applied()
public async Task Date_and_DateTimeFormat_Parameters_are_correctly_applied()
{
// Arrange
var swagger = @"{
Expand Down Expand Up @@ -356,7 +357,7 @@ public void Date_and_DateTimeFormat_Parameters_are_correctly_applied()
}
}";

var document = OpenApiDocument.FromJsonAsync(swagger, "", SchemaType.OpenApi3).Result;
var document = await OpenApiDocument.FromJsonAsync(swagger, "", SchemaType.OpenApi3);

// Act once with defaults and once with custom values
var generatorDefault = new CSharpClientGenerator(document, new CSharpClientGeneratorSettings());
Expand Down
19 changes: 10 additions & 9 deletions src/NSwag.CodeGeneration.CSharp.Tests/QueryParameterTests.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
using Xunit;
using System.Threading.Tasks;
using Xunit;

namespace NSwag.CodeGeneration.CSharp.Tests
{
public class QueryParameterTests
{
[Fact]
public void When_query_parameter_is_set_to_explode_and_style_is_form_object_parameters_are_expanded()
public async Task When_query_parameter_is_set_to_explode_and_style_is_form_object_parameters_are_expanded()
{
var spec = @"{
""openapi"": ""3.0.0"",
Expand Down Expand Up @@ -64,7 +65,7 @@ public void When_query_parameter_is_set_to_explode_and_style_is_form_object_para
}
";

var document = OpenApiDocument.FromJsonAsync(spec).Result;
var document = await OpenApiDocument.FromJsonAsync(spec);

// Act
var generator = new CSharpClientGenerator(document, new CSharpClientGeneratorSettings());
Expand All @@ -80,7 +81,7 @@ public void When_query_parameter_is_set_to_explode_and_style_is_form_object_para
}

[Fact]
public void When_query_parameter_is_untyped_free_form_object_parameters_are_expanded()
public async Task When_query_parameter_is_untyped_free_form_object_parameters_are_expanded()
{
var spec = @"{
""openapi"": ""3.0.0"",
Expand Down Expand Up @@ -130,7 +131,7 @@ public void When_query_parameter_is_untyped_free_form_object_parameters_are_expa
}
";

var document = OpenApiDocument.FromJsonAsync(spec).Result;
var document = await OpenApiDocument.FromJsonAsync(spec);

// Act
var generator = new CSharpClientGenerator(document, new CSharpClientGeneratorSettings());
Expand All @@ -146,7 +147,7 @@ public void When_query_parameter_is_untyped_free_form_object_parameters_are_expa
}

[Fact]
public void When_query_parameter_is_typed_free_form_object_parameters_are_expanded()
public async Task When_query_parameter_is_typed_free_form_object_parameters_are_expanded()
{
var spec = @"{
""openapi"": ""3.0.0"",
Expand Down Expand Up @@ -198,7 +199,7 @@ public void When_query_parameter_is_typed_free_form_object_parameters_are_expand
}
";

var document = OpenApiDocument.FromJsonAsync(spec).Result;
var document = await OpenApiDocument.FromJsonAsync(spec);

// Act
var generator = new CSharpClientGenerator(document, new CSharpClientGeneratorSettings());
Expand All @@ -214,7 +215,7 @@ public void When_query_parameter_is_typed_free_form_object_parameters_are_expand
}

[Fact]
public void When_query_parameter_is_mixed_free_form_object_parameters_are_expanded()
public async Task When_query_parameter_is_mixed_free_form_object_parameters_are_expanded()
{
var spec = @"{
""openapi"": ""3.0.0"",
Expand Down Expand Up @@ -281,7 +282,7 @@ public void When_query_parameter_is_mixed_free_form_object_parameters_are_expand
}
";

var document = OpenApiDocument.FromJsonAsync(spec).Result;
var document = await OpenApiDocument.FromJsonAsync(spec);

// Act
var generator = new CSharpClientGenerator(document, new CSharpClientGeneratorSettings());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public CSharpClientGeneratorSettings()
GenerateBaseUrlProperty = true;
ExposeJsonSerializerSettings = false;
InjectHttpClient = true;
ProtectedMethods = new string[0];
ProtectedMethods = [];
}

/// <summary>Gets or sets the full name of the base class.</summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ protected CSharpGeneratorBaseSettings()
ParameterArrayType = "System.Collections.Generic.IEnumerable";
ParameterDictionaryType = "System.Collections.Generic.IDictionary";

AdditionalNamespaceUsages = new string[0];
AdditionalContractNamespaceUsages = new string[0];
AdditionalNamespaceUsages = [];
AdditionalContractNamespaceUsages = [];
}

/// <summary>Gets the CSharp generator settings.</summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public CSharpFileTemplateModel(
/// <summary>Gets the all the namespace usages.</summary>
public string[] NamespaceUsages => (_outputType == ClientGeneratorOutputType.Contracts ?
_settings.AdditionalContractNamespaceUsages?.Where(n => n != null).ToArray() :
_settings.AdditionalNamespaceUsages?.Where(n => n != null).ToArray()) ?? new string[] { };
_settings.AdditionalNamespaceUsages?.Where(n => n != null).ToArray()) ?? [];

/// <summary>Gets a value indicating whether the C#8 nullable reference types are enabled for this file.</summary>
public bool GenerateNullableReferenceTypes => _settings.CSharpGeneratorSettings.GenerateNullableReferenceTypes;
Expand Down Expand Up @@ -155,7 +155,7 @@ public IEnumerable<string> ExceptionClassNames
return new[] { settings.ExceptionClass.Replace("{controller}", string.Empty) };
}
}
return new string[] { };
return [];
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ public IEnumerable<CSharpExceptionDescriptionModel> ExceptionDescriptions
}
else
{
return new CSharpExceptionDescriptionModel[] { };
return [];
}
});
}
Expand All @@ -215,7 +215,7 @@ public string RouteName
}

/// <summary>True if the operation has any security schemes</summary>
public bool RequiresAuthentication => (_operation.ActualSecurity?.Count() ?? 0) != 0;
public bool RequiresAuthentication => (_operation.ActualSecurity?.Count ?? 0) != 0;

/// <summary>Gets the security schemas that apply to this operation</summary>
public IEnumerable<OpenApiSecurityRequirement> Security => _operation.ActualSecurity;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<NoWarn>$(NoWarn);CA1707</NoWarn>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<NoDefaultLaunchSettingsFile>true</NoDefaultLaunchSettingsFile>
<NoWarn>$(NoWarn);CA1707;IDE1006</NoWarn>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,12 @@ public class FooController : Controller
[Route("foos/")]
public Foo[] GetFoos([FromUri] Bar[] bars)
{
return new Foo[0];
return [];
}
}

public class FromUriAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Parameter)]
public class FromUriAttribute : Attribute;

public enum Bar
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ namespace NSwag.CodeGeneration.TypeScript.Models
public class TypeScriptFileTemplateModel
{
private readonly TypeScriptClientGeneratorSettings _settings;
#pragma warning disable IDE0052
private readonly TypeScriptTypeResolver _resolver;
#pragma warning restore IDE0052
private readonly string _clientCode;
private readonly IEnumerable<CodeArtifact> _clientTypes;
private readonly OpenApiDocument _document;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public TypeScriptClientGenerator(OpenApiDocument document, TypeScriptClientGener

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

Expand Down
Loading
Loading