Skip to content

Commit

Permalink
[Dart] Fix enum generation (#6729)
Browse files Browse the repository at this point in the history
* [Dart] Fix enum generation

* Update generated Order file

* Re-add constructor

* Generate dart2 files

* Dart - nicer enum formatting

* Dart - generate enum name as className+enumName

* Dart - dont initialize vars to null by default

Fixes #3633

* Dart - Generate inlined enums and deserialize them

* Merge branch 'master' of github.com:agilob/openapi-generator into 6727

* Dart - Fix using default value

* Fix typo

* Regenerate add dart files

* dart Revert override for dart dio and jaguar

* Fix dart model tests

* Fix dart1 generated template

* Use {{{datatypeWithEnum}}}

* Dart - throw when enum not known

* Fix generating enum with datatype from list
  • Loading branch information
agilob authored Jul 23, 2020
1 parent d6549f7 commit 90d8c32
Show file tree
Hide file tree
Showing 62 changed files with 597 additions and 382 deletions.
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;
}
}

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";
}
}

@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}}
{{^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

0 comments on commit 90d8c32

Please sign in to comment.