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

feat: avoid rewriting exported JSON localizaton files if identical #694

Merged
Show file tree
Hide file tree
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
6 changes: 6 additions & 0 deletions lib/i18n-js.rb
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,12 @@ def self.write_file(file_path, translations)
digest = Digest::MD5.hexdigest(contents)
file_path = file_path.gsub(/:digest/, digest)

# Don't rewrite the file if it already exists and has the same content.
# It helps the asset pipeline or webpack understand that file wasn't changed.
if File.exist?(file_path) && File.read(file_path) == contents
return file_path
end

File.open(file_path, "w") do |file|
file << contents
end
Expand Down
40 changes: 40 additions & 0 deletions test/i18n-js/exporter_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -188,4 +188,44 @@ def transform(translations:)
assert_json_file "test/fixtures/expected/transformed.json",
"test/output/everything.json"
end

test "do not overwrite exported files if identical" do
I18n.load_path << Dir["./test/fixtures/yml/*.yml"]
exported_file_path = "test/output/everything.json"

# First run
actual_files = I18nJS.call(config_file: "./test/config/everything.yml")
assert_exported_files [exported_file_path], actual_files
exported_file_mtime = File.mtime(exported_file_path)

# Second run
I18nJS.call(config_file: "./test/config/everything.yml")

# mtime should be the same
assert_equal exported_file_mtime,
File.mtime(exported_file_path)
end

test "overwrite exported files if not identical" do
I18n.load_path << Dir["./test/fixtures/yml/*.yml"]
exported_file_path = "test/output/everything.json"

# First run
actual_files = I18nJS.call(config_file: "./test/config/everything.yml")
assert_exported_files [exported_file_path], actual_files

# Change content of existed exported file (add space to the end of file).
File.open(exported_file_path, 'a') { |f| f << ' ' }
exported_file_mtime = File.mtime(exported_file_path)

# Second run
I18nJS.call(config_file: "./test/config/everything.yml")

# File should overwritten to the correct one.
assert_json_file "test/fixtures/expected/everything.json",
exported_file_path

# mtime should be newer
assert File.mtime(exported_file_path) > exported_file_mtime
end
end