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 $ and \ in strings | Fix bad prop names #60

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
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
72 changes: 55 additions & 17 deletions lib/src/generators/schema.dart
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ class SchemaGenerator extends BaseGenerator {
// ==========================================

/// Union class for ${schemas.map((e) => '[$e]').join(', ')}
@Freezed(unionKey: '$unionKey')
@Freezed(unionKey: r'$unionKey')
sealed class $union with _\$$union {
const $union._();\n
""", mode: FileMode.append);
Expand Down Expand Up @@ -255,7 +255,7 @@ class SchemaGenerator extends BaseGenerator {
);
if (unionValue != null) {
unionValues.add(unionValue);
unionValue = "\n@FreezedUnionValue('$unionValue')";
unionValue = "\n@FreezedUnionValue(r'$unionValue')";
} else {
unionValue = '';
}
Expand Down Expand Up @@ -300,7 +300,7 @@ class SchemaGenerator extends BaseGenerator {
// ==========================================

enum ${union}Type {
${unionValues.map((e) => "@JsonValue('$e')\n${e.camelCase},").join('\n')}
${unionValues.map((e) => "@JsonValue(r'$e')\n${e.camelCase},").join('\n')}
}
""";
}
Expand Down Expand Up @@ -577,9 +577,26 @@ class SchemaGenerator extends BaseGenerator {
// Store the toMap string for later
String toMap = '';

// Clean up the properties
final propNames = <String>[];
final props = s.properties?.map((name, prop) {
// Remove bad characters from the key
var newKey = name.replaceAll(RegExp(r'[^a-zA-Z0-9_]'), '');
// Remove leading numbers and underscores
newKey = newKey.replaceAll(RegExp(r'^[0-9_]+'), '');
// Ensure the key is not empty
if (newKey.isEmpty) {
newKey = '_prop';
}
// Add key while ensuring it is unique
while (propNames.contains(newKey)) {
newKey += '_';
}
propNames.add(newKey);
return MapEntry(newKey, prop);
});

// Loop through properties
final props = s.properties;
final propNames = props?.keys.toList() ?? <String>[];
bool firstPass = true;
List<SchemaValidation> validations = [];
for (final propName in propNames) {
Expand All @@ -600,7 +617,7 @@ class SchemaGenerator extends BaseGenerator {
validations.add(v);
}

toMap += "'$propName': $dartName,\n";
toMap += "r'$propName': $dartName,\n";
}

String validationConstants = '';
Expand All @@ -621,7 +638,7 @@ class SchemaGenerator extends BaseGenerator {
factory $name.fromJson(Map<String, dynamic> json) => _\$${name}FromJson(json);

/// List of all property names of schema
static const List<String> propertyNames = ${json.encode(propNames).replaceAll('"', "'")};
static const List<String> propertyNames = ${json.encode(propNames).replaceAll('"', "'").escaped()};

$validationConstants

Expand Down Expand Up @@ -658,7 +675,7 @@ class SchemaGenerator extends BaseGenerator {
}) {
List<String> jsonOpts = [];
if (jsonName != name) {
jsonOpts.add("name: '$jsonName'");
jsonOpts.add("name: r'$jsonName'");
}
if (nullable && !required) {
jsonOpts.add("includeIfNull: false");
Expand All @@ -683,7 +700,7 @@ class SchemaGenerator extends BaseGenerator {
c += getJsonKey(nullable: nullable);
if (hasDefault && !required) {
if (defaultValue is String) {
c += "@Default('$defaultValue') ";
c += "@Default(r'$defaultValue') ";
} else {
c += "@Default($defaultValue) ";
}
Expand Down Expand Up @@ -934,7 +951,7 @@ class SchemaGenerator extends BaseGenerator {

if (p.ref == null) {
if (p.defaultValue != null && !required) {
c += "@Default('${p.defaultValue}') ";
c += "@Default(r'${p.defaultValue}') ";
}
if (required) {
c += "required ";
Expand Down Expand Up @@ -995,11 +1012,26 @@ class SchemaGenerator extends BaseGenerator {
required Schema schema,
}) {
final s = schema.mapOrNull(enumeration: (s) => s)!;
final values = s.values;

if (values == null) {
return;
}
// Collect all enum values and ensure they are valid
final valuesMap = <({String jsonKey, String dartName})>[];

s.values?.forEach((originalName) {
// Remove bad characters from the name
var newName = originalName.replaceAll(RegExp(r'[^a-zA-Z0-9_]'), '');
// Remove leading numbers and underscores
newName = newName.replaceAll(RegExp(r'^[0-9_]+'), '');
// Ensure the name is not empty
if (newName.isEmpty) {
newName = 'Value';
}

// Add key while ensuring it is unique
while (valuesMap.map((e) => e.dartName).contains(newName)) {
newName += '_';
}
valuesMap.add((jsonKey: originalName, dartName: newName));
});

file.writeAsStringSync("""
// ==========================================
Expand All @@ -1011,11 +1043,11 @@ class SchemaGenerator extends BaseGenerator {
""", mode: FileMode.append);

// Loop through enum values
for (var v in values) {
for (var v in valuesMap) {
// Write enum value
file.writeAsStringSync("""
@JsonValue('$v')
${_safeEnumValue(v, s)},
@JsonValue(r'${v.jsonKey}')
${_safeEnumValue(v.dartName, s)},
""", mode: FileMode.append);
}

Expand Down Expand Up @@ -1202,3 +1234,9 @@ class SchemaGenerator extends BaseGenerator {
}
}
}

extension on String {
String escaped() {
return replaceAll(r'\', r'\\').replaceAll(r'$', r'\$');
}
}
Loading