io.swagger.codegen.languages.RustServerCodegen Maven / Gradle / Ivy
package io.swagger.codegen.languages;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.swagger.codegen.*;
import io.swagger.models.*;
import io.swagger.models.parameters.BodyParameter;
import io.swagger.models.parameters.Parameter;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.RefProperty;
import io.swagger.models.properties.*;
import io.swagger.util.Yaml;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.*;
import java.util.Map.Entry;
import org.apache.commons.lang3.StringUtils;
public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(RustServerCodegen.class);
private HashMap modelXmlNames = new HashMap();
private static final String NO_FORMAT = "%%NO_FORMAT";
protected String apiVersion = "1.0.0";
protected String serverHost = "localhost";
protected int serverPort = 8080;
protected String projectName = "swagger-server";
protected String apiPath = "rust-server";
protected String packageName;
protected String packageVersion;
protected String externCrateName;
protected Map> pathSetMap = new HashMap>();
public RustServerCodegen() {
super();
// set the output folder here
outputFolder = "generated-code/rust-server";
/*
* Models. You can write model files using the modelTemplateFiles map.
* if you want to create one template for file, you can do so here.
* for multiple files for model, just put another entry in the `modelTemplateFiles` with
* a different extension
*/
modelTemplateFiles.clear();
/*
* Api classes. You can write classes for each Api file with the apiTemplateFiles map.
* as with models, add multiple entries with different extensions for multiple files per
* class
*/
apiTemplateFiles.clear();
/*
* Template Location. This is the location which templates will be read from. The generator
* will use the resource stream to attempt to read the templates.
*/
embeddedTemplateDir = templateDir = "rust-server";
/*
* Reserved words. Override this with reserved words specific to your language
*/
setReservedWordsLowerCase(
Arrays.asList(
// From https://doc.rust-lang.org/grammar.html#keywords
"abstract", "alignof", "as", "become", "box", "break", "const",
"continue", "crate", "do", "else", "enum", "extern", "false",
"final", "fn", "for", "if", "impl", "in", "let", "loop", "macro",
"match", "mod", "move", "mut", "offsetof", "override", "priv",
"proc", "pub", "pure", "ref", "return", "Self", "self", "sizeof",
"static", "struct", "super", "trait", "true", "type", "typeof",
"unsafe", "unsized", "use", "virtual", "where", "while", "yield"
)
);
defaultIncludes = new HashSet(
Arrays.asList(
"map",
"array")
);
languageSpecificPrimitives = new HashSet(
Arrays.asList(
"bool",
"char",
"i8",
"i16",
"i32",
"i64",
"u8",
"u16",
"u32",
"u64",
"isize",
"usize",
"f32",
"f64",
"str")
);
instantiationTypes.clear();
instantiationTypes.put("array", "Vec");
instantiationTypes.put("map", "Map");
typeMapping.clear();
typeMapping.put("number", "f64");
typeMapping.put("integer", "i32");
typeMapping.put("long", "i64");
typeMapping.put("float", "f32");
typeMapping.put("double", "f64");
typeMapping.put("string", "String");
typeMapping.put("UUID", "uuid::Uuid");
typeMapping.put("byte", "u8");
typeMapping.put("ByteArray", "swagger::ByteArray");
typeMapping.put("binary", "swagger::ByteArray");
typeMapping.put("boolean", "bool");
typeMapping.put("date", "chrono::DateTime");
typeMapping.put("DateTime", "chrono::DateTime");
typeMapping.put("password", "String");
typeMapping.put("File", "Box, Error=Error> + Send>");
typeMapping.put("file", "Box, Error=Error> + Send>");
typeMapping.put("array", "Vec");
typeMapping.put("map", "HashMap");
importMapping = new HashMap();
cliOptions.clear();
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME,
"Rust crate name (convention: snake_case).")
.defaultValue("swagger_client"));
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION,
"Rust crate version.")
.defaultValue("1.0.0"));
/*
* Additional Properties. These values can be passed to the templates and
* are available in models, apis, and supporting files
*/
additionalProperties.put("apiVersion", apiVersion);
additionalProperties.put("apiPath", apiPath);
/*
* Supporting Files. You can write single files for the generator with the
* entire object tree available. If the input file has a suffix of `.mustache
* it will be processed by the template engine. Otherwise, it will be copied
*/
supportingFiles.add(new SupportingFile("swagger.mustache", "api", "swagger.yaml"));
supportingFiles.add(new SupportingFile("Cargo.mustache", "", "Cargo.toml"));
supportingFiles.add(new SupportingFile("cargo-config", ".cargo", "config"));
supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore"));
supportingFiles.add(new SupportingFile("lib.mustache", "src", "lib.rs"));
supportingFiles.add(new SupportingFile("models.mustache", "src", "models.rs"));
supportingFiles.add(new SupportingFile("server-mod.mustache", "src/server", "mod.rs"));
supportingFiles.add(new SupportingFile("server-auth.mustache", "src/server", "auth.rs"));
supportingFiles.add(new SupportingFile("client-mod.mustache", "src/client", "mod.rs"));
supportingFiles.add(new SupportingFile("mimetypes.mustache", "src", "mimetypes.rs"));
supportingFiles.add(new SupportingFile("example-server.mustache", "examples", "server.rs"));
supportingFiles.add(new SupportingFile("example-client.mustache", "examples", "client.rs"));
supportingFiles.add(new SupportingFile("example-server_lib.mustache", "examples/server_lib", "mod.rs"));
supportingFiles.add(new SupportingFile("example-server_server.mustache", "examples/server_lib", "server.rs"));
supportingFiles.add(new SupportingFile("example-ca.pem", "examples", "ca.pem"));
supportingFiles.add(new SupportingFile("example-server-chain.pem", "examples", "server-chain.pem"));
supportingFiles.add(new SupportingFile("example-server-key.pem", "examples", "server-key.pem"));
writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md"));
}
@Override
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) {
setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME));
}
else {
setPackageName("swagger_client");
}
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) {
setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION));
}
else {
setPackageVersion("1.0.0");
}
additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName);
additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion);
additionalProperties.put("externCrateName", externCrateName);
}
public void setPackageName(String packageName) {
this.packageName = packageName;
// Also set the extern crate name, which has any '-' replace with a '_'.
this.externCrateName = packageName.replace('-', '_');
}
public void setPackageVersion(String packageVersion) {
this.packageVersion = packageVersion;
}
@Override
public String apiPackage() {
return apiPath;
}
/**
* Configures the type of generator.
*
* @return the CodegenType for this generator
* @see io.swagger.codegen.CodegenType
*/
@Override
public CodegenType getTag() {
return CodegenType.SERVER;
}
/**
* Configures a friendly name for the generator. This will be used by the generator
* to select the library with the -l flag.
*
* @return the friendly name for the generator
*/
@Override
public String getName() {
return "rust-server";
}
/**
* Returns human-friendly help for the generator. Provide the consumer with help
* tips, parameters here
*
* @return A string value for the help message
*/
@Override
public String getHelp() {
return "Generates a Rust client/server library (beta) using the swagger-codegen project.";
}
@Override
public void preprocessSwagger(Swagger swagger) {
Info info = swagger.getInfo();
List versionComponents = new ArrayList(Arrays.asList(info.getVersion().split("[.]")));
if (versionComponents.size() < 1) {
versionComponents.add("1");
}
while (versionComponents.size() < 3) {
versionComponents.add("0");
}
info.setVersion(StringUtils.join(versionComponents, "."));
String host = swagger.getHost();
if (host != null) {
String[] parts = host.split(":");
if (parts.length > 1) {
serverHost = parts[0];
try {
serverPort = Integer.valueOf(parts[1]);
} catch (NumberFormatException e) {
LOGGER.warn("Port of Swagger host is not an integer : " + host, e);
}
} else {
serverHost = host;
}
}
additionalProperties.put("serverHost", serverHost);
additionalProperties.put("serverPort", serverPort);
}
@Override
public String toApiName(String name) {
if (name.length() == 0) {
return "default";
}
return underscore(name);
}
/**
* Escapes a reserved word as defined in the `reservedWords` array. Handle escaping
* those terms here. This logic is only called if a variable matches the reserved words
*
* @return the escaped term
*/
@Override
public String escapeReservedWord(String name) {
if (this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name; // add an underscore to the name
}
/**
* Location to write api files. You can use the apiPackage() as defined when the class is
* instantiated
*/
@Override
public String apiFileFolder() {
return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar);
}
@Override
public String toModelName(String name) {
// camelize the model name
// phone_number => PhoneNumber
String camelizedName = camelize(toModelFilename(name));
// model name cannot use reserved keyword, e.g. return
if (isReservedWord(camelizedName)) {
camelizedName = "Model" + camelizedName;
LOGGER.warn(camelizedName + " (reserved word) cannot be used as model name. Renamed to " + camelizedName);
}
// model name starts with number
else if (name.matches("^\\d.*")) {
// e.g. 200Response => Model200Response (after camelize)
camelizedName = "Model" + camelizedName;
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelizedName);
}
return camelizedName;
}
@Override
public String toParamName(String name) {
// should be the same as variable name (stolen from RubyClientCodegen)
return toVarName(name);
}
@Override
public String toVarName(String name) {
String sanitizedName = super.sanitizeName(name);
// for reserved word or word starting with number, append _
if (isReservedWord(sanitizedName) || sanitizedName.matches("^\\d.*")) {
sanitizedName = escapeReservedWord(sanitizedName);
}
return underscore(sanitizedName);
}
@Override
public String toOperationId(String operationId) {
// method name cannot use reserved keyword, e.g. return
if (isReservedWord(operationId)) {
LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId)));
operationId = "call_" + operationId;
}
return camelize(operationId);
}
@Override
public String toModelFilename(String name) {
if (!StringUtils.isEmpty(modelNamePrefix)) {
name = modelNamePrefix + "_" + name;
}
if (!StringUtils.isEmpty(modelNameSuffix)) {
name = name + "_" + modelNameSuffix;
}
name = sanitizeName(name);
// model name cannot use reserved keyword, e.g. return
if (isReservedWord(name)) {
LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name));
name = "model_" + name; // e.g. return => ModelReturn (after camelize)
}
return underscore(name);
}
@Override
public String toEnumName(CodegenProperty property) {
return sanitizeName(camelize(property.name)) + "Enum";
}
@Override
public String toEnumVarName(String value, String datatype) {
String var = null;
if (value.length() == 0) {
var = "EMPTY";
}
// for symbol, e.g. $, #
else if (getSymbolName(value) != null) {
var = getSymbolName(value).toUpperCase();
}
// number
else if ("Integer".equals(datatype) || "Long".equals(datatype) ||
"Float".equals(datatype) || "Double".equals(datatype)) {
String varName = "NUMBER_" + value;
varName = varName.replaceAll("-", "MINUS_");
varName = varName.replaceAll("\\+", "PLUS_");
varName = varName.replaceAll("\\.", "_DOT_");
var = varName;
}
// string
var = value.replaceAll("\\W+", "_").toUpperCase();
if (var.matches("\\d.*")) {
var = "_" + var;
} else {
var = sanitizeName(var);
}
return var;
}
@Override
public String toEnumValue(String value, String datatype) {
if ("Integer".equals(datatype) || "Long".equals(datatype) ||
"Float".equals(datatype) || "Double".equals(datatype)) {
return value;
} else {
return "\"" + escapeText(value) + "\"";
}
}
@Override
public String toApiFilename(String name) {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// e.g. PetApi.go => pet_api.go
return underscore(name);
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
boolean isMimetypeXml(String mimetype) {
return mimetype.toLowerCase().startsWith("application/xml");
}
boolean isMimetypePlainText(String mimetype) {
return mimetype.toLowerCase().startsWith("text/plain");
}
boolean isMimetypeWwwFormUrlEncoded(String mimetype) {
return mimetype.toLowerCase().startsWith("application/x-www-form-urlencoded");
}
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) {
CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger);
// The Rust code will need to contain a series of regular expressions.
// For performance, we'll construct these at start-of-day and re-use
// them. That means we need labels for them.
//
// Construct a Rust constant (uppercase) token name, and ensure it's
// unique using a numeric tie-breaker if required.
String basePathId = sanitizeName(op.path.replace("/", "_").replace("{", "").replace("}", "").replaceAll("^_", "")).toUpperCase();
String pathId = basePathId;
int pathIdTiebreaker = 2;
boolean found = false;
while (pathSetMap.containsKey(pathId)) {
Map pathSetEntry = pathSetMap.get(pathId);
if (pathSetEntry.get("path").equals(op.path)) {
found = true;
break;
}
pathId = basePathId + pathIdTiebreaker;
pathIdTiebreaker++;
}
// Save off the regular expression and path details in the
// "pathSetMap", which we'll add to the source document that will be
// processed by the templates.
if (!found) {
Map pathSetEntry = new HashMap();
pathSetEntry.put("path", op.path);
pathSetEntry.put("PATH_ID", pathId);
if (!op.pathParams.isEmpty()) {
pathSetEntry.put("hasPathParams", "true");
}
// Don't prefix with '^' so that the templates can put the
// basePath on the front.
pathSetEntry.put("pathRegEx", op.path.replace("{", "(?P<").replace("}", ">[^/?#]*)") + "$");
pathSetMap.put(pathId, pathSetEntry);
}
op.vendorExtensions.put("operation_id", underscore(op.operationId));
op.vendorExtensions.put("uppercase_operation_id", underscore(op.operationId).toUpperCase());
op.vendorExtensions.put("path", op.path.replace("{", ":").replace("}", ""));
op.vendorExtensions.put("PATH_ID", pathId);
op.vendorExtensions.put("hasPathParams", !op.pathParams.isEmpty());
op.vendorExtensions.put("HttpMethod", Character.toUpperCase(op.httpMethod.charAt(0)) + op.httpMethod.substring(1).toLowerCase());
for (CodegenParameter param : op.allParams) {
processParam(param, op);
}
List consumes = new ArrayList();
if (operation.getConsumes() != null) {
if (operation.getConsumes().size() > 0) {
// use consumes defined in the operation
consumes = operation.getConsumes();
}
} else if (swagger != null && swagger.getConsumes() != null && swagger.getConsumes().size() > 0) {
// use consumes defined globally
consumes = swagger.getConsumes();
LOGGER.debug("No consumes defined in operation. Using global consumes (" + swagger.getConsumes() + ") for " + op.operationId);
}
boolean consumesPlainText = false;
boolean consumesXml = false;
// if "consumes" is defined (per operation or using global definition)
if (consumes != null && !consumes.isEmpty()) {
List
© 2015 - 2025 Weber Informatics LLC | Privacy Policy