The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
GDGT-2087 validate localization strings (#72756)
YBa94047288a91
diff --git a/.github/workflows/i18n.yml b/.github/workflows/i18n.ymlindex 12ef3bc72ca..666f9b253b6 100644--- a/.github/workflows/i18n.yml+++ b/.github/workflows/i18n.yml@@ -33,19 +33,19 @@ jobs:runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}timeout-minutes: 15steps:- - uses: actions/checkout@v4- - name: Prepare front-end environment- uses: ./.github/actions/prepare-frontend- - name: Prepare back-end environment- uses: ./.github/actions/prepare-backend- - name: Install xgettext if necessary- run: |- if ! command -v xgettext > /dev/null; then- sudo apt install gettext- fi- - name: Check xgettext version- run: xgettext --version- - name: Check i18n tags/make sure template can be built- run: ./bin/i18n/update-translation-template- - name: Verify i18n translations (.po files)- run: ./bin/i18n/build-translation-resources+ - uses: actions/checkout@v4+ - name: Prepare front-end environment+ uses: ./.github/actions/prepare-frontend+ - name: Prepare back-end environment+ uses: ./.github/actions/prepare-backend+ - name: Install xgettext if necessary+ run: |+ if ! command -v xgettext > /dev/null; then+ sudo apt install gettext+ fi+ - name: Check xgettext version+ run: xgettext --version+ - name: Check i18n tags/make sure template can be built+ run: ./bin/i18n/update-translation-template+ - name: Verify i18n translations (.po files)+ run: ./bin/i18n/build-translation-resourcesdiff --git a/.github/workflows/translation-update.yml b/.github/workflows/translation-update.ymlindex 4443b08f2fd..0e64da5875d 100644--- a/.github/workflows/translation-update.yml+++ b/.github/workflows/translation-update.yml@@ -74,6 +74,16 @@ jobs:git commit -a -m "Update translations $Date" --allow-empty --no-verifygit push -u origin $BRANCH_NAME+ - name: Upload i18n violations report+ id: upload-violations+ if: always()+ uses: actions/upload-artifact@v4+ with:+ name: i18n-violations+ path: target/i18n-violations.*+ if-no-files-found: warn+ retention-days: 30+- name: Crowdin uploaduses: crowdin/github-action@ce33ce793a5cbc401d9cd748716e03fc90c001f1 # v2id: crowdin-upload@@ -105,6 +115,35 @@ jobs:echo "pr_number=$PR_NUMBER" >> $GITHUB_OUTPUT+ - name: Comment violations summary on PR+ if: ${{ steps.create_pr.outputs.pr_number && hashFiles('target/i18n-violations.csv') != '' }}+ env:+ GH_TOKEN: ${{ secrets.METABASE_AUTOMATION_USER_TOKEN }}+ ARTIFACT_URL: ${{ steps.upload-violations.outputs.artifact-url }}+ run: | # sh+ PR_NUMBER=${{ steps.create_pr.outputs.pr_number }}+ SUMMARY=$(awk -F',' 'NR>1 {gsub(/"/, "", $2); n=split($2,a,"+"); for(i=1;i<=n;i++) counts[a[i]]++} END {for (t in counts) printf "- **%s**: %d\n", t, counts[t]}' target/i18n-violations.csv)+ if [ -z "$SUMMARY" ]; then+ echo "No violations to report."+ exit 0+ fi+ if [ -n "$ARTIFACT_URL" ]; then+ REPORT_LINK="[Full report]($ARTIFACT_URL) (downloads the \`i18n-violations\` artifact)"+ else+ REPORT_LINK="Full report: download the \`i18n-violations\` artifact from this workflow run."+ fi+ gh pr comment "$PR_NUMBER" --body "$(cat <<EOF+ ### Translation violations filtered from this update++ Translated strings that are invalid MessageFormat were dropped from the build. They fall back to English at runtime until corrected in Crowdin.+ Partially translated strings that violate other validations are recorded in the report below, but are left in the build as-is to avoid loss of contextual knowledge for the user.++ $SUMMARY++ $REPORT_LINK+ EOF+ )"+- name: Auto approve PRuses: juliangruber/approve-pull-request-action@f83b836abaed1b3ab639ae61f9117c52ae405f65 # v1with:diff --git a/bin/build/src/i18n/autofix.clj b/bin/build/src/i18n/autofix.cljnew file mode 100644index 00000000000..f11b7c22255--- /dev/null+++ b/bin/build/src/i18n/autofix.clj@@ -0,0 +1,41 @@+(ns i18n.autofix+ "Automatic corrections applied to parsed `.po` contents before validation and artifact+ generation. These fixes rescue translations that would otherwise fail `java.text.MessageFormat`+ parsing due to common translator mistakes — currently, unescaped apostrophes in word-adjacent+ positions (e.g. Catalan `d'aquí` becomes `d''aquí`).++ Applied only to backend messages. Frontend strings use ttag at runtime with different escaping+ rules and pass through unchanged.++ Runs once per locale, upstream of `i18n.validation/invalid-messages-in-po` and the backend/+ frontend artifact writers, so the validation scanner and artifact builders process the same data."+ (:require+ [clojure.string :as str]+ [i18n.common :as i18n]))++(set! *warn-on-reflection* true)++(def ^:private apostrophe-regex+ "Matches a single apostrophe surrounded by word-like characters (letters, digits, spaces,+ diacritics). Preserves apostrophes adjacent to non-word characters like `{` / `}` since those+ are typically intentional MessageFormat escapes (e.g. `'{0}'` meaning literal `{0}`)."+ #"(?<![^a-zA-Z0-9\s\u00C0-\u017F])'(?![^a-zA-Z0-9\s\u00C0-\u017F])")++(defn- escape-apostrophes [^String s]+ (when (some? s) (str/replace s apostrophe-regex "''")))++(defn- fix-apostrophes-in-message [message]+ (if (:plural? message)+ (update message :str-plural #(map escape-apostrophes %))+ (update message :str escape-apostrophes)))++(defn autofix-po-contents+ "Applies automatic fixes to the `:messages` in `po-contents`."+ [po-contents]+ (update po-contents :messages+ (fn [msgs]+ (map (fn [m]+ (if (i18n/backend-message? m)+ (fix-apostrophes-in-message m)+ m))+ msgs))))diff --git a/bin/build/src/i18n/common.clj b/bin/build/src/i18n/common.cljindex 2cf6482df87..b888494dee8 100644--- a/bin/build/src/i18n/common.clj+++ b/bin/build/src/i18n/common.clj@@ -63,6 +63,29 @@{:headers (po-headers locale):messages (po-messages-seq locale)})+(defn backend-message?+ "True if `message` (the shape returned by `po-messages-seq`) originates from a Clojure source file+ — i.e. one of its `:source-references` ends in `.clj` or `.cljc`. This is the same filter used by+ `i18n.create-artifacts.backend` when writing the backend `.edn` artifacts, and by `i18n.validation`+ when deciding which translations to sanity-check as `java.text.MessageFormat` patterns. Frontend+ strings use a different format system (`#, javascript-format` in the `.po`) and their own+ validation rules, so this scanner skips them."+ [{:keys [source-references]}]+ (boolean+ (let [paths (eduction+ ;; Sometimes 2 paths exist in a single string, space separated+ (mapcat #(str/split % #" "))+ ;; Strip off the line number at the end of some paths+ (map #(str/split % #":"))+ (map first)+ source-references)]+ (some (fn [path]+ (some+ (fn [suffix]+ (str/ends-with? path suffix))+ [".clj" ".cljc"]))+ paths))))+(defn print-message-count-xform"Transducer that prints a count of how many translation strings we process/write."[rf]diff --git a/bin/build/src/i18n/create_artifacts.clj b/bin/build/src/i18n/create_artifacts.cljindex a5970a235b4..c02f9b0abfb 100644--- a/bin/build/src/i18n/create_artifacts.clj+++ b/bin/build/src/i18n/create_artifacts.clj@@ -1,10 +1,15 @@(ns i18n.create-artifacts(:require+ [clojure.data.csv :as csv]+ [clojure.java.io :as io][clojure.pprint :as pprint]+ [clojure.string :as str]+ [i18n.autofix :as i18n.autofix][i18n.common :as i18n][i18n.create-artifacts.backend :as backend][i18n.create-artifacts.frontend :as frontend][i18n.pseudo-locale :as pseudo-locale]+ [i18n.validation :as i18n.validation][metabuild-common.core :as u]))(set! *warn-on-reflection* true)@@ -25,17 +30,78 @@(pprint/pprint (locales-dot-edn))))(u/assert-file-exists file))))-(defn- create-artifacts-for-locale! [locale]+(defn- msgids-to-drop+ "Set of `msgid`s to exclude from build artifacts, given a seq of violations. If any plural form+ of a message has a droppable violation, the entire message is excluded."+ [violations]+ (into #{}+ (comp (filter i18n.validation/drop-from-build?)+ (map :msgid))+ violations))++(defn- create-artifacts-for-locale!+ "Generate frontend + backend artifacts for one `locale`. Parses the `.po` once, runs the autofix+ pass, then threads the cleaned contents through the scanner and both builders. Returns the+ violations the scanner flagged (post-autofix) for the aggregate report."+ [locale](u/step (format "Create artifacts for locale %s" (pr-str locale))- (frontend/create-artifact-for-locale! locale)- (backend/create-artifact-for-locale! locale)- (u/announce "Artifacts for locale %s created successfully." (pr-str locale))))+ (let [po-contents (i18n.autofix/autofix-po-contents (i18n/po-contents locale))+ violations (i18n.validation/invalid-messages-in-po locale po-contents)+ drop-msgids (msgids-to-drop violations)]+ (frontend/create-artifact-for-locale! locale drop-msgids po-contents)+ (backend/create-artifact-for-locale! locale drop-msgids po-contents)+ (when (seq drop-msgids)+ (u/announce "Filtered %d invalid translations from %s" (count drop-msgids) locale))+ (u/announce "Artifacts for locale %s created successfully." (pr-str locale))+ violations)))++(def ^:private violations-report-directory+ (u/filename u/project-root-directory "target"))++(def ^:private violations-csv-columns+ ["locale" "types" "dropped" "backend" "plural_index" "msgid" "msgid_plural" "msgstr"+ "error" "expected_args" "actual_args" "source_refs"])++(defn- violation->row [{:keys [locale types backend? plural-index msgid msgid-plural msgstr+ error expected-arg-counts actual-arg-count source-refs]+ :as violation}]+ (->>+ [locale+ (str/join "+" (sort (map name types)))+ (boolean (i18n.validation/drop-from-build? violation))+ (boolean backend?)+ plural-index+ msgid+ msgid-plural+ msgstr+ error+ (some->> expected-arg-counts (str/join ","))+ actual-arg-count+ (str/join " " source-refs)]+ (mapv (fnil str ""))))++(defn- write-violations-report! [violations]+ (u/step "Write i18n violations report"+ (u/create-directory-unless-exists! violations-report-directory)+ (let [csv-file (u/filename violations-report-directory "i18n-violations.csv")+ edn-file (u/filename violations-report-directory "i18n-violations.edn")]+ (with-open [w (io/writer csv-file)]+ (csv/write-csv w (cons violations-csv-columns (map violation->row violations))))+ (spit edn-file (with-out-str (pprint/pprint (vec violations))))+ (let [by-type (frequencies (mapcat :types violations))]+ (u/announce "Wrote %d translation violations to %s" (count violations) csv-file)+ (doseq [t [:invalid-message-format :skipped-arg-index :arg-count-mismatch]]+ (u/announce " %s: %d" (name t) (get by-type t 0)))))))(defn- create-artifacts-for-all-locales! [];; Empty directory in case some locales were removed(u/delete-file-if-exists! backend/target-directory)(u/delete-file-if-exists! frontend/target-directory)- (doall (pmap create-artifacts-for-locale! (i18n/locales))))+ (let [per-locale-violations (doall (pmap create-artifacts-for-locale! (i18n/locales)))+ all-violations (->> per-locale-violations+ (apply concat)+ (sort-by (juxt :locale (comp str :types) :msgid :plural-index)))]+ (write-violations-report! all-violations)))(defn create-all-artifacts!"Create backend and frontend i18n artifacts."diff --git a/bin/build/src/i18n/create_artifacts/backend.clj b/bin/build/src/i18n/create_artifacts/backend.cljindex 4f539ac09ab..832628edcf4 100644--- a/bin/build/src/i18n/create_artifacts/backend.clj+++ b/bin/build/src/i18n/create_artifacts/backend.clj@@ -1,7 +1,6 @@(ns i18n.create-artifacts.backend(:require[clojure.java.io :as io]- [clojure.string :as str][i18n.common :as i18n][metabuild-common.core :as u])(:import@@ -10,38 +9,11 @@(set! *warn-on-reflection* true)-(defn- backend-message? [{:keys [source-references]}]- (boolean- (let [paths (eduction- ;; Sometimes 2 paths exist in a single string, space separated- (mapcat #(str/split % #" "))- ;; Strip off the line number at the end of some paths- (map #(str/split % #":"))- (map first)- source-references)]- (some (fn [path]- (some- (fn [suffix]- (str/ends-with? path suffix))- [".clj" ".cljc"]))- paths))))--(def ^:private apostrophe-regex- "Regex that matches incorrectly escaped apostrophe characters.- Matches on a single apostrophe surrounded by any letter, number, space, or diacritical character (chars with accents like é) and is case-insensitive"- #"(?<![^a-zA-Z0-9\s\u00C0-\u017F])'(?![^a-zA-Z0-9\s\u00C0-\u017F])")--(defn- fix-unescaped-apostrophes [message]- (let [escape-fn #(str/replace % apostrophe-regex "''")]- (if (:plural? message)- (update message :str-plural #(map escape-fn %))- (update message :str escape-fn))))-(defn- messages->edn- [messages]+ [messages drop-msgids](eduction- (filter backend-message?)- (map fix-unescaped-apostrophes)+ (filter i18n/backend-message?)+ (remove (fn [{:keys [id]}] (contains? drop-msgids id)))i18n/print-message-count-xformmessages))@@ -52,7 +24,7 @@(defn- target-filename [locale](u/filename target-directory (format "%s.edn" locale)))-(defn- write-edn-file! [po-contents target-file]+(defn- write-edn-file! [po-contents drop-msgids target-file](u/step "Write EDN file"(with-open [os (FileOutputStream. (io/file target-file))w (OutputStreamWriter. os StandardCharsets/UTF_8)]@@ -63,7 +35,7 @@(.write w ":messages\n")(.write w "{\n")(doseq [{msg-id :id, msg-str :str, msg-str-plural :str-plural}- (messages->edn (:messages po-contents))+ (messages->edn (:messages po-contents) drop-msgids):let [msg-strs (or msg-str-plural [msg-str])]](.write w (pr-str msg-id))(.write w "\n")@@ -78,11 +50,20 @@(.write w "}\n"))))(defn create-artifact-for-locale!- "Create an artifact with translated strings for `locale` for backend (Clojure) usage."- [locale]+ "Create an artifact with translated strings for `locale` for backend (Clojure) usage.++ `drop-msgids` is a set of English source strings to exclude from the output (typically those+ whose translations had fatal validation errors); they fall back to English at runtime.++ `po-contents` is the parsed + autofixed `.po` content from+ `(i18n.autofix/autofix-po-contents (i18n.common/po-contents locale))`. Passed by the caller+ rather than re-parsed here so scanner and writer stay in sync."+ [locale drop-msgids po-contents](let [target-file (target-filename locale)](u/step (format "Create backend artifact %s from %s" target-file (i18n/locale-source-po-filename locale))(u/create-directory-unless-exists! target-directory)(u/delete-file-if-exists! target-file)- (write-edn-file! (i18n/po-contents locale) target-file)- (u/assert-file-exists target-file))))+ (write-edn-file! po-contents drop-msgids target-file)+ (u/assert-file-exists target-file)+ (when (seq drop-msgids)+ (u/announce "Filtered %d invalid backend translations from %s" (count drop-msgids) locale)))))diff --git a/bin/build/src/i18n/create_artifacts/frontend.clj b/bin/build/src/i18n/create_artifacts/frontend.cljindex 7f4e1f71e70..e21861f6d96 100644--- a/bin/build/src/i18n/create_artifacts/frontend.clj+++ b/bin/build/src/i18n/create_artifacts/frontend.clj@@ -22,11 +22,12 @@[message-id](str/replace message-id #"\{\s*(\d+)\s*\}" "\\${ $1 }"))-(defn- ->translations-map [messages]+(defn- ->translations-map [messages drop-msgids]{"" (into {}(comp;; filter out i18n messages that aren't used on the FE client(filter frontend-message?)+ (remove (fn [{:keys [id]}] (contains? drop-msgids id)))i18n/print-message-count-xform(map (fn [message][(->ttag-reference (:id message))@@ -38,14 +39,11 @@(defn- ->i18n-map"Convert the contents of a `.po` file to map format used in the frontend client."- [po-contents]+ [po-contents drop-msgids]{:charset "utf-8":headers (into {} (for [[k v] (:headers po-contents)][(str/lower-case k) v]))- :translations (->translations-map (:messages po-contents))})--(defn- i18n-map [locale]- (->i18n-map (i18n/po-contents locale)))+ :translations (->translations-map (:messages po-contents) drop-msgids)})(def target-directory"Target directory for frontend i18n resources."@@ -55,8 +53,15 @@(u/filename target-directory (format "%s.json" (str/replace locale #"-" "_"))))(defn create-artifact-for-locale!- "Create an artifact with translated strings for `locale` for frontend (JS) usage."- [locale]+ "Create an artifact with translated strings for `locale` for frontend (JS) usage.++ `drop-msgids` is a set of English source strings to exclude from the output (typically those+ whose translations had fatal validation errors).++ `po-contents` is the parsed + autofixed `.po` content from+ `(i18n.autofix/autofix-po-contents (i18n.common/po-contents locale))`. Passed by the caller+ rather than re-parsed here so scanner and writer stay in sync."+ [locale drop-msgids po-contents](let [target-file (target-filename locale)](u/step (format "Create frontend artifact %s from %s" target-file (i18n/locale-source-po-filename locale))(u/create-directory-unless-exists! target-directory)@@ -64,5 +69,5 @@(u/step "Write JSON"(with-open [os (FileOutputStream. (io/file target-file))w (OutputStreamWriter. os StandardCharsets/UTF_8)]- (json/generate-stream (i18n-map locale) w)))+ (json/generate-stream (->i18n-map po-contents drop-msgids) w)))(u/assert-file-exists target-file))))diff --git a/bin/build/src/i18n/validation.clj b/bin/build/src/i18n/validation.cljnew file mode 100644index 00000000000..4677d0526bb--- /dev/null+++ b/bin/build/src/i18n/validation.clj@@ -0,0 +1,112 @@+(ns i18n.validation+ "Scan `locales/*.po` files for translation violations — invalid `java.text.MessageFormat`+ patterns, skipped argument indices, and argument-count mismatches between English source and+ translated strings. Produces structured violation records suitable for:++ - Filtering invalid translations from the backend `.edn` build pipeline.+ - Emitting a CSV/EDN artifact that surfaces what was filtered (and why) so translators can+ fix the originals in Crowdin.++ The pure predicates live in `metabase.util.i18n.validation` so they can be shared with the+ macro-time call-site check (`metabase.util.i18n/validate-number-of-args`) and the regression-+ guard test (`metabase.util.i18n.validation-test`) without pulling in jgettext."+ (:require+ [clojure.string :as str]+ [i18n.common :as i18n]+ [metabase.util.i18n.validation :as validation]))++(set! *warn-on-reflection* true)++(defn- present? [s]+ (and (string? s) (not (str/blank? s))))++(defn- msgstr-forms+ "Seq of `{:plural-index int-or-nil :msgstr String}` for the msgstr(s) on a parsed `.po` message+ (the shape returned by `i18n.common/po-contents`). Blank entries are dropped — those represent+ missing translations, not malformed ones, so they're outside this scanner's scope."+ [{:keys [plural? str str-plural]}]+ (if plural?+ (keep-indexed (fn [i s] (when (present? s) {:plural-index i :msgstr s}))+ str-plural)+ (when (present? str)+ [{:plural-index nil :msgstr str}])))++(defn- arg-count-fn+ "Return the right arg-count function for `backend?` — `MessageFormat`-based for backend strings,+ regex-based for frontend."+ [backend?]+ (if backend? validation/message-format-arg-count validation/regex-arg-count))++(defn- check-violations+ "Return a flat violation map for `msgstr` (may have empty `:types`). Backend strings get all three+ checks; frontend strings get only the format-system-agnostic ones. All applicable types are+ collected — no short-circuiting. Single `MessageFormat` parse for backend strings."+ [msgstr message backend?]+ (let [count-fn (arg-count-fn backend?)+ format-error (when backend? (validation/message-format-error msgstr))+ skip? (if backend?+ (when-not format-error (validation/skipped-arg-index? msgstr))+ (validation/regex-skipped-arg-index? msgstr))+ actual (when-not format-error (count-fn msgstr))+ expected (keep count-fn [(:id message) (:id-plural message)])+ arg-mismatch (when actual (validation/arg-count-mismatch actual expected))]+ (cond-> {:types (cond-> #{}+ format-error (conj :invalid-message-format)+ skip? (conj :skipped-arg-index)+ arg-mismatch (conj :arg-count-mismatch))}+ format-error (assoc :error format-error)+ arg-mismatch (merge arg-mismatch))))++(defn invalid-messages-in-po+ "Return a seq of violation maps for `locale`'s `.po` file. Each map has:++ :types — set of applicable violation keywords (e.g. `#{:invalid-message-format}` or+ `#{:skipped-arg-index :arg-count-mismatch}` when both fire on the same form)+ :locale — the locale code (e.g. `\"fr\"`, `\"pt-BR\"`)+ :msgid — the English singular source string+ :msgid-plural — the English plural source string (nil for non-plural entries)+ :msgstr — the offending translated string+ :plural-index — `nil` for singular, `0..n` for plural forms+ :backend? — true if the message originates from `.clj`/`.cljc` source+ :error — (`:invalid-message-format`) the `IllegalArgumentException` message+ :expected-arg-counts, :actual-arg-count+ — (`:arg-count-mismatch`) the acceptable set and what the translation has+ :source-refs — seq of `path:line` references from the `.po` `#:` comments++ Every message (backend AND frontend) is scanned. Backend messages get all three checks (validity,+ skipped-index, arg-count). Frontend messages get only the format-system-agnostic checks (skipped-+ index, arg-count) using regex-based helpers to avoid `MessageFormat` apostrophe misparsing.++ Callers pass in pre-parsed `po-contents` (from `i18n.common/po-contents`) to avoid reparsing the+ `.po` file — both the build pipeline and the scanner need it, and the build orchestrator+ (`i18n.create-artifacts`) reads it once and threads it through."+ [locale po-contents]+ (for [message (:messages po-contents)+ form (msgstr-forms message)+ :let [msgstr (:msgstr form)+ backend? (i18n/backend-message? message)+ result (check-violations msgstr message backend?)]+ :when (seq (:types result))]+ (merge {:locale locale+ :msgid (:id message)+ :msgid-plural (:id-plural message)+ :msgstr msgstr+ :plural-index (:plural-index form)+ :backend? backend?+ :source-refs (vec (:source-references message))}+ result)))++(defn drop-from-build?+ "Predicate that the build-time filter consults to decide whether a violation's translated string+ should be excluded from its generated artifact (`.edn` for backend, `.json` for frontend).++ Drop only translations that would throw at runtime and trigger English fallback anyway —+ i.e. `:invalid-message-format` (the `MessageFormat` constructor throws on bad patterns).+ `:skipped-arg-index` and `:arg-count-mismatch` translations render imperfectly (literal `{N}`+ in output, or silently-dropped args) but don't throw; we keep them so users see mostly-+ localized text instead of full English fallback.++ The violations report at `target/i18n-violations.csv` includes every violation regardless of+ drop status; the `dropped` column indicates which ones were excluded from the artifacts."+ [violation]+ (contains? (:types violation) :invalid-message-format))diff --git a/bin/build/test/i18n/autofix_test.clj b/bin/build/test/i18n/autofix_test.cljnew file mode 100644index 00000000000..f1bc5309483--- /dev/null+++ b/bin/build/test/i18n/autofix_test.clj@@ -0,0 +1,97 @@+(ns i18n.autofix-test+ (:require+ [clojure.test :refer :all]+ [i18n.autofix :as autofix]))++(defn- backend-msg [str-value]+ {:id "Hello"+ :id-plural nil+ :str str-value+ :str-plural nil+ :plural? false+ :source-references ["metabase/foo.clj:10"]})++(defn- frontend-msg [str-value]+ {:id "Hello"+ :id-plural nil+ :str str-value+ :str-plural nil+ :plural? false+ :source-references ["frontend/src/metabase/foo.tsx:20"]})++(defn- backend-plural-msg [str-plural]+ {:id "Hello {0}"+ :id-plural "Hello {0} people"+ :str nil+ :str-plural str-plural+ :plural? true+ :source-references ["metabase/foo.clj:10"]})++(defn- fix-backend-str [s]+ (-> {:headers {} :messages [(backend-msg s)]}+ autofix/autofix-po-contents+ :messages+ first+ :str))++(defn- fix-frontend-str [s]+ (-> {:headers {} :messages [(frontend-msg s)]}+ autofix/autofix-po-contents+ :messages+ first+ :str))++(deftest ^:parallel backend-apostrophe-fix-test+ (testing "Word-adjacent apostrophes in backend messages get doubled"+ (are [input expected] (= expected (fix-backend-str input))+ "d'aquí a {0} mesos" "d''aquí a {0} mesos"+ "It's {0}" "It''s {0}"+ "won't {0} do" "won''t {0} do"+ "Cam's file" "Cam''s file"))++ (testing "Already-escaped apostrophes are not re-doubled"+ (is (= "It''s fine" (fix-backend-str "It''s fine"))))++ (testing "Intentional MessageFormat escapes (apostrophe adjacent to {}) are preserved"+ (are [input expected] (= expected (fix-backend-str input))+ "'{0}'" "'{0}'"+ "'{login}' literal" "'{login}' literal"+ "'''{{...}}''' clause" "'''{{...}}''' clause"))++ (testing "Strings without apostrophes pass through unchanged"+ (is (= "Hello {0}" (fix-backend-str "Hello {0}")))+ (is (= "" (fix-backend-str ""))))++ (testing "nil msgstr passes through as nil"+ (is (nil? (fix-backend-str nil)))))++(deftest ^:parallel backend-plural-apostrophe-fix-test+ (testing "Each plural form gets its apostrophes fixed"+ (let [fixed (-> {:headers {} :messages [(backend-plural-msg ["d'aquí" "d'aquí a {0}"])]}+ autofix/autofix-po-contents+ :messages+ first+ :str-plural)]+ (is (= ["d''aquí" "d''aquí a {0}"] fixed)))))++(deftest ^:parallel frontend-messages-pass-through-unchanged-test+ (testing "Frontend messages keep their apostrophes untouched — ttag doesn't use MessageFormat escapes"+ (are [input] (= input (fix-frontend-str input))+ "d'aquí a {0} mesos"+ "It's {0}"+ "won't do")))++(deftest ^:parallel po-contents-shape-preserved-test+ (testing "Headers pass through untouched"+ (let [input {:headers {"Content-Type" "text/plain; charset=UTF-8"+ "Plural-Forms" "nplurals=2; plural=(n != 1);"}+ :messages []}]+ (is (= (:headers input)+ (:headers (autofix/autofix-po-contents input))))))++ (testing "Message count is preserved — autofix transforms, never drops"+ (let [input {:headers {}+ :messages [(backend-msg "a'b")+ (frontend-msg "c'd")+ (backend-plural-msg ["e'f" "g'h"])]}]+ (is (= 3 (count (:messages (autofix/autofix-po-contents input))))))))diff --git a/bin/build/test/i18n/create_artifacts/backend_test.clj b/bin/build/test/i18n/create_artifacts/backend_test.cljindex 4feca11108e..f9fdb698473 100644--- a/bin/build/test/i18n/create_artifacts/backend_test.clj+++ b/bin/build/test/i18n/create_artifacts/backend_test.clj@@ -2,11 +2,12 @@(:require[clojure.edn :as edn][clojure.test :refer :all]+ [i18n.common :as i18n][i18n.create-artifacts.backend :as backend][i18n.create-artifacts.test-common :as test-common]))(deftest edn-test- (#'backend/write-edn-file! test-common/po-contents "/tmp/out.edn")+ (#'backend/write-edn-file! test-common/po-contents #{} "/tmp/out.edn")(is (= {:headers{"MIME-Version" "1.0""Content-Type" "text/plain; charset=UTF-8"@@ -28,7 +29,7 @@(testing "messages present in any .clj and .cljc files are detected as backend messages"#_{:clj-kondo/ignore [:equals-true]}(are [source-references expected] (= expected- (@#'backend/backend-message? {:source-references source-references}))+ (i18n/backend-message? {:source-references source-references}));; Simple .clj and .cljc files with and without line numbers["test.clj"] true["test.clj:123"] truediff --git a/bin/build/test/i18n/create_artifacts/frontend_test.clj b/bin/build/test/i18n/create_artifacts/frontend_test.cljindex 7cf109bf73d..98635fce61e 100644--- a/bin/build/test/i18n/create_artifacts/frontend_test.clj+++ b/bin/build/test/i18n/create_artifacts/frontend_test.clj@@ -37,4 +37,4 @@"Median of ${ 0 }"{:msgstr ["Median of ${ 0 }"]}}}}- (#'frontend/->i18n-map test-common/po-contents))))+ (#'frontend/->i18n-map test-common/po-contents #{}))))diff --git a/bin/i18n/README.md b/bin/i18n/README.mdindex 1b6e1132a66..ebb7df5e368 100644--- a/bin/i18n/README.md+++ b/bin/i18n/README.md@@ -1,6 +1,58 @@-## i18n info+# i18n info-#### Building the backend pot file+Metabase's internationalization pipeline has two halves that the scripts in this directory+orchestrate:++1. **[Extraction](#extraction)** — scan Clojure/TypeScript source for `trs` / `tru` / ttag `t`+ tagged-template call sites, emit a gettext source template at `locales/metabase.po`.+2. **[Artifact generation](#artifact-generation)** — read back translated `locales/*.po` files,+ apply [autofixes](#autofix-pass) for unambiguously repairable translator mistakes, validate+ the rest, and emit the runtime artifacts at `resources/i18n/*.edn` (backend) and+ `resources/frontend_client/app/locales/*.json` (frontend). Translations the scanner still+ flags as fatal are dropped; the full triage queue lands in the [violations report](#violations-report).++Between the two, [Crowdin](https://crowdin.com/project/metabase-i18n) is where translators fill in+the `msgstr` values. The [`.github/workflows/translation-update.yml`](../../.github/workflows/translation-update.yml)+workflow runs weekly to pull translations down and open a PR.++```mermaid+flowchart LR+ subgraph Extract ["Phase 1: Extraction"]+ direction LR+ Source["source<br/>(.clj/.cljc/.ts/.tsx)"]+ Pot[(locales/metabase.po)]+ Source -->|update-translation-template| Pot+ end++ subgraph Sync ["Phase 2: Crowdin sync"]+ direction LR+ Crowdin{{Crowdin}}+ LocalePo[(locales/*.po)]+ Crowdin -->|download| LocalePo+ end++ subgraph Build ["Phase 3: Artifact generation"]+ direction TB+ Autofix[["autofix pass<br/>(e.g. escape bare apostrophes)"]]+ Scanner[["validation scanner"]]+ Edn["resources/i18n/*.edn<br/>(backend)"]+ Json["resources/frontend_client/<br/>app/locales/*.json<br/>(frontend)"]+ Csv["target/i18n-violations.csv"]+ Autofix --> Scanner+ Scanner ==> Edn+ Scanner ==> Json+ Scanner ==> Csv+ end++ Pot -->|upload| Crowdin+ LocalePo ==>|build-translation-resources| Autofix+```++## Extraction++_Source code → `locales/metabase.po`_++### Building the backend pot fileBuilding the backend pot file can be done from the command line (from the project root directory):@@ -13,7 +65,7 @@ Grouped into 1313 distinct pot entriesThis is called from `update-translation-template` which builds frontend, backend, and automagic dashboard pot files and then merges them into one artifact with `msgcat`.-##### Developer information+#### Developer informationWe use a custom script to build up our backend pot (po template) file. Start a repl from this folder and the work is done in the `src/i18n/enumerate.clj` file.@@ -82,7 +134,7 @@ msgid "Not something with an ID: {0}"msgstr ""```-###### Overrides+##### OverridesYou'll note that we defined a single file `"/src/metabase/util.clj"` but ended up with an entry from `fingerprinters.clj`. This is because that usage of `trs` is inside of a macro which emits a defrecord. The quoting means that the form doesn't actually match our spec since it has more sequence stuff:@@ -92,3 +144,186 @@ user=> '`(trs "foobar")```More information in the [grasp issue](https://github.com/borkdude/grasp/issues/28). A quick workaround is just including this manual override.++## Artifact generation++_`locales/*.po` → `resources/i18n/*.edn` + `resources/frontend_client/app/locales/*.json`_++Once translators have filled in `locales/<locale>.po` through Crowdin, the build pipeline turns+those into the runtime artifacts that Metabase actually ships:++- **Backend**: `resources/i18n/<locale>.edn` — consumed by `metabase.util.i18n.impl/translate` via+ `java.text.MessageFormat`.+- **Frontend**: `resources/frontend_client/app/locales/<locale>.json` — consumed by+ [ttag](https://ttag.js.org/) in the browser.++Run the whole pipeline locally with:++```shell+❯ ./bin/i18n/build-translation-resources+```++This calls `clojure -X:build:build/i18n`, which invokes+`i18n.create-artifacts/create-all-artifacts!`. For each locale:++1. Parse the `.po` file via `i18n.common/po-contents` (jgettext).+2. Run the [autofix pass](#autofix-pass) via `i18n.autofix/autofix-po-contents` to silently correct+ translator mistakes that can be unambiguously repaired (currently: unescaped apostrophes for+ backend strings).+3. Run the scanner `i18n.validation/invalid-messages-in-po` on the post-autofix contents to produce+ a seq of violation maps for every `msgstr` that *still* fails validation — see+ [violations report](#violations-report) below.+4. Derive a drop-set of msgids using `i18n.validation/drop-from-build?` (see+ [drop policy](#drop-policy)) and pass it, along with the post-autofix `po-contents`, to both+ backend and frontend artifact writers. The writers skip any message in the drop-set — the+ runtime falls back to English for those msgids.+5. After all locales finish, aggregate violations across every locale and write+ `target/i18n-violations.csv` and `target/i18n-violations.edn`.++The source of truth for this pipeline lives in `bin/build/src/i18n/`:++- `autofix.clj` — pre-validation fixes (e.g. apostrophe escaping).+- `validation.clj` — the scanner + drop policy.+- `create_artifacts.clj` — orchestrator + report writer.+- `create_artifacts/backend.clj` — backend `.edn` writer.+- `create_artifacts/frontend.clj` — frontend `.json` writer.+- `common.clj` — `.po` parser and shared helpers (`backend-message?`, `po-contents`).++### Autofix pass++Runs once per locale, *before* validation, on the parsed `po-contents`. Its job is to silently+correct translator mistakes that can be unambiguously repaired — making translations that would+otherwise fail the scanner ship correctly. Both the scanner and the artifact writers consume the+post-autofix contents, so they agree on what's being shipped.++Current autofixes (all backend-only — frontend `msgstr` values pass through unchanged because+ttag has different escaping rules):++- **Apostrophe escaping.** Word-adjacent single apostrophes (e.g. Catalan `d'aquí`, English+ `It's`) are doubled to `''` so `java.text.MessageFormat` treats them as literal characters+ instead of escape delimiters. Apostrophes that are already doubled, or that sit next to `{` /+ `}` (i.e. intentional MessageFormat escapes like `'{0}'`), pass through untouched.++This is handled *before* the scanner, so translations that only had apostrophe typos never reach+the violations report. If you ever see `d'aquí`-style entries in the report, it means autofix+couldn't reach them (likely a non-backend context) and you'd need to fix them in Crowdin.++Extending the autofix layer: add additional transformations to `i18n.autofix/autofix-po-contents`+only when the fix is (a) deterministic, (b) semantically neutral (rendered output unchanged), and+(c) covers a common translator mistake. Everything else should surface in the violations report+instead.++### Drop policy++`drop-from-build?` only returns `true` for violations whose translations would throw at runtime+and trigger English fallback anyway — i.e. `:invalid-message-format`. `:skipped-arg-index` and+`:arg-count-mismatch` render imperfectly but don't throw; we keep them so users see mostly-+localized text rather than regress to full English fallback.++## Violations report++_`target/i18n-violations.csv`_++Every artifact-generation run emits a report of violations found, in two forms:++- `target/i18n-violations.csv` — one row per violation, RFC 4180-compliant, openable in any+ spreadsheet app. This is the file that gets uploaded as the `i18n-violations` artifact in CI.+- `target/i18n-violations.edn` — same data as a vector of Clojure maps, for programmatic use.++In CI, [`.github/workflows/i18n.yml`](../../.github/workflows/i18n.yml) and+[`.github/workflows/translation-update.yml`](../../.github/workflows/translation-update.yml)+upload the artifact. The auto-generated translation-update PR gets a summary comment with+per-type counts and a direct link to the artifact.++### Columns++| Column | Meaning |+|-----------------|---------|+| `locale` | The locale the violation was found in (e.g. `fr`, `de`, `pt-BR`, `ar-SA`). |+| `types` | The set of violation types for this row, joined with `+` (e.g. `skipped-arg-index+arg-count-mismatch`). See [violation types](#violation-types) below. |+| `dropped` | `true` if this translation was **excluded** from the built `.edn`/`.json` artifact (runtime will fall back to English). `false` if it was kept in the artifact despite imperfection (runtime renders with the issue visible). |+| `backend` | `true` if the msgid originates from Clojure source (`.clj` / `.cljc`), `false` if from frontend source (`.ts` / `.tsx` / `.js` / `.jsx`). This determines which format-system rules were applied. |+| `plural_index` | For singular (non-plural) strings this is empty. For plural strings it's the index of the affected form (`0`, `1`, …) within the locale's `msgstr[N]` array. |+| `msgid` | The English singular source string — the key translators see in Crowdin. |+| `msgid_plural` | The English plural form, if the string has one. Empty for non-plural strings. |+| `msgstr` | The translated string that failed validation — the actual text the translator produced. |+| `error` | Populated only for `invalid-message-format` rows — the `java.text.MessageFormat` exception message (e.g. `Unmatched braces in the pattern.`). Empty for other types. |+| `expected_args` | For `arg-count-mismatch` rows: the acceptable placeholder count(s), derived from `msgid` and `msgid_plural`. Comma-separated (e.g. `0,1` for a plural where singular has 0 placeholders and plural has 1). |+| `actual_args` | For `arg-count-mismatch` rows: the number of distinct placeholder indices actually used in `msgstr`. |+| `source_refs` | Space-separated `path:line` pointers back to the source code where this msgid is used. |++### Violation types++Three types can appear in the `types` column. A single row may list multiple (separated by `+`)+when they fire together.++#### `invalid-message-format`++The `msgstr` isn't a valid `java.text.MessageFormat` pattern — the constructor throws+`IllegalArgumentException`. Typical causes:++- Unmatched braces (`{0` or `{{...}}` without proper escaping).+- Named placeholders like `{login}` that Java MessageFormat can't parse (it expects numeric indices).++These rows always have `dropped=true`. At runtime, `MessageFormat`'s constructor would throw,+triggering the runtime's try/catch and falling back to English anyway — so the build pre-empts+it and guarantees a clean `.edn` artifact.++**Action for translators:** Fix the `msgstr` in Crowdin. Usually means matching the English+string's escaping conventions (double-apostrophes for literal `'`, matched braces, etc.).++#### `skipped-arg-index`++The translated string's `{N}` placeholders reference non-contiguous indices (e.g. `{0}` and+`{2}` but no `{1}`), or use the same index multiple times in a way that produces a gap. At+runtime, missing indices render literally (`{2}` appears as the four characters `{2}` in the+output).++These rows have `dropped=false` — the translation is kept in the artifact. The user sees mostly-+localized text with a literal `{N}` glitch, rather than full English fallback.++**Action for translators:** Fix the `msgstr` so all placeholders are contiguous (`{0}`, `{1}`,+`{2}`, …).++#### `arg-count-mismatch`++The translated string's placeholder count doesn't match any acceptable count from the English+source forms. `expected_args` is the set of acceptable counts (singular's count and plural's+count, if applicable); `actual_args` is what the translation has.++These rows have `dropped=false`. At runtime, missing placeholders render as literal text (`{0}`+shows up verbatim), or extra caller-supplied args get silently dropped.++Common cause: the translator added an extra `{0}` (e.g. for pluralization) when English didn't+have one, or omitted a `{0}` that English required.++> **Note:** Romance-language apostrophe mistakes (e.g. Catalan `d'aquí` swallowing a trailing+> `{0}` in MessageFormat's escape semantics) would have triggered this violation. The+> [autofix pass](#autofix-pass) handles them upstream, so they shouldn't appear in the+> report. The mistakes would still be present in Crowdin though.++**Action for translators:** Match the English source's placeholder count. If the source has+`{0}` and `{1}`, the translation must too — or the plural form of the source, which might have+a different count.++### How to use the report++1. **Sort by `locale`** to see per-language issues — often one translator has a systematic+ problem (e.g. Catalan translators consistently forget to double apostrophes).+2. **Filter `dropped=true`** to see what's silently falling back to English — these are the most+ user-visible regressions for locale users.+3. **Filter `types=invalid-message-format`** if you're triaging Crowdin bugs — these are always+ the highest-priority fixes.+4. **Use `source_refs`** to understand which UI the violation affects, and whether it's a high-+ traffic string or rare edge case.++Each row has enough info to find the string in Crowdin: the `msgid` is the source key, `locale`+tells you which language to open.++### Runtime behavior summary++| Violation type | Build-time action | Runtime behavior |+|--------------------------|------------------------|------------------|+| `invalid-message-format` | Dropped from artifact | English fallback |+| `skipped-arg-index` | Kept in artifact | Localized text with literal `{N}` for missing indices |+| `arg-count-mismatch` | Kept in artifact | Localized text with literal `{N}` for missing placeholders, or extra args silently dropped |diff --git a/src/metabase/util/i18n.clj b/src/metabase/util/i18n.cljindex 34fdadb6c55..4049c536380 100644--- a/src/metabase/util/i18n.clj+++ b/src/metabase/util/i18n.clj@@ -5,6 +5,7 @@[clojure.walk :as walk][metabase.util.i18n.common :as i18n.common][metabase.util.i18n.impl :as i18n.impl]+ [metabase.util.i18n.validation :as i18n.validation][metabase.util.json :as json][metabase.util.log :as log][net.cgrand.macrovich :as macros]@@ -164,10 +165,10 @@message-format (MessageFormat. format-string);; number of {n} placeholders in format string including any you may have skipped. e.g. "{0} {2}" -> 3expected-num-args-by-index (count (.getFormatsByArgumentIndex message-format))- ;; number of {n} placeholders in format string *not* including ones you make have skipped. e.g. "{0} {2}" -> 2+ ;; number of {n} placeholders in format string *not* including ones you may have skipped. e.g. "{0} {2}" -> 2expected-num-args (count (.getFormats message-format))actual-num-args (count args)]- (assert (= expected-num-args expected-num-args-by-index)+ (assert (not (i18n.validation/skipped-arg-index? format-string))(format "(deferred-)trs/tru with format string %s is missing some {} placeholders. Expected %s. Did you skip any?"(pr-str (.toPattern message-format))(str/join ", " (map (partial format "{%d}") (range expected-num-args-by-index)))))diff --git a/src/metabase/util/i18n/validation.clj b/src/metabase/util/i18n/validation.cljnew file mode 100644index 00000000000..acb2d44a9ad--- /dev/null+++ b/src/metabase/util/i18n/validation.clj@@ -0,0 +1,138 @@+(ns metabase.util.i18n.validation+ "Pure helpers for validating `java.text.MessageFormat` patterns. These primitives are shared by+ three callers:++ - `metabase.util.i18n/validate-number-of-args` — macro-expansion-time check on `(deferred-tru+ …)` / `(deferred-trs …)` call sites in our own Clojure code.+ - `i18n.validation` (in `bin/build/src`) — build-time `.po`-file scanner that catches broken+ Crowdin translations before they ship.+ - `metabase.util.i18n.validation-test` — regression guard on the built `.edn` artifacts.++ Kept free of jgettext and other build-only deps so all three layers can require it."+ (:import+ (java.text MessageFormat)))++(set! *warn-on-reflection* true)++(defn message-format-error+ "If `s` is not a valid `java.text.MessageFormat` pattern, return the underlying+ `IllegalArgumentException` message. Returns `nil` for valid patterns, and also for `nil` input+ (there's no pattern to validate)."+ [^String s]+ (when (some? s)+ (try+ (MessageFormat. s)+ nil+ (catch IllegalArgumentException e (.getMessage e)))))++(defn valid-message-format?+ "True if `s` parses as a valid `java.text.MessageFormat` pattern."+ [^String s]+ (nil? (message-format-error s)))++(defn message-format-arg-count+ "Count of distinct argument indices referenced by `s` (e.g. `{0} {0} {1}` → 2). Returns `nil` if+ `s` is not a valid MessageFormat pattern, or if `s` is `nil`."+ [^String s]+ (when (some? s)+ (try+ (count (.getFormatsByArgumentIndex (MessageFormat. s)))+ (catch IllegalArgumentException _ nil))))++(defn skipped-arg-index?+ "True if `s` is a valid MessageFormat that references a non-contiguous set of argument indices —+ e.g. `\"{0} {2}\"` skips `{1}`. Returns `false` for valid strings with no skip and for invalid+ ones (use `valid-message-format?` for that).++ Why we care: at runtime the caller passes args for indices `0..N`. A skipped `{2}` in `\"{0}+ {2}\"` either renders literally as `{2}` (if caller passes 2 args) or silently inflates the+ expected arg count past what callers supply. Both are bugs.++ This is the same check `metabase.util.i18n/validate-number-of-args` enforces against developer+ call sites at macro-expansion time; centralizing it here lets the build-time `.po` scanner reuse+ the exact same primitive against translated strings."+ [^String s]+ (when (some? s)+ (try+ (let [mf (MessageFormat. s)]+ (not= (count (.getFormats mf))+ (count (.getFormatsByArgumentIndex mf))))+ (catch IllegalArgumentException _ false))))++;;; -------------------------------------------------- Regex-based helpers --------------------------------------------------+;; For frontend strings (`#, javascript-format` in the `.po`), `MessageFormat` is the wrong parser+;; — it treats apostrophes as escape characters and doesn't know about JS's format system. These+;; regex-based helpers scan for `{N}` patterns directly, which matches what ttag actually does on+;; the JS side.+;;+;; For backend strings, continue using the `MessageFormat`-based helpers above — they're the+;; authoritative parser the runtime uses. Regex would diverge on: (a) `'{0}'` is literal in+;; MessageFormat but regex sees an arg; (b) `{0,number,integer}` has a format specifier regex misses.++(defn regex-arg-indices+ "Set of integer argument indices found by scanning for `{N}` patterns via regex. Format-system-+ agnostic — works for Java MessageFormat strings, JS ttag strings, or anything that uses `{0}`+ positional placeholders."+ [^String s]+ (when (some? s)+ (into (sorted-set) (map #(parse-long (second %))) (re-seq #"\{(\d+)\}" s))))++(defn regex-arg-count+ "Count of distinct `{N}` indices in `s` via regex. Returns `nil` for `nil` input (matching the+ nil-contract of `message-format-arg-count`), 0 for strings with no placeholders."+ [^String s]+ (when (some? s)+ (count (regex-arg-indices s))))++(defn regex-skipped-arg-index?+ "True if `s` has `{N}` placeholders with non-contiguous indices (e.g. `\"{0} {2}\"` skips+ `{1}`). Uses regex, so works for both backend and frontend strings without `MessageFormat`+ parsing."+ [^String s]+ (let [indices (regex-arg-indices s)]+ (and (seq indices)+ (not= (count indices) (inc (apply max indices))))))++;;; -------------------------------------------------- Cross-string checks -------------------------------------------------++(defn- normalize-acceptable-counts+ "Coerce `acceptable-counts` — either a single number or a seqable of numbers — into a sorted set,+ dropping nils."+ [acceptable-counts]+ (into (sorted-set)+ (filter some?)+ (if (number? acceptable-counts) [acceptable-counts] acceptable-counts)))++(defn arg-count-mismatch+ "If `actual-count` is not in `acceptable-counts`, return+ `{:expected-arg-counts <sorted-set> :actual-arg-count n}`. Otherwise `nil`.++ `actual-count` may be:+ - an integer (pre-computed by the caller — avoids redundant parsing)+ - a string (parsed via `message-format-arg-count` — convenience for the macro-time path)++ `acceptable-counts` may be a single number or any seqable of numbers; `nil` entries are ignored.++ Call shapes:++ ;; Macro-time — parse the format string, compare against caller's arg count:+ (arg-count-mismatch format-string (count args))++ ;; Scanner — caller already computed actual and expected via the appropriate count-fn:+ (arg-count-mismatch actual-count expected-counts)++ ## Why the translation-time call accepts a *set* rather than a single number++ Languages with >2 plural forms (Arabic nplurals=6, Russian nplurals=4, Chinese nplurals=1, …)+ have form-index-to-n mappings that don't align with English's 2-form model. A translated plural+ form's arg count is valid as long as it matches *some* English form's arg count — i.e. is in the+ set `{count(msgid), count(msgid_plural)}`. See the `Plural-Forms` header in any+ `resources/i18n/<locale>.edn` for per-locale CLDR rules."+ [actual-count acceptable-counts]+ (let [actual (if (string? actual-count)+ (message-format-arg-count actual-count)+ actual-count)+ accepted (normalize-acceptable-counts acceptable-counts)]+ (when (and actual (seq accepted) (not (contains? accepted actual)))+ {:expected-arg-counts accepted+ :actual-arg-count actual})))diff --git a/test/metabase/util/i18n/validation_test.clj b/test/metabase/util/i18n/validation_test.cljnew file mode 100644index 00000000000..1c1973ef89f--- /dev/null+++ b/test/metabase/util/i18n/validation_test.clj@@ -0,0 +1,167 @@+(ns metabase.util.i18n.validation-test+ "Regression guard on the built `resources/i18n/*.edn` artifacts. The build pipeline+ (`bin/build/src/i18n/create_artifacts/backend.clj`) filters invalid translations out before+ writing the `.edn`, with a violation report at `target/i18n-violations.csv`. This test asserts+ the filter is doing its job — no shipped translation should fail any of the+ `metabase.util.i18n.validation` predicates.++ When `.edn` files are absent (fresh checkout, no build run), the test no-ops. The CI `i18n`+ workflow runs `./bin/i18n/build-translation-resources` before invoking it."+ (:require+ [clojure.java.io :as io]+ [clojure.test :refer :all]+ [clojure.tools.reader.edn :as edn]+ [metabase.util.i18n.impl :as i18n.impl]+ [metabase.util.i18n.validation :as validation]))++(set! *warn-on-reflection* true)++;;; ------------------------------------------------ Unit tests for predicates ------------------------------------------------++(deftest ^:parallel message-format-error-test+ (are [s expected] (= expected (some? (validation/message-format-error s)))+ "Hello {0}" false+ "Hello" false+ "" false+ "{0} and {1}" false+ "It''s {0}" false ; escaped apostrophe+ "Bad {0 unclosed" true ; missing closing brace+ "Bad {x} named" true ; non-numeric placeholder+ "Extra { brace" true) ; bare opening brace+ (testing "nil input returns nil (no error)"+ (is (nil? (validation/message-format-error nil)))))++(deftest ^:parallel valid-message-format?-test+ (are [s expected] (= expected (validation/valid-message-format? s))+ "Hello {0}" true+ "{0} and {1}" true+ "It''s {0}" true+ "no placeholders" true+ "" true+ "Bad {0 unclosed" false+ "Extra { brace" false))++(deftest ^:parallel message-format-arg-count-test+ (are [s expected] (= expected (validation/message-format-arg-count s))+ "Hello" 0+ "{0}" 1+ "{0} and {1}" 2+ "{0} and {0} again" 1 ; duplicate index counts once+ "{0,number,integer}" 1 ; format specifier still counts+ "It''s {0}" 1 ; escaped apostrophe, arg still visible+ "'{0}'" 0 ; apostrophe-escaped braces = literal, no arg+ "" 0+ nil nil ; nil in, nil out+ "Bad { brace" nil)) ; invalid pattern returns nil++(deftest ^:parallel skipped-arg-index?-test+ (are [s expected] (= expected (validation/skipped-arg-index? s))+ "{0} {2}" true ; skips {1}+ "{1}" true ; skips {0}+ "{0} {0}" true ; getFormats=2 vs getFormatsByArgumentIndex=1+ "{0} {1}" false+ "{0}" false+ "no args" false+ "" false+ nil nil ; nil passthrough+ "Bad { brace" false)) ; invalid pattern returns false++(deftest ^:parallel regex-arg-indices-test+ (are [s expected] (= expected (validation/regex-arg-indices s))+ "{0} foo {1}" #{0 1}+ "{0} and {0}" #{0} ; deduped+ "{0} {2}" #{0 2}+ "no args" #{}+ "" #{}+ "{0,number,integer}" #{} ; regex doesn't match format specifiers+ "you're {0}" #{0} ; apostrophe is not special for regex+ nil nil))++(deftest ^:parallel regex-arg-count-test+ (are [s expected] (= expected (validation/regex-arg-count s))+ "{0} foo {1}" 2+ "{0} and {0}" 1+ "no args" 0+ "" 0+ nil nil ; nil in, nil out (matches message-format-arg-count contract)+ "you're {0}" 1))++(deftest ^:parallel regex-skipped-arg-index?-test+ (are [s expected] (= expected (validation/regex-skipped-arg-index? s))+ "{0} {2}" true ; skips {1}+ "{1}" true ; skips {0}+ "{0} {1}" false+ "{0}" false+ "no args" nil ; no indices → (and (seq #{}) ...) → nil+ "" nil+ nil nil))++(deftest ^:parallel arg-count-mismatch-test+ (testing "string input (macro-time path — parses format string)"+ (is (nil? (validation/arg-count-mismatch "{0} {1}" 2))+ "matching count returns nil")+ (is (= {:expected-arg-counts #{2} :actual-arg-count 1}+ (validation/arg-count-mismatch "{0}" 2))+ "fewer args than expected")+ (is (= {:expected-arg-counts #{1} :actual-arg-count 2}+ (validation/arg-count-mismatch "{0} {1}" 1))+ "more args than expected"))+ (testing "integer input (scanner path — pre-computed count)"+ (is (nil? (validation/arg-count-mismatch 2 #{1 2}))+ "actual in acceptable set")+ (is (some? (validation/arg-count-mismatch 3 #{0 1}))+ "actual not in acceptable set"))+ (testing "set-based acceptable counts (plural forms)"+ (is (nil? (validation/arg-count-mismatch 0 [0 1]))+ "0 args matches msgid count")+ (is (nil? (validation/arg-count-mismatch 1 [0 1]))+ "1 arg matches msgid_plural count")+ (is (some? (validation/arg-count-mismatch 2 [0 1]))+ "2 args matches neither"))+ (testing "nil handling"+ (is (nil? (validation/arg-count-mismatch nil 2))+ "nil actual → no mismatch")+ (is (nil? (validation/arg-count-mismatch 1 [nil]))+ "all-nil acceptable → no mismatch")))++(deftest ^:parallel regex-vs-message-format-divergence-test+ (testing "apostrophe escaping — regex sees arg, MessageFormat doesn't"+ (is (= 0 (validation/message-format-arg-count "'{0}'"))+ "MessageFormat: '{0}' is literal")+ (is (= 1 (validation/regex-arg-count "'{0}'"))+ "regex: sees {0} regardless of quotes"))+ (testing "format specifiers — MessageFormat sees arg, regex doesn't"+ (is (= 1 (validation/message-format-arg-count "{0,number,integer}"))+ "MessageFormat: parses format specifier")+ (is (= 0 (validation/regex-arg-count "{0,number,integer}"))+ "regex: doesn't match {0,number,integer}")))++;;; ------------------------------------------- Integration test on built .edn files -------------------------------------------++(defn- locale-resource ^java.net.URL [locale-name]+ (io/resource (format "i18n/%s.edn" locale-name)))++(defn- translated-forms+ "Normalize a translation value into a seq of form-strings. Plural entries are vectors; we drop+ non-string elements defensively so a missing plural form doesn't NPE inside MessageFormat."+ [translated]+ (if (string? translated)+ [translated]+ (filter string? translated)))++(deftest ^:parallel translations-are-valid-message-format-test+ (testing "Every translated string in resources/i18n/*.edn is a valid MessageFormat pattern"+ ;; Only MessageFormat validity is asserted here. Skipped indices and arg-count mismatches are+ ;; intentionally allowed in the build output — they render imperfectly at runtime but don't+ ;; throw, so dropping them would cause an unnecessary regression to full English fallback.+ ;; See `bin/build/src/i18n/validation.clj` `drop-from-build?`.+ (doseq [locale-name (i18n.impl/available-locale-names)+ :let [resource (locale-resource locale-name)]+ :when resource+ :let [messages (-> resource slurp edn/read-string :messages)]+ [english translated] messages+ t (translated-forms translated)]+ (testing (format "locale %s, source %s, translated %s" locale-name (pr-str english) (pr-str t))+ (is (validation/valid-message-format? t)+ (format "Translated string is not a valid java.text.MessageFormat pattern — the build filter should have dropped it. Inspect target/i18n-violations.csv. msgid=%s locale=%s"+ (pr-str english) locale-name))))))