Skip to content

Commit

Permalink
[csharp] Move nullable reference types switch to abstract (#9661)
Browse files Browse the repository at this point in the history
* moved switch to abstract

* build samples

* added nullable option to csproj

* removed unused method

* added switch back to aspnetcore

* build samples
  • Loading branch information
devhl-labs authored Jun 9, 2021
1 parent f1ee1cb commit 46f8a67
Show file tree
Hide file tree
Showing 9 changed files with 36 additions and 25 deletions.
2 changes: 1 addition & 1 deletion docs/generators/aspnetcore.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|licenseUrl|The URL of the license| |http://localhost|
|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|
|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|
|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|
Expand Down
1 change: 1 addition & 0 deletions docs/generators/csharp-netcore.md
Original file line number Diff line number Diff line change
Expand Up @@ -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|
|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|
|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|
|optionalEmitDefaultValues|Set DataMember's EmitDefaultValue.| |false|
|optionalMethodArgument|C# Optional method argument, e.g. void square(int x=10) (.net 4.0+ only).| |true|
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,9 @@ public class CodegenConstants {
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 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_DESC = "The templating engine plugin to use: \"mustache\" (default) or \"handlebars\" (beta)";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
protected boolean useCollection = false;
protected boolean returnICollection = false;
protected boolean netCoreProjectFileFlag = false;
protected boolean nullReferenceTypesFlag = false;

protected String modelPropertyNaming = CodegenConstants.MODEL_PROPERTY_NAMING_TYPE.PascalCase.name();

Expand Down Expand Up @@ -356,6 +357,12 @@ public void processOpts() {
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)) {
String useInterfacePrefix = additionalProperties.get(CodegenConstants.INTERFACE_PREFIX).toString();
if ("false".equals(useInterfacePrefix.toLowerCase(Locale.ROOT))) {
Expand Down Expand Up @@ -1112,6 +1119,13 @@ public String getInterfacePrefix() {
return interfacePrefix;
}

public void setNullableReferenceTypes(final Boolean nullReferenceTypesFlag){
this.nullReferenceTypesFlag = nullReferenceTypesFlag;
if (nullReferenceTypesFlag == true){
this.nullableType.add("string");
}
}

public void setInterfacePrefix(final String interfacePrefix) {
this.interfacePrefix = interfacePrefix;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
public static final String USE_NEWTONSOFT = "useNewtonsoft";
public static final String USE_DEFAULT_ROUTING = "useDefaultRouting";
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 userSecretsGuid = randomUUID().toString();
Expand All @@ -85,7 +84,6 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
private boolean useFrameworkReference = false;
private boolean useNewtonsoft = true;
private boolean useDefaultRouting = true;
private boolean nullableReferenceTypes = false;
private String newtonsoftVersion = "3.0.0";

public AspNetCoreServerCodegen() {
Expand Down Expand Up @@ -211,6 +209,10 @@ public AspNetCoreServerCodegen() {
cliOptions.add(swashbuckleVersion);

// CLI Switches
addSwitch(CodegenConstants.NULLABLE_REFERENCE_TYPES,
CodegenConstants.NULLABLE_REFERENCE_TYPES_DESC,
this.nullReferenceTypesFlag);

addSwitch(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG,
CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC,
sortParamsByRequiredFlag);
Expand Down Expand Up @@ -251,11 +253,6 @@ public AspNetCoreServerCodegen() {
"Use default routing for the ASP.NET Core version.",
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,
CodegenConstants.ENUM_NAME_SUFFIX_DESC,
enumNameSuffix);
Expand Down Expand Up @@ -373,7 +370,6 @@ public void processOpts() {
setIsFramework();
setUseNewtonsoft();
setUseEndpointRouting();
setNullableReferenceTypes();

supportingFiles.add(new SupportingFile("build.sh.mustache", "", "build.sh"));
supportingFiles.add(new SupportingFile("build.bat.mustache", "", "build.bat"));
Expand Down Expand Up @@ -528,7 +524,7 @@ public String toRegularExpression(String pattern) {
@Override
public String getNullableType(Schema p, String 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 + "?";
} else {
return type;
Expand Down Expand Up @@ -657,20 +653,6 @@ private void setUseSwashbuckle() {
}
}

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() {
if (isLibrary) {
operationIsAsync = false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,10 @@ public CSharpNetCoreClientCodegen() {
cliOptions.add(modelPropertyNaming.defaultValue("PascalCase"));

// CLI Switches
addSwitch(CodegenConstants.NULLABLE_REFERENCE_TYPES,
CodegenConstants.NULLABLE_REFERENCE_TYPES_DESC,
this.nullReferenceTypesFlag);

addSwitch(CodegenConstants.HIDE_GENERATION_TIMESTAMP,
CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC,
this.hideGenerationTimestamp);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@
<RepositoryType>git</RepositoryType>{{#releaseNote}}
<PackageReleaseNotes>{{releaseNote}}</PackageReleaseNotes>{{/releaseNote}}{{#packageTags}}
<PackageTags>{{{packageTags}}}</PackageTags>{{/packageTags}}
{{#nullableReferenceTypes}}
<Nullable>annotations</Nullable>
{{/nullableReferenceTypes}}
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
<RootNamespace>{{packageName}}</RootNamespace>
<Version>{{packageVersion}}</Version>
{{#nullableReferenceTypes}}
<Nullable>annotations</Nullable>
{{/nullableReferenceTypes}}
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.*;
import io.swagger.v3.parser.util.SchemaTypeUtil;
import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.CodegenModel;
import org.openapitools.codegen.CodegenProperty;
import org.openapitools.codegen.DefaultCodegen;
Expand Down Expand Up @@ -335,7 +336,7 @@ public void nullablePropertyWithNullableReferenceTypesTest() {
.addProperties("subObject", new Schema().addProperties("name", new StringSchema()).nullable(true))
.addRequiredItem("id");
final DefaultCodegen codegen = new AspNetCoreServerCodegen();
codegen.additionalProperties().put(AspNetCoreServerCodegen.NULLABLE_REFERENCE_TYPES, true);
codegen.additionalProperties().put(CodegenConstants.NULLABLE_REFERENCE_TYPES, true);
codegen.processOpts();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
Expand Down

0 comments on commit 46f8a67

Please sign in to comment.