Skip to content

Commit

Permalink
Still bad. Escape string uri params
Browse files Browse the repository at this point in the history
  • Loading branch information
inferrna committed Aug 28, 2023
1 parent c62fd87 commit 1cb2950
Show file tree
Hide file tree
Showing 5 changed files with 68 additions and 47 deletions.
8 changes: 4 additions & 4 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@
<dependency>
<groupId>io.swagger.core.v3</groupId>
<artifactId>swagger-models</artifactId>
<version>2.2.8</version>
<version>2.2.12</version>
</dependency>
<dependency>
<groupId>com.ibm.icu</groupId>
Expand All @@ -156,7 +156,7 @@
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
<version>2.10.1</version>
<scope>provided</scope>
</dependency>
<dependency>
Expand All @@ -168,8 +168,8 @@
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<swagger-codegen-version>3.0.41</swagger-codegen-version>
<swagger-codegen-generators-version>1.0.40</swagger-codegen-generators-version>
<swagger-codegen-version>3.0.46</swagger-codegen-version>
<swagger-codegen-generators-version>1.0.42</swagger-codegen-generators-version>
<maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.8.1</junit-version>
<icu4j-version>73.1</icu4j-version>
Expand Down
74 changes: 32 additions & 42 deletions src/main/java/com/rust/codegen/RustGenerator.java
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
package com.rust.codegen;

import com.google.gson.Gson;
import com.ibm.icu.text.Transliterator;
import io.swagger.codegen.v3.*;
import io.swagger.codegen.v3.generators.DefaultCodegenConfig;
import io.swagger.codegen.v3.generators.util.OpenAPIUtil;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.media.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.util.*;
import java.io.File;
Expand All @@ -19,7 +16,6 @@

public class RustGenerator extends DefaultCodegenConfig {

static Logger LOGGER = LoggerFactory.getLogger(RustGenerator.class);
private final boolean useDecimal;
private final boolean allFieldsIsRequired;
private final boolean allParamsIsRequired;
Expand All @@ -34,7 +30,6 @@ public class RustGenerator extends DefaultCodegenConfig {
protected String testsFolder = "src/tests";
protected String modelFolder= "src/models";
protected HashMap<String, String> arrayModels;
protected Transliterator transliterator;

/**
* Configures the type of generator.
Expand Down Expand Up @@ -68,9 +63,6 @@ public String getHelp() {

public RustGenerator() {
super();
//String rules = "Any-Latin; Latin-ASCII";
//transliterator = Transliterator.createFromRules("transliterator", rules, Transliterator.FORWARD);
transliterator = Transliterator.getInstance("Any-Latin");

allFieldsIsRequired = Optional.ofNullable(System.getProperty("allFieldsIsRequired"))
.map(v -> v.equals("true"))
Expand Down Expand Up @@ -106,11 +98,11 @@ public RustGenerator() {
apiTemplateFiles.put(
"api.mustache", // the template to use
".rs"); // the extension for each file to write
/*

apiTemplateFiles.put(
"api2nd.mustache", // the template to use
"2nd.rs"); // the extension for each file to write
*/

modelDocTemplateFiles.put("model_doc.mustache", ".md");
apiDocTemplateFiles.put("api_doc.mustache", ".md");

Expand Down Expand Up @@ -206,6 +198,7 @@ public RustGenerator() {
typeMapping.put("int32", "i32");
typeMapping.put("long", "i64");
typeMapping.put("int64", "i64");
typeMapping.put("BigDecimal", "i128");
if(useDecimal) {
typeMapping.put("number", "Decimal");
typeMapping.put("float", "Decimal");
Expand All @@ -217,6 +210,7 @@ public RustGenerator() {
}
typeMapping.put("boolean", "bool");
typeMapping.put("string", "String");
typeMapping.put("String", "String");
typeMapping.put("UUID", "String");
typeMapping.put("date", "String");
typeMapping.put("DateTime", "String");
Expand Down Expand Up @@ -317,7 +311,7 @@ public Map<String, Object> postProcessModels(Map<String, Object> objs) {
model.setName(toModelName(model.getName()));

boolean isArray = getBooleanValue(model, IS_ARRAY_MODEL_EXT_NAME);

//TODO: fix openfigi generation
if (isArray) {
//System.out.printf("Model %s is an array!! Model: %s\n", model.getName(), new Gson().toJson(model));
arrayModels.put(model.getClassname(), model.getArrayModelType());
Expand Down Expand Up @@ -399,18 +393,9 @@ public String modelFileFolder() {
return (outputFolder + File.separator + modelFolder).replace("/", File.separator);
}

String transliterate(String inputText) {
if (inputText != null) {
return transliterator.transliterate(inputText);
} else {
return inputText;
}
}

@Override
public String toVarName(String name) {
// replace - with _ e.g. created-at => created_at
name = transliterate(name);
name = sanitizeName(name.replaceAll("-", "_"));


Expand Down Expand Up @@ -448,12 +433,11 @@ public String toModelName(String name) {

@Override
public String toModelFilename(String name) {
name = transliterate(name);
if (!StringUtils.isEmpty(modelNamePrefix)) {
if (!modelNamePrefix.isEmpty()) {
name = modelNamePrefix + "_" + name;
}

if (!StringUtils.isEmpty(modelNameSuffix)) {
if (!modelNameSuffix.isEmpty()) {
name = name + "_" + modelNameSuffix;
}

Expand All @@ -477,7 +461,6 @@ public String toModelFilename(String name) {
@Override
public String toApiTestFilename(String name) {
// replace - with _ e.g. created-at => created_at
name = transliterate(name);
name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.

// e.g. PetApi.rs => pet_api.rs
Expand All @@ -486,7 +469,6 @@ public String toApiTestFilename(String name) {

@Override
public String toApiFilename(String name) {
name = transliterate(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'.

Expand All @@ -500,7 +482,6 @@ public String toApiFilename(String name) {
}
@Override
public String toApiName(String name) {
name = transliterate(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'.

Expand Down Expand Up @@ -564,13 +545,33 @@ public String getTypeDeclaration(Schema schema) {
ArraySchema arraySchema = (ArraySchema)schema;
inner = arraySchema.getItems();
return "Vec<" + this.getTypeDeclaration(inner) + ">";
} else if (schema.get$ref() != null) {
String[] refh = schema.get$ref().split("/");
String modelName = this.toModelName(refh[refh.length-1]);

if (schemaType.equals("array") && arrayModels.containsKey(modelName)) {
String innerType = arrayModels.get(modelName);
if (!this.typeMapping.containsKey(innerType)) {
innerType = toModelName(innerType);
} else {
innerType = this.typeMapping.get(innerType);
}
System.out.printf("!!! Got array schema %s with inner type %s\n", modelName, innerType);
return "Vec<" + innerType + ">";
} else {
return String.format("%s", modelName);
}
} else if (schema instanceof MapSchema) {
MapSchema mapSchema = (MapSchema)schema;
inner = (Schema)mapSchema.getAdditionalProperties();
return "::std::collections::HashMap<String, " + this.getTypeDeclaration(inner) + ">";
} else if (schema instanceof StringSchema) {
String format = schema.getFormat();
if(format != null && typeMapping.containsKey(format)) {
List<String> enum_vals = schema.getEnum();
if(enum_vals != null && enum_vals.size()>0) {
System.out.printf("WARNING: enum schema %s -> %s %n", schema.getType(), enum_vals.get(0));
return schemaType;
} else if(format != null && typeMapping.containsKey(format)) {
return typeMapping.get(format);
} else {
return "String";
Expand Down Expand Up @@ -603,20 +604,6 @@ public String getTypeDeclaration(Schema schema) {
} else {
if (this.typeMapping.containsKey(schemaType)) {
return (String)this.typeMapping.get(schemaType);
} else if (schema.get$ref() != null) {
String[] refh = schema.get$ref().split("/");
String modelName = this.toModelName(refh[refh.length-1]);

if (schemaType.equals("array") && arrayModels.containsKey(modelName)) {
String innerType = arrayModels.get(modelName);
if (!this.typeMapping.containsKey(innerType)) {
innerType = toModelName(innerType);
}
System.out.printf("!!! Got array schema %s with inner type %s\n", modelName, innerType);
return "Vec<" + innerType + ">";
} else {
return String.format("%s", modelName);
}
} else if (this.typeMapping.containsValue(schemaType)) {
return schemaType;
} else {
Expand Down Expand Up @@ -681,6 +668,9 @@ public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
public void postProcessParameter(CodegenParameter parameter) {
super.postProcessParameter(parameter);
String dataType = parameter.getDataType();
/*if (parameter.paramName.toLowerCase().equals("format")) {
System.out.printf("Format schema: %s\n", new Gson().toJson(parameter));
}*/
if(dataType != null && dataType.equals("DateTime")) {
parameter.dataFormat = "datetime";
if(parameter.example == null) parameter.example = "2019-03-19T18:38:33.131642+03:00";
Expand Down
3 changes: 2 additions & 1 deletion src/main/resources/rust/api.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use crate::models::*;
use super::{Error, configuration};
use headers::{Authorization, Header};
use headers::authorization::Credentials;
use crate::ToUriParam;
{{! #isUseDecimal}}
use rust_decimal::Decimal;
{{! /isUseDecimal}}
Expand Down Expand Up @@ -143,7 +144,7 @@ impl<C: hyper::client::connect::Connect + Clone + Send + Sync + 'static>{{classn
"".to_string()
}
};
let uri_str = format!("{}/{{{path}}}{}", configuration.base_path, query_string{{#pathParams}}, {{baseName}}={{paramName}}.outline_print(){{#isListContainer}}.join(",").as_ref(){{/isListContainer}}{{/pathParams}});
let uri_str = format!("{}/{{{path}}}{}", configuration.base_path, query_string{{#pathParams}}, {{baseName}}={{paramName}}{{#isString}}.to_uri_param(){{/isString}}{{^isString}}.outline_print(){{/isString}}{{#isListContainer}}.join(",").as_ref().to_uri_param(){{/isListContainer}}{{/pathParams}});

// TODO(farcaller): handle error
// if let Err(e) = uri {
Expand Down
29 changes: 29 additions & 0 deletions src/main/resources/rust/lib.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,35 @@ pub mod serialize_quoted_numbers_opt;

//mod tests; //Put testing data and token to tests before uncomment

pub fn escape_uri_param(param: &str) -> String {
let mut escaped = String::new();
for c in param.chars() {
match c {
'A'..='Z' | 'a'..='z' | '0'..='9' | '-' | '_' | '.' | '~' => escaped.push(c),
_ => {
escaped.push('%');
escaped.push_str(&format!("{:02X}", c as u8));
}
}
}

escaped
}


pub trait ToUriParam<'a>: OutlinePrint<'a> {
fn to_uri_param(&'a self) -> String {
self.outline_print()
}
}
impl<'a> ToUriParam<'a> for &'a str {
fn to_uri_param(&'a self) -> String {
escape_uri_param(&self)
}
}
pub trait OutlinePrint<'a>: fmt::Display {
fn outline_print(&'a self) -> String {
format!("{}", self)
Expand Down
1 change: 1 addition & 0 deletions src/main/resources/rust/model.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ pub struct {{classname}} {
{{/dataFormat}}
#[serde(rename = "{{{baseName}}}")]
{{^required}}
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(default)]
{{/required}}
{{#isString}}
Expand Down

0 comments on commit 1cb2950

Please sign in to comment.