A missing Dutch string should fail the build on the machine that introduced the English one. A catalog entry Xcode has marked stale should fail it too. So should a %d that survived in English and disappeared in French. I would rather see that in the build log than as a raw key, or a crash, on a phone in another language. And yes, this is another little gem from iOS app I work on at Dawn Technology.
UI copy lives in string catalogs. A Settings bundle still uses .strings files, because Apple does not take a catalog there. English is the source. The sample below requires nl, de, and fr as well. Add any other locale you ship by putting it in projectLocales. The check runs on every local build and on Xcode Cloud, because it is a Run Script phase on the app target, not a step that exists only in CI.
The phase is named Check Translations. It is marked always out of date, so Xcode does not decide the phase has nothing to do and skip it. The script is one line:
sh "${SRCROOT}/check_translations.sh"
Put check_translations.sh and check_translations.swift at the repository root. Both files are at the end of this post. The same command works from a terminal. The shell wrapper compiles the Swift file as a small Mac tool and caches the binary on a hash of the source. That compilation has a trap: an iOS target's script phase exports SDKROOT as the iPhoneOS SDK, and swiftc will try to build your Mac tool for iOS if you let it. I wrote that up in Swift scripts for Xcode and Xcode Cloud. This post is about what the checker treats as a broken string, and the program that does it.
Three constants at the top of the Swift file are the ones you change:
private let projectLocales = ["en", "nl", "de", "fr"]
private let sourceLocale = "en"
private let requiredCatalogNames: Set<String> = [
"Localizable.xcstrings",
"InfoPlist.xcstrings"
]
private let appCatalogRelativePath = "App/Localizable.xcstrings"
appCatalogRelativePath is the catalog --export-en reads, and the catalog a .localized() call uses when no nearer Localizable.xcstrings exists. Point it at yours.
A failing check writes to standard error in the shape Xcode already understands:
/path/to/Localizable.xcstrings:1: error: missing nl translation for key "Sign in" (en: "Sign in")
error: fails the build. warning: turns the line yellow and lets the build continue. The path is absolute, so the issue navigator can open the file.
Be precise about the line number. A .strings file is text, and the checker remembers the line of each "key" = "value"; match. A string catalog is JSON. The checker decodes it and, for almost every catalog diagnostic, reports line 1. The one exception is an empty key, where it searches the file text for the encoded key and counts newlines. I would rather the message name the key and the locale than pretend the JSON decoder kept a source location it never had.
The checker walks the repository. It skips .git, DerivedData, BuildTools, SwiftGen, ci_scripts, and any directory whose name ends in Tests. What it keeps is every .xcstrings catalog and every .strings file that lives in a locale.lproj directory.
A catalog is decoded as JSON. sourceLanguage wins. In the sample that is en. Each key has localizations, and each localization has a stringUnit with a state and a value. A unit whose state is new or stale is treated as absent:
private func localizationValue(_ localization: CatalogLocalization) -> String? {
guard let unit = localization.stringUnit else { return nil }
if unit.state == "new" || unit.state == "stale" { return nil }
return unit.value
}
Xcode marks a string stale when the English value changed and the translation was not updated. I want that to fail as a missing translation. Shipping the previous Dutch sentence under a new English meaning is a worse bug than an empty gap, and it is harder to spot in review.
An empty value, or a value that is only whitespace, is its own error. The locale has an entry. The entry does not say anything.
.strings files are grouped by path with the locale folder stripped, so Settings.bundle/nl.lproj/Root.strings and Settings.bundle/de.lproj/Root.strings are one table. A Settings bundle often has no en.lproj, because the English titles live in Root.plist. The checker never opens that plist. If a table has no English file, the locale with the most keys becomes the source, and the other files in the group are compared to it. A key missing from one of those files fails the build. A locale folder that was never created does not, because the required-locale list is not applied to .strings groups.
That list applies when the catalog's filename is in requiredCatalogNames. A widget or app extension that has its own Localizable.xcstrings is included, because the filename matches. A catalog with any other filename is still checked for internal consistency. It is not required to contain every shipping locale. Add AppShortcuts.xcstrings to the set if you ship App Shortcut phrases and want the same rule there.
For every locale that is not the source:
new and stale entries are dropped, is an error. The message includes the English value, so you can see which string the translation has to cover..strings file is an error.That split is the policy. A translator can leave an obsolete key behind. They cannot ship a build where English gained a key and Dutch never received it. A stale Dutch entry fails with the missing-translation message, not with a message that says stale. The state is how the catalog told the checker to ignore the old value.
If a catalog has no translations at all, that is an error too. If the whole tree contains no catalogs and no .strings groups, the checker fails rather than reporting a pass on an empty search.
A translation that drops a format token does not fail to compile. It crashes later, in a language you are probably not reading while you look at the crash. The checker pulls tokens out of the English value and out of the translation and compares them.
The pattern covers printf tokens and named tokens. %@, %d, %1$@, width and precision, and ${name} all count. The two lists are sorted before they are compared. Order may differ. Counts may not. A French string that swaps two %@ placeholders still passes, because the checker cannot know which word was supposed to receive which value. A string that drops one %d does not pass. The log names the key, the source locale, and both token lists.
The decoder only reads stringUnit. A key that exists only as a plural variations block would look missing, or would not be seen at all if every locale stored it that way. Extend CatalogLocalization if you ship plurals.
.localized() call has to name a real keyAfter the tables, the checker scans Swift for string literals used as "…" .localized(. The catalog is the list of keys that call is allowed to ask for.
The catalog for a call is the nearest Localizable.xcstrings, walking up from the Swift file toward the repo root. An extension that keeps its catalog next to its sources is checked against that file. Every other call uses appCatalogRelativePath. InfoPlist.xcstrings is completeness-checked, and it is not the lookup catalog for this call. A string that exists only there, and is then passed to .localized(), fails the build. That call would not find it at runtime either.
An interpolated literal is a warning:
interpolated .localized() string cannot be matched to a catalog key
The key depends on a value the checker cannot see. An empty literal is ignored. The checker skips its own source file, so the patterns in the program are not keys.
String(localized:) and strings that exist only in a storyboard are outside this scan. If a call site uses a different API, this program will not notice a typo in it.
SwiftGen still generates L10n from an English .strings file. I did not want a second parser for that export. Call the checker before SwiftGen:
sh "${SRCROOT}/check_translations.sh" --export-en "${DERIVED}/Localizable.strings"
--export-en reads the catalog at appCatalogRelativePath, writes the English pairs, and returns. It does not run the check. The check is the earlier build phase. A red catalog fails there, and the SwiftGen phase does not run.
The export is not a dump of every English key. SwiftGen's pretty identifier turns different catalog keys into one Swift member. Email and Email: both want email. connected and Connected both want connected. Two members with the same name will not compile, so the export keeps one key per generated path and leaves the others in the catalog. .localized() can still find the key that was left out. L10n only gets the one that was kept.
When several keys collapse to the same path, the winner is chosen in this order:
% beats a key that does not.Email stays. Email: is skipped.Connected stays. connected is skipped.The log line names the destination and the number of collisions it skipped. Those skipped keys are still in the catalog. They are still checked against every shipping locale. They are still valid arguments to .localized(). They do not get an L10n member.
Check Translations should be the first build phase, before Sources. If SwiftGen runs after Sources, the Strings.swift already in the tree is what this build compiles, and the file SwiftGen just rewrote is what the next build compiles.
From the repo root, after you have pointed appCatalogRelativePath at your catalog:
sh check_translations.sh
English in the catalog is the list of strings the app is allowed to show. Every shipping locale has to cover that list, with the same placeholders, and a new or stale entry does not count as coverage. A "…" .localized() call has to name a key in the catalog next to that call. SwiftGen sees that English list after collisions are removed.
Save this next to the Swift file. chmod +x is optional. The build phase calls it with sh.
#!/bin/sh
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
SCRIPT="${SCRIPT_DIR}/check_translations.swift"
export SRCROOT="${SRCROOT:-${SCRIPT_DIR}}"
if ! xcrun --sdk macosx --find swiftc >/dev/null 2>&1; then
echo "error: swiftc is required to check translations" >&2
exit 1
fi
# Xcode iOS script phases export SDKROOT=iPhoneOS. Compile this host tool against macOS.
MACOSX_SDK="$(xcrun --sdk macosx --show-sdk-path)"
CACHE_DIR="${DERIVED_FILE_DIR:-${TMPDIR:-/tmp}/check-translations}"
mkdir -p "${CACHE_DIR}"
STAMP="$(md5 -q "${SCRIPT}")"
BIN="${CACHE_DIR}/check_translations-${STAMP}"
if [ ! -x "${BIN}" ]; then
find "${CACHE_DIR}" -maxdepth 1 -name 'check_translations-*' -delete 2>/dev/null || true
xcrun --sdk macosx swiftc \
-sdk "${MACOSX_SDK}" \
-target "$(uname -m)-apple-macosx14.0" \
-module-name CheckTranslations \
-o "${BIN}" \
"${SCRIPT}"
fi
"${BIN}" "$@"
This is the whole program. Change the four constants at the top, then run it.
#!/usr/bin/env swift
import Foundation
/// Fail the build when translations are missing or placeholders do not match.
///
/// Change `projectLocales` to the locales you ship. `en` is the source.
/// Catalogs whose filename is in `requiredCatalogNames` must contain every locale.
/// Other catalogs are still compared internally.
/// `--export-en <path>` writes the English strings of `appCatalogRelativePath`
/// for SwiftGen, dropping keys that would generate the same Swift identifier.
private let projectLocales = ["en", "nl", "de", "fr"]
private let sourceLocale = "en"
private let requiredCatalogNames: Set<String> = [
"Localizable.xcstrings",
"InfoPlist.xcstrings"
]
private let appCatalogRelativePath = "App/Localizable.xcstrings"
private let skipDirectoryNames: Set<String> = [
".git", ".build", ".derived", ".swiftpm", "DerivedData", "Pods", "build",
"BuildTools", "SwiftGen", "ci_scripts"
]
private struct Issue {
let url: URL
let line: Int
let level: String
let message: String
var formatted: String {
"\(url.path):\(line): \(level): \(message)"
}
}
private struct CatalogFile: Decodable {
let sourceLanguage: String?
let strings: [String: CatalogEntry]?
}
private struct CatalogEntry: Decodable {
let localizations: [String: CatalogLocalization]?
}
private struct CatalogLocalization: Decodable {
let stringUnit: CatalogStringUnit?
}
private struct CatalogStringUnit: Decodable {
let state: String?
let value: String?
}
private typealias LocaleTable = [String: (value: String, line: Int)]
private let stringsEntryRegex = try! NSRegularExpression(
pattern: #""((?:\\.|[^"\\])*)"\s*=\s*"((?:\\.|[^"\\])*)"\s*;"#,
options: [.dotMatchesLineSeparators]
)
private let formatTokenRegex = try! NSRegularExpression(
pattern: #"%(?:[1-9]\d*\$)?(?:[-#0 +])*(?:\d+|\*)?(?:\.(?:\d+|\*))?(?:hh|h|ll|l|L|z|j|t)?[@%aAdDiIoOuUxXfFeEgGcCsSpn]|\$\{[^}]+\}"#
)
private let localeDirectoryRegex = try! NSRegularExpression(
pattern: #"(?:^|/)([a-z]{2}(?:-[A-Z]{2})?)\.lproj/"#
)
private let localizedLiteralRegex = try! NSRegularExpression(
pattern: #""((?:\\.|[^"\\])*)"\s*\.localized\s*\("#
)
private func eprint(_ message: String) {
FileHandle.standardError.write(Data((message + "\n").utf8))
}
private func repoRoot() -> URL {
if let srcroot = ProcessInfo.processInfo.environment["SRCROOT"] {
return URL(fileURLWithPath: srcroot)
}
let script = URL(fileURLWithPath: CommandLine.arguments[0]).standardizedFileURL
return script.deletingLastPathComponent()
}
private func readText(from url: URL) throws -> String {
let data = try Data(contentsOf: url)
if data.starts(with: [0xFF, 0xFE]) || data.starts(with: [0xFE, 0xFF]) {
guard let text = String(data: data, encoding: .utf16) else {
throw CocoaError(.fileReadInapplicableStringEncoding)
}
return text
}
if data.starts(with: [0xEF, 0xBB, 0xBF]), let text = String(data: data, encoding: .utf8) {
return text
}
guard let text = String(data: data, encoding: .utf8) else {
throw CocoaError(.fileReadInapplicableStringEncoding)
}
return text
}
private func unescapeStringsValue(_ value: String) -> String {
var output = ""
var index = value.startIndex
while index < value.endIndex {
let character = value[index]
let next = value.index(after: index)
if character == "\\" && next < value.endIndex {
let escaped = value[next]
switch escaped {
case "n": output.append("\n")
case "r": output.append("\r")
case "t": output.append("\t")
case "\"": output.append("\"")
case "\\": output.append("\\")
default: output.append(escaped)
}
index = value.index(after: next)
continue
}
output.append(character)
index = next
}
return output
}
private func escapeStringsValue(_ value: String) -> String {
value
.replacingOccurrences(of: "\\", with: "\\\\")
.replacingOccurrences(of: "\"", with: "\\\"")
.replacingOccurrences(of: "\n", with: "\\n")
.replacingOccurrences(of: "\r", with: "\\r")
.replacingOccurrences(of: "\t", with: "\\t")
}
private func displayKey(_ key: String) -> String {
key.replacingOccurrences(of: "\n", with: "\\n").replacingOccurrences(of: "\r", with: "\\r")
}
private func lineNumber(in text: String, utf16Offset: Int) -> Int {
let nsText = text as NSString
let clamped = min(max(utf16Offset, 0), nsText.length)
return nsText.substring(to: clamped).filter { $0 == "\n" }.count + 1
}
private func jsonEncodedKey(_ key: String) -> String? {
guard let data = try? JSONEncoder().encode(key) else { return nil }
return String(data: data, encoding: .utf8)
}
private func findKeyLine(in text: String, key: String) -> Int {
guard let needle = jsonEncodedKey(key), let range = text.range(of: needle) else {
return 1
}
return text[..<range.lowerBound].filter { $0 == "\n" }.count + 1
}
private func formatTokens(_ value: String) -> [String] {
let nsValue = value as NSString
return formatTokenRegex.matches(in: value, range: NSRange(location: 0, length: nsValue.length)).map {
nsValue.substring(with: $0.range)
}
}
private func parseStringsFile(at url: URL) -> (entries: LocaleTable, issues: [Issue]) {
let text: String
do {
text = try readText(from: url)
} catch {
return ([:], [Issue(url: url, line: 1, level: "error", message: "unable to read strings file (\(error.localizedDescription))")])
}
let nsText = text as NSString
var entries = LocaleTable()
var issues: [Issue] = []
let matches = stringsEntryRegex.matches(in: text, range: NSRange(location: 0, length: nsText.length))
for match in matches {
let key = unescapeStringsValue(nsText.substring(with: match.range(at: 1)))
let value = unescapeStringsValue(nsText.substring(with: match.range(at: 2)))
let line = lineNumber(in: text, utf16Offset: match.range.location)
if entries[key] != nil {
issues.append(Issue(url: url, line: line, level: "error", message: "duplicate key \"\(displayKey(key))\""))
continue
}
entries[key] = (value, line)
}
return (entries, issues)
}
private func localizationValue(_ localization: CatalogLocalization) -> String? {
guard let unit = localization.stringUnit else { return nil }
if unit.state == "new" || unit.state == "stale" { return nil }
return unit.value
}
private func parseCatalog(at url: URL) -> (source: String, parsed: [String: LocaleTable], issues: [Issue]) {
let text: String
let data: Data
do {
text = try readText(from: url)
data = Data(text.utf8)
} catch {
return (sourceLocale, [:], [Issue(url: url, line: 1, level: "error", message: "unable to read catalog (\(error.localizedDescription))")])
}
let catalog: CatalogFile
do {
catalog = try JSONDecoder().decode(CatalogFile.self, from: data)
} catch {
return (sourceLocale, [:], [Issue(url: url, line: 1, level: "error", message: "invalid string catalog (\(error.localizedDescription))")])
}
let source = catalog.sourceLanguage ?? sourceLocale
guard let strings = catalog.strings else {
return (source, [:], [Issue(url: url, line: 1, level: "error", message: "catalog is missing a strings dictionary")])
}
var parsed: [String: LocaleTable] = [:]
var issues: [Issue] = []
for (key, entry) in strings {
if key.isEmpty {
issues.append(Issue(url: url, line: findKeyLine(in: text, key: key), level: "error", message: "empty translation key"))
continue
}
guard let localizations = entry.localizations else { continue }
for (locale, localization) in localizations {
guard let value = localizationValue(localization) else { continue }
parsed[locale, default: [:]][key] = (value, 1)
}
}
return (source, parsed, issues)
}
private func compareLocales(
url: URL,
sourceLocale: String,
parsed: [String: LocaleTable],
requiredLocales: [String] = []
) -> (errors: [Issue], warnings: [Issue]) {
var errors: [Issue] = []
var warnings: [Issue] = []
var resolvedSource = sourceLocale
let sourceEntries: LocaleTable
if let entries = parsed[sourceLocale] {
sourceEntries = entries
} else if let richest = parsed.max(by: { $0.value.count < $1.value.count }) {
resolvedSource = richest.key
sourceEntries = richest.value
} else {
return ([Issue(url: url, line: 1, level: "error", message: "catalog has no translations")], [])
}
for locale in requiredLocales where parsed[locale] == nil {
errors.append(Issue(url: url, line: 1, level: "error", message: "missing locale \(locale) in catalog"))
}
for (locale, entries) in parsed.sorted(by: { $0.key < $1.key }) {
for (key, item) in entries where item.value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
errors.append(
Issue(
url: url,
line: item.line,
level: "error",
message: "empty translation for key \"\(displayKey(key))\" (\(locale))"
)
)
}
}
for (locale, entries) in parsed.sorted(by: { $0.key < $1.key }) {
guard locale != resolvedSource else { continue }
let missing = Set(sourceEntries.keys).subtracting(entries.keys).sorted()
let extra = Set(entries.keys).subtracting(sourceEntries.keys).sorted()
for key in missing {
let sourceValue = sourceEntries[key]?.value ?? ""
let sourceLine = sourceEntries[key]?.line ?? 1
errors.append(
Issue(
url: url,
line: sourceLine,
level: "error",
message: "missing \(locale) translation for key \"\(displayKey(key))\" (\(resolvedSource): \"\(displayKey(sourceValue))\")"
)
)
}
for key in extra {
warnings.append(
Issue(
url: url,
line: entries[key]?.line ?? 1,
level: "warning",
message: "key \"\(displayKey(key))\" exists in \(locale) but not in \(resolvedSource)"
)
)
}
for key in Set(sourceEntries.keys).intersection(entries.keys).sorted() {
let sourceTokens = formatTokens(sourceEntries[key]?.value ?? "")
let localeTokens = formatTokens(entries[key]?.value ?? "")
if sourceTokens.sorted() != localeTokens.sorted() {
errors.append(
Issue(
url: url,
line: entries[key]?.line ?? 1,
level: "error",
message: "placeholder mismatch for key \"\(displayKey(key))\": \(resolvedSource) \(sourceTokens) vs \(locale) \(localeTokens)"
)
)
}
}
}
return (errors, warnings)
}
private func collectFiles(in directory: URL, extension fileExtension: String) -> [URL] {
let fileManager = FileManager.default
guard let contents = try? fileManager.contentsOfDirectory(
at: directory,
includingPropertiesForKeys: [.isDirectoryKey],
options: [.skipsHiddenFiles]
) else {
return []
}
var files: [URL] = []
for url in contents {
let name = url.lastPathComponent
if skipDirectoryNames.contains(name) || name.hasSuffix("Tests") {
continue
}
let isDirectory = (try? url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) ?? false
if isDirectory {
files.append(contentsOf: collectFiles(in: url, extension: fileExtension))
} else if url.pathExtension == fileExtension {
files.append(url)
}
}
return files
}
private func discoverCatalogs(in root: URL) -> [URL] {
collectFiles(in: root, extension: "xcstrings").sorted { $0.path < $1.path }
}
private func discoverStringsGroups(in root: URL) -> [String: [String: URL]] {
var groups: [String: [String: URL]] = [:]
let rootPath = root.standardizedFileURL.path
for url in collectFiles(in: root, extension: "strings") {
let relative = url.path.replacingOccurrences(of: rootPath + "/", with: "")
let nsRelative = relative as NSString
let matches = localeDirectoryRegex.matches(in: relative, range: NSRange(location: 0, length: nsRelative.length))
guard let match = matches.last else { continue }
let locale = nsRelative.substring(with: match.range(at: 1))
let group = nsRelative.substring(to: match.range.location) + "/*.lproj/" + nsRelative.substring(from: NSMaxRange(match.range))
groups[group, default: [:]][locale] = url
}
return groups
}
private func catalogKeys(at url: URL) -> (keys: Set<String>, issues: [Issue]) {
let data: Data
do {
data = try Data(contentsOf: url)
} catch {
return ([], [Issue(url: url, line: 1, level: "error", message: "unable to read catalog (\(error.localizedDescription))")])
}
let catalog: CatalogFile
do {
catalog = try JSONDecoder().decode(CatalogFile.self, from: data)
} catch {
return ([], [Issue(url: url, line: 1, level: "error", message: "invalid string catalog (\(error.localizedDescription))")])
}
guard let strings = catalog.strings else {
return ([], [])
}
return (Set(strings.keys), [])
}
/// Prefer a `Localizable.xcstrings` sitting next to the call, walking up toward
/// the repo root. An extension that keeps its own catalog is then checked
/// against that catalog. Everything else uses `appCatalogRelativePath`.
private func catalogURL(forSwiftFile url: URL, root: URL) -> URL {
let rootPath = root.standardizedFileURL.path
var directory = url.deletingLastPathComponent().standardizedFileURL
while directory.path.hasPrefix(rootPath) {
let candidate = directory.appendingPathComponent("Localizable.xcstrings")
if FileManager.default.fileExists(atPath: candidate.path) {
return candidate
}
let parent = directory.deletingLastPathComponent()
if parent.path == directory.path {
break
}
directory = parent
}
return root.appendingPathComponent(appCatalogRelativePath)
}
private func checkSourceLocalizationKeys(root: URL) -> (errors: [Issue], warnings: [Issue]) {
var errors: [Issue] = []
var warnings: [Issue] = []
var keysByCatalog: [URL: Set<String>] = [:]
func keys(for catalog: URL) -> Set<String> {
if let cached = keysByCatalog[catalog] {
return cached
}
let loaded = catalogKeys(at: catalog)
errors.append(contentsOf: loaded.issues)
keysByCatalog[catalog] = loaded.keys
return loaded.keys
}
for file in collectFiles(in: root, extension: "swift") {
if file.lastPathComponent == "check_translations.swift" {
continue
}
let text: String
do {
text = try readText(from: file)
} catch {
errors.append(Issue(url: file, line: 1, level: "error", message: "unable to read Swift file (\(error.localizedDescription))"))
continue
}
let catalog = catalogURL(forSwiftFile: file, root: root)
let known = keys(for: catalog)
let nsText = text as NSString
let matches = localizedLiteralRegex.matches(in: text, range: NSRange(location: 0, length: nsText.length))
for match in matches {
let raw = nsText.substring(with: match.range(at: 1))
let line = lineNumber(in: text, utf16Offset: match.range.location)
if raw.contains("\\(") {
warnings.append(
Issue(
url: file,
line: line,
level: "warning",
message: "interpolated .localized() string cannot be matched to a catalog key"
)
)
continue
}
let key = unescapeStringsValue(raw)
if key.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
continue
}
if !known.contains(key) {
errors.append(
Issue(
url: file,
line: line,
level: "error",
message: "localized key \"\(displayKey(key))\" is missing from \(catalog.lastPathComponent)"
)
)
}
}
}
return (errors, warnings)
}
private func checkCatalog(at url: URL) -> (errors: [Issue], warnings: [Issue]) {
let (source, parsed, issues) = parseCatalog(at: url)
var errors = issues
let required = requiredCatalogNames.contains(url.lastPathComponent) ? projectLocales : []
let compared = compareLocales(url: url, sourceLocale: source, parsed: parsed, requiredLocales: required)
errors.append(contentsOf: compared.errors)
return (errors, compared.warnings)
}
private func checkStringsGroup(_ locales: [String: URL]) -> (errors: [Issue], warnings: [Issue]) {
var errors: [Issue] = []
var parsed: [String: LocaleTable] = [:]
for (locale, url) in locales.sorted(by: { $0.key < $1.key }) {
let result = parseStringsFile(at: url)
errors.append(contentsOf: result.issues)
parsed[locale] = result.entries
}
guard let firstURL = locales.values.first else {
return (errors, [])
}
let compared = compareLocales(url: firstURL, sourceLocale: sourceLocale, parsed: parsed)
errors.append(contentsOf: compared.errors)
return (errors, compared.warnings)
}
/// Approximate SwiftGen `swiftIdentifier: "pretty"` so keys that would generate
/// the same member (`Email` vs `Email:`, `connected` vs `Connected`) export once.
private func swiftGenPrettyIdentifier(_ raw: String) -> String {
var underscored = ""
for character in raw {
if character.isLetter || character.isNumber {
underscored.append(character)
} else {
underscored.append("_")
}
}
if let first = underscored.first, first.isNumber {
underscored.insert("_", at: underscored.startIndex)
}
let words = underscored.split(separator: "_", omittingEmptySubsequences: true).map { word -> String in
let text = String(word)
guard let first = text.first else { return text }
return String(first).uppercased() + text.dropFirst()
}
let camel = words.joined()
if camel.isEmpty {
return "_"
}
if raw.first?.isNumber == true, camel.first != "_" {
return "_" + camel
}
return camel
}
private func lowerFirstWord(_ identifier: String) -> String {
guard let first = identifier.first, first.isUppercase else { return identifier }
return String(first).lowercased() + identifier.dropFirst()
}
private func swiftGenIdentifierPath(_ key: String) -> String {
var parts = key.split(separator: ".", omittingEmptySubsequences: true)
.map { swiftGenPrettyIdentifier(String($0)) }
guard !parts.isEmpty else { return "_" }
parts[parts.count - 1] = lowerFirstWord(parts[parts.count - 1])
return parts.joined(separator: ".")
}
private func preferredSwiftGenKey(_ lhs: String, _ rhs: String) -> Bool {
let leftFormat = lhs.contains("%")
let rightFormat = rhs.contains("%")
if leftFormat != rightFormat {
return leftFormat && !rightFormat
}
let punctuation = CharacterSet.punctuationCharacters.union(.symbols)
let leftTrimmed = lhs.trimmingCharacters(in: punctuation)
let rightTrimmed = rhs.trimmingCharacters(in: punctuation)
if leftTrimmed.caseInsensitiveCompare(rightTrimmed) == .orderedSame, lhs.count != rhs.count {
return lhs.count < rhs.count
}
let leftUpper = lhs.filter(\.isUppercase).count
let rightUpper = rhs.filter(\.isUppercase).count
if leftUpper != rightUpper {
return leftUpper > rightUpper
}
return lhs < rhs
}
private func keysToSkipForSwiftGen(_ keys: [String]) -> Set<String> {
var byPath: [String: [String]] = [:]
for key in keys {
byPath[swiftGenIdentifierPath(key), default: []].append(key)
}
var skip: Set<String> = []
for colliding in byPath.values where colliding.count > 1 {
let chosen = colliding.sorted { preferredSwiftGenKey($0, $1) }.first!
skip.formUnion(colliding.filter { $0 != chosen })
}
return skip
}
private func exportEnglishStrings(from catalog: URL, to destination: URL) -> Int32 {
let (source, parsed, issues) = parseCatalog(at: catalog)
if !issues.isEmpty {
issues.forEach { eprint($0.formatted) }
return 1
}
let entries = parsed[source] ?? parsed[sourceLocale] ?? [:]
let skip = keysToSkipForSwiftGen(Array(entries.keys))
let directory = destination.deletingLastPathComponent()
try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
let lines = entries.keys.sorted()
.filter { !skip.contains($0) }
.map { key in
"\"\(escapeStringsValue(key))\" = \"\(escapeStringsValue(entries[key]?.value ?? ""))\";"
}
.joined(separator: "\n") + "\n"
do {
try lines.write(to: destination, atomically: true, encoding: .utf8)
} catch {
eprint("\(destination.path):1: error: unable to write exported strings (\(error.localizedDescription))")
return 1
}
print("Exported \(entries.count - skip.count) \(source) strings to \(destination.path) (skipped \(skip.count) SwiftGen identifier collision(s))")
return 0
}
private func runCheck(root: URL) -> Int32 {
let catalogs = discoverCatalogs(in: root)
let stringsGroups = discoverStringsGroups(in: root)
if catalogs.isEmpty && stringsGroups.isEmpty {
eprint("\(root.path):1: error: no localization tables found to check")
return 1
}
var errors: [Issue] = []
var warnings: [Issue] = []
for catalog in catalogs {
let result = checkCatalog(at: catalog)
errors.append(contentsOf: result.errors)
warnings.append(contentsOf: result.warnings)
}
for groupName in stringsGroups.keys.sorted() {
let result = checkStringsGroup(stringsGroups[groupName] ?? [:])
errors.append(contentsOf: result.errors)
warnings.append(contentsOf: result.warnings)
}
let sourceUsage = checkSourceLocalizationKeys(root: root)
errors.append(contentsOf: sourceUsage.errors)
warnings.append(contentsOf: sourceUsage.warnings)
(warnings + errors).forEach { eprint($0.formatted) }
let tableCount = catalogs.count + stringsGroups.count
if !errors.isEmpty {
eprint("error: translation check failed with \(errors.count) error(s) and \(warnings.count) warning(s)")
return 1
}
print("Translation check passed (\(tableCount) tables, \(warnings.count) warning(s))")
return 0
}
private func main() -> Int32 {
let arguments = Array(CommandLine.arguments.dropFirst())
let root = repoRoot()
if arguments.first == "--export-en" {
guard arguments.count >= 2 else {
eprint("error: --export-en requires a destination path")
return 1
}
let catalog = root.appendingPathComponent(appCatalogRelativePath)
return exportEnglishStrings(from: catalog, to: URL(fileURLWithPath: arguments[1]))
}
return runCheck(root: root)
}
exit(main())