-
Notifications
You must be signed in to change notification settings - Fork 4
/
Config.swift
85 lines (70 loc) · 2.62 KB
/
Config.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import Foundation
import GysbBase
public struct Config : Decodable {
public struct PackageDependency : Decodable {
public enum Requirement : Decodable {
case exact(String)
case revision(String)
public enum CodingKeys : String, CodingKey {
case type
case identifier
}
}
public var url: String
public var requirement: Requirement
}
public struct TargetDependency : Decodable {
public var name: String
}
public init() {}
public var configPath: URL? = nil
public var packageDependencies: [PackageDependency] = []
public var targetDependencies: [TargetDependency] = []
public var includes: [String] = []
public var includesFiles: [URL] = []
public enum CodingKeys : String, CodingKey {
case packageDependencies
case targetDependencies
case includes
}
}
public extension Config {
public init(from decoder: Decoder) throws {
let kc = try decoder.container(keyedBy: CodingKeys.self)
self.packageDependencies = try kc.decodeIfPresent([PackageDependency].self, forKey: .packageDependencies) ?? []
self.targetDependencies = try kc.decodeIfPresent([TargetDependency].self, forKey: .targetDependencies) ?? []
self.includes = try kc.decodeIfPresent([String].self, forKey: .includes) ?? []
}
public mutating func updateIncludePaths() throws {
guard let configPath = configPath else {
self.includesFiles = []
return
}
let dir = configPath.deletingLastPathComponent()
let paths: [URL] = try includes.flatMap { (include: String) -> [URL] in
try glob(pattern: include, in: dir)
}
self.includesFiles = paths
}
public static func fromJSON(path: URL) throws -> Config {
let data = try Data.init(contentsOf: path)
var config = try JSONDecoder().decode(Config.self, from: data)
config.configPath = path
try config.updateIncludePaths()
return config
}
public static func searchForSource(path: URL) -> URL? {
let fm = FileManager.default
var dir = path.deletingLastPathComponent().absoluteURL
while true {
let checkPath = dir.appendingPathComponent("gysb.json")
if fm.fileExists(atPath: checkPath.path) {
return checkPath
}
if dir.pathComponents.count == 1 {
return nil
}
dir.deleteLastPathComponent()
}
}
}