[csharp] Move nullable reference types switch to abstract (#9661)

* moved switch to abstract

* build samples

* added nullable option to csproj

* removed unused method

* added switch back to aspnetcore

* build samples
This commit is contained in:
devhl-labs 2021-06-09 04:09:39 -04:00 committed by GitHub
parent f1ee1cbe2e
commit 46f8a6733a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 36 additions and 25 deletions

View File

@ -19,7 +19,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|licenseUrl|The URL of the license| |http://localhost| |licenseUrl|The URL of the license| |http://localhost|
|modelClassModifier|Model Class Modifier can be nothing or partial| |partial| |modelClassModifier|Model Class Modifier can be nothing or partial| |partial|
|newtonsoftVersion|Version for Microsoft.AspNetCore.Mvc.NewtonsoftJson for ASP.NET Core 3.0+| |3.0.0| |newtonsoftVersion|Version for Microsoft.AspNetCore.Mvc.NewtonsoftJson for ASP.NET Core 3.0+| |3.0.0|
|nullableReferenceTypes|Annotate Project with <Nullable>annotations</Nullable> and use ? annotation on all nullable attributes. Only supported on C# 8 / ASP.NET Core 3.0 or newer.| |false| |nullableReferenceTypes|Use nullable annotations in the project. Only supported on C# 8 / ASP.NET Core 3.0 or newer.| |false|
|operationIsAsync|Set methods to async or sync (default).| |false| |operationIsAsync|Set methods to async or sync (default).| |false|
|operationModifier|Operation Modifier can be virtual or abstract|<dl><dt>**virtual**</dt><dd>Keep method virtual</dd><dt>**abstract**</dt><dd>Make method abstract</dd></dl>|virtual| |operationModifier|Operation Modifier can be virtual or abstract|<dl><dt>**virtual**</dt><dd>Keep method virtual</dd><dt>**abstract**</dt><dd>Make method abstract</dd></dl>|virtual|
|operationResultTask|Set methods result to Task&lt;&gt;.| |false| |operationResultTask|Set methods result to Task&lt;&gt;.| |false|

View File

@ -17,6 +17,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |PascalCase| |modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |PascalCase|
|netCoreProjectFile|Use the new format (.NET Core) for .NET project files (.csproj).| |false| |netCoreProjectFile|Use the new format (.NET Core) for .NET project files (.csproj).| |false|
|nonPublicApi|Generates code with reduced access modifiers; allows embedding elsewhere without exposing non-public API calls to consumers.| |false| |nonPublicApi|Generates code with reduced access modifiers; allows embedding elsewhere without exposing non-public API calls to consumers.| |false|
|nullableReferenceTypes|Use nullable annotations in the project. Only supported on C# 8 / ASP.NET Core 3.0 or newer.| |false|
|optionalAssemblyInfo|Generate AssemblyInfo.cs.| |true| |optionalAssemblyInfo|Generate AssemblyInfo.cs.| |true|
|optionalEmitDefaultValues|Set DataMember's EmitDefaultValue.| |false| |optionalEmitDefaultValues|Set DataMember's EmitDefaultValue.| |false|
|optionalMethodArgument|C# Optional method argument, e.g. void square(int x=10) (.net 4.0+ only).| |true| |optionalMethodArgument|C# Optional method argument, e.g. void square(int x=10) (.net 4.0+ only).| |true|

View File

@ -211,6 +211,9 @@ public class CodegenConstants {
public static final String DOTNET_FRAMEWORK = "targetFramework"; public static final String DOTNET_FRAMEWORK = "targetFramework";
public static final String DOTNET_FRAMEWORK_DESC = "The target .NET framework version. To target multiple frameworks, use `;` as the separator, e.g. `netstandard2.1;netcoreapp3.0`"; public static final String DOTNET_FRAMEWORK_DESC = "The target .NET framework version. To target multiple frameworks, use `;` as the separator, e.g. `netstandard2.1;netcoreapp3.0`";
public static final String NULLABLE_REFERENCE_TYPES = "nullableReferenceTypes";
public static final String NULLABLE_REFERENCE_TYPES_DESC = "Use nullable annotations in the project. Only supported on C# 8 / ASP.NET Core 3.0 or newer.";
public static final String TEMPLATING_ENGINE = "templatingEngine"; public static final String TEMPLATING_ENGINE = "templatingEngine";
public static final String TEMPLATING_ENGINE_DESC = "The templating engine plugin to use: \"mustache\" (default) or \"handlebars\" (beta)"; public static final String TEMPLATING_ENGINE_DESC = "The templating engine plugin to use: \"mustache\" (default) or \"handlebars\" (beta)";

View File

@ -47,6 +47,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
protected boolean useCollection = false; protected boolean useCollection = false;
protected boolean returnICollection = false; protected boolean returnICollection = false;
protected boolean netCoreProjectFileFlag = false; protected boolean netCoreProjectFileFlag = false;
protected boolean nullReferenceTypesFlag = false;
protected String modelPropertyNaming = CodegenConstants.MODEL_PROPERTY_NAMING_TYPE.PascalCase.name(); protected String modelPropertyNaming = CodegenConstants.MODEL_PROPERTY_NAMING_TYPE.PascalCase.name();
@ -356,6 +357,12 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
additionalProperties.put(CodegenConstants.NETCORE_PROJECT_FILE, netCoreProjectFileFlag); additionalProperties.put(CodegenConstants.NETCORE_PROJECT_FILE, netCoreProjectFileFlag);
} }
if (additionalProperties.containsKey(CodegenConstants.NULLABLE_REFERENCE_TYPES)) {
setNullableReferenceTypes(convertPropertyToBooleanAndWriteBack(CodegenConstants.NULLABLE_REFERENCE_TYPES));
} else {
additionalProperties.put(CodegenConstants.NULLABLE_REFERENCE_TYPES, nullReferenceTypesFlag);
}
if (additionalProperties.containsKey(CodegenConstants.INTERFACE_PREFIX)) { if (additionalProperties.containsKey(CodegenConstants.INTERFACE_PREFIX)) {
String useInterfacePrefix = additionalProperties.get(CodegenConstants.INTERFACE_PREFIX).toString(); String useInterfacePrefix = additionalProperties.get(CodegenConstants.INTERFACE_PREFIX).toString();
if ("false".equals(useInterfacePrefix.toLowerCase(Locale.ROOT))) { if ("false".equals(useInterfacePrefix.toLowerCase(Locale.ROOT))) {
@ -1112,6 +1119,13 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
return interfacePrefix; return interfacePrefix;
} }
public void setNullableReferenceTypes(final Boolean nullReferenceTypesFlag){
this.nullReferenceTypesFlag = nullReferenceTypesFlag;
if (nullReferenceTypesFlag == true){
this.nullableType.add("string");
}
}
public void setInterfacePrefix(final String interfacePrefix) { public void setInterfacePrefix(final String interfacePrefix) {
this.interfacePrefix = interfacePrefix; this.interfacePrefix = interfacePrefix;
} }

View File

@ -60,7 +60,6 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
public static final String USE_NEWTONSOFT = "useNewtonsoft"; public static final String USE_NEWTONSOFT = "useNewtonsoft";
public static final String USE_DEFAULT_ROUTING = "useDefaultRouting"; public static final String USE_DEFAULT_ROUTING = "useDefaultRouting";
public static final String NEWTONSOFT_VERSION = "newtonsoftVersion"; public static final String NEWTONSOFT_VERSION = "newtonsoftVersion";
public static final String NULLABLE_REFERENCE_TYPES = "nullableReferenceTypes";
private String packageGuid = "{" + randomUUID().toString().toUpperCase(Locale.ROOT) + "}"; private String packageGuid = "{" + randomUUID().toString().toUpperCase(Locale.ROOT) + "}";
private String userSecretsGuid = randomUUID().toString(); private String userSecretsGuid = randomUUID().toString();
@ -85,7 +84,6 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
private boolean useFrameworkReference = false; private boolean useFrameworkReference = false;
private boolean useNewtonsoft = true; private boolean useNewtonsoft = true;
private boolean useDefaultRouting = true; private boolean useDefaultRouting = true;
private boolean nullableReferenceTypes = false;
private String newtonsoftVersion = "3.0.0"; private String newtonsoftVersion = "3.0.0";
public AspNetCoreServerCodegen() { public AspNetCoreServerCodegen() {
@ -211,6 +209,10 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
cliOptions.add(swashbuckleVersion); cliOptions.add(swashbuckleVersion);
// CLI Switches // CLI Switches
addSwitch(CodegenConstants.NULLABLE_REFERENCE_TYPES,
CodegenConstants.NULLABLE_REFERENCE_TYPES_DESC,
this.nullReferenceTypesFlag);
addSwitch(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, addSwitch(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG,
CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC, CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC,
sortParamsByRequiredFlag); sortParamsByRequiredFlag);
@ -251,11 +253,6 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
"Use default routing for the ASP.NET Core version.", "Use default routing for the ASP.NET Core version.",
useDefaultRouting); useDefaultRouting);
addSwitch(NULLABLE_REFERENCE_TYPES,
"Annotate Project with <Nullable>annotations</Nullable> and use ? annotation on all nullable attributes. " +
"Only supported on C# 8 / ASP.NET Core 3.0 or newer.",
nullableReferenceTypes);
addOption(CodegenConstants.ENUM_NAME_SUFFIX, addOption(CodegenConstants.ENUM_NAME_SUFFIX,
CodegenConstants.ENUM_NAME_SUFFIX_DESC, CodegenConstants.ENUM_NAME_SUFFIX_DESC,
enumNameSuffix); enumNameSuffix);
@ -373,7 +370,6 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
setIsFramework(); setIsFramework();
setUseNewtonsoft(); setUseNewtonsoft();
setUseEndpointRouting(); setUseEndpointRouting();
setNullableReferenceTypes();
supportingFiles.add(new SupportingFile("build.sh.mustache", "", "build.sh")); supportingFiles.add(new SupportingFile("build.sh.mustache", "", "build.sh"));
supportingFiles.add(new SupportingFile("build.bat.mustache", "", "build.bat")); supportingFiles.add(new SupportingFile("build.bat.mustache", "", "build.bat"));
@ -528,7 +524,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
@Override @Override
public String getNullableType(Schema p, String type) { public String getNullableType(Schema p, String type) {
if (languageSpecificPrimitives.contains(type)) { if (languageSpecificPrimitives.contains(type)) {
if (isSupportNullable() && ModelUtils.isNullable(p) && (nullableType.contains(type) || nullableReferenceTypes)) { if (isSupportNullable() && ModelUtils.isNullable(p) && (nullableType.contains(type) || nullReferenceTypesFlag)) {
return type + "?"; return type + "?";
} else { } else {
return type; return type;
@ -657,20 +653,6 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
} }
} }
private void setNullableReferenceTypes() {
if (additionalProperties.containsKey(NULLABLE_REFERENCE_TYPES)) {
if (aspnetCoreVersion.getOptValue().startsWith("2.")) {
LOGGER.warn("Nullable annotation are not supported in ASP.NET core version 2. Setting {} to false",
NULLABLE_REFERENCE_TYPES);
additionalProperties.put(NULLABLE_REFERENCE_TYPES, false);
} else {
nullableReferenceTypes = convertPropertyToBooleanAndWriteBack(NULLABLE_REFERENCE_TYPES);
}
} else {
additionalProperties.put(NULLABLE_REFERENCE_TYPES, nullableReferenceTypes);
}
}
private void setOperationIsAsync() { private void setOperationIsAsync() {
if (isLibrary) { if (isLibrary) {
operationIsAsync = false; operationIsAsync = false;

View File

@ -230,6 +230,10 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
cliOptions.add(modelPropertyNaming.defaultValue("PascalCase")); cliOptions.add(modelPropertyNaming.defaultValue("PascalCase"));
// CLI Switches // CLI Switches
addSwitch(CodegenConstants.NULLABLE_REFERENCE_TYPES,
CodegenConstants.NULLABLE_REFERENCE_TYPES_DESC,
this.nullReferenceTypesFlag);
addSwitch(CodegenConstants.HIDE_GENERATION_TIMESTAMP, addSwitch(CodegenConstants.HIDE_GENERATION_TIMESTAMP,
CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC,
this.hideGenerationTimestamp); this.hideGenerationTimestamp);

View File

@ -19,6 +19,9 @@
<RepositoryType>git</RepositoryType>{{#releaseNote}} <RepositoryType>git</RepositoryType>{{#releaseNote}}
<PackageReleaseNotes>{{releaseNote}}</PackageReleaseNotes>{{/releaseNote}}{{#packageTags}} <PackageReleaseNotes>{{releaseNote}}</PackageReleaseNotes>{{/releaseNote}}{{#packageTags}}
<PackageTags>{{{packageTags}}}</PackageTags>{{/packageTags}} <PackageTags>{{{packageTags}}}</PackageTags>{{/packageTags}}
{{#nullableReferenceTypes}}
<Nullable>annotations</Nullable>
{{/nullableReferenceTypes}}
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>

View File

@ -15,6 +15,9 @@
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType> <GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
<RootNamespace>{{packageName}}</RootNamespace> <RootNamespace>{{packageName}}</RootNamespace>
<Version>{{packageVersion}}</Version> <Version>{{packageVersion}}</Version>
{{#nullableReferenceTypes}}
<Nullable>annotations</Nullable>
{{/nullableReferenceTypes}}
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>

View File

@ -21,6 +21,7 @@ import com.google.common.collect.Sets;
import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.*; import io.swagger.v3.oas.models.media.*;
import io.swagger.v3.parser.util.SchemaTypeUtil; import io.swagger.v3.parser.util.SchemaTypeUtil;
import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.CodegenModel; import org.openapitools.codegen.CodegenModel;
import org.openapitools.codegen.CodegenProperty; import org.openapitools.codegen.CodegenProperty;
import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.DefaultCodegen;
@ -335,7 +336,7 @@ public class CSharpModelTest {
.addProperties("subObject", new Schema().addProperties("name", new StringSchema()).nullable(true)) .addProperties("subObject", new Schema().addProperties("name", new StringSchema()).nullable(true))
.addRequiredItem("id"); .addRequiredItem("id");
final DefaultCodegen codegen = new AspNetCoreServerCodegen(); final DefaultCodegen codegen = new AspNetCoreServerCodegen();
codegen.additionalProperties().put(AspNetCoreServerCodegen.NULLABLE_REFERENCE_TYPES, true); codegen.additionalProperties().put(CodegenConstants.NULLABLE_REFERENCE_TYPES, true);
codegen.processOpts(); codegen.processOpts();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model); OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI); codegen.setOpenAPI(openAPI);