Skip to content

Commit

Permalink
[csharp] Changed enums to start from 0 (#15503)
Browse files Browse the repository at this point in the history
* zero based enums

* changed locale
  • Loading branch information
devhl-labs committed May 14, 2023
1 parent 780d266 commit fd20632
Show file tree
Hide file tree
Showing 75 changed files with 1,738 additions and 2 deletions.
1 change: 1 addition & 0 deletions docs/generators/csharp-netcore.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|useDateTimeOffset|Use DateTimeOffset to model date-time properties| |false|
|useOneOfDiscriminatorLookup|Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and only one match in oneOf's schemas) will be skipped.| |false|
|validatable|Generates self-validatable models.| |true|
|zeroBasedEnums|Enumerations with string values will start from 0 when true, 1 when false. If not set, enumerations with string values will start from 0 if the first value is 'unknown', case insensitive.| |null|

## IMPORT MAPPING

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,9 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
// true if support nullable type
protected boolean supportNullable = Boolean.FALSE;

protected Boolean zeroBasedEnums = null;
protected static final String zeroBasedEnumVendorExtension = "x-zero-based-enum";

// nullable type
protected Set<String> nullableType = new HashSet<>();

Expand Down Expand Up @@ -408,6 +411,11 @@ public void processOpts() {
setNullableReferenceTypes(convertPropertyToBooleanAndWriteBack(CodegenConstants.NULLABLE_REFERENCE_TYPES));
}

String zeroBasedEnums = "zeroBasedEnums";
if (additionalProperties.containsKey(zeroBasedEnums)) {
setZeroBasedEnums(convertPropertyToBooleanAndWriteBack(zeroBasedEnums));
}

if (additionalProperties.containsKey(CodegenConstants.INTERFACE_PREFIX)) {
String useInterfacePrefix = additionalProperties.get(CodegenConstants.INTERFACE_PREFIX).toString();
if ("false".equals(useInterfacePrefix.toLowerCase(Locale.ROOT))) {
Expand Down Expand Up @@ -459,6 +467,19 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert
property.datatypeWithEnum = property.datatypeWithEnum.replace(property.items.datatypeWithEnum, model.classname + "." + property.items.datatypeWithEnum);
property.dataType = property.datatypeWithEnum;
}

if (property.isEnum && !property.vendorExtensions.containsKey(this.zeroBasedEnumVendorExtension)) {
if (Boolean.TRUE.equals(this.zeroBasedEnums)) {
property.vendorExtensions.put(this.zeroBasedEnumVendorExtension, true);
} else if (!Boolean.FALSE.equals(this.zeroBasedEnums)) {
if (property.allowableValues.containsKey("values")){
final List<Object> allowableValues = (List<Object>) property.allowableValues.get("values");
boolean isZeroBased = String.valueOf(allowableValues.get(0)).toLowerCase(Locale.ROOT).equals("unknown");
property.vendorExtensions.put(this.zeroBasedEnumVendorExtension, isZeroBased);
}
}
}

if (property.isMap || property.isContainer) {
// maps of enums will be marked both isMap and isEnum, correct that now
property.isEnum = false;
Expand All @@ -479,6 +500,18 @@ public ModelsMap postProcessModels(ModelsMap objs) {
var.name = "_" + var.name;
}
}

if (cm.isEnum && !cm.vendorExtensions.containsKey(this.zeroBasedEnumVendorExtension)) {
if (Boolean.TRUE.equals(this.zeroBasedEnums)) {
cm.vendorExtensions.put(this.zeroBasedEnumVendorExtension, true);
} else if (!Boolean.FALSE.equals(this.zeroBasedEnums)) {
if (cm.allowableValues.containsKey("values")){
final List<Object> allowableValues = (List<Object>) cm.allowableValues.get("values");
boolean isZeroBased = String.valueOf(allowableValues.get(0)).toLowerCase(Locale.ROOT).equals("unknown");
cm.vendorExtensions.put(this.zeroBasedEnumVendorExtension, isZeroBased);
}
}
}
}
// process enum in models
return postProcessModelsEnum(objs);
Expand Down Expand Up @@ -1335,6 +1368,10 @@ public String getInterfacePrefix() {
return interfacePrefix;
}

public void setZeroBasedEnums(final Boolean zeroBasedEnums) {
this.zeroBasedEnums = zeroBasedEnums;
}

public void setNullableReferenceTypes(final Boolean nullReferenceTypesFlag) {
this.nullReferenceTypesFlag = nullReferenceTypesFlag;
additionalProperties.put("nullableReferenceTypes", nullReferenceTypesFlag);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,10 @@ public CSharpNetCoreClientCodegen() {
"The default DateTime format (only `generichost` library supports this option).",
this.dateTimeFormat);

addOption("zeroBasedEnums",
"Enumerations with string values will start from 0 when true, 1 when false. If not set, enumerations with string values will start from 0 if the first value is 'unknown', case insensitive.",
null);

CliOption framework = new CliOption(
CodegenConstants.DOTNET_FRAMEWORK,
CodegenConstants.DOTNET_FRAMEWORK_DESC
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
[EnumMember(Value = "{{{value}}}")]
{{/useGenericHost}}
{{/isString}}
{{name}} = {{^isString}}{{{value}}}{{/isString}}{{#isString}}{{-index}}{{/isString}}{{^-last}},{{/-last}}
{{name}}{{^isString}} = {{{value}}}{{/isString}}{{#isString}}{{^vendorExtensions.x-zero-based-enum}} = {{-index}}{{/vendorExtensions.x-zero-based-enum}}{{/isString}}{{^-last}},{{/-last}}

{{/enumVars}}
{{/allowableValues}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
[EnumMember(Value = "{{{value}}}")]
{{/isString}}
{{/useGenericHost}}
{{name}} = {{^isString}}{{{value}}}{{/isString}}{{#isString}}{{-index}}{{/isString}}{{^-last}},{{/-last}}
{{name}}{{^isString}} = {{{value}}}{{/isString}}{{#isString}}{{^vendorExtensions.x-zero-based-enum}} = {{-index}}{{/vendorExtensions.x-zero-based-enum}}{{/isString}}{{^-last}},{{/-last}}

{{/enumVars}}
{{/allowableValues}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2279,3 +2279,8 @@ components:
pattern: ^a
- type: string
pattern: ^b
ZeroBasedEnum:
type: string
enum:
- unknown
- notUnknown
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ docs/User.md
docs/UserApi.md
docs/Whale.md
docs/Zebra.md
docs/ZeroBasedEnum.md
git_push.sh
src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj
src/Org.OpenAPITools/Api/AnotherFakeApi.cs
Expand Down Expand Up @@ -210,4 +211,5 @@ src/Org.OpenAPITools/Model/TriangleInterface.cs
src/Org.OpenAPITools/Model/User.cs
src/Org.OpenAPITools/Model/Whale.cs
src/Org.OpenAPITools/Model/Zebra.cs
src/Org.OpenAPITools/Model/ZeroBasedEnum.cs
src/Org.OpenAPITools/Org.OpenAPITools.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,7 @@ Class | Method | HTTP request | Description
- [Model.User](docs/User.md)
- [Model.Whale](docs/Whale.md)
- [Model.Zebra](docs/Zebra.md)
- [Model.ZeroBasedEnum](docs/ZeroBasedEnum.md)


<a id="documentation-for-authorization"></a>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2206,6 +2206,11 @@ components:
type: string
- pattern: ^b
type: string
ZeroBasedEnum:
enum:
- unknown
- notUnknown
type: string
_foo_get_default_response:
example:
string:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Org.OpenAPITools.Model.ZeroBasedEnum

## Properties

Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/


using Xunit;

using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using Org.OpenAPITools.Model;
using Org.OpenAPITools.Client;
using System.Reflection;
using Newtonsoft.Json;

namespace Org.OpenAPITools.Test.Model
{
/// <summary>
/// Class for testing ZeroBasedEnum
/// </summary>
/// <remarks>
/// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech).
/// Please update the test case below to test the model.
/// </remarks>
public class ZeroBasedEnumTests : IDisposable
{
// TODO uncomment below to declare an instance variable for ZeroBasedEnum
//private ZeroBasedEnum instance;

public ZeroBasedEnumTests()
{
// TODO uncomment below to create an instance of ZeroBasedEnum
//instance = new ZeroBasedEnum();
}

public void Dispose()
{
// Cleanup when everything is done.
}

/// <summary>
/// Test an instance of ZeroBasedEnum
/// </summary>
[Fact]
public void ZeroBasedEnumInstanceTest()
{
// TODO uncomment below to test "IsType" ZeroBasedEnum
//Assert.IsType<ZeroBasedEnum>(instance);
}



}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/


using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter;
using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils;

namespace Org.OpenAPITools.Model
{
/// <summary>
/// Defines ZeroBasedEnum
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum ZeroBasedEnum
{
/// <summary>
/// Enum Unknown for value: unknown
/// </summary>
[EnumMember(Value = "unknown")]
Unknown,

/// <summary>
/// Enum NotUnknown for value: notUnknown
/// </summary>
[EnumMember(Value = "notUnknown")]
NotUnknown

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ docs/models/TriangleInterface.md
docs/models/User.md
docs/models/Whale.md
docs/models/Zebra.md
docs/models/ZeroBasedEnum.md
docs/scripts/git_push.ps1
docs/scripts/git_push.sh
src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs
Expand Down Expand Up @@ -216,5 +217,6 @@ src/Org.OpenAPITools/Model/TriangleInterface.cs
src/Org.OpenAPITools/Model/User.cs
src/Org.OpenAPITools/Model/Whale.cs
src/Org.OpenAPITools/Model/Zebra.cs
src/Org.OpenAPITools/Model/ZeroBasedEnum.cs
src/Org.OpenAPITools/Org.OpenAPITools.csproj
src/Org.OpenAPITools/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2206,6 +2206,11 @@ components:
type: string
- pattern: ^b
type: string
ZeroBasedEnum:
enum:
- unknown
- notUnknown
type: string
_foo_get_default_response:
example:
string:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Org.OpenAPITools.Model.ZeroBasedEnum

## Properties

Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------

[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md)

Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/


using Xunit;

using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using Org.OpenAPITools.Model;
using Org.OpenAPITools.Client;
using System.Reflection;

namespace Org.OpenAPITools.Test.Model
{
/// <summary>
/// Class for testing ZeroBasedEnum
/// </summary>
/// <remarks>
/// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech).
/// Please update the test case below to test the model.
/// </remarks>
public class ZeroBasedEnumTests : IDisposable
{
// TODO uncomment below to declare an instance variable for ZeroBasedEnum
//private ZeroBasedEnum instance;

public ZeroBasedEnumTests()
{
// TODO uncomment below to create an instance of ZeroBasedEnum
//instance = new ZeroBasedEnum();
}

public void Dispose()
{
// Cleanup when everything is done.
}

/// <summary>
/// Test an instance of ZeroBasedEnum
/// </summary>
[Fact]
public void ZeroBasedEnumInstanceTest()
{
// TODO uncomment below to test "IsType" ZeroBasedEnum
//Assert.IsType<ZeroBasedEnum>(instance);
}



}

}
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,8 @@ public static string SanitizeFilename(string filename)
return Pet.StatusEnumToJsonValue(petStatusEnum);
if (obj is Zebra.TypeEnum zebraTypeEnum)
return Zebra.TypeEnumToJsonValue(zebraTypeEnum);
if (obj is ZeroBasedEnum zeroBasedEnum)
return ZeroBasedEnumConverter.ToJsonValue(zeroBasedEnum);
if (obj is ICollection collection)
{
List<string?> entries = new List<string?>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,8 @@ public HostConfiguration(IServiceCollection services)
_jsonOptions.Converters.Add(new UserJsonConverter());
_jsonOptions.Converters.Add(new WhaleJsonConverter());
_jsonOptions.Converters.Add(new ZebraJsonConverter());
_jsonOptions.Converters.Add(new ZeroBasedEnumConverter());
_jsonOptions.Converters.Add(new ZeroBasedEnumNullableConverter());
_services.AddSingleton(new JsonSerializerOptionsProvider(_jsonOptions));
_services.AddSingleton<IApiFactory, ApiFactory>();
_services.AddTransient<TAnotherFakeApi, TAnotherFakeApi>();
Expand Down
Loading

0 comments on commit fd20632

Please sign in to comment.