1
1
mirror of https://github.com/yonaskolb/XcodeGen.git synced 2024-12-13 18:22:14 +03:00
XcodeGen/Sources/ProjectSpec/Decoding.swift
2017-09-14 00:48:57 +02:00

67 lines
1.9 KiB
Swift

//
// Decoding.swift
// XcodeGen
//
// Created by Yonas Kolb on 19/5/17.
//
//
import Foundation
import JSONUtilities
import PathKit
import Yams
extension Dictionary where Key: JSONKey {
public func json<T: NamedJSONDictionaryConvertible>(atKeyPath keyPath: JSONUtilities.KeyPath, invalidItemBehaviour: InvalidItemBehaviour<T> = .remove) throws -> [T] {
guard let dictionary = json(atKeyPath: keyPath) as JSONDictionary? else {
return []
}
var items: [T] = []
for (key, _) in dictionary {
let jsonDictionary: JSONDictionary = try dictionary.json(atKeyPath: .key(key))
let item = try T(name: key, jsonDictionary: jsonDictionary)
items.append(item)
}
return items
}
public func json<T: NamedJSONConvertible>(atKeyPath keyPath: JSONUtilities.KeyPath, invalidItemBehaviour: InvalidItemBehaviour<T> = .remove) throws -> [T] {
guard let dictionary = json(atKeyPath: keyPath) as JSONDictionary? else {
return []
}
var items: [T] = []
for (key, value) in dictionary {
let item = try T(name: key, json: value)
items.append(item)
}
return items
}
}
public protocol NamedJSONDictionaryConvertible {
init(name: String, jsonDictionary: JSONDictionary) throws
}
public protocol NamedJSONConvertible {
init(name: String, json: Any) throws
}
extension JSONObjectConvertible {
public init(path: Path) throws {
let content: String = try path.read()
if content == "" {
try self.init(jsonDictionary: [:])
return
}
let yaml = try Yams.load(yaml: content)
guard let jsonDictionary = yaml as? JSONDictionary else {
throw JSONUtilsError.fileNotAJSONDictionary
}
try self.init(jsonDictionary: jsonDictionary)
}
}