-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSettings.cs
67 lines (53 loc) · 1.94 KB
/
Settings.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Encodings.Web;
using Microsoft.Extensions.Logging;
using Celestial.Triggers;
namespace Celestial;
public class Settings
{
public IEnumerable<Trigger> Triggers { get; set; } = Enumerable.Empty<Trigger>();
public double? Latitude { get; set; }
public double? Longitude { get; set; }
public static async Task<Settings> LoadFromFileAsync(string path, ILogger logger)
{
JsonSerializerOptions options = GetJsonOptions();
if (File.Exists(path))
{
using (var fs = new FileStream(path, FileMode.Open))
{
Settings? read = await JsonSerializer.DeserializeAsync<Settings>(fs, options);
if (read != null)
{
logger.LogInformation("Successfully loaded settings from {path}", path);
return read;
}
}
}
logger.LogInformation("Generating new config file with defaults at {path}", path);
FileInfo info = new FileInfo(path);
if (info.Directory != null)
{
logger.LogInformation("Config directory {directory} does not exist, creating", info.DirectoryName);
info.Directory.Create();
}
Settings settings = new Settings();
using (var fs = new FileStream(path, FileMode.Create))
{
await JsonSerializer.SerializeAsync(fs, settings, options);
}
return settings;
}
private static JsonSerializerOptions GetJsonOptions()
{
var options = new JsonSerializerOptions()
{
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true
};
options.Converters.Add(new JsonStringEnumConverter());
return options;
}
}