Last active
June 29, 2022 15:09
-
-
Save mluisbrown/c78b640c384c23a2804b102de6466e48 to your computer and use it in GitHub Desktop.
Swift script to extract all string literals from a Swift source file in the format of a Localizable.strings file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/swift | |
import Foundation | |
func processFile(_ path: String, keyPrefix: String?) { | |
guard let file = freopen(path, "r", stdin) else { | |
fputs("Failed to open file.\n", stderr) | |
return | |
} | |
defer { | |
fclose(file) | |
} | |
let pattern = #""(?:\.|[^"])*""# | |
let regex = try! NSRegularExpression(pattern: pattern) | |
var keyCount = 0 | |
let keyPrefix = keyPrefix ?? "key" | |
while let line = readLine() { | |
let range = NSRange(location: 0, length: line.utf16.count) | |
regex.enumerateMatches(in: line, range: range) { result, _, _ in | |
guard let match = result, | |
let range = Range(match.range, in: line) else { return } | |
print("\"\(keyPrefix).\(keyCount)\" = \(line[range]);") | |
keyCount += 1 | |
} | |
} | |
} | |
func run() { | |
guard CommandLine.arguments.count > 1 else { | |
fputs("Syntax: xstrings <filename> [<key prefix>]\n", stderr) | |
return | |
} | |
let keyPrefix: String? = CommandLine.arguments.count > 2 ? CommandLine.arguments[2] : nil | |
processFile(CommandLine.arguments[1], keyPrefix: keyPrefix) | |
} | |
run() |
Use python man.
No doubt that Python, Ruby, Perl or similar would be a better choice for this, but since I don't know any of those well enough it would have taken me longer than doing it in Swift. The benefit of Swift is that you can also compile to a binary executable.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use python man.