From aedfb12eda0fb4aed3fb9cd282b46740c15a1dbb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Guitaut?= Date: Fri, 4 Oct 2024 15:21:58 +0200 Subject: [PATCH] DEV: Output failing MF keys when compilation fails MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Currently, when the MessageFormat compiler fails on some translations, we just have the raw output from the compiler in the logs and that’s not always very helpful. Now, when there is an error, we iterate over the translation keys and try to compile them one by one. When we detect one that is failing, it’s added to a list that is now outputted in the logs. That way, it’s easier to know which keys are not properly translated, and the problems can be addressed quicker. --- lib/js_locale_helper.rb | 12 +++++++++++- spec/lib/js_locale_helper_spec.rb | 9 +++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/lib/js_locale_helper.rb b/lib/js_locale_helper.rb index 8b396707e1f..bcdc56b4e5c 100644 --- a/lib/js_locale_helper.rb +++ b/lib/js_locale_helper.rb @@ -163,7 +163,17 @@ module JsLocaleHelper require("discourse-mf"); JS rescue => e - Rails.logger.error("Failed to compile message formats for #{locale} '#{e}'") + message_formats[locale.to_s] + .filter_map do |key, value| + next if MessageFormat.compile(locale, value, strict: false) + rescue StandardError + key + end + .then do |strings| + Rails.logger.error( + "Failed to compile message formats for #{locale}.\n\nBroken strings are: #{strings.join(", ")}\n\nError: #{e}", + ) + end <<~JS console.error("Failed to compile message formats for #{locale}. Some translation strings will be missing."); JS diff --git a/spec/lib/js_locale_helper_spec.rb b/spec/lib/js_locale_helper_spec.rb index 7ba797febc9..c0a92275c9a 100644 --- a/spec/lib/js_locale_helper_spec.rb +++ b/spec/lib/js_locale_helper_spec.rb @@ -169,8 +169,10 @@ RSpec.describe JsLocaleHelper do let(:translated_message) do v8_ctx.eval("I18n._mfMessages.get('posts_likes_MF', {count: 3, ratio: 'med'})") end + let(:fake_logger) { FakeLogger.new } before do + Rails.logger.broadcast_to(fake_logger) overriden_translation_ja.update_columns( value: "{ count, plural, one {返信 # 件、} other {返信 # 件、} }", ) @@ -178,6 +180,8 @@ RSpec.describe JsLocaleHelper do v8_ctx.eval(output) end + after { Rails.logger.stop_broadcasting_to(fake_logger) } + context "when locale is 'en'" do let(:locale) { "en" } @@ -258,6 +262,11 @@ RSpec.describe JsLocaleHelper do it "raises an error" do expect(output).to match(/Failed to compile message formats/) end + + it "logs which keys are problematic" do + output + expect(fake_logger.errors).to include(/posts_likes_MF/) + end end end