Skip to content

Instantly share code, notes, and snippets.

@letatas
Created January 8, 2020 14:51
Show Gist options
  • Save letatas/9a58ad4f0a979b19579334bd80516f4a to your computer and use it in GitHub Desktop.
Save letatas/9a58ad4f0a979b19579334bd80516f4a to your computer and use it in GitHub Desktop.
Second script used to update intent definition localization strings files (usage can be found here: https://stackoverflow.com/questions/52659028/xcode-10-how-to-refresh-localization-of-a-siri-shortcut-intent-definiotion-fil)
#!/usr/bin/swift
import Foundation
guard CommandLine.arguments.count == 3 else {
print("Usage:\n\t\(CommandLine.arguments[0]) <STRINGS_TO_TRANSFER_FILE> <STRING_FILE_ON_WHICH_TRANSFER_STRINGS>\n")
exit(1)
}
let source = CommandLine.arguments[1]
let destination = CommandLine.arguments[2]
guard let existingStrings = try? String(contentsOfFile: source) else {
print("❌ Impossible to load", source)
exit(1)
}
guard let stringsFile = try? String(contentsOfFile: destination) else {
print("❌ Impossible to load", destination)
exit(1)
}
extension String {
static private var stringsLineRegex : NSRegularExpression = {
let pattern = #"""
(".*")\s*=\s*(".*")\s*;
"""#
return try! NSRegularExpression(pattern: pattern, options: [])
}()
private var escapedQuote : String { replacingOccurrences(of: "\\\"", with: "{{ESCAPED_QUOTE}}") }
private var unescapedQuote : String { replacingOccurrences(of: "{{ESCAPED_QUOTE}}", with: "\\\"") }
var parsedStringsLine : (key: String, value: String)? {
guard let match = Self.stringsLineRegex.firstMatch(in: self, options: [], range: NSRange(startIndex..<endIndex, in: self))
else { return nil }
guard
let keyRange = Range(match.range(at: 1), in: self),
let valueRange = Range(match.range(at: 2), in: self)
else { return nil }
return (String(self[keyRange]).unescapedQuote, String(self[valueRange]).unescapedQuote)
}
var parsedStringsFile : [String:String] {
var result = [String:String]()
components(separatedBy: .newlines)
.compactMap { $0.parsedStringsLine }
.forEach { result[$0.key] = $0.value }
return result
}
func updateStringsFile(with existingStrings: [String:String]) -> String {
var result = [String]()
for line in components(separatedBy: .newlines) {
if let (key, _) = line.parsedStringsLine,
let existingValue = existingStrings[key] {
let newLine = "\(key) = \(existingValue);"
result.append(newLine)
}
else {
result.append(line)
}
}
return result.joined(separator: "\n")
}
}
let newFile = stringsFile.updateStringsFile(with:existingStrings.parsedStringsFile)
do {
try newFile.write(toFile: destination, atomically: true, encoding: .utf8)
}
catch {
print("❌ Impossible to write the updated file to", destination)
exit(1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment