-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathDynamicConfigFile.cs
More file actions
563 lines (499 loc) · 19.5 KB
/
DynamicConfigFile.cs
File metadata and controls
563 lines (499 loc) · 19.5 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
extern alias References;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using References::Newtonsoft.Json;
namespace Oxide.Core.Configuration
{
/// <summary>
/// Represents a config file with a dynamic layout
/// </summary>
public class DynamicConfigFile : ConfigFile, IEnumerable<KeyValuePair<string, object>>
{
public JsonSerializerSettings Settings { get; set; } = new JsonSerializerSettings();
private Dictionary<string, object> _keyvalues;
private readonly JsonSerializerSettings _settings;
private readonly string _chroot;
/// <summary>
/// Initializes a new instance of the DynamicConfigFile class
/// </summary>
public DynamicConfigFile(string filename) : base(filename)
{
_keyvalues = new Dictionary<string, object>();
_settings = new JsonSerializerSettings();
_settings.Converters.Add(new KeyValuesConverter());
_chroot = Interface.Oxide.InstanceDirectory;
}
/// <summary>
/// Loads this config from the specified file
/// </summary>
/// <param name="filename"></param>
public override void Load(string filename = null)
{
filename = CheckPath(filename ?? Filename);
string source = File.ReadAllText(filename);
_keyvalues = JsonConvert.DeserializeObject<Dictionary<string, object>>(source, _settings);
}
/// <summary>
/// Loads this config from the specified file
/// </summary>
/// <param name="filename"></param>
public T ReadObject<T>(string filename = null)
{
filename = CheckPath(filename ?? Filename);
T customObject;
if (Exists(filename))
{
string source = File.ReadAllText(filename);
customObject = JsonConvert.DeserializeObject<T>(source, Settings);
}
else
{
customObject = Activator.CreateInstance<T>();
WriteObject(customObject, false, filename);
}
return customObject;
}
/// <summary>
/// Saves this config to the specified file
/// </summary>
/// <param name="filename"></param>
public override void Save(string filename = null)
{
filename = CheckPath(filename ?? Filename);
string dir = Utility.GetDirectoryName(filename);
if (dir != null && !Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
File.WriteAllText(filename, JsonConvert.SerializeObject(_keyvalues, Formatting.Indented, _settings));
}
/// <summary>
/// Saves this config to the specified file
/// </summary>
/// <param name="sync"></param>
/// <param name="filename"></param>
/// <param name="config"></param>
public void WriteObject<T>(T config, bool sync = false, string filename = null)
{
filename = CheckPath(filename ?? Filename);
string dir = Utility.GetDirectoryName(filename);
if (dir != null && !Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
string json = JsonConvert.SerializeObject(config, Formatting.Indented, Settings);
File.WriteAllText(filename, json);
if (sync)
{
_keyvalues = JsonConvert.DeserializeObject<Dictionary<string, object>>(json, _settings);
}
}
/// <summary>
/// Checks if the file or specified file exists
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public bool Exists(string filename = null)
{
filename = CheckPath(filename ?? Filename);
string dir = Utility.GetDirectoryName(filename);
if (dir != null && !Directory.Exists(dir))
{
return false;
}
return File.Exists(filename);
}
/// <summary>
/// Removes specified file
/// </summary>
/// <param name="filename"></param>
public void Delete(string filename = null)
{
filename = CheckPath(filename ?? Filename);
if (Exists(filename))
{
File.Delete(filename);
}
}
/// <summary>
/// Check if file path is in chroot directory
/// </summary>
/// <param name="filename"></param>
private string CheckPath(string filename)
{
filename = SanitizeName(filename);
string path = Path.GetFullPath(filename);
if (!path.StartsWith(_chroot, StringComparison.Ordinal))
{
throw new Exception($"Only access to oxide directory!\nPath: {path}");
}
return path;
}
/// <summary>
/// Makes the specified name safe for use in a filename
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static string SanitizeName(string name)
{
if (string.IsNullOrEmpty(name))
{
return string.Empty;
}
name = name.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar);
name = Regex.Replace(name, "[" + Regex.Escape(new string(Path.GetInvalidPathChars())) + "]", "_");
name = Regex.Replace(name, @"\.+", ".");
return name.TrimStart('.');
}
[Obsolete("SanitiseName is deprecated, use SanitizeName instead")]
public static string SanitiseName(string name)
{
return SanitizeName(name);
}
/// <summary>
/// Clears this config
/// </summary>
public void Clear()
{
_keyvalues.Clear();
}
/// <summary>
/// Removes key from config
/// </summary>
public void Remove(string key)
{
_keyvalues.Remove(key);
}
/// <summary>
/// Gets or sets a setting on this config by key
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public object this[string key]
{
get
{
return _keyvalues.TryGetValue(key, out object val) ? val : null;
}
set
{
_keyvalues[key] = value;
}
}
/// <summary>
/// Gets or sets a nested setting on this config by key
/// </summary>
/// <param name="keyLevel1"></param>
/// <param name="keyLevel2"></param>
/// <returns></returns>
public object this[string keyLevel1, string keyLevel2]
{
get { return Get(keyLevel1, keyLevel2); }
set { Set(keyLevel1, keyLevel2, value); }
}
/// <summary>
/// Gets or sets a nested setting on this config by key
/// </summary>
/// <param name="keyLevel1"></param>
/// <param name="keyLevel2"></param>
/// <param name="keyLevel3"></param>
/// <returns></returns>
public object this[string keyLevel1, string keyLevel2, string keyLevel3]
{
get { return Get(keyLevel1, keyLevel2, keyLevel3); }
set { Set(keyLevel1, keyLevel2, keyLevel3, value); }
}
/// <summary>
/// Converts a configuration value to another type
/// </summary>
/// <param name="value"></param>
/// <param name="destinationType"></param>
/// <returns></returns>
public object ConvertValue(object value, Type destinationType)
{
if (!destinationType.IsGenericType)
{
return Convert.ChangeType(value, destinationType);
}
if (destinationType.GetGenericTypeDefinition() == typeof(List<>))
{
Type valueType = destinationType.GetGenericArguments()[0];
IList list = (IList)Activator.CreateInstance(destinationType);
foreach (object val in (IList)value)
{
list.Add(Convert.ChangeType(val, valueType));
}
return list;
}
if (destinationType.GetGenericTypeDefinition() == typeof(Dictionary<,>))
{
Type keyType = destinationType.GetGenericArguments()[0];
Type valueType = destinationType.GetGenericArguments()[1];
IDictionary dict = (IDictionary)Activator.CreateInstance(destinationType);
foreach (object key in ((IDictionary)value).Keys)
{
dict.Add(Convert.ChangeType(key, keyType), Convert.ChangeType(((IDictionary)value)[key], valueType));
}
return dict;
}
throw new InvalidCastException("Generic types other than List<> and Dictionary<,> are not supported");
}
/// <summary>
/// Converts a configuration value to another type and returns it as that type
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public T ConvertValue<T>(object value) => (T)ConvertValue(value, typeof(T));
/// <summary>
/// Gets a configuration value at the specified path
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public object Get(params string[] path)
{
if (path.Length < 1)
{
throw new ArgumentException("path must not be empty");
}
if (!_keyvalues.TryGetValue(path[0], out object val))
{
return null;
}
for (int i = 1; i < path.Length; i++)
{
Dictionary<string, object> dict = val as Dictionary<string, object>;
if (dict == null || !dict.TryGetValue(path[i], out val))
{
return null;
}
}
return val;
}
/// <summary>
/// Gets a configuration value at the specified path and converts it to the specified type
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="path"></param>
/// <returns></returns>
public T Get<T>(params string[] path) => ConvertValue<T>(Get(path));
/// <summary>
/// Sets a configuration value at the specified path
/// </summary>
/// <param name="pathAndTrailingValue"></param>
public void Set(params object[] pathAndTrailingValue)
{
if (pathAndTrailingValue.Length < 2)
{
throw new ArgumentException("path must not be empty");
}
string[] path = new string[pathAndTrailingValue.Length - 1];
for (int i = 0; i < pathAndTrailingValue.Length - 1; i++)
{
path[i] = (string)pathAndTrailingValue[i];
}
object value = pathAndTrailingValue[pathAndTrailingValue.Length - 1];
if (path.Length == 1)
{
_keyvalues[path[0]] = value;
return;
}
if (!_keyvalues.TryGetValue(path[0], out object val))
{
_keyvalues[path[0]] = val = new Dictionary<string, object>();
}
for (int i = 1; i < path.Length - 1; i++)
{
if (!(val is Dictionary<string, object>))
{
throw new ArgumentException("path is not a dictionary");
}
Dictionary<string, object> oldVal = (Dictionary<string, object>)val;
if (!oldVal.TryGetValue(path[i], out val))
{
oldVal[path[i]] = val = new Dictionary<string, object>();
}
}
((Dictionary<string, object>)val)[path[path.Length - 1]] = value;
}
#region IEnumerable
public IEnumerator<KeyValuePair<string, object>> GetEnumerator() => _keyvalues.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => _keyvalues.GetEnumerator();
#endregion IEnumerable
}
/// <summary>
/// A mechanism to convert a keyvalues dictionary to and from json
/// </summary>
public class KeyValuesConverter : JsonConverter
{
/// <summary>
/// Returns if this converter can convert the specified type or not
/// </summary>
/// <param name="objectType"></param>
/// <returns></returns>
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Dictionary<string, object>) || objectType == typeof(List<object>);
}
private void Throw(string message)
{
throw new Exception(message);
}
/// <summary>
/// Reads an instance of the specified type from json
/// </summary>
/// <param name="reader"></param>
/// <param name="objectType"></param>
/// <param name="existingValue"></param>
/// <param name="serializer"></param>
/// <returns></returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (objectType == typeof(Dictionary<string, object>))
{
// Get the dictionary to populate
Dictionary<string, object> dict = existingValue as Dictionary<string, object> ?? new Dictionary<string, object>();
if (reader.TokenType == JsonToken.StartArray)
{
return dict;
}
// Read until end of object
while (reader.Read() && reader.TokenType != JsonToken.EndObject)
{
// Read property name
if (reader.TokenType != JsonToken.PropertyName)
{
Throw("Unexpected token: " + reader.TokenType);
}
string propname = reader.Value as string;
if (!reader.Read())
{
Throw("Unexpected end of json");
}
// What type of object are we reading?
switch (reader.TokenType)
{
case JsonToken.String:
case JsonToken.Float:
case JsonToken.Boolean:
case JsonToken.Bytes:
case JsonToken.Date:
case JsonToken.Null:
dict[propname] = reader.Value;
break;
case JsonToken.Integer:
string value = reader.Value.ToString();
int result;
if (int.TryParse(value, out result))
{
dict[propname] = result;
}
else
{
dict[propname] = value;
}
break;
case JsonToken.StartObject:
dict[propname] = serializer.Deserialize<Dictionary<string, object>>(reader);
break;
case JsonToken.StartArray:
dict[propname] = serializer.Deserialize<List<object>>(reader);
break;
default:
Throw("Unexpected token: " + reader.TokenType);
break;
}
}
// Return it
return dict;
}
if (objectType == typeof(List<object>))
{
// Get the list to populate
List<object> list = existingValue as List<object> ?? new List<object>();
// Read until end of array
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
// What type of object are we reading?
switch (reader.TokenType)
{
case JsonToken.String:
case JsonToken.Float:
case JsonToken.Boolean:
case JsonToken.Bytes:
case JsonToken.Date:
case JsonToken.Null:
list.Add(reader.Value);
break;
case JsonToken.Integer:
string value = reader.Value.ToString();
int result;
if (int.TryParse(value, out result))
{
list.Add(result);
}
else
{
list.Add(value);
}
break;
case JsonToken.StartObject:
list.Add(serializer.Deserialize<Dictionary<string, object>>(reader));
break;
case JsonToken.StartArray:
list.Add(serializer.Deserialize<List<object>>(reader));
break;
default:
Throw("Unexpected token: " + reader.TokenType);
break;
}
}
// Return it
return list;
}
return existingValue;
}
/// <summary>
/// Writes an instance of the specified type to json
/// </summary>
/// <param name="writer"></param>
/// <param name="value"></param>
/// <param name="serializer"></param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value is Dictionary<string, object>)
{
// Get the dictionary to write
Dictionary<string, object> dict = (Dictionary<string, object>)value;
// Start object
writer.WriteStartObject();
// Simply loop through and serialise
foreach (KeyValuePair<string, object> pair in dict.OrderBy(i => i.Key))
{
writer.WritePropertyName(pair.Key, true);
serializer.Serialize(writer, pair.Value);
}
// End object
writer.WriteEndObject();
}
else if (value is List<object>)
{
// Get the list to write
List<object> list = (List<object>)value;
// Start array
writer.WriteStartArray();
// Simply loop through and serialise
foreach (object t in list)
{
serializer.Serialize(writer, t);
}
// End array
writer.WriteEndArray();
}
}
}
}