minor code improvement (#9091)

This commit is contained in:
William Cheng 2021-03-27 14:57:26 +08:00 committed by GitHub
parent b1837693b1
commit b7f389aacb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 38 additions and 37 deletions

View File

@ -37,7 +37,7 @@ import java.util.regex.Pattern;
import static org.openapitools.codegen.utils.StringUtils.camelize; import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore; import static org.openapitools.codegen.utils.StringUtils.underscore;
abstract public class AbstractPythonCodegen extends DefaultCodegen implements CodegenConfig { public abstract class AbstractPythonCodegen extends DefaultCodegen implements CodegenConfig {
private final Logger LOGGER = LoggerFactory.getLogger(AbstractPythonCodegen.class); private final Logger LOGGER = LoggerFactory.getLogger(AbstractPythonCodegen.class);
protected String packageName = "openapi_client"; protected String packageName = "openapi_client";
@ -144,7 +144,7 @@ abstract public class AbstractPythonCodegen extends DefaultCodegen implements Co
public String toDefaultValue(Schema p) { public String toDefaultValue(Schema p) {
if (ModelUtils.isBooleanSchema(p)) { if (ModelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
if (Boolean.valueOf(p.getDefault().toString()) == false) if (!Boolean.valueOf(p.getDefault().toString()))
return "False"; return "False";
else else
return "True"; return "True";
@ -166,11 +166,13 @@ abstract public class AbstractPythonCodegen extends DefaultCodegen implements Co
if (Pattern.compile("\r\n|\r|\n").matcher((String) p.getDefault()).find()) if (Pattern.compile("\r\n|\r|\n").matcher((String) p.getDefault()).find())
return "'''" + p.getDefault() + "'''"; return "'''" + p.getDefault() + "'''";
else else
return "'" + ((String) p.getDefault()).replaceAll("'", "\'") + "'"; return "'" + ((String) p.getDefault()).replace("'", "\'") + "'";
} }
} else if (ModelUtils.isArraySchema(p)) { } else if (ModelUtils.isArraySchema(p)) {
if (p.getDefault() != null) { if (p.getDefault() != null) {
return p.getDefault().toString(); return p.getDefault().toString();
} else {
return null;
} }
} }
@ -231,13 +233,13 @@ abstract public class AbstractPythonCodegen extends DefaultCodegen implements Co
// method name cannot use reserved keyword, e.g. return // method name cannot use reserved keyword, e.g. return
if (isReservedWord(operationId)) { if (isReservedWord(operationId)) {
LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId))); LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, underscore(sanitizeName("call_" + operationId)));
operationId = "call_" + operationId; operationId = "call_" + operationId;
} }
// operationId starts with a number // operationId starts with a number
if (operationId.matches("^\\d.*")) { if (operationId.matches("^\\d.*")) {
LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId))); LOGGER.warn("{} (starting with a number) cannot be used as method name. Renamed to {}", operationId, underscore(sanitizeName("call_" + operationId)));
operationId = "call_" + operationId; operationId = "call_" + operationId;
} }
@ -275,7 +277,7 @@ abstract public class AbstractPythonCodegen extends DefaultCodegen implements Co
if (exitValue != 0) { if (exitValue != 0) {
LOGGER.error("Error running the command ({}). Exit value: {}", command, exitValue); LOGGER.error("Error running the command ({}). Exit value: {}", command, exitValue);
} else { } else {
LOGGER.info("Successfully executed: " + command); LOGGER.info("Successfully executed: {}", command);
} }
} catch (InterruptedException | IOException e) { } catch (InterruptedException | IOException e) {
LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage()); LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage());
@ -287,12 +289,12 @@ abstract public class AbstractPythonCodegen extends DefaultCodegen implements Co
@Override @Override
public String toExampleValue(Schema schema) { public String toExampleValue(Schema schema) {
return toExampleValueRecursive(schema, new ArrayList<String>(), 5); return toExampleValueRecursive(schema, new ArrayList<>(), 5);
} }
private String toExampleValueRecursive(Schema schema, List<String> included_schemas, int indentation) { private String toExampleValueRecursive(Schema schema, List<String> includedSchemas, int indentation) {
String indentation_string = ""; String indentationString = "";
for (int i = 0; i < indentation; i++) indentation_string += " "; for (int i = 0; i < indentation; i++) indentationString += " ";
String example = null; String example = null;
if (schema.getExample() != null) { if (schema.getExample() != null) {
example = schema.getExample().toString(); example = schema.getExample().toString();
@ -345,9 +347,9 @@ abstract public class AbstractPythonCodegen extends DefaultCodegen implements Co
refSchema.setTitle(ref); refSchema.setTitle(ref);
} }
if (StringUtils.isNotBlank(schema.getTitle()) && !"null".equals(schema.getTitle())) { if (StringUtils.isNotBlank(schema.getTitle()) && !"null".equals(schema.getTitle())) {
included_schemas.add(schema.getTitle()); includedSchemas.add(schema.getTitle());
} }
return toExampleValueRecursive(refSchema, included_schemas, indentation); return toExampleValueRecursive(refSchema, includedSchemas, indentation);
} }
} else { } else {
LOGGER.warn("allDefinitions not defined in toExampleValue!\n"); LOGGER.warn("allDefinitions not defined in toExampleValue!\n");
@ -410,25 +412,25 @@ abstract public class AbstractPythonCodegen extends DefaultCodegen implements Co
example = "True"; example = "True";
} else if (ModelUtils.isArraySchema(schema)) { } else if (ModelUtils.isArraySchema(schema)) {
if (StringUtils.isNotBlank(schema.getTitle()) && !"null".equals(schema.getTitle())) { if (StringUtils.isNotBlank(schema.getTitle()) && !"null".equals(schema.getTitle())) {
included_schemas.add(schema.getTitle()); includedSchemas.add(schema.getTitle());
} }
ArraySchema arrayschema = (ArraySchema) schema; ArraySchema arrayschema = (ArraySchema) schema;
example = "[\n" + indentation_string + toExampleValueRecursive(arrayschema.getItems(), included_schemas, indentation + 1) + "\n" + indentation_string + "]"; example = "[\n" + indentationString + toExampleValueRecursive(arrayschema.getItems(), includedSchemas, indentation + 1) + "\n" + indentationString + "]";
} else if (ModelUtils.isMapSchema(schema)) { } else if (ModelUtils.isMapSchema(schema)) {
if (StringUtils.isNotBlank(schema.getTitle()) && !"null".equals(schema.getTitle())) { if (StringUtils.isNotBlank(schema.getTitle()) && !"null".equals(schema.getTitle())) {
included_schemas.add(schema.getTitle()); includedSchemas.add(schema.getTitle());
} }
Object additionalObject = schema.getAdditionalProperties(); Object additionalObject = schema.getAdditionalProperties();
if (additionalObject instanceof Schema) { if (additionalObject instanceof Schema) {
Schema additional = (Schema) additionalObject; Schema additional = (Schema) additionalObject;
String the_key = "'key'"; String theKey = "'key'";
if (additional.getEnum() != null && !additional.getEnum().isEmpty()) { if (additional.getEnum() != null && !additional.getEnum().isEmpty()) {
the_key = additional.getEnum().get(0).toString(); theKey = additional.getEnum().get(0).toString();
if (ModelUtils.isStringSchema(additional)) { if (ModelUtils.isStringSchema(additional)) {
the_key = "'" + escapeText(the_key) + "'"; theKey = "'" + escapeText(theKey) + "'";
} }
} }
example = "{\n" + indentation_string + the_key + " : " + toExampleValueRecursive(additional, included_schemas, indentation + 1) + "\n" + indentation_string + "}"; example = "{\n" + indentationString + theKey + " : " + toExampleValueRecursive(additional, includedSchemas, indentation + 1) + "\n" + indentationString + "}";
} else { } else {
example = "{ }"; example = "{ }";
} }
@ -462,13 +464,13 @@ abstract public class AbstractPythonCodegen extends DefaultCodegen implements Co
if (toExclude != null && reqs.contains(toExclude)) { if (toExclude != null && reqs.contains(toExclude)) {
reqs.remove(toExclude); reqs.remove(toExclude);
} }
for (String toRemove : included_schemas) { for (String toRemove : includedSchemas) {
if (reqs.contains(toRemove)) { if (reqs.contains(toRemove)) {
reqs.remove(toRemove); reqs.remove(toRemove);
} }
} }
if (StringUtils.isNotBlank(schema.getTitle()) && !"null".equals(schema.getTitle())) { if (StringUtils.isNotBlank(schema.getTitle()) && !"null".equals(schema.getTitle())) {
included_schemas.add(schema.getTitle()); includedSchemas.add(schema.getTitle());
} }
if (null != schema.getRequired()) for (Object toAdd : schema.getRequired()) { if (null != schema.getRequired()) for (Object toAdd : schema.getRequired()) {
reqs.add((String) toAdd); reqs.add((String) toAdd);
@ -480,14 +482,14 @@ abstract public class AbstractPythonCodegen extends DefaultCodegen implements Co
if (StringUtils.isBlank(refTitle) || "null".equals(refTitle)) { if (StringUtils.isBlank(refTitle) || "null".equals(refTitle)) {
schema2.setTitle(propname); schema2.setTitle(propname);
} }
example += "\n" + indentation_string + underscore(propname) + " = " + example += "\n" + indentationString + underscore(propname) + " = " +
toExampleValueRecursive(schema2, included_schemas, indentation + 1) + ", "; toExampleValueRecursive(schema2, includedSchemas, indentation + 1) + ", ";
} }
} }
} }
example += ")"; example += ")";
} else { } else {
LOGGER.warn("Type " + schema.getType() + " not handled properly in toExampleValue"); LOGGER.warn("Type {} not handled properly in toExampleValue", schema.getType());
} }
if (ModelUtils.isStringSchema(schema)) { if (ModelUtils.isStringSchema(schema)) {
@ -549,7 +551,7 @@ abstract public class AbstractPythonCodegen extends DefaultCodegen implements Co
// type is a model class, e.g. User // type is a model class, e.g. User
example = this.packageName + "." + type + "()"; example = this.packageName + "." + type + "()";
} else { } else {
LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue"); LOGGER.warn("Type {} not handled properly in setParameterExampleValue", type);
} }
if (example == null) { if (example == null) {
@ -632,13 +634,13 @@ abstract public class AbstractPythonCodegen extends DefaultCodegen implements Co
// model name cannot use reserved keyword, e.g. return // model name cannot use reserved keyword, e.g. return
if (isReservedWord(name)) { if (isReservedWord(name)) {
LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name)); LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, camelize("model_" + name));
name = "model_" + name; // e.g. return => ModelReturn (after camelize) name = "model_" + name; // e.g. return => ModelReturn (after camelize)
} }
// model name starts with number // model name starts with number
if (name.matches("^\\d.*")) { if (name.matches("^\\d.*")) {
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, camelize("model_" + name));
name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) name = "model_" + name; // e.g. 200Response => Model200Response (after camelize)
} }

View File

@ -219,12 +219,13 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
// free form object (type: object) // free form object (type: object)
if (ModelUtils.hasValidation(ref)) { if (ModelUtils.hasValidation(ref)) {
return schema; return schema;
} else if (getAllOfDescendants(simpleRef, openAPI).size() > 0) { } else if (!getAllOfDescendants(simpleRef, openAPI).isEmpty()) {
return schema; return schema;
} } else {
return unaliasSchema(allSchemas.get(ModelUtils.getSimpleRef(schema.get$ref())), return unaliasSchema(allSchemas.get(ModelUtils.getSimpleRef(schema.get$ref())),
usedImportMappings); usedImportMappings);
} }
}
} else if (ModelUtils.hasValidation(ref)) { } else if (ModelUtils.hasValidation(ref)) {
// non object non array non map schemas that have validations // non object non array non map schemas that have validations
// are returned so we can generate those schemas as models // are returned so we can generate those schemas as models
@ -246,7 +247,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
try { try {
date = (OffsetDateTime) dateValue; date = (OffsetDateTime) dateValue;
} catch (ClassCastException e) { } catch (ClassCastException e) {
LOGGER.warn("Invalid `date` format for value {}", dateValue.toString()); LOGGER.warn("Invalid `date` format for value {}", dateValue);
date = ((Date) dateValue).toInstant().atOffset(ZoneOffset.UTC); date = ((Date) dateValue).toInstant().atOffset(ZoneOffset.UTC);
} }
strValue = date.format(iso8601Date); strValue = date.format(iso8601Date);
@ -263,7 +264,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
try { try {
dateTime = (OffsetDateTime) dateTimeValue; dateTime = (OffsetDateTime) dateTimeValue;
} catch (ClassCastException e) { } catch (ClassCastException e) {
LOGGER.warn("Invalid `date-time` format for value {}", dateTimeValue.toString()); LOGGER.warn("Invalid `date-time` format for value {}", dateTimeValue);
dateTime = ((Date) dateTimeValue).toInstant().atOffset(ZoneOffset.UTC); dateTime = ((Date) dateTimeValue).toInstant().atOffset(ZoneOffset.UTC);
} }
strValue = dateTime.format(iso8601DateTime); strValue = dateTime.format(iso8601DateTime);
@ -286,10 +287,9 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
// python servers: should only use default values for optional params // python servers: should only use default values for optional params
// python clients: should only use default values for required params // python clients: should only use default values for required params
Object defaultObject = null; Object defaultObject = null;
Boolean enumLengthOne = (p.getEnum() != null && p.getEnum().size() == 1);
if (p.getDefault() != null) { if (p.getDefault() != null) {
defaultObject = p.getDefault(); defaultObject = p.getDefault();
} else if (enumLengthOne) { } else if (p.getEnum() != null && p.getEnum().size() == 1) {
defaultObject = p.getEnum().get(0); defaultObject = p.getEnum().get(0);
} }
@ -305,7 +305,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
} else if (ModelUtils.isStringSchema(p) && !ModelUtils.isByteArraySchema(p) && !ModelUtils.isBinarySchema(p) && !ModelUtils.isFileSchema(p) && !ModelUtils.isUUIDSchema(p) && !ModelUtils.isEmailSchema(p)) { } else if (ModelUtils.isStringSchema(p) && !ModelUtils.isByteArraySchema(p) && !ModelUtils.isBinarySchema(p) && !ModelUtils.isFileSchema(p) && !ModelUtils.isUUIDSchema(p) && !ModelUtils.isEmailSchema(p)) {
defaultValue = ensureQuotes(defaultValue); defaultValue = ensureQuotes(defaultValue);
} else if (ModelUtils.isBooleanSchema(p)) { } else if (ModelUtils.isBooleanSchema(p)) {
if (Boolean.valueOf(defaultValue) == false) { if (!Boolean.valueOf(defaultValue)) {
defaultValue = "False"; defaultValue = "False";
} else { } else {
defaultValue = "True"; defaultValue = "True";
@ -329,9 +329,8 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen {
HashMap<String, Object> val = (HashMap<String, Object>) objs.get("operations"); HashMap<String, Object> val = (HashMap<String, Object>) objs.get("operations");
ArrayList<CodegenOperation> operations = (ArrayList<CodegenOperation>) val.get("operation"); ArrayList<CodegenOperation> operations = (ArrayList<CodegenOperation>) val.get("operation");
ArrayList<HashMap<String, String>> imports = (ArrayList<HashMap<String, String>>) objs.get("imports");
for (CodegenOperation operation : operations) { for (CodegenOperation operation : operations) {
if (operation.imports.size() == 0) { if (operation.imports.isEmpty()) {
continue; continue;
} }
String[] modelNames = operation.imports.toArray(new String[0]); String[] modelNames = operation.imports.toArray(new String[0]);