Skip to content

Instantly share code, notes, and snippets.

@mluisbrown
Last active June 29, 2022 15:09
Show Gist options
  • Save mluisbrown/c78b640c384c23a2804b102de6466e48 to your computer and use it in GitHub Desktop.
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
#!/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()
@RuiAAPeres
Copy link

Use python man.

@mluisbrown
Copy link
Author

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