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

[Dart] Fix enum generation #6729

Merged
merged 26 commits into from
Jul 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
16e991c
[Dart] Fix enum generation
agilob Jun 20, 2020
9689bdf
Update generated Order file
agilob Jun 20, 2020
7ca7b3d
Re-add constructor
agilob Jun 20, 2020
6b9c5b0
Generate dart2 files
agilob Jun 20, 2020
c2751a3
Dart - nicer enum formatting
agilob Jun 20, 2020
b55e1a3
Dart - generate enum name as className+enumName
agilob Jun 21, 2020
5f7082e
Dart - dont initialize vars to null by default
agilob Jun 21, 2020
5030a99
Dart - Generate inlined enums and deserialize them
agilob Jun 21, 2020
9e6a682
Merge branch 'master' of github.com:agilob/openapi-generator into 6727
agilob Jun 28, 2020
4c2b320
Merge branch 'master' into 6727
agilob Jun 28, 2020
3ae0100
Dart - Fix using default value
agilob Jun 28, 2020
3bf4c15
Fix typo
agilob Jun 28, 2020
3f8cc2a
Regenerate add dart files
agilob Jun 28, 2020
26ee46c
Merge branch 'master' of github.com:agilob/openapi-generator into 6727
agilob Jun 28, 2020
fb09346
dart Revert override for dart dio and jaguar
agilob Jun 28, 2020
d38383f
Fix dart model tests
agilob Jun 28, 2020
6b352d8
Merge branch 'master' of github.com:OpenAPITools/openapi-generator in…
agilob Jun 29, 2020
73d45fa
Merge branch 'master' of github.com:OpenAPITools/openapi-generator in…
agilob Jun 29, 2020
3325489
Merge branch 'master' of github.com:OpenAPITools/openapi-generator in…
agilob Jun 30, 2020
7c215c6
Merge branch 'master' of github.com:OpenAPITools/openapi-generator in…
agilob Jul 2, 2020
b8e8403
Fix dart1 generated template
agilob Jul 2, 2020
c90511c
Merge branch 'master' of github.com:agilob/openapi-generator into 6727
agilob Jul 21, 2020
eec86f3
Use {{{datatypeWithEnum}}}
agilob Jul 21, 2020
75c4b8c
Dart - throw when enum not known
agilob Jul 21, 2020
b4a3c92
Merge branch 'master' of github.com:OpenAPITools/openapi-generator in…
agilob Jul 22, 2020
e7f3e8e
Fix generating enum with datatype from list
agilob Jul 22, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1768,7 +1768,7 @@ public void setParameterContentType(CodegenParameter codegenParameter, MediaType
if (encoding != null) {
codegenParameter.contentType = encoding.getContentType();
} else {
LOGGER.debug("encoding not specified for " + codegenParameter.baseName);
LOGGER.debug("encoding not specified for {}", codegenParameter.baseName);
}
}
}
Expand All @@ -1790,6 +1790,9 @@ public String toExampleValue(Schema schema) {
/**
* Return the default value of the property
*
* Return null if you do NOT want a default value.
* Any non-null value will cause {{#defaultValue} check to pass.
*
* @param schema Property schema
* @return string presentation of the default value of the property
*/
Expand All @@ -1810,7 +1813,7 @@ public String toDefaultValue(Schema schema) {
*/
@SuppressWarnings("squid:S3923")
private String getPropertyDefaultValue(Schema schema) {
/**
/*
* Although all branches return null, this is left intentionally as examples for new contributors
*/
if (ModelUtils.isBooleanSchema(schema)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

package org.openapitools.codegen.languages;

import com.google.common.collect.Sets;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Schema;

Expand All @@ -30,9 +31,8 @@

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.*;

import static org.openapitools.codegen.utils.StringUtils.camelize;
Expand All @@ -50,6 +50,7 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
public static final String PUB_HOMEPAGE = "pubHomepage";
public static final String USE_ENUM_EXTENSION = "useEnumExtension";
public static final String SUPPORT_DART2 = "supportDart2";

protected boolean browserClient = true;
protected String pubName = "openapi";
protected String pubVersion = "1.0.0";
Expand Down Expand Up @@ -106,9 +107,11 @@ public DartClientCodegen() {
modelTestTemplateFiles.put("model_test.mustache", ".dart");
apiTestTemplateFiles.put("api_test.mustache", ".dart");

List<String> reservedWordsList = new ArrayList<String>();
List<String> reservedWordsList = new ArrayList<>();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(DartClientCodegen.class.getResourceAsStream("/dart/dart-keywords.txt"), Charset.forName("UTF-8")));
BufferedReader reader = new BufferedReader(
new InputStreamReader(DartClientCodegen.class.getResourceAsStream("/dart/dart-keywords.txt"),
StandardCharsets.UTF_8));
while (reader.ready()) {
reservedWordsList.add(reader.readLine());
}
Expand All @@ -118,18 +121,17 @@ public DartClientCodegen() {
}
setReservedWordsLowerCase(reservedWordsList);

languageSpecificPrimitives = new HashSet<String>(
Arrays.asList(
"String",
"bool",
"int",
"num",
"double")
languageSpecificPrimitives = Sets.newHashSet(
"String",
"bool",
"int",
"num",
"double"
);
instantiationTypes.put("array", "List");
instantiationTypes.put("map", "Map");

typeMapping = new HashMap<String, String>();
typeMapping = new HashMap<>();
typeMapping.put("Array", "List");
typeMapping.put("array", "List");
typeMapping.put("List", "List");
Expand Down Expand Up @@ -329,7 +331,7 @@ public String toVarName(String name) {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_");

// if it's all uppper case, do nothing
// if it's all upper case, do nothing
if (name.matches("^[A-Z_]*$")) {
return name;
}
Expand Down Expand Up @@ -403,9 +405,9 @@ public String toModelTestFilename(String name) {
@Override
public String toDefaultValue(Schema schema) {
if (ModelUtils.isMapSchema(schema)) {
return "{}";
return "const {}";
} else if (ModelUtils.isArraySchema(schema)) {
return "[]";
return "const []";
}

if (schema.getDefault() != null) {
Expand All @@ -414,7 +416,7 @@ public String toDefaultValue(Schema schema) {
}
return schema.getDefault().toString();
} else {
return "null";
return null;
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This fixes not setting null value on properties that don't have default value. Dart is evolving to non-null by default language, so this will be important in the next releases of the language.

}
}

Expand All @@ -435,7 +437,7 @@ public String getTypeDeclaration(Schema p) {
@Override
public String getSchemaType(Schema p) {
String openAPIType = super.getSchemaType(p);
String type = null;
String type;
if (typeMapping.containsKey(openAPIType)) {
type = typeMapping.get(openAPIType);
if (languageSpecificPrimitives.contains(type)) {
Expand Down Expand Up @@ -495,19 +497,16 @@ private boolean buildEnumFromVendorExtension(CodegenModel cm) {
return false;
}
Object extension = cm.vendorExtensions.get("x-enum-values");
List<Map<String, Object>> values =
(List<Map<String, Object>>) extension;
List<Map<String, String>> enumVars =
new ArrayList<Map<String, String>>();
List<Map<String, Object>> values = (List<Map<String, Object>>) extension;
List<Map<String, String>> enumVars = new ArrayList<>();
for (Map<String, Object> value : values) {
Map<String, String> enumVar = new HashMap<String, String>();
Map<String, String> enumVar = new HashMap<>();
String name = camelize((String) value.get("identifier"), true);
if (isReservedWord(name)) {
name = escapeReservedWord(name);
}
enumVar.put("name", name);
enumVar.put("value", toEnumValue(
value.get("numericValue").toString(), cm.dataType));
enumVar.put("value", toEnumValue(value.get("numericValue").toString(), cm.dataType));
if (value.containsKey("description")) {
enumVar.put("description", value.get("description").toString());
}
Expand Down Expand Up @@ -611,13 +610,12 @@ public void postProcessFile(File file, String fileType) {
}

// only procees the following type (or we can simply rely on the file extension to check if it's a Dart file)
Set<String> supportedFileType = new HashSet<String>(
Arrays.asList(
"supporting-mustache",
"model-test",
"model",
"api-test",
"api"));
Set<String> supportedFileType = Sets.newHashSet(
"supporting-mustache",
"model-test",
"model",
"api-test",
"api");
if (!supportedFileType.contains(fileType)) {
return;
}
Expand All @@ -632,7 +630,7 @@ public void postProcessFile(File file, String fileType) {
if (exitValue != 0) {
LOGGER.error("Error running the command ({}). Exit code: {}", command, exitValue);
} else {
LOGGER.info("Successfully executed: " + command);
LOGGER.info("Successfully executed: {}", command);
}
} catch (Exception e) {
LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,13 +130,21 @@ public void setBrowserClient(boolean browserClient) {
}

@Override
public String toDefaultValue(Schema p) {
if (ModelUtils.isMapSchema(p)) {
public String toDefaultValue(Schema schema) {
if (ModelUtils.isMapSchema(schema)) {
return "const {}";
} else if (ModelUtils.isArraySchema(p)) {
} else if (ModelUtils.isArraySchema(schema)) {
return "const []";
}
return super.toDefaultValue(p);

if (schema.getDefault() != null) {
if (ModelUtils.isStringSchema(schema)) {
return "\"" + schema.getDefault().toString().replaceAll("\"", "\\\"") + "\"";
}
return schema.getDefault().toString();
} else {
return "null";
agilob marked this conversation as resolved.
Show resolved Hide resolved
}
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,13 +132,21 @@ public String getHelp() {
}

@Override
public String toDefaultValue(Schema p) {
if (ModelUtils.isMapSchema(p)) {
public String toDefaultValue(Schema schema) {
if (ModelUtils.isMapSchema(schema)) {
return "const {}";
} else if (ModelUtils.isArraySchema(p)) {
} else if (ModelUtils.isArraySchema(schema)) {
return "const []";
}
return super.toDefaultValue(p);

if (schema.getDefault() != null) {
if (ModelUtils.isStringSchema(schema)) {
return "\"" + schema.getDefault().toString().replaceAll("\"", "\\\"") + "\"";
}
return schema.getDefault().toString();
} else {
return "null";
}
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
class {{classname}} {
{{#vars}}
{{#description}}/* {{{description}}} */{{/description}}
{{{dataType}}} {{name}} = {{{defaultValue}}};
{{^defaultValue}}{{{dataType}}} {{name}} = null;{{/defaultValue}}{{#defaultValue}}{{{dataType}}} {{name}} = {{defaultValue}};{{/defaultValue}}
{{#allowableValues}}
{{#min}} // range from {{min}} to {{max}}{{/min}}//{{^min}}enum {{name}}Enum { {{#values}} {{.}}, {{/values}} };{{/min}}{
{{/allowableValues}}
Expand Down
45 changes: 32 additions & 13 deletions modules/openapi-generator/src/main/resources/dart2/class.mustache
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
class {{classname}} {
{{#vars}}
{{#description}}/* {{{description}}} */{{/description}}
{{{dataType}}} {{name}} = {{{defaultValue}}};
{{#description}}/// {{{description}}}{{/description}}
agilob marked this conversation as resolved.
Show resolved Hide resolved
{{^isEnum}}
{{^defaultValue}}{{{dataType}}} {{name}};{{/defaultValue}}{{#defaultValue}}{{{dataType}}} {{name}} = {{defaultValue}};{{/defaultValue}}
{{/isEnum}}
{{#isEnum}}
{{#allowableValues}}
{{#min}} // range from {{min}} to {{max}}{{/min}}//{{^min}}enum {{name}}Enum { {{#values}} {{.}}, {{/values}} };{{/min}}{
{{#min}} // range from {{min}} to {{max}}{{/min}}{{classname}}{{{enumName}}} {{name}}{{#required}} = {{{defaultValue}}}{{/required}}{{^required}}{{/required}};
{{/allowableValues}}
{{/isEnum}}
{{/vars}}

{{classname}}({
{{#vars}}
{{#required}}@required this.{{name}},{{/required}}{{^required}}this.{{name}},{{/required}}
{{#required}}@required this.{{name}}{{/required}}{{^required}}this.{{name}}{{#defaultValue}} = {{defaultValue}}{{/defaultValue}}{{/required}},
{{/vars}}
});

Expand Down Expand Up @@ -78,7 +82,12 @@ class {{classname}} {
json['{{baseName}}'].toDouble();
{{/isDouble}}
{{^isDouble}}
{{^isEnum}}
{{name}} = json['{{baseName}}'];
{{/isEnum}}
{{#isEnum}}
{{name}} = {{classname}}{{{enumName}}}.fromJson(json['{{baseName}}']);
{{/isEnum}}
{{/isDouble}}
{{/isMapContainer}}
{{/isListContainer}}
Expand All @@ -89,7 +98,7 @@ class {{classname}} {
}

Map<String, dynamic> toJson() {
Map <String, dynamic> json = {};
Map<String, dynamic> json = {};
{{#vars}}
{{^isNullable}}
if ({{name}} != null)
Expand All @@ -102,7 +111,12 @@ class {{classname}} {
{{/isDate}}
{{^isDateTime}}
{{^isDate}}
{{^isEnum}}
json['{{baseName}}'] = {{name}};
{{/isEnum}}
{{#isEnum}}
json['{{baseName}}'] = {{name}}.value;
{{/isEnum}}
{{/isDate}}
{{/isDateTime}}
{{/vars}}
Expand All @@ -114,7 +128,7 @@ class {{classname}} {
}

static Map<String, {{classname}}> mapFromJson(Map<String, dynamic> json) {
var map = Map<String, {{classname}}>();
final map = Map<String, {{classname}}>();
if (json != null && json.isNotEmpty) {
json.forEach((String key, dynamic value) => map[key] = {{classname}}.fromJson(value));
}
Expand All @@ -123,12 +137,17 @@ class {{classname}} {

// maps a json object with a list of {{classname}}-objects as value to a dart map
static Map<String, List<{{classname}}>> mapListFromJson(Map<String, dynamic> json) {
var map = Map<String, List<{{classname}}>>();
if (json != null && json.isNotEmpty) {
json.forEach((String key, dynamic value) {
map[key] = {{classname}}.listFromJson(value);
});
}
return map;
final map = Map<String, List<{{classname}}>>();
if (json != null && json.isNotEmpty) {
json.forEach((String key, dynamic value) {
map[key] = {{classname}}.listFromJson(value);
});
}
return map;
}
}
{{#vars}}
{{#isEnum}}
{{>enum_inline}}
{{/isEnum}}
{{/vars}}
17 changes: 12 additions & 5 deletions modules/openapi-generator/src/main/resources/dart2/enum.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,27 @@ class {{classname}} {
{{#description}}
/// {{description}}
{{/description}}
static const {{classname}} {{{name}}} = const {{classname}}._internal({{{value}}});
static const {{classname}} {{{name}}} = {{classname}}._internal({{value}});
{{/enumVars}}
{{/allowableValues}}

{{dataType}} toJson (){
return this.value;
{{dataType}} toJson () {
return value;
}

@override
String toString () {
return value;
}

static {{classname}} fromJson({{dataType}} value) {
return new {{classname}}TypeTransformer().decode(value);
return {{classname}}TypeTransformer().decode(value);
}

static List<{{classname}}> listFromJson(List<dynamic> json) {
return json == null ? new List<{{classname}}>() : json.map((value) => {{classname}}.fromJson(value)).toList();
return json == null
? List<{{classname}}>()
: json.map((value) => {{classname}}.fromJson(value)).toList();
}
}

Expand Down
Loading