From 3ad86d2ee247e1d60e9f3d6914b3d0a7deaa6249 Mon Sep 17 00:00:00 2001 From: "Charles-P. Clermont" Date: Thu, 9 Sep 2021 09:10:37 -0400 Subject: [PATCH] Write JSON to file, not a Ruby Hash. Fixes #432 --- lib/theme_check/corrector.rb | 2 +- lib/theme_check/json_file.rb | 13 +++++++++---- test/json_file_test.rb | 9 +++++++++ 3 files changed, 19 insertions(+), 5 deletions(-) diff --git a/lib/theme_check/corrector.rb b/lib/theme_check/corrector.rb index d06d9947..124823ed 100644 --- a/lib/theme_check/corrector.rb +++ b/lib/theme_check/corrector.rb @@ -34,7 +34,7 @@ def create(theme, relative_path, content) def create_default_locale_json(theme) theme.default_locale_json = JsonFile.new("locales/#{theme.default_locale}.default.json", theme.storage) - theme.default_locale_json.update_contents('{}') + theme.default_locale_json.update_contents({}) end end end diff --git a/lib/theme_check/json_file.rb b/lib/theme_check/json_file.rb index 75d5a02c..f91060b6 100644 --- a/lib/theme_check/json_file.rb +++ b/lib/theme_check/json_file.rb @@ -20,14 +20,19 @@ def parse_error @parser_error end - def update_contents(new_content = '{}') + def update_contents(new_content = {}) + raise ArgumentError if new_content.is_a?(String) @content = new_content end def write - if source != @content - @storage.write(@relative_path, content) - @source = content + pretty = JSON.pretty_generate(@content) + if source.rstrip != pretty.rstrip + # Most editors add a trailing \n at the end of files. Here we + # try to maintain the convention. + eof = source.end_with?("\n") ? "\n" : "" + @storage.write(@relative_path, pretty + eof) + @source = pretty end end diff --git a/test/json_file_test.rb b/test/json_file_test.rb index 46478d65..0f0d139d 100644 --- a/test/json_file_test.rb +++ b/test/json_file_test.rb @@ -32,6 +32,15 @@ def test_parse_error_with_error assert_instance_of(JSON::ParserError, @json.parse_error) end + def test_write + storage = make_storage("a.json" => '{ "hello": "world" }') + expected = { hello: "friend" } + @json = ThemeCheck::JsonFile.new("a.json", storage) + @json.update_contents(expected) + @json.write + assert_equal(JSON.pretty_generate(expected), storage.read("a.json")) + end + private def make_json_file(name, content)