Skip to content

Commit aa69ee5

Browse files
committed
Between macOS and Linux, I have quite a few options that are common. So
I need to have a common configuration json
1 parent fed47e9 commit aa69ee5

1 file changed

Lines changed: 31 additions & 24 deletions

File tree

Sources/JSONConfig.swift

Lines changed: 31 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -11,34 +11,41 @@ import PerfectLib
1111
public class JSONConfig {
1212
public static let shared = JSONConfig()
1313
private var json:[String:Any]?
14-
public var source : String? {
15-
didSet {
16-
if self.source != oldValue {
17-
self.json = nil
18-
19-
guard let source = self.source else { return }
20-
let file = File(source)
21-
do {
22-
try file.open(.read, permissions: .readUser)
23-
defer {
24-
file.close()
25-
}
26-
27-
let text = try file.readString()
28-
self.json = try text.jsonDecode() as? [String:Any]
29-
30-
} catch {
31-
print("JSONConfig error: " + error.localizedDescription)
14+
15+
/// initialze the configuration with json at source. The json is first populated by the json at defaults (if it exists)
16+
public func initialize(withJsonAt source:String, defaultsInJsonAt defaults:String? = nil) {
17+
self.json = nil
18+
if let defaults = defaults {
19+
self.read(jsonAt: defaults)
20+
}
21+
self.read(jsonAt: source)
22+
}
23+
24+
private func read(jsonAt path:String) {
25+
let file = File(path)
26+
do {
27+
try file.open(.read, permissions: .readUser)
28+
defer {
29+
file.close()
30+
}
31+
32+
let text = try file.readString()
33+
let dict = try text.jsonDecode() as? [String:Any]
34+
if nil == self.json {
35+
self.json = dict
36+
}
37+
else if let dict = dict {
38+
for (k,v) in dict {
39+
self.json?[k] = v
3240
}
3341
}
42+
43+
} catch {
44+
print("JSONConfig error: " + error.localizedDescription)
3445
}
46+
3547
}
36-
37-
private convenience init(_ json:[String:Any]?) {
38-
self.init()
39-
self.json = json
40-
}
41-
48+
4249
public func value(forKey key:String) -> Any? {
4350
guard let json = self.json else { return nil }
4451
return json[key]

0 commit comments

Comments
 (0)