]> git.r.bdr.sh - rbdr/lyricli/blob - Sources/configuration.swift
Merge branch 'feature/read-song-from-command-line' into develop
[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) as! [String:Any] {
25 for (key, value) in parsedConfig {
26
27 if key == "enabled_sources" {
28 configuration[key] = value as! [String]
29 }
30 else {
31 configuration[key] = value as! String
32 }
33 }
34 }
35 }
36
37 writeConfiguration()
38 }
39
40 private func writeConfiguration() {
41
42 var error: NSError?
43
44 if let outputStream = OutputStream(toFileAtPath: configurationPath, append: false) {
45 outputStream.open()
46 JSONSerialization.writeJSONObject(configuration, to: outputStream, options: [JSONSerialization.WritingOptions.prettyPrinted], error: &error)
47 outputStream.close()
48 }
49 }
50
51 // Allow access as an object
52 subscript(index: String) -> Any? {
53 get {
54 return configuration[index]
55 }
56
57 set(newValue) {
58 configuration[index] = newValue
59 writeConfiguration()
60 }
61 }
62 }