Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(rust): oneOf generation for client #17915

Merged
merged 14 commits into from
Feb 24, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 8 additions & 0 deletions bin/configs/rust-hyper-oneOf-array-map-import.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
generatorName: rust
outputDir: samples/client/others/rust/hyper/oneOf-array-map
library: hyper
inputSpec: modules/openapi-generator/src/test/resources/3_0/oneOfArrayMapImport.yaml
templateDir: modules/openapi-generator/src/main/resources/rust
additionalProperties:
supportAsync: false
packageName: oneof-array-map-hyper
8 changes: 8 additions & 0 deletions bin/configs/rust-reqwest-oneOf-array-map-import.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
generatorName: rust
outputDir: samples/client/others/rust/reqwest/oneOf-array-map
library: reqwest
inputSpec: modules/openapi-generator/src/test/resources/3_0/oneOfArrayMapImport.yaml
templateDir: modules/openapi-generator/src/main/resources/rust
additionalProperties:
supportAsync: false
packageName: oneof-array-map-reqwest
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.CodegenProperty;
import org.openapitools.codegen.DefaultCodegen;
import org.openapitools.codegen.GeneratorLanguage;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.FileSchema;
import io.swagger.v3.oas.models.media.Schema;
import org.openapitools.codegen.*;
import org.openapitools.codegen.utils.ModelUtils;
import org.openapitools.codegen.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand Down Expand Up @@ -232,6 +233,74 @@ public String sanitizeIdentifier(String name, CasingType casingType, String esca
return name;
}

@Override
public String getTypeDeclaration(Schema p) {
Comment on lines +236 to +237
Copy link
Contributor Author

@DDtKey DDtKey Feb 21, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It was error-prone because almost copy-paste between rust-generators, so only extracted to AbstractRustCodegen and unified with client .

We can see that only client samples were affected by this PR.

if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
String innerType = getTypeDeclaration(inner);
return typeMapping.get("array") + "<" + innerType + ">";
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = ModelUtils.getAdditionalProperties(p);
String innerType = getTypeDeclaration(inner);
StringBuilder typeDeclaration = new StringBuilder(typeMapping.get("map")).append("<").append(typeMapping.get("string")).append(", ");
typeDeclaration.append(innerType).append(">");
return typeDeclaration.toString();
} else if (!org.apache.commons.lang3.StringUtils.isEmpty(p.get$ref())) {
String datatype;
try {
datatype = p.get$ref();

if (datatype.indexOf("#/components/schemas/") == 0) {
datatype = toModelName(datatype.substring("#/components/schemas/".length()));
datatype = "models::" + datatype;
}
} catch (Exception e) {
LOGGER.warn("Error obtaining the datatype from schema (model):{}. Datatype default to Object", p);
datatype = "Object";
LOGGER.error(e.getMessage(), e);
}
return datatype;
} else if (p instanceof FileSchema) {
return typeMapping.get("file");
}

return super.getTypeDeclaration(p);
}

@Override
public CodegenModel fromModel(String name, Schema model) {
LOGGER.trace("Creating model from schema: {}", model);

Map<String, Schema> allDefinitions = ModelUtils.getSchemas(this.openAPI);
CodegenModel mdl = super.fromModel(name, model);

mdl.vendorExtensions.put("x-upper-case-name", name.toUpperCase(Locale.ROOT));
if (!org.apache.commons.lang3.StringUtils.isEmpty(model.get$ref())) {
Schema schema = allDefinitions.get(ModelUtils.getSimpleRef(model.get$ref()));
mdl.dataType = typeMapping.get(schema.getType());
}
if (ModelUtils.isArraySchema(model)) {
if (typeMapping.containsKey(mdl.arrayModelType)) {
mdl.arrayModelType = typeMapping.get(mdl.arrayModelType);
} else {
mdl.arrayModelType = toModelName(mdl.arrayModelType);
}
} else if ((!mdl.anyOf.isEmpty()) || (!mdl.oneOf.isEmpty())) {
mdl.dataType = getSchemaType(model);
}

Schema additionalProperties = ModelUtils.getAdditionalProperties(model);

if (additionalProperties != null) {
mdl.additionalPropertiesType = getTypeDeclaration(additionalProperties);
}

LOGGER.trace("Created model: {}", mdl);

return mdl;
}

@Override
public String toVarName(String name) {
// obtain the name from nameMapping directly if provided
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.FileSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.parameters.RequestBody;
Expand Down Expand Up @@ -703,41 +702,6 @@ public CodegenParameter fromRequestBody(RequestBody body, Set<String> imports, S
return codegenParameter;
}

@Override
public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
String innerType = getTypeDeclaration(inner);
return typeMapping.get("array") + "<" + innerType + ">";
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = ModelUtils.getAdditionalProperties(p);
String innerType = getTypeDeclaration(inner);
StringBuilder typeDeclaration = new StringBuilder(typeMapping.get("map")).append("<").append(typeMapping.get("string")).append(", ");
typeDeclaration.append(innerType).append(">");
return typeDeclaration.toString();
} else if (!StringUtils.isEmpty(p.get$ref())) {
String datatype;
try {
datatype = p.get$ref();

if (datatype.indexOf("#/components/schemas/") == 0) {
datatype = toModelName(datatype.substring("#/components/schemas/".length()));
datatype = "models::" + datatype;
}
} catch (Exception e) {
LOGGER.warn("Error obtaining the datatype from schema (model):{}. Datatype default to Object", p);
datatype = "Object";
LOGGER.error(e.getMessage(), e);
}
return datatype;
} else if (p instanceof FileSchema) {
return typeMapping.get("File");
}

return super.getTypeDeclaration(p);
}

@Override
public String toInstantiationType(Schema p) {
if (ModelUtils.isArraySchema(p)) {
Expand All @@ -752,39 +716,6 @@ public String toInstantiationType(Schema p) {
}
}

@Override
public CodegenModel fromModel(String name, Schema model) {
LOGGER.trace("Creating model from schema: {}", model);

Map<String, Schema> allDefinitions = ModelUtils.getSchemas(this.openAPI);
CodegenModel mdl = super.fromModel(name, model);

mdl.vendorExtensions.put("x-upper-case-name", name.toUpperCase(Locale.ROOT));
if (!StringUtils.isEmpty(model.get$ref())) {
Schema schema = allDefinitions.get(ModelUtils.getSimpleRef(model.get$ref()));
mdl.dataType = typeMapping.get(schema.getType());
}
if (ModelUtils.isArraySchema(model)) {
if (typeMapping.containsKey(mdl.arrayModelType)) {
mdl.arrayModelType = typeMapping.get(mdl.arrayModelType);
} else {
mdl.arrayModelType = toModelName(mdl.arrayModelType);
}
} else if ((!mdl.anyOf.isEmpty()) || (!mdl.oneOf.isEmpty())) {
mdl.dataType = getSchemaType(model);
}

Schema additionalProperties = ModelUtils.getAdditionalProperties(model);

if (additionalProperties != null) {
mdl.additionalPropertiesType = getTypeDeclaration(additionalProperties);
}

LOGGER.trace("Created model: {}", mdl);

return mdl;
}

@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> bundle) {
generateYAMLSpecFile(bundle);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.FileSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.parser.util.SchemaTypeUtil;
Expand All @@ -42,8 +43,6 @@
import java.math.BigInteger;
import java.util.*;

import static org.openapitools.codegen.utils.StringUtils.camelize;

public class RustClientCodegen extends AbstractRustCodegen implements CodegenConfig {
private final Logger LOGGER = LoggerFactory.getLogger(RustClientCodegen.class);
private boolean useSingleRequestParameter = false;
Expand Down Expand Up @@ -149,11 +148,13 @@ public RustClientCodegen() {
typeMapping.clear();
typeMapping.put("integer", "i32");
typeMapping.put("long", "i64");
typeMapping.put("number", "f32");
typeMapping.put("number", "f64");
DDtKey marked this conversation as resolved.
Show resolved Hide resolved
typeMapping.put("float", "f32");
typeMapping.put("double", "f64");
typeMapping.put("boolean", "bool");
typeMapping.put("string", "String");
typeMapping.put("array", "Vec");
typeMapping.put("map", "std::collections::HashMap");
typeMapping.put("UUID", "uuid::Uuid");
typeMapping.put("URI", "String");
typeMapping.put("date", "string");
Expand Down Expand Up @@ -205,11 +206,45 @@ public RustClientCodegen() {
setLibrary(REQWEST_LIBRARY);
}

@Override
public CodegenModel fromModel(String name, Schema model) {
CodegenModel mdl = super.fromModel(name, model);

// set alias names to oneOf in composed-schema to use as enum variant names
if (mdl.getComposedSchemas() != null && mdl.getComposedSchemas().getOneOf() != null
&& !mdl.getComposedSchemas().getOneOf().isEmpty()) {

List<Schema> schemas = ModelUtils.getInterfaces(model);
List<CodegenProperty> oneOfs = mdl.getComposedSchemas().getOneOf();
if (oneOfs.size() != schemas.size()) {
// For safety reasons, this should never happen unless there is an error in the code
throw new RuntimeException("oneOf size does not match the model");
}

for (int i = 0; i < oneOfs.size(); i++) {
CodegenProperty oneOf = oneOfs.get(i);
Schema schema = schemas.get(i);
String aliasType = getTypeDeclaration(schema);
if (aliasType.startsWith("models::")) {
aliasType = aliasType.substring("models::".length());
}
oneOf.setName(aliasType);
}
}

return mdl;
}

@Override
public ModelsMap postProcessModels(ModelsMap objs) {
// Remove the discriminator field from the model, serde will take care of this
for (ModelMap model : objs.getModels()) {
System.out.println("\nMODEL: \n\n");
System.out.println(model);
System.out.println("\n\n\n");

DDtKey marked this conversation as resolved.
Show resolved Hide resolved
CodegenModel cm = model.getModel();

if (cm.discriminator != null) {
String reserved_var_name = cm.discriminator.getPropertyBaseName();

Expand Down Expand Up @@ -397,47 +432,6 @@ public String modelDocFileFolder() {
return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar);
}

@Override
public String getTypeDeclaration(Schema p) {
Schema unaliasSchema = unaliasSchema(p);
if (ModelUtils.isArraySchema(unaliasSchema)) {
ArraySchema ap = (ArraySchema) unaliasSchema;
Schema inner = ap.getItems();
if (inner == null) {
LOGGER.warn("{}(array property) does not have a proper inner type defined.Default to string",
ap.getName());
inner = new StringSchema().description("TODO default missing array inner type to string");
}
return "Vec<" + getTypeDeclaration(inner) + ">";
} else if (ModelUtils.isMapSchema(unaliasSchema)) {
Schema inner = ModelUtils.getAdditionalProperties(unaliasSchema);
if (inner == null) {
LOGGER.warn("{}(map property) does not have a proper inner type defined. Default to string", unaliasSchema.getName());
inner = new StringSchema().description("TODO default missing map inner type to string");
}
return "::std::collections::HashMap<String, " + getTypeDeclaration(inner) + ">";
}

// Not using the supertype invocation, because we want to UpperCamelize
// the type.
String schemaType = getSchemaType(unaliasSchema);
if (typeMapping.containsKey(schemaType)) {
return typeMapping.get(schemaType);
}

if (typeMapping.containsValue(schemaType)) {
return schemaType;
}

if (languageSpecificPrimitives.contains(schemaType)) {
return schemaType;
}

// return fully-qualified model name
// crate::models::{{classnameFile}}::{{classname}}
return "crate::models::" + toModelName(schemaType);
DDtKey marked this conversation as resolved.
Show resolved Hide resolved
}

@Override
public String getSchemaType(Schema p) {
String schemaType = super.getSchemaType(p);
Expand Down