Skip to content

Commit

Permalink
Fix Android Escaping of "'", "&" and "@".
Browse files Browse the repository at this point in the history
Inspired by PR from Falko Richter:
netbe#133
  • Loading branch information
uliluckas committed Aug 28, 2024
1 parent 8d6dc73 commit 4c3cdf7
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 0 deletions.
10 changes: 10 additions & 0 deletions lib/babelish/csv2android.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ def language_filepaths(language)

def process_value(row_value, default_value)
value = super(row_value, default_value)
value = escape_android_characters(value)

# if the value begins and ends with a quote we must leave them unescapted
if value.size > 4 && value[0, 2] == "\\\"" && value[value.size - 2, value.size] == "\\\""
value[0, 2] = "\""
Expand All @@ -28,6 +30,14 @@ def process_value(row_value, default_value)
value.to_utf8
end

# see https://developer.android.com/guide/topics/resources/string-resource#escaping_quotes
def escape_android_characters(value)
value.gsub!(/'/, "'" => "\\'") # \' should be the result...
value.gsub!(/&/, "&" => "&")
value.gsub!(/@/, "@" => "\@")
value
end

def get_row_format(row_key, row_value, comment = nil, indentation = 0)
entry = comment.to_s.empty? ? "" : "\n\t<!-- #{comment} -->\n"
entry + "\t<string name=\"#{row_key}\">#{row_value}</string>\n"
Expand Down
27 changes: 27 additions & 0 deletions test/babelish/test_csv2android.rb
Original file line number Diff line number Diff line change
Expand Up @@ -69,4 +69,31 @@ def test_converting_with_basename
# clean up
system("rm -rf ./values-en")
end

def test_android_character_escaping
converter = Babelish::CSV2Android.new(
"test/data/test_data_with_characters_that_need_escaping.csv",
{ "English" => "en" },
output_basename: "escaped_strings"
)
converter.convert
exist = File.exist?("values-en/escaped_strings.xml")
assert exist, "the ouptut file does not exist"

output = File.read("values-en/escaped_strings.xml")
expected_output = File.read(
"test/data/test_data_with_characters_that_need_escaping.xml"
)

assert_equal expected_output, output

assert_true FileUtils.identical?(
"values-en/escaped_strings.xml",
"test/data/test_data_with_characters_that_need_escaping.xml"
)

# clean up
system("rm -rf ./values-en")

end
end
3 changes: 3 additions & 0 deletions test/data/test_data_with_characters_that_need_escaping.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
variables,English
NEEDS_ESCAPING,? ' @ < &
ANOTHER_STRING,hello
5 changes: 5 additions & 0 deletions test/data/test_data_with_characters_that_need_escaping.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="NEEDS_ESCAPING">\? \' \@ &lt; &amp;</string>
<string name="ANOTHER_STRING">hello</string>
</resources>

0 comments on commit 4c3cdf7

Please sign in to comment.