]> git.r.bdr.sh - rbdr/lyricli/blob - Sources/configuration.swift
bc217694b1ab189a1748bc3b0d7754f7094bdaf3
[rbdr/lyricli] / Sources / configuration.swift
1 import Foundation
2
3 /// Handles reading and writing the configuration
4 public class Configuration {
5
6 let configurationPath = NSString(string: "~/.lyricli.conf").expandingTildeInPath
7
8 // The defaults are added here
9
10 private var configuration: [String: Any] = [
11 "enabled_sources": ["arguments"],
12 "default": true
13 ]
14
15 static let sharedInstance: Configuration = Configuration()
16
17 private init() {
18
19 // Read the config file and attempt toset any of the values. Otherwise
20 // Don't do anything.
21 // IMPROVEMENT: Enable a debug mode
22
23 if let data = try? NSData(contentsOfFile: configurationPath) as Data {
24 if let parsedConfig = try? JSONSerialization.jsonObject(with: data) {
25 if let parsedConfig = parsedConfig as? [String: Any] {
26 for (key, value) in parsedConfig {
27
28 if key == "enabled_sources" {
29 if let value = value as? [String] {
30 configuration[key] = value
31 }
32 } else {
33 if let value = value as? String {
34 configuration[key] = value
35 }
36 }
37 }
38 }
39 }
40 }
41
42 writeConfiguration()
43 }
44
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 as an object
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 }