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

Enable .NET analyzers #1676

Merged
merged 1 commit into from
Mar 28, 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
69 changes: 41 additions & 28 deletions Directory.Build.props
Original file line number Diff line number Diff line change
@@ -1,31 +1,44 @@
<Project>
<PropertyGroup>
<VersionPrefix>11.0.0</VersionPrefix>

<Authors>Rico Suter</Authors>
<Copyright>Copyright © Rico Suter, 2022</Copyright>

<SignAssembly>True</SignAssembly>
<AssemblyOriginatorKeyFile>../NJsonSchema.snk</AssemblyOriginatorKeyFile>

<PackageTags>json schema validation generator .net</PackageTags>
<PackageProjectUrl>http://NJsonSchema.org</PackageProjectUrl>
<Description>JSON Schema reader, generator and validator for .NET</Description>
<PackageIcon>NuGetIcon.png</PackageIcon>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<Company />
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<DebugSymbols>True</DebugSymbols>

<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<Nullable>enable</Nullable>

<UseArtifactsOutput>true</UseArtifactsOutput>

</PropertyGroup>
<PropertyGroup>
<VersionPrefix>11.0.0</VersionPrefix>

<Authors>Rico Suter</Authors>
<Copyright>Copyright © Rico Suter, 2022</Copyright>

<SignAssembly>True</SignAssembly>
<AssemblyOriginatorKeyFile>../NJsonSchema.snk</AssemblyOriginatorKeyFile>

<PackageTags>json schema validation generator .net</PackageTags>
<PackageProjectUrl>http://NJsonSchema.org</PackageProjectUrl>
<Description>JSON Schema reader, generator and validator for .NET</Description>
<PackageIcon>NuGetIcon.png</PackageIcon>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<Company />
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<DebugSymbols>True</DebugSymbols>

<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<Nullable>enable</Nullable>

<UseArtifactsOutput>true</UseArtifactsOutput>

</PropertyGroup>

<PropertyGroup Label="Analyzer settings">
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<AnalysisLevel>latest-Recommended</AnalysisLevel>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
<!--
[CA1200] Avoid using cref tags with a prefix
[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
-->
<NoWarn>$(NoWarn);CA1200;CA1510;CA1716;CA1720</NoWarn>
</PropertyGroup>

</Project>
2 changes: 1 addition & 1 deletion Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,6 @@
<ItemGroup>
<GlobalPackageReference Include="GitHubActionsTestLogger" Version="2.3.3" />
<GlobalPackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" />
<GlobalPackageReference Include="PolySharp" Version="1.13.2" />
<GlobalPackageReference Include="PolySharp" Version="1.14.1" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@
namespace NJsonSchema.Annotations;

/// <summary>Interface to add an extension data property to a class or property, implementation needs to inherit from System.Attribute.</summary>
#pragma warning disable CA1711 // Rename type name IJsonSchemaExtensionDataAttribute so that it does not end in 'Attribute'
public interface IJsonSchemaExtensionDataAttribute
#pragma warning restore CA1711
{
/// <summary>Gets the extension data.</summary>
IReadOnlyDictionary<string, object> ExtensionData { get; }
Expand Down
1 change: 1 addition & 0 deletions src/NJsonSchema.Benchmark/NJsonSchema.Benchmark.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
<NoWarn>$(NoWarn),xUnit1013</NoWarn>
<SignAssembly>false</SignAssembly>
<Nullable>disable</Nullable>
<EnableNETAnalyzers>false</EnableNETAnalyzers>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn),1587,1998,1591,618,SYSLIB0012</NoWarn>
<Nullable>disable</Nullable>
<EnableNETAnalyzers>false</EnableNETAnalyzers>
</PropertyGroup>

<ItemGroup>
Expand Down
4 changes: 2 additions & 2 deletions src/NJsonSchema.CodeGeneration.CSharp/CSharpGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,13 +81,13 @@ public override IEnumerable<CodeArtifact> GenerateTypes()
}

/// <inheritdoc />
protected override string GenerateFile(IEnumerable<CodeArtifact> artifactCollection)
protected override string GenerateFile(IEnumerable<CodeArtifact> artifacts)
{
var model = new FileTemplateModel
{
Namespace = Settings.Namespace ?? string.Empty,
GenerateNullableReferenceTypes = Settings.GenerateNullableReferenceTypes,
TypesCode = artifactCollection.Concatenate()
TypesCode = artifacts.Concatenate()
};

var template = Settings.TemplateFactory.CreateTemplate("CSharp", "File", model);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public static class CSharpJsonSerializerGenerator
public static string GenerateJsonSerializerParameterCode(CSharpGeneratorSettings settings, IEnumerable<string>? additionalJsonConverters)
{
var jsonConverters = GetJsonConverters(settings, additionalJsonConverters);
var hasJsonConverters = jsonConverters.Any();
var hasJsonConverters = jsonConverters.Count > 0;

return GenerateForJsonLibrary(settings, jsonConverters, hasJsonConverters);
}
Expand Down Expand Up @@ -95,24 +95,17 @@ private static string GenerateForJsonLibrary(CSharpGeneratorSettings settings, L

private static string GenerateConverters(List<string> jsonConverters, CSharpJsonLibrary jsonLibrary)
{
if (jsonConverters.Any())
if (jsonConverters.Count > 0)
{
switch (jsonLibrary)
return jsonLibrary switch
{
case CSharpJsonLibrary.NewtonsoftJson:
return "new Newtonsoft.Json.JsonConverter[] { " + string.Join(", ", jsonConverters.Select(c => "new " + c + "()")) + " }";

case CSharpJsonLibrary.SystemTextJson:
return "new System.Text.Json.Serialization.JsonConverter[] { " + string.Join(", ", jsonConverters.Select(c => "new " + c + "()")) + " }";

default: // TODO: possibly add more json converters
return string.Empty;
}
}
else
{
return string.Empty;
CSharpJsonLibrary.NewtonsoftJson => "new Newtonsoft.Json.JsonConverter[] { " + string.Join(", ", jsonConverters.Select(c => "new " + c + "()")) + " }",
CSharpJsonLibrary.SystemTextJson => "new System.Text.Json.Serialization.JsonConverter[] { " + string.Join(", ", jsonConverters.Select(c => "new " + c + "()")) + " }",
_ => string.Empty
};
}

return string.Empty;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ private static string ResolveBoolean(bool isNullable)
return isNullable ? "bool?" : "bool";
}

private string ResolveInteger(JsonSchema schema, bool isNullable, string? typeNameHint)
private static string ResolveInteger(JsonSchema schema, bool isNullable, string? typeNameHint)
{
if (schema.Format == JsonFormatStrings.Byte)
{
Expand Down
10 changes: 5 additions & 5 deletions src/NJsonSchema.CodeGeneration.CSharp/CSharpValueGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,11 @@ public CSharpValueGenerator(CSharpGeneratorSettings settings)
if (schema.Type.IsArray() ||
schema.Type.IsObject())
{
targetType = !string.IsNullOrEmpty(_settings.DictionaryInstanceType) && targetType.StartsWith(_settings.DictionaryType + "<")
targetType = !string.IsNullOrEmpty(_settings.DictionaryInstanceType) && targetType.StartsWith(_settings.DictionaryType + "<", StringComparison.Ordinal)
? _settings.DictionaryInstanceType + targetType.Substring(_settings.DictionaryType.Length)
: targetType;

targetType = !string.IsNullOrEmpty(_settings.ArrayInstanceType) && targetType.StartsWith(_settings.ArrayType + "<")
targetType = !string.IsNullOrEmpty(_settings.ArrayInstanceType) && targetType.StartsWith(_settings.ArrayType + "<", StringComparison.Ordinal)
? _settings.ArrayInstanceType + targetType.Substring(_settings.ArrayType.Length)
: targetType;

Expand All @@ -93,11 +93,11 @@ public override string GetNumericValue(JsonObjectType type, object value, string
switch (format)
{
case JsonFormatStrings.Byte:
return "(byte)" + Convert.ToByte(value).ToString(CultureInfo.InvariantCulture);
return "(byte)" + Convert.ToByte(value, CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture);
case JsonFormatStrings.Integer:
return Convert.ToInt32(value).ToString(CultureInfo.InvariantCulture);
return Convert.ToInt32(value, CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture);
case JsonFormatStrings.Long:
return Convert.ToInt64(value) + "L";
return Convert.ToInt64(value, CultureInfo.InvariantCulture) + "L";
case JsonFormatStrings.Double:
return ConvertNumberToString(value) + "D";
case JsonFormatStrings.Float:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
// <author>Rico Suter, mail@rsuter.com</author>
//-----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using NJsonSchema.CodeGeneration.Models;
Expand Down Expand Up @@ -145,7 +146,7 @@ public class ClassTemplateModel : ClassTemplateModelBase
_schema?.InheritsSchema(_resolver.ExceptionSchema) == true;

/// <summary>Gets a value indicating whether to use the DateFormatConverter.</summary>
public bool UseDateFormatConverter => _settings.DateType.StartsWith("System.DateTime");
public bool UseDateFormatConverter => _settings.DateType.StartsWith("System.DateTime", StringComparison.Ordinal);

/// <summary>Gets or sets the access modifier of generated classes and interfaces.</summary>
public string TypeAccessModifier => _settings.TypeAccessModifier;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

using NJsonSchema.Annotations;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using NJsonSchema.CodeGeneration.Models;

Expand Down Expand Up @@ -78,8 +79,8 @@ public IEnumerable<EnumerationItemModel> Enums
{
Name = _settings.EnumNameGenerator.Generate(i, name, value, _schema),
Value = value.ToString(),
InternalValue = valueInt64.ToString(),
InternalFlagValue = valueInt64.ToString()
InternalValue = valueInt64.ToString(CultureInfo.InvariantCulture),
InternalFlagValue = valueInt64.ToString(CultureInfo.InvariantCulture)
});
}
else
Expand All @@ -89,7 +90,7 @@ public IEnumerable<EnumerationItemModel> Enums
Name = _settings.EnumNameGenerator.Generate(i, name, value, _schema),
Value = value.ToString(),
InternalValue = value.ToString(),
InternalFlagValue = (1 << i).ToString()
InternalFlagValue = (1 << i).ToString(CultureInfo.InvariantCulture)
});
}
}
Expand All @@ -102,8 +103,8 @@ public IEnumerable<EnumerationItemModel> Enums
{
Name = _settings.EnumNameGenerator.Generate(i, name, value, _schema),
Value = value.ToString(),
InternalValue = i.ToString(),
InternalFlagValue = (1 << i).ToString()
InternalValue = i.ToString(CultureInfo.InvariantCulture),
InternalFlagValue = (1 << i).ToString(CultureInfo.InvariantCulture)
});
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
<IsPackable>false</IsPackable>
<NoWarn>$(NoWarn),1998,1591,618</NoWarn>
<Nullable>disable</Nullable>
<EnableNETAnalyzers>false</EnableNETAnalyzers>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn),1587,1998,1591,618</NoWarn>
<Nullable>disable</Nullable>
<EnableNETAnalyzers>false</EnableNETAnalyzers>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ private static string GetStringToDateTime(DataConversionParameters parameters, J
return "dayjs";

default:
throw new ArgumentOutOfRangeException();
throw new ArgumentOutOfRangeException(nameof(parameters));
}
}

Expand All @@ -168,7 +168,7 @@ private static string GetDateToString(DataConversionParameters parameters, JsonS
return "toFormat('yyyy-MM-dd')";

default:
throw new ArgumentOutOfRangeException();
throw new ArgumentOutOfRangeException(nameof(parameters));
}
}

Expand Down Expand Up @@ -207,7 +207,7 @@ private static string GetDateTimeToString(DataConversionParameters parameters, J
return "toISOString()";

default:
throw new ArgumentOutOfRangeException();
throw new ArgumentOutOfRangeException(nameof(parameters));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ public string Inheritance
public bool GenerateConstructorInterface => _settings.GenerateConstructorInterface;

/// <summary>Gets or sets a value indicating whether POJO objects in the constructor data are converted to DTO instances (default: true).</summary>
public bool ConvertConstructorInterfaceData => _settings.ConvertConstructorInterfaceData && Properties.Any(p => p.SupportsConstructorConversion);
public bool ConvertConstructorInterfaceData => _settings.ConvertConstructorInterfaceData && Properties.Exists(p => p.SupportsConstructorConversion);

/// <summary>Gets the null value.</summary>
public string NullValue => _settings.NullValue.ToString().ToLowerInvariant();
Expand Down Expand Up @@ -134,13 +134,13 @@ public string IndexerPropertyValueType
public bool HandleReferences => _settings.HandleReferences;

/// <summary>Gets a value indicating whether the type has properties.</summary>
public bool HasProperties => Properties.Any();
public bool HasProperties => Properties.Count > 0;

/// <summary>Gets the property models.</summary>
public List<PropertyModel> Properties { get; }

/// <summary>Gets a value indicating whether any property has a default value.</summary>
public bool HasDefaultValues => Properties.Any(p => p.HasDefaultValue);
public bool HasDefaultValues => Properties.Exists(p => p.HasDefaultValue);

/// <summary>Gets a value indicating whether </summary>
public bool RequiresStrictPropertyInitialization => _settings.RequiresStrictPropertyInitialization;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,9 @@ protected override CodeArtifact GenerateType(JsonSchema schema, string typeNameH
}
else
{
#pragma warning disable CA2208
throw new ArgumentOutOfRangeException(nameof(Settings.EnumStyle), Settings.EnumStyle, "Unknown enum style");
#pragma warning restore CA2208
}

var template = Settings.TemplateFactory.CreateTemplate("TypeScript", templateName, model);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,9 @@ public override string Resolve(JsonSchema schema, bool isNullable, string? typeN
/// <summary>Gets a value indicating whether the schema supports constructor conversion.</summary>
/// <param name="schema">The schema.</param>
/// <returns>The result.</returns>
#pragma warning disable CA1822
public bool SupportsConstructorConversion(JsonSchema? schema)
#pragma warning restore CA1822
{
return schema?.ActualSchema.ResponsibleDiscriminatorObject == null;
}
Expand Down Expand Up @@ -109,7 +111,7 @@ private string Resolve(JsonSchema schema, string? typeNameHint, bool addInterfac

if (type.IsInteger() && !schema.ActualTypeSchema.IsEnumeration)
{
return ResolveInteger(schema.ActualTypeSchema, typeNameHint);
return TypeScriptTypeResolver.ResolveInteger(schema.ActualTypeSchema, typeNameHint);
}

if (type.IsBoolean())
Expand Down Expand Up @@ -167,7 +169,9 @@ private string Resolve(JsonSchema schema, string? typeNameHint, bool addInterfac
return $"{{ [key in {keyType}]?: {valueType}; }}";
}

#pragma warning disable CA2208
throw new ArgumentOutOfRangeException(nameof(Settings.EnumStyle), Settings.EnumStyle, "Unknown enum style");
#pragma warning restore CA2208
}

return $"{{ [key: {keyType}]: {valueType}; }}";
Expand Down Expand Up @@ -290,7 +294,7 @@ private string ResolveString(JsonSchema schema, string? typeNameHint)
return "string";
}

private string ResolveInteger(JsonSchema schema, string? typeNameHint)
private static string ResolveInteger(JsonSchema schema, string? typeNameHint)
{
return "number";
}
Expand Down
3 changes: 2 additions & 1 deletion src/NJsonSchema.CodeGeneration/CodeArtifactExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
// <author>Rico Suter, mail@rsuter.com</author>
//-----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
Expand Down Expand Up @@ -69,7 +70,7 @@ public static IEnumerable<CodeArtifact> OrderByBaseDependency(this IEnumerable<C
}

// resolve arrays
if (baseTypeName.EndsWith("[]"))
if (baseTypeName.EndsWith("[]", StringComparison.Ordinal))
{
return baseTypeName.Substring(0, baseTypeName.Length - 2);
}
Expand Down