]> git.r.bdr.sh - rbdr/lyricli/blob - Sources/configuration.swift
f1a1ee1203ac04c5e129d80ff69ab98b96be220a
[rbdr/lyricli] / Sources / configuration.swift
1 import Foundation
2
3 // Reads and writes the configuration. Config keys are accessed as a dictionary.
4 class Configuration {
5 // Location of the global configuration file
6 private let configurationPath = NSString(string: "~/.lyricli.conf").expandingTildeInPath
7
8 // Default options, will be automatically written to the global config if
9 // not found.
10 private var configuration: [String: Any] = [
11 "enabled_sources": ["arguments"]
12 ]
13
14 // The shared instance of the object
15 static let shared: Configuration = Configuration()
16
17 private init() {
18
19 // Read the config file and attempt to set any of the values. Otherwise
20 // don't do anything.
21
22 if let data = try? NSData(contentsOfFile: configurationPath) as Data {
23 if let parsedConfig = try? JSONSerialization.jsonObject(with: data) {
24 if let parsedConfig = parsedConfig as? [String: Any] {
25 for (key, value) in parsedConfig {
26
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 }
36 }
37 }
38 }
39 }
40
41 writeConfiguration()
42 }
43
44 // Write the configuration back to the file
45 private func writeConfiguration() {
46
47 var error: NSError?
48
49 if let outputStream = OutputStream(toFileAtPath: configurationPath, append: false) {
50 outputStream.open()
51 JSONSerialization.writeJSONObject(configuration,
52 to: outputStream,
53 options: [JSONSerialization.WritingOptions.prettyPrinted],
54 error: &error)
55 outputStream.close()
56 }
57 }
58
59 // Allow access to the config properties as a dictionary
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 }