Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251import Foundationimport ParcelCoreimport Testing
@Suite struct LocalizationSourceTests { private static let sources = URL(fileURLWithPath: #filePath) .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() .appending(path: "Sources")
@Test func localizedKeysExistInTheirTargetCatalog() throws { let files = try #require(FileManager.default.enumerator(at: Self.sources, includingPropertiesForKeys: nil)) var checked = 0 for case let file as URL in files where file.pathExtension == "swift" { let relative = String(file.path.dropFirst(Self.sources.path.count + 1)) let target = try #require(relative.split(separator: "/").first) let source = try String(contentsOf: file, encoding: .utf8) for reference in try references(in: source, file: relative) { let catalog = Self.sources.appending(path: "\(target)/Resources/\(reference.table).xcstrings") try #require( FileManager.default.fileExists(atPath: catalog.path), "\(relative): missing catalog \(reference.table) for \(reference.literal)") let keys = try JSONDecoder().decode(Catalog.self, from: Data(contentsOf: catalog)).strings.keys #expect( try contains(reference.literal, in: Array(keys)), "\(relative): missing \(reference.literal) in \(reference.table).xcstrings") checked += 1 } } #expect(checked > 0) }
@Test func sourceTreeContainsNoGeneratedTables() throws { let files = try #require(FileManager.default.enumerator(at: Self.sources, includingPropertiesForKeys: nil)) for case let file as URL in files { #expect( !["strings", "stringsdict"].contains(file.pathExtension), "Generated resource in Sources: \(file.path)") } }
@Test func missingKeysDoNotMatchOtherCatalogEntries() throws { let source = #"String(localized: "Missing \(value)", table: "UI", bundle: .module)"# let reference = try #require(references(in: source, file: "Example.swift").first) #expect(try !contains(reference.literal, in: [])) #expect(try !contains(reference.literal, in: ["Present %@", "Missing", "Missing %@ suffix"])) #expect(try contains(reference.literal, in: ["Missing %@"])) }
private func contains(_ literal: String, in keys: [String]) throws -> Bool { let key = try normalized(literal) return try keys.contains { try normalized($0, swiftLiteral: false) == key } }
@Test func scannerKeepsTablesEscapesAndInterpolations() throws { let source = #""" String(localized: "Quote: \"hello\"", table: "UI", bundle: .module) String( localized: "Line \(line): \(String(value))", table: "Parser", bundle: .module) String(localized: "Default table", bundle: .module) SettingsText.string("Settings key") AppearanceText.string("Palette key") String(localized: "Values: \(values.joined(separator: ")"))", table: "Schema", bundle: .module) minimumsText("Forget learned minimum size for \(bundleID)") """# let found = try references(in: source, file: "Example.swift") #expect(found.map(\.table) == ["UI", "Parser", "Localizable", "Settings", "Appearance", "Schema", "Minimums"]) #expect(try normalized(found[0].literal) == "Quote: \"hello\"") #expect(try normalized(found[1].literal) == normalized("Line %lld: %@", swiftLiteral: false)) #expect(try normalized(#"New\nline\t\\path"#) == "New\nline\t\\path") #expect(try normalized("Missing") != normalized("Present")) #expect(try normalized(found[5].literal) == normalized("Values: %@", swiftLiteral: false)) }
@Test func scannerHandlesMultilineContinuations() throws { let source = #"String(localized: """"# + "\n First line \\\n second line.\n " + #"""", table: "UI", bundle: .module)"# let found = try references(in: source, file: "Example.swift") #expect(found.first?.literal == "First line second line.") #expect(found.first?.table == "UI") }
@Test func scannerChecksDiagnosticHelpers() throws { #expect(try references(in: #"FeedbackText.string("Room")"#, file: "Example.swift").first?.table == "Feedback") #expect( try references(in: #"AppText.localized("Reason: \(error)")"#, file: "Example.swift").first?.table == "App") #expect( try references(in: #"FeedbackText.format("Retiled %lld windows.", count)"#, file: "Example.swift").first? .table == "Feedback") #expect( try references(in: #"throw error("Missing token")"#, file: "ParcelConfig/TOMLParser.swift").first?.table == "Parser") #expect( try references(in: #"throw editingError("Missing value")"#, file: "ParcelConfig/TOMLDocument.swift").first? .table == "Parser") }
@Test func defaultAppNameKeysAreEnumeratedRatherThanSkipped() throws { let found = try references( in: "SettingsText.string(String.LocalizationValue(name))", file: "ParcelUI/Settings/WindowRulesText.swift") #expect(found.count == DefaultFloatApps.all.count) #expect(Set(found.map(\.literal)) == Set(DefaultFloatApps.all.map(\.name))) #expect(found.allSatisfy { $0.table == "Settings" }) #expect(found.map(\.literal).contains("Calculator")) #expect(found.map(\.literal).contains("QuickTime Player")) #expect(throws: (any Error).self) { try references( in: "SettingsText.string(String.LocalizationValue(other))", file: "ParcelUI/Settings/WindowRulesText.swift") } }
@Test func unknownDynamicKeysFailRatherThanBeingSkipped() { #expect(throws: (any Error).self) { try references(in: "String(localized: unknown, bundle: .module)", file: "Example.swift") } }
private func references(in source: String, file: String) throws -> [Reference] { var calls = #"String\s*\(\s*localized:\s*|(?:SettingsText|AppearanceText)\.string\s*\(\s*|(?<!func )\bminimumsText\s*\(\s*|FeedbackText\.(?:string|format)\s*\(\s*|AppText\.localized\s*\(\s*"# if file == "ParcelConfig/TOMLParser.swift" { calls += #"|(?<!func )\berror\s*\(\s*"# } if file == "ParcelConfig/TOMLDocument.swift" { calls += #"|(?<!func )\beditingError\s*\(\s*"# } let callPattern = try NSRegularExpression(pattern: calls) let tablePattern = try NSRegularExpression(pattern: #"^\s*,\s*table:\s*"([^"]+)""#) var result: [Reference] = [] for call in callPattern.matches(in: source, range: NSRange(source.startIndex..., in: source)) { let range = try #require(Range(call.range, in: source)) let suffix = String(source[range.upperBound...]) let spelling = String(source[range]) guard suffix.first == "\"" else { if file == "ParcelUI/Settings/WindowRulesText.swift", spelling.hasPrefix("SettingsText.string"), suffix.hasPrefix("String.LocalizationValue(name))") { result.append( contentsOf: DefaultFloatApps.all.map { Reference(literal: $0.name, table: "Settings") }) continue } // These helpers forward their literal arguments; their call sites are checked above. let forwarding = [ "ParcelConfig/TOMLParser.swift": "message, table: \"Parser\"", "ParcelConfig/TOMLDocument.swift": "message, table: \"Parser\"", "ParcelUI/Settings/SettingsText.swift": "value, table: \"Settings\"", "ParcelUI/Settings/AppearancePreferencesView.swift": "value, table: \"Appearance\"", "ParcelUI/Settings/SettingsMinimumsModel.swift": "value, table: \"Minimums\"", "ParcelUI/Feedback/FeedbackNotice.swift": "value, table: \"Feedback\"", "ParcelApp/AppText.swift": "value, table: \"App\"", ] if let prefix = forwarding[file], spelling.hasPrefix("String"), suffix.hasPrefix(prefix) { continue } throw ScanError.nonliteralKey(file) } let literal: String let remainder: String if suffix.hasPrefix("\"\"\"") { let body = suffix.dropFirst(3) let end = try #require(body.range(of: "\"\"\"")) let lines = body[..<end.lowerBound].components(separatedBy: "\n") let indentation = try #require(lines.last) literal = lines.dropFirst().dropLast().map { String($0.dropFirst(indentation.count)) } .joined(separator: "\n").replacingOccurrences(of: "\\\n", with: "") remainder = String(body[end.upperBound...]) } else { var characters = suffix.dropFirst().makeIterator() literal = try consumeDelimited(&characters, closing: "\"") remainder = String(Array(characters)) } let tableMatch = tablePattern.firstMatch( in: remainder, range: NSRange(remainder.startIndex..., in: remainder)) let tableRange = tableMatch.flatMap { Range($0.range(at: 1), in: remainder) } let table = tableRange.map { String(remainder[$0]) } ?? (spelling.hasPrefix("minimumsText") ? "Minimums" : spelling.hasPrefix("FeedbackText") ? "Feedback" : spelling.hasPrefix("SettingsText") ? "Settings" : spelling.hasPrefix("AppearanceText") ? "Appearance" : spelling.hasPrefix("AppText") ? "App" : spelling.hasPrefix("String") ? "Localizable" : "Parser") result.append(Reference(literal: literal, table: table)) } return result }
private func consumeDelimited<I: IteratorProtocol>(_ characters: inout I, closing: Character) throws -> String where I.Element == Character { var result = "" var delimiters = [closing] while let character = characters.next() { if character == "\\", delimiters.last == "\"" { let next = characters.next() let escaped = try #require(next) result.append(contentsOf: [character, escaped]) if escaped == "(" { delimiters.append(")") } continue } if character == delimiters.last { delimiters.removeLast() if delimiters.isEmpty { return result } } else if delimiters.last == ")" { if character == "(" { delimiters.append(")") } if character == "\"" { delimiters.append("\"") } } result.append(character) } throw ScanError.unterminatedLiteral }
private func normalized(_ text: String, swiftLiteral: Bool = true) throws -> String { var result = "" var characters = text.makeIterator() while let character = characters.next() { guard swiftLiteral && character == "\\" else { result.append(character) continue } let escape = characters.next() let escaped = try #require(escape) if escaped == "(" { _ = try consumeDelimited(&characters, closing: ")") result.append("\u{FFFC}") } else { let escapes: [Character: Character] = [ "n": "\n", "r": "\r", "t": "\t", "0": "\0", "\"": "\"", "\\": "\\", ] result.append(try #require(escapes[escaped])) } } return result.replacingOccurrences( of: #"%(?:\d+\$)?(?:@|lld|ld|d|llu|lu|u|f|g)"#, with: "\u{FFFC}", options: .regularExpression) }
private struct Reference { let literal: String let table: String }
private struct Catalog: Decodable { let strings: [String: Entry] struct Entry: Decodable {} }
private enum ScanError: Error { case nonliteralKey(String) case unterminatedLiteral }}