Skip to content

Commit

Permalink
Avoid re-exporting files when content hasn't changed (#694)
Browse files Browse the repository at this point in the history
Close 693.
  • Loading branch information
oleksii-leonov committed Dec 30, 2022
1 parent 9dfd146 commit d2e0170
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/i18n-js.rb
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
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

0 comments on commit d2e0170

Please sign in to comment.