better code format in c#, aspnet generators (#11662)

This commit is contained in:
William Cheng 2022-02-19 14:40:12 +08:00 committed by GitHub
parent c161358aa8
commit 2918b8706e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 69 additions and 71 deletions

View File

@ -49,7 +49,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
public static final String GENERATE_BODY = "generateBody"; public static final String GENERATE_BODY = "generateBody";
public static final String BUILD_TARGET = "buildTarget"; public static final String BUILD_TARGET = "buildTarget";
public static final String MODEL_CLASS_MODIFIER = "modelClassModifier"; public static final String MODEL_CLASS_MODIFIER = "modelClassModifier";
public static final String TARGET_FRAMEWORK= "targetFramework"; public static final String TARGET_FRAMEWORK = "targetFramework";
public static final String PROJECT_SDK = "projectSdk"; public static final String PROJECT_SDK = "projectSdk";
public static final String SDK_WEB = "Microsoft.NET.Sdk.Web"; public static final String SDK_WEB = "Microsoft.NET.Sdk.Web";
@ -150,8 +150,8 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
// CLI options // CLI options
addOption(CodegenConstants.PACKAGE_DESCRIPTION, addOption(CodegenConstants.PACKAGE_DESCRIPTION,
CodegenConstants.PACKAGE_DESCRIPTION_DESC, CodegenConstants.PACKAGE_DESCRIPTION_DESC,
packageDescription); packageDescription);
addOption(CodegenConstants.LICENSE_URL, addOption(CodegenConstants.LICENSE_URL,
CodegenConstants.LICENSE_URL_DESC, CodegenConstants.LICENSE_URL_DESC,
@ -474,10 +474,9 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
continue; continue;
} }
if(consumesString.toString().isEmpty()) { if (consumesString.toString().isEmpty()) {
consumesString = new StringBuilder("\"" + consume.get("mediaType") + "\""); consumesString = new StringBuilder("\"" + consume.get("mediaType") + "\"");
} } else {
else {
consumesString.append(", \"").append(consume.get("mediaType")).append("\""); consumesString.append(", \"").append(consume.get("mediaType")).append("\"");
} }
@ -502,7 +501,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
} }
} }
if(!consumesString.toString().isEmpty()) { if (!consumesString.toString().isEmpty()) {
operation.vendorExtensions.put("x-aspnetcore-consumes", consumesString.toString()); operation.vendorExtensions.put("x-aspnetcore-consumes", consumesString.toString());
} }
} }
@ -598,7 +597,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
private void setBuildTarget() { private void setBuildTarget() {
setCliOption(buildTarget); setCliOption(buildTarget);
if ("library".equals(buildTarget.getOptValue())) { if ("library".equals(buildTarget.getOptValue())) {
LOGGER.warn("buildTarget is {} so changing default isLibrary to true", buildTarget.getOptValue()); LOGGER.warn("buildTarget is {} so changing default isLibrary to true", buildTarget.getOptValue());
isLibrary = true; isLibrary = true;
projectSdk = SDK_LIB; projectSdk = SDK_LIB;
additionalProperties.put(CLASS_MODIFIER, "abstract"); additionalProperties.put(CLASS_MODIFIER, "abstract");
@ -621,7 +620,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
compatibilityVersion = "Version_" + aspnetCoreVersion.getOptValue().replace(".", "_"); compatibilityVersion = "Version_" + aspnetCoreVersion.getOptValue().replace(".", "_");
} }
LOGGER.info("ASP.NET core version: {}", aspnetCoreVersion.getOptValue()); LOGGER.info("ASP.NET core version: {}", aspnetCoreVersion.getOptValue());
if(!additionalProperties.containsKey(CodegenConstants.TEMPLATE_DIR)){ if (!additionalProperties.containsKey(CodegenConstants.TEMPLATE_DIR)) {
templateDir = embeddedTemplateDir = "aspnetcore" + File.separator + determineTemplateVersion(aspnetCoreVersion.getOptValue()); templateDir = embeddedTemplateDir = "aspnetcore" + File.separator + determineTemplateVersion(aspnetCoreVersion.getOptValue());
} }
additionalProperties.put(COMPATIBILITY_VERSION, compatibilityVersion); additionalProperties.put(COMPATIBILITY_VERSION, compatibilityVersion);

View File

@ -334,9 +334,9 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
@Override @Override
public String apiDocFileFolder() { public String apiDocFileFolder() {
if (GENERICHOST.equals(getLibrary())){ if (GENERICHOST.equals(getLibrary())) {
return (outputFolder + "/" + apiDocPath + File.separatorChar + "apis").replace('/', File.separatorChar); return (outputFolder + "/" + apiDocPath + File.separatorChar + "apis").replace('/', File.separatorChar);
}else{ } else {
return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar); return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar);
} }
} }
@ -396,9 +396,9 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
} }
// avoid breaking changes // avoid breaking changes
if (GENERICHOST.equals(getLibrary())){ if (GENERICHOST.equals(getLibrary())) {
Comparator<CodegenProperty> comparatorByDefaultValue = new Comparator<CodegenProperty>() { Comparator<CodegenProperty> comparatorByDefaultValue = new Comparator<CodegenProperty>() {
@Override @Override
public int compare(CodegenProperty one, CodegenProperty another) { public int compare(CodegenProperty one, CodegenProperty another) {
if (one.defaultValue == another.defaultValue) if (one.defaultValue == another.defaultValue)
return 0; return 0;
@ -502,9 +502,9 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
@Override @Override
public String modelDocFileFolder() { public String modelDocFileFolder() {
if (GENERICHOST.equals(getLibrary())){ if (GENERICHOST.equals(getLibrary())) {
return (outputFolder + "/" + modelDocPath + File.separator + "models").replace('/', File.separatorChar); return (outputFolder + "/" + modelDocPath + File.separator + "models").replace('/', File.separatorChar);
}else{ } else {
return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar); return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar);
} }
} }
@ -630,7 +630,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
clientPackage = "Client"; clientPackage = "Client";
if (GENERICHOST.equals(getLibrary())){ if (GENERICHOST.equals(getLibrary())) {
setLibrary(GENERICHOST); setLibrary(GENERICHOST);
additionalProperties.put("useGenericHost", true); additionalProperties.put("useGenericHost", true);
// all c# libraries should be doing this, but we only do it here to avoid breaking changes // all c# libraries should be doing this, but we only do it here to avoid breaking changes
@ -656,7 +656,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
additionalProperties.put("multiTarget", true); additionalProperties.put("multiTarget", true);
} else { } else {
// just a single value // just a single value
frameworks = new String [] {inputFramework}; frameworks = new String[]{inputFramework};
} }
for (String framework : frameworks) { for (String framework : frameworks) {
@ -668,14 +668,14 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
} }
if (frameworkStrategy != FrameworkStrategy.NETSTANDARD_2_0 && "restsharp".equals(getLibrary())) { if (frameworkStrategy != FrameworkStrategy.NETSTANDARD_2_0 && "restsharp".equals(getLibrary())) {
LOGGER.warn("If using built-in templates, RestSharp only supports netstandard 2.0 or later."); LOGGER.warn("If using built-in templates, RestSharp only supports netstandard 2.0 or later.");
} }
} }
if (!strategyMatched) { if (!strategyMatched) {
// throws exception if the input targetFramework is invalid // throws exception if the input targetFramework is invalid
throw new IllegalArgumentException("The input (" + inputFramework + ") contains Invalid .NET framework version: " + throw new IllegalArgumentException("The input (" + inputFramework + ") contains Invalid .NET framework version: " +
framework + ". List of supported versions: " + framework + ". List of supported versions: " +
frameworkStrategies.stream() frameworkStrategies.stream()
.map(p -> p.name) .map(p -> p.name)
.collect(Collectors.joining(", "))); .collect(Collectors.joining(", ")));
@ -694,12 +694,12 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
setNetCoreProjectFileFlag(true); setNetCoreProjectFileFlag(true);
if (!additionalProperties.containsKey(CodegenConstants.NULLABLE_REFERENCE_TYPES) && !strategies.stream().anyMatch(s -> if (!additionalProperties.containsKey(CodegenConstants.NULLABLE_REFERENCE_TYPES) && !strategies.stream().anyMatch(s ->
s.equals(FrameworkStrategy.NETCOREAPP_2_0) || s.equals(FrameworkStrategy.NETCOREAPP_2_0) ||
s.equals(FrameworkStrategy.NETCOREAPP_2_1) || s.equals(FrameworkStrategy.NETCOREAPP_2_1) ||
s.equals(FrameworkStrategy.NETCOREAPP_3_0) || s.equals(FrameworkStrategy.NETCOREAPP_3_0) ||
s.equals(FrameworkStrategy.NETCOREAPP_3_1) || s.equals(FrameworkStrategy.NETCOREAPP_3_1) ||
s.equals(FrameworkStrategy.NET_5_0) || s.equals(FrameworkStrategy.NET_5_0) ||
s.equals(FrameworkStrategy.NETFRAMEWORK_4_7))) { s.equals(FrameworkStrategy.NETFRAMEWORK_4_7))) {
// starting in .net 6.0, NRT is enabled by default. If not specified, lets enable NRT to match the framework's default // starting in .net 6.0, NRT is enabled by default. If not specified, lets enable NRT to match the framework's default
setNullableReferenceTypes(true); setNullableReferenceTypes(true);
} }
@ -749,19 +749,17 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
apiTestTemplateFiles.put("api_test.mustache", ".cs"); apiTestTemplateFiles.put("api_test.mustache", ".cs");
} }
if(HTTPCLIENT.equals(getLibrary())) { if (HTTPCLIENT.equals(getLibrary())) {
supportingFiles.add(new SupportingFile("FileParameter.mustache", clientPackageDir, "FileParameter.cs")); supportingFiles.add(new SupportingFile("FileParameter.mustache", clientPackageDir, "FileParameter.cs"));
typeMapping.put("file", "FileParameter"); typeMapping.put("file", "FileParameter");
addRestSharpSupportingFiles(clientPackageDir, packageFolder, excludeTests, testPackageFolder, testPackageName, modelPackageDir); addRestSharpSupportingFiles(clientPackageDir, packageFolder, excludeTests, testPackageFolder, testPackageName, modelPackageDir);
additionalProperties.put("apiDocPath", apiDocPath); additionalProperties.put("apiDocPath", apiDocPath);
additionalProperties.put("modelDocPath", modelDocPath); additionalProperties.put("modelDocPath", modelDocPath);
} } else if (GENERICHOST.equals(getLibrary())) {
else if (GENERICHOST.equals(getLibrary())){
addGenericHostSupportingFiles(clientPackageDir, packageFolder, excludeTests, testPackageFolder, testPackageName, modelPackageDir); addGenericHostSupportingFiles(clientPackageDir, packageFolder, excludeTests, testPackageFolder, testPackageName, modelPackageDir);
additionalProperties.put("apiDocPath", apiDocPath + File.separatorChar + "apis"); additionalProperties.put("apiDocPath", apiDocPath + File.separatorChar + "apis");
additionalProperties.put("modelDocPath", modelDocPath + File.separatorChar + "models"); additionalProperties.put("modelDocPath", modelDocPath + File.separatorChar + "models");
} } else {
else{
addRestSharpSupportingFiles(clientPackageDir, packageFolder, excludeTests, testPackageFolder, testPackageName, modelPackageDir); addRestSharpSupportingFiles(clientPackageDir, packageFolder, excludeTests, testPackageFolder, testPackageName, modelPackageDir);
additionalProperties.put("apiDocPath", apiDocPath); additionalProperties.put("apiDocPath", apiDocPath);
additionalProperties.put("modelDocPath", modelDocPath); additionalProperties.put("modelDocPath", modelDocPath);
@ -777,7 +775,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
List<Server> servers) { List<Server> servers) {
CodegenOperation op = super.fromOperation(path, httpMethod, operation, servers); CodegenOperation op = super.fromOperation(path, httpMethod, operation, servers);
if (!GENERICHOST.equals(getLibrary())){ if (!GENERICHOST.equals(getLibrary())) {
return op; return op;
} }
@ -808,32 +806,32 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
return op; return op;
} }
private void addTestInstructions(){ private void addTestInstructions() {
if (GENERICHOST.equals(getLibrary())){ if (GENERICHOST.equals(getLibrary())) {
additionalProperties.put("testInstructions", additionalProperties.put("testInstructions",
"/* *********************************************************************************" + "/* *********************************************************************************" +
"\n* Follow these manual steps to construct tests." + "\n* Follow these manual steps to construct tests." +
"\n* This file will not be overwritten." + "\n* This file will not be overwritten." +
"\n* *********************************************************************************" + "\n* *********************************************************************************" +
"\n* 1. Navigate to ApiTests.Base.cs and ensure any tokens are being created correctly." + "\n* 1. Navigate to ApiTests.Base.cs and ensure any tokens are being created correctly." +
"\n* Take care not to commit credentials to any repository." + "\n* Take care not to commit credentials to any repository." +
"\n*" + "\n*" +
"\n* 2. Mocking is coordinated by ApiTestsBase#AddApiHttpClients." + "\n* 2. Mocking is coordinated by ApiTestsBase#AddApiHttpClients." +
"\n* To mock the client, use the generic AddApiHttpClients." + "\n* To mock the client, use the generic AddApiHttpClients." +
"\n* To mock the server, change the client's BaseAddress." + "\n* To mock the server, change the client's BaseAddress." +
"\n*" + "\n*" +
"\n* 3. Locate the test you want below" + "\n* 3. Locate the test you want below" +
"\n* - remove the skip property from the Fact attribute" + "\n* - remove the skip property from the Fact attribute" +
"\n* - set the value of any variables if necessary" + "\n* - set the value of any variables if necessary" +
"\n*" + "\n*" +
"\n* 4. Run the tests and ensure they work." + "\n* 4. Run the tests and ensure they work." +
"\n*" + "\n*" +
"\n*/"); "\n*/");
} }
} }
public void addRestSharpSupportingFiles(final String clientPackageDir, final String packageFolder, public void addRestSharpSupportingFiles(final String clientPackageDir, final String packageFolder,
final AtomicReference<Boolean> excludeTests, final String testPackageFolder, final String testPackageName, final String modelPackageDir){ final AtomicReference<Boolean> excludeTests, final String testPackageFolder, final String testPackageName, final String modelPackageDir) {
supportingFiles.add(new SupportingFile("IApiAccessor.mustache", clientPackageDir, "IApiAccessor.cs")); supportingFiles.add(new SupportingFile("IApiAccessor.mustache", clientPackageDir, "IApiAccessor.cs"));
supportingFiles.add(new SupportingFile("Configuration.mustache", clientPackageDir, "Configuration.cs")); supportingFiles.add(new SupportingFile("Configuration.mustache", clientPackageDir, "Configuration.cs"));
supportingFiles.add(new SupportingFile("ApiClient.mustache", clientPackageDir, "ApiClient.cs")); supportingFiles.add(new SupportingFile("ApiClient.mustache", clientPackageDir, "ApiClient.cs"));
@ -842,10 +840,10 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
supportingFiles.add(new SupportingFile("ExceptionFactory.mustache", clientPackageDir, "ExceptionFactory.cs")); supportingFiles.add(new SupportingFile("ExceptionFactory.mustache", clientPackageDir, "ExceptionFactory.cs"));
supportingFiles.add(new SupportingFile("OpenAPIDateConverter.mustache", clientPackageDir, "OpenAPIDateConverter.cs")); supportingFiles.add(new SupportingFile("OpenAPIDateConverter.mustache", clientPackageDir, "OpenAPIDateConverter.cs"));
supportingFiles.add(new SupportingFile("ClientUtils.mustache", clientPackageDir, "ClientUtils.cs")); supportingFiles.add(new SupportingFile("ClientUtils.mustache", clientPackageDir, "ClientUtils.cs"));
if(needsCustomHttpMethod) { if (needsCustomHttpMethod) {
supportingFiles.add(new SupportingFile("HttpMethod.mustache", clientPackageDir, "HttpMethod.cs")); supportingFiles.add(new SupportingFile("HttpMethod.mustache", clientPackageDir, "HttpMethod.cs"));
} }
if(needsUriBuilder) { if (needsUriBuilder) {
supportingFiles.add(new SupportingFile("WebRequestPathBuilder.mustache", clientPackageDir, "WebRequestPathBuilder.cs")); supportingFiles.add(new SupportingFile("WebRequestPathBuilder.mustache", clientPackageDir, "WebRequestPathBuilder.cs"));
} }
if (ProcessUtils.hasHttpSignatureMethods(openAPI)) { if (ProcessUtils.hasHttpSignatureMethods(openAPI)) {
@ -883,7 +881,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
} }
public void addGenericHostSupportingFiles(final String clientPackageDir, final String packageFolder, public void addGenericHostSupportingFiles(final String clientPackageDir, final String packageFolder,
final AtomicReference<Boolean> excludeTests, final String testPackageFolder, final String testPackageName, final String modelPackageDir){ final AtomicReference<Boolean> excludeTests, final String testPackageFolder, final String testPackageName, final String modelPackageDir) {
supportingFiles.add(new SupportingFile("TokenProvider`1.mustache", clientPackageDir, "TokenProvider`1.cs")); supportingFiles.add(new SupportingFile("TokenProvider`1.mustache", clientPackageDir, "TokenProvider`1.cs"));
supportingFiles.add(new SupportingFile("RateLimitProvider`1.mustache", clientPackageDir, "RateLimitProvider`1.cs")); supportingFiles.add(new SupportingFile("RateLimitProvider`1.mustache", clientPackageDir, "RateLimitProvider`1.cs"));
supportingFiles.add(new SupportingFile("TokenContainer`1.mustache", clientPackageDir, "TokenContainer`1.cs")); supportingFiles.add(new SupportingFile("TokenContainer`1.mustache", clientPackageDir, "TokenContainer`1.cs"));
@ -952,7 +950,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
this.optionalEmitDefaultValuesFlag = flag; this.optionalEmitDefaultValuesFlag = flag;
} }
public void setConditionalSerialization(boolean flag){ public void setConditionalSerialization(boolean flag) {
this.conditionalSerialization = flag; this.conditionalSerialization = flag;
} }
@ -972,10 +970,11 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
/** /**
* Sets the api name. This value must be a valid class name. * Sets the api name. This value must be a valid class name.
*
* @param apiName The api name * @param apiName The api name
*/ */
public void setApiName(String apiName) { public void setApiName(String apiName) {
if (!"".equals(apiName) && (Boolean.FALSE.equals(apiName.matches("^[a-zA-Z0-9_]*$")) || Boolean.FALSE.equals(apiName.matches("^[a-zA-Z].*")))){ if (!"".equals(apiName) && (Boolean.FALSE.equals(apiName.matches("^[a-zA-Z0-9_]*$")) || Boolean.FALSE.equals(apiName.matches("^[a-zA-Z].*")))) {
throw new RuntimeException("Invalid project name " + apiName + ". May only contain alphanumeric characaters or underscore and start with a letter."); throw new RuntimeException("Invalid project name " + apiName + ". May only contain alphanumeric characaters or underscore and start with a letter.");
} }
this.apiName = apiName; this.apiName = apiName;
@ -1000,8 +999,8 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
throw new IllegalArgumentException("Invalid .NET framework version: " + throw new IllegalArgumentException("Invalid .NET framework version: " +
dotnetFramework + ". List of supported versions: " + dotnetFramework + ". List of supported versions: " +
frameworkStrategies.stream() frameworkStrategies.stream()
.map(p -> p.name) .map(p -> p.name)
.collect(Collectors.joining(", "))); .collect(Collectors.joining(", ")));
} else { } else {
this.targetFramework = dotnetFramework; this.targetFramework = dotnetFramework;
} }