Skip to content

Instantly share code, notes, and snippets.

@jbrennan
Created August 31, 2018 20:11
Show Gist options
  • Save jbrennan/33a81c8edaee9da27cfa4207e3f732d5 to your computer and use it in GitHub Desktop.
Save jbrennan/33a81c8edaee9da27cfa4207e3f732d5 to your computer and use it in GitHub Desktop.
Simple file for converting Localizable.strings key=values back into a codebase
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
let translations = translationsFor(stringsFilePath: "/Users/jasonbrennan/peloton/Argon/Argon/Supporting Files/Localizable.strings")
for translation in translations {
replace(translation: translation, inProjectDirectory: "/Users/jasonbrennan/peloton/Argon/Argon")
}
}
func translationsFor(stringsFilePath: String) -> [String: String] {
return NSDictionary(contentsOfFile: stringsFilePath) as! [String : String]
}
func replace(translation: (key: String, value: String), inProjectDirectory directory: String) {
print("replacing: \(translation.key)")
// Go through each file, searching for NSLocalizedString("whatever_translation.key_is"
// and replace it with the associated **value** from the translation table
// thereby eliminating our use of keys
forEachFile(inDirectory: directory) { (file) in
return file.contents.replacingOccurrences(
of: "NSLocalizedString(\"\(translation.key)\"",
with: "NSLocalizedString(\"\(translation.value.replacingOccurrences(of: "\n", with: "\\n"))\"")
}
}
private func forEachFile(inDirectory directory: String, runBlock block: (File) -> String) {
let enumerator = FileManager.default.enumerator(at: URL(string: directory)!,
includingPropertiesForKeys: [],
options: [.skipsHiddenFiles], errorHandler: { (url, error) -> Bool in
print("directoryEnumerator error at \(url): ", error)
return true
})!
for case let fileURL as URL in enumerator where fileURL.hasDirectoryPath == false && fileURL.pathExtension == "swift" {
let replacedString = block(File(path: fileURL.path, contents: (try! String(contentsOfFile: fileURL.path))))
try? replacedString.write(toFile: fileURL.path, atomically: true, encoding: .utf8)
}
}
}
struct File {
let path: String
let contents: String
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment