From 7bc9b51a82e9008c758e9bf73803ca73535ba3fe Mon Sep 17 00:00:00 2001 From: Jumpaku Date: Sat, 15 Jun 2024 11:45:39 +0900 Subject: [PATCH] fix(embed): escape dollar symbol of JSON string literal (#21) With the original version, `embed.dart` cannot generate a compilable Dart code if the source JSON has a string literal containing a dollar symbol ($). For example, the following code will be generated from {"dollar": "$"}: ```dart const _$variable = (dollar: "$"); // the string literal "$" is not valid, which is a beginning of string interpolation. ``` In the revised version, I fixed it to generate the following code from that JSON: ```dart const _$variable = (dollar: "\$"); // $ is escaped! ``` I also added a test case. --- embed/CHANGELOG.md | 4 ++++ embed/lib/src/literal/dart_literals.dart | 2 +- embed/pubspec.yaml | 2 +- .../literal/literal_embedding_generator_test.dart | 11 +++++++++++ 4 files changed, 17 insertions(+), 2 deletions(-) diff --git a/embed/CHANGELOG.md b/embed/CHANGELOG.md index d743c2f..72e61e0 100644 --- a/embed/CHANGELOG.md +++ b/embed/CHANGELOG.md @@ -1,5 +1,9 @@ # CHANGELOG +## 1.3.1 + +- fix(embed): escape dollar symbol of JSON string literal (#21 by @Jumpaku) + ## 1.3.0 - Update `toml` dependency to 0.15.0 (#17 by @bramp) diff --git a/embed/lib/src/literal/dart_literals.dart b/embed/lib/src/literal/dart_literals.dart index 4610e13..636943b 100644 --- a/embed/lib/src/literal/dart_literals.dart +++ b/embed/lib/src/literal/dart_literals.dart @@ -72,7 +72,7 @@ class StringLiteral extends DartLiteral { @override String toString() { - final literal = value.replaceAll('"', r'\"'); + final literal = value.replaceAll('"', r'\"').replaceAll(r'$', r'\$'); return '"$literal"'; } } diff --git a/embed/pubspec.yaml b/embed/pubspec.yaml index ae5825c..e6f1996 100644 --- a/embed/pubspec.yaml +++ b/embed/pubspec.yaml @@ -1,6 +1,6 @@ name: embed description: Code generation for embedding arbitrary file content into Dart code. -version: 1.3.0 +version: 1.3.1 repository: https://github.com/fujidaiti/embed.dart.git environment: diff --git a/embed/test/literal/literal_embedding_generator_test.dart b/embed/test/literal/literal_embedding_generator_test.dart index 2534850..1f8eeed 100644 --- a/embed/test/literal/literal_embedding_generator_test.dart +++ b/embed/test/literal/literal_embedding_generator_test.dart @@ -243,3 +243,14 @@ const _$mapPattern = {"a": 0, "b": 0.0, "c": true}; """, ) Map? mapPattern; + +@TestEmbedLiteral( + extension: "json", + content: r""" +{ "dollar": "$" } +""", + shouldGenerate: r""" +const _$stringLiteralsDollar = (dollar: "\$"); +""", +) +var stringLiteralsDollar;