Created
February 1, 2019 10:50
-
-
Save kruperfone/c19abb087dbcde0647d8867e5e71ab02 to your computer and use it in GitHub Desktop.
This file contains hidden or 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/xcrun --sdk macosx swift | |
/* | |
Create `test.plist` file in project dir | |
Add `PlistCodeGenerator.swift` file to project dir | |
Add to build phases: ${PROJECT_DIR}/PlistCodeGenerator.swift | |
Add output.swift to project target | |
*/ | |
import Foundation | |
// Path to script files | |
let manager = FileManager() | |
let directory = manager.currentDirectoryPath | |
print("Current directory: \(directory)") | |
let plistName = "test.plist" | |
let plistPath = "\(directory)/\(plistName)" | |
print("Plist path: \(plistPath)") | |
let outputName = "output.swift" | |
let outputPath = "\(directory)/\(outputName)" | |
print("Output path: \(outputPath)") | |
let data = try! Data(contentsOf: URL(string: "file:///\(plistPath)")!) | |
let list = try! PropertyListSerialization.propertyList(from: data, options: [], format: nil) as! [String: Any] | |
manager.createFile(atPath: outputPath, contents: nil, attributes: nil) | |
// MARK: Parsing | |
func parseKey(dict: [String: Any], key: String, level: Int) -> String { | |
let tab = String(repeating: " ", count: level) | |
let value = dict[key]! | |
switch value { | |
case let v as String: | |
return "\(tab)static let \(key) = \"\(v)\"" | |
case is Bool, is Int, is Double: | |
return "\(tab)static let \(key) = \(value)" | |
case let date as Date: | |
return "\(tab)/// \(date)\n\(tab)static let \(key) = Date(timeIntervalSince1970: \(date.timeIntervalSince1970))" | |
case let dict as [String: Any]: | |
return """ | |
\(tab)enum \(key.capitalized) { | |
\(parseDict(dict: dict, level: level + 1)) | |
\(tab)} | |
""" | |
default: | |
fatalError("Unsupported type") | |
} | |
} | |
func parseDict(dict: [String: Any], level: Int) -> String { | |
var content: String = "" | |
for key in dict.keys.sorted() { | |
let result = parseKey(dict: dict, key: key, level: level) | |
content += "\(result)\n" | |
} | |
return content | |
} | |
let envContent = parseDict(dict: list, level: 1) | |
let output = """ | |
import Foundation | |
enum ENV { | |
\(envContent) | |
} | |
""" | |
// Writing | |
try! output.write(toFile: outputPath, atomically: true, encoding: .utf8) | |
exit(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment