This commit is contained in:
Max Howell
2019-01-17 16:33:38 -05:00
parent 8e0d766924
commit 97e9cbaa8f
16 changed files with 754 additions and 0 deletions

View File

@@ -0,0 +1,28 @@
import Foundation
public extension CodingUserInfoKey {
static let relativePath = CodingUserInfoKey(rawValue: "dev.mxcl.Path.relative")!
}
extension Path: Codable {
public init(from decoder: Decoder) throws {
let value = try decoder.singleValueContainer().decode(String.self)
if value.hasPrefix("/") {
string = value
} else {
guard let root = decoder.userInfo[.relativePath] as? Path else {
throw DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: "Path cannot decode a relative path if `userInfo[.relativePath]` not set to a Path object."))
}
string = (root/value).string
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
if let root = encoder.userInfo[.relativePath] as? Path {
try container.encode(relative(to: root))
} else {
try container.encode(string)
}
}
}