Skip to content

Commit

Permalink
Merge pull request #271 from christianhelle/nswag-v14-prerequisites
Browse files Browse the repository at this point in the history
Implement CustomCSharpPropertyNameGenerator
  • Loading branch information
christianhelle authored Jan 8, 2024
2 parents ddfe94b + 31f0cb9 commit 7253024
Showing 1 changed file with 54 additions and 4 deletions.
58 changes: 54 additions & 4 deletions src/Refitter.Core/CustomCSharpPropertyNameGenerator.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,60 @@
using System.Diagnostics.CodeAnalysis;

using NJsonSchema;
using NJsonSchema.CodeGeneration.CSharp;
using NJsonSchema.CodeGeneration;

namespace Refitter.Core;

internal class CustomCSharpPropertyNameGenerator : CSharpPropertyNameGenerator
internal class CustomCSharpPropertyNameGenerator : IPropertyNameGenerator
{
public override string Generate(JsonSchemaProperty property) =>
string.IsNullOrWhiteSpace(property.Name) ? "_" : base.Generate(property);
private static readonly char[] ReservedFirstPassChars = ['"', '\'', '@', '?', '!', '$', '[', ']', '(', ')', '.', '=', '+'];
private static readonly char[] ReservedSecondPassChars = ['*', ':', '-', '#', '&'];

public string Generate(JsonSchemaProperty property) =>
string.IsNullOrWhiteSpace(property.Name)
? "_"
: ReplaceNameContainingReservedCharacters(property);

/// <summary>
/// This code is taken directly from NJsonSchema.CodeGeneration.CSharp.CSharpPropertyNameGenerator
/// which since v14.0.0 is no longer extensible.
/// See https://github.com/RicoSuter/NJsonSchema/blob/3585d60e949e43284601e0bea16c33de4c6c21f5/src/NJsonSchema.CodeGeneration.CSharp/CSharpPropertyNameGenerator.cs#L12"
/// </summary>
[ExcludeFromCodeCoverage]
private static string ReplaceNameContainingReservedCharacters(JsonSchemaProperty property)
{
var name = property.Name;

if (name.IndexOfAny(ReservedFirstPassChars) != -1)
{
name = name
.Replace("\"", string.Empty)
.Replace("'", string.Empty)
.Replace("@", string.Empty)
.Replace("?", string.Empty)
.Replace("!", string.Empty)
.Replace("$", string.Empty)
.Replace("[", string.Empty)
.Replace("]", string.Empty)
.Replace("(", "_")
.Replace(")", string.Empty)
.Replace(".", "-")
.Replace("=", "-")
.Replace("+", "plus");
}

name = ConversionUtilities.ConvertToUpperCamelCase(name, true);

if (name.IndexOfAny(ReservedSecondPassChars) != -1)
{
name = name
.Replace("*", "Star")
.Replace(":", "_")
.Replace("-", "_")
.Replace("#", "_")
.Replace("&", "And");
}

return name;
}
}

0 comments on commit 7253024

Please sign in to comment.