]> git.r.bdr.sh - rbdr/lyricli/blame - Sources/configuration.swift
Added Spotify source support (#2)
[rbdr/lyricli] / Sources / configuration.swift
CommitLineData
4425e900
BB
1import Foundation
2
d852b84e
BB
3// Reads and writes the configuration. Config keys are accessed as a dictionary.
4class Configuration {
5 // Location of the global configuration file
6 private let configurationPath = NSString(string: "~/.lyricli.conf").expandingTildeInPath
4425e900 7
d852b84e
BB
8 // Default options, will be automatically written to the global config if
9 // not found.
4425e900 10 private var configuration: [String: Any] = [
d1a147d4 11 "enabled_sources": ["arguments", "itunes", "spotify"]
4425e900
BB
12 ]
13
d852b84e
BB
14 // The shared instance of the object
15 static let shared: Configuration = Configuration()
4425e900
BB
16
17 private init() {
18
d852b84e
BB
19 // Read the config file and attempt to set any of the values. Otherwise
20 // don't do anything.
4425e900
BB
21
22 if let data = try? NSData(contentsOfFile: configurationPath) as Data {
1263f62c
BB
23 if let parsedConfig = try? JSONSerialization.jsonObject(with: data) {
24 if let parsedConfig = parsedConfig as? [String: Any] {
25 for (key, value) in parsedConfig {
4425e900 26
1263f62c
BB
27 if key == "enabled_sources" {
28 if let value = value as? [String] {
29 configuration[key] = value
30 }
31 } else {
32 if let value = value as? String {
33 configuration[key] = value
34 }
35 }
4425e900
BB
36 }
37 }
38 }
39 }
40
41 writeConfiguration()
42 }
43
d852b84e 44 // Write the configuration back to the file
4425e900
BB
45 private func writeConfiguration() {
46
47 var error: NSError?
48
49 if let outputStream = OutputStream(toFileAtPath: configurationPath, append: false) {
50 outputStream.open()
1263f62c
BB
51 JSONSerialization.writeJSONObject(configuration,
52 to: outputStream,
53 options: [JSONSerialization.WritingOptions.prettyPrinted],
54 error: &error)
4425e900
BB
55 outputStream.close()
56 }
57 }
58
d852b84e 59 // Allow access to the config properties as a dictionary
4425e900
BB
60 subscript(index: String) -> Any? {
61 get {
62 return configuration[index]
63 }
64
65 set(newValue) {
66 configuration[index] = newValue
67 writeConfiguration()
68 }
69 }
70}