Skip to content

Commit

Permalink
Add analysis rules and relaxations
Browse files Browse the repository at this point in the history
  • Loading branch information
lahma committed Nov 20, 2024
1 parent 588d18f commit 6478472
Show file tree
Hide file tree
Showing 111 changed files with 408 additions and 301 deletions.
70 changes: 68 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,68 @@
<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
[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]
[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
[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
[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
[CA1507] Use nameof in place of string literal
[CA1510] Use 'ArgumentNullException.ThrowIfNull' instead of explicitly throwing a new exception instance
[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
[CA1845] Use span-based 'string.Concat' and 'AsSpan' instead of 'Substring'
[CA1847] Use 'string.Contains(char)' instead of 'string.Contains(string)' - needs polyfill
[CA1854] Prefer a 'TryGetValue' call over a Dictionary indexer access
[CA1861] Prefer 'static readonly' fields over constant array arguments
[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;IDE0017;IDE0019;IDE0021;IDE0022;IDE0025;IDE0027;IDE0028;IDE0029;IDE0032;IDE0039;IDE0045;IDE0046;IDE0055;IDE0056;IDE0057;IDE0059;IDE0060;IDE0063;IDE0074;IDE0078;IDE0083;IDE0090;IDE0100;IDE0130;IDE0160;IDE0260;IDE0270;IDE0290;IDE0300;IDE0301;IDE0330;CA1304;IDE0305;IDE1005;CA1200;CA1305;CA1310;CA1507;CA1510;CA1716;CA1720;CA1725;CA1845;CA1847;CA1854;CA1861;CA1866;CA1870;CA2249;CA2263;SYSLIB0012</NoWarn>
</PropertyGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

namespace NSwag.AspNet.Owin.Middlewares
{
internal class RedirectToIndexMiddleware : OwinMiddleware
internal sealed class RedirectToIndexMiddleware : OwinMiddleware
{
private readonly string _internalUiRoute;
private readonly string _internalSwaggerRoute;
Expand Down
12 changes: 5 additions & 7 deletions src/NSwag.AspNet.Owin/Middlewares/SwaggerUiIndexMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

namespace NSwag.AspNet.Owin.Middlewares
{
internal class SwaggerUiIndexMiddleware<T> : OwinMiddleware
internal sealed class SwaggerUiIndexMiddleware<T> : OwinMiddleware
where T : OpenApiDocumentGeneratorSettings, new()
{
private readonly string _indexPath;
Expand All @@ -27,12 +27,10 @@ public override async Task Invoke(IOwinContext context)
if (context.Request.Path.HasValue && string.Equals(context.Request.Path.Value.Trim('/'), _indexPath.Trim('/'), StringComparison.OrdinalIgnoreCase))
{
var stream = typeof(SwaggerUiIndexMiddleware<T>).Assembly.GetManifestResourceStream(_resourcePath);
using (var reader = new StreamReader(stream))
{
context.Response.Headers["Content-Type"] = "text/html; charset=utf-8";
context.Response.StatusCode = 200;
context.Response.Write(await _settings.TransformHtmlAsync(reader.ReadToEnd(), context.Request, CancellationToken.None));
}
using var reader = new StreamReader(stream);
context.Response.Headers["Content-Type"] = "text/html; charset=utf-8";
context.Response.StatusCode = 200;
context.Response.Write(await _settings.TransformHtmlAsync(reader.ReadToEnd(), context.Request, CancellationToken.None));
}
else
{
Expand Down
4 changes: 2 additions & 2 deletions src/NSwag.AspNet.WebApi/JsonExceptionFilterAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ public override void OnActionExecuted(HttpActionExecutedContext context)
}
}

private int GetStatusCode(Exception exception, HttpActionExecutedContext context)
private static int GetStatusCode(Exception exception, HttpActionExecutedContext context)
{
if (context.ActionContext.ActionDescriptor is ReflectedHttpActionDescriptor actionDescriptor)
{
Expand All @@ -105,7 +105,7 @@ private int GetStatusCode(Exception exception, HttpActionExecutedContext context
return 500;
}

private JsonSerializerSettings CopySettings(JsonSerializerSettings settings)
private static JsonSerializerSettings CopySettings(JsonSerializerSettings settings)
{
var settingsCopy = new JsonSerializerSettings();

Expand Down
6 changes: 3 additions & 3 deletions src/NSwag.AspNetCore.Launcher/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

namespace NSwag.AspNetCore.Launcher
{
internal class Program
internal sealed class Program
{
// Used to load NSwag.Commands into a process running with the app's dependency context
private const string EntryPointType = "NSwag.Commands.Generation.AspNetCore.AspNetCoreToOpenApiGeneratorCommandEntryPoint";
Expand Down Expand Up @@ -60,7 +60,7 @@ internal class Program
["System.Text.Encodings.Web"] = new AssemblyLoadInfo(new Version(4, 0, 0)),
};

static int Main(string[] args)
private static int Main(string[] args)
{
// Usage: NSwag.Console.AspNetCore [settingsFile] [toolsDirectory]
if (args.Length < 2)
Expand Down Expand Up @@ -169,7 +169,7 @@ private static bool TryLoadReferencedAssemblies()
return true;
}

private class AssemblyLoadInfo
private sealed class AssemblyLoadInfo
{
public AssemblyLoadInfo(Version minimumRequiredVersion)
{
Expand Down
5 changes: 2 additions & 3 deletions src/NSwag.AspNetCore/JsonExceptionFilterAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using NJsonSchema.Converters;
using NJsonSchema.NewtonsoftJson.Converters;
using NSwag.Annotations;
using NSwag.Generation.AspNetCore;
Expand Down Expand Up @@ -82,7 +81,7 @@ public override void OnActionExecuted(ActionExecutedContext context)
}
}

private int GetStatusCode(Exception exception, ActionExecutedContext context)
private static int GetStatusCode(Exception exception, ActionExecutedContext context)
{
if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor)
{
Expand Down Expand Up @@ -116,7 +115,7 @@ private int GetStatusCode(Exception exception, ActionExecutedContext context)
return 500;
}

private JsonSerializerSettings CopySettings(JsonSerializerSettings settings)
private static JsonSerializerSettings CopySettings(JsonSerializerSettings settings)
{
var settingsCopy = new JsonSerializerSettings();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

namespace NSwag.AspNetCore.Middlewares
{
internal class RedirectToIndexMiddleware
internal sealed class RedirectToIndexMiddleware
{
private readonly RequestDelegate _nextDelegate;

Expand Down
20 changes: 9 additions & 11 deletions src/NSwag.AspNetCore/Middlewares/SwaggerUiIndexMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

namespace NSwag.AspNetCore.Middlewares
{
internal class SwaggerUiIndexMiddleware
internal sealed class SwaggerUiIndexMiddleware
{
private readonly RequestDelegate _nextDelegate;
private readonly string _indexPath;
Expand All @@ -26,16 +26,14 @@ public async Task Invoke(HttpContext context)
if (context.Request.Path.HasValue && string.Equals(context.Request.Path.Value.Trim('/'), _indexPath.Trim('/'), StringComparison.OrdinalIgnoreCase))
{
var stream = typeof(SwaggerUiIndexMiddleware).GetTypeInfo().Assembly.GetManifestResourceStream(_resourcePath);
using (var reader = new StreamReader(stream))
{
context.Response.Headers["Content-Type"] = "text/html; charset=utf-8";
context.Response.StatusCode = 200;
await context.Response.WriteAsync(
await _settings.TransformHtmlAsync(
await reader.ReadToEndAsync(),
context.Request,
context.RequestAborted));
}
using var reader = new StreamReader(stream);
context.Response.Headers["Content-Type"] = "text/html; charset=utf-8";
context.Response.StatusCode = 200;
await context.Response.WriteAsync(
await _settings.TransformHtmlAsync(
await reader.ReadToEndAsync(),
context.Request,
context.RequestAborted));
}
else
{
Expand Down
2 changes: 1 addition & 1 deletion src/NSwag.AspNetCore/OpenApiConfigureMvcOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

namespace NSwag.AspNetCore
{
internal class OpenApiConfigureMvcOptions : ConfigureOptions<MvcOptions>
internal sealed class OpenApiConfigureMvcOptions : ConfigureOptions<MvcOptions>
{
public OpenApiConfigureMvcOptions()
: base(options => options.Conventions.Add(new OpenApiMvcApplicationModelConvention()))
Expand Down
2 changes: 1 addition & 1 deletion src/NSwag.AspNetCore/OpenApiDocumentProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

namespace NSwag.AspNetCore
{
internal class OpenApiDocumentProvider : IDocumentProvider, IOpenApiDocumentGenerator
internal sealed class OpenApiDocumentProvider : IDocumentProvider, IOpenApiDocumentGenerator
{
private readonly IServiceProvider _serviceProvider;
private readonly IEnumerable<OpenApiDocumentRegistration> _documents;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace NSwag.AspNetCore
{
internal class OpenApiMvcApplicationModelConvention : IApplicationModelConvention
internal sealed class OpenApiMvcApplicationModelConvention : IApplicationModelConvention
{
public void Apply(ApplicationModel application)
{
Expand Down
7 changes: 3 additions & 4 deletions src/NSwag.AspNetCore/SwaggerUiSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
using System.Text;
using Newtonsoft.Json;
using NSwag.Generation;
using NJsonSchema;
using System.Threading;
using System.Threading.Tasks;

Expand Down Expand Up @@ -70,7 +69,7 @@ public bool EnableTryItOut
public string CustomHeadContent { get; set; } = "";

/// <summary>Gets or sets a value indicating whether the Swagger specification should be validated.</summary>
public bool ValidateSpecification { get; set; } = false;
public bool ValidateSpecification { get; set; }

/// <summary>Gets the additional Swagger UI 3 settings.</summary>
public IDictionary<string, object> AdditionalSettings { get; } = new Dictionary<string, object>();
Expand Down Expand Up @@ -134,7 +133,7 @@ public bool WithCredentials
public Func<HttpRequest, CancellationToken, Task<IEnumerable<SwaggerUiRoute>>> SwaggerRoutesFactory { get; set; }
#endif

internal override string ActualSwaggerDocumentPath => SwaggerRoutes.Any() ? "" : base.ActualSwaggerDocumentPath;
internal override string ActualSwaggerDocumentPath => SwaggerRoutes.Count > 0 ? "" : base.ActualSwaggerDocumentPath;

#if AspNetOwin
internal override async Task<string> TransformHtmlAsync(string html, IOwinRequest request, CancellationToken cancellationToken)
Expand Down Expand Up @@ -165,7 +164,7 @@ internal override async Task<string> TransformHtmlAsync(string html, HttpRequest
(await SwaggerRoutesFactory(request, cancellationToken)).ToList() :
SwaggerRoutes;

htmlBuilder.Replace("{Urls}", !swaggerRoutes.Any()
htmlBuilder.Replace("{Urls}", swaggerRoutes.Count == 0
? "undefined"
: JsonConvert.SerializeObject(
#pragma warning disable 618
Expand Down
5 changes: 1 addition & 4 deletions src/NSwag.AspNetCore/SwaggerUiSettingsBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,7 @@
using NSwag.Generation;
using System;
using System.Collections.Generic;
using NJsonSchema;
using System.Globalization;
using Newtonsoft.Json;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
Expand Down Expand Up @@ -122,7 +119,7 @@ protected string GetCustomScriptHtml(HttpRequest request)
/// <summary>Generates the additional objects JavaScript code.</summary>
/// <param name="additionalSettings">The additional settings.</param>
/// <returns>The code.</returns>
protected string GenerateAdditionalSettings(IDictionary<string, object> additionalSettings)
protected static string GenerateAdditionalSettings(IDictionary<string, object> additionalSettings)
{
var code = "";
foreach (var pair in additionalSettings)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ public void When_the_generation_of_dto_classes_are_disabled_then_file_is_generat
Assert.DoesNotContain("public partial class ComplexTypeResponse", code);
}

private OpenApiDocument GetOpenApiDocument()
private static OpenApiDocument GetOpenApiDocument()
{
JsonSchema complexTypeSchema = new JsonSchema();
complexTypeSchema.Title = "ComplexType";
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 @@ -3,7 +3,6 @@
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using NJsonSchema;
using NJsonSchema.Generation;
using NJsonSchema.NewtonsoftJson.Generation;
using NSwag.Generation.WebApi;
using Xunit;
Expand All @@ -30,9 +29,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 +44,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
Loading

0 comments on commit 6478472

Please sign in to comment.