ConfigFile.cs 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text.RegularExpressions;
  7. namespace BepInEx.Configuration
  8. {
  9. /// <summary>
  10. /// A helper class to handle persistent data.
  11. /// </summary>
  12. public class ConfigFile
  13. {
  14. private static readonly Regex sanitizeKeyRegex = new Regex(@"[^a-zA-Z0-9\-\.]+");
  15. internal static ConfigFile CoreConfig { get; } = new ConfigFile(Paths.BepInExConfigPath);
  16. protected internal Dictionary<ConfigDefinition, string> Cache { get; } = new Dictionary<ConfigDefinition, string>();
  17. public ReadOnlyCollection<ConfigDefinition> ConfigDefinitions => Cache.Keys.ToList().AsReadOnly();
  18. /// <summary>
  19. /// An event that is fired every time the config is reloaded.
  20. /// </summary>
  21. public event EventHandler ConfigReloaded;
  22. public string ConfigFilePath { get; }
  23. /// <summary>
  24. /// If enabled, writes the config to disk every time a value is set.
  25. /// </summary>
  26. public bool SaveOnConfigSet { get; set; } = true;
  27. public ConfigFile(string configPath)
  28. {
  29. ConfigFilePath = configPath;
  30. if (File.Exists(ConfigFilePath))
  31. {
  32. Reload();
  33. }
  34. else
  35. {
  36. Save();
  37. }
  38. }
  39. private object _ioLock = new object();
  40. /// <summary>
  41. /// Reloads the config from disk. Unsaved changes are lost.
  42. /// </summary>
  43. public void Reload()
  44. {
  45. lock (_ioLock)
  46. {
  47. Dictionary<ConfigDefinition, string> descriptions = Cache.ToDictionary(x => x.Key, x => x.Key.Description);
  48. string currentSection = "";
  49. foreach (string rawLine in File.ReadAllLines(ConfigFilePath))
  50. {
  51. string line = rawLine.Trim();
  52. if (line.StartsWith("#")) //comment
  53. continue;
  54. if (line.StartsWith("[") && line.EndsWith("]")) //section
  55. {
  56. currentSection = line.Substring(1, line.Length - 2);
  57. continue;
  58. }
  59. string[] split = line.Split('='); //actual config line
  60. if (split.Length != 2)
  61. continue; //empty/invalid line
  62. string currentKey = split[0].Trim();
  63. string currentValue = split[1].Trim();
  64. var definition = new ConfigDefinition(currentSection, currentKey);
  65. if (descriptions.ContainsKey(definition))
  66. definition.Description = descriptions[definition];
  67. Cache[definition] = currentValue;
  68. }
  69. ConfigReloaded?.Invoke(this, EventArgs.Empty);
  70. }
  71. }
  72. /// <summary>
  73. /// Writes the config to disk.
  74. /// </summary>
  75. public void Save()
  76. {
  77. lock (_ioLock)
  78. {
  79. if (!Directory.Exists(Paths.ConfigPath))
  80. Directory.CreateDirectory(Paths.ConfigPath);
  81. using (StreamWriter writer = new StreamWriter(File.Create(ConfigFilePath), System.Text.Encoding.UTF8))
  82. foreach (var sectionKv in Cache.GroupBy(x => x.Key.Section).OrderBy(x => x.Key))
  83. {
  84. writer.WriteLine($"[{sectionKv.Key}]");
  85. foreach (var entryKv in sectionKv)
  86. {
  87. writer.WriteLine();
  88. if (!string.IsNullOrEmpty(entryKv.Key.Description))
  89. writer.WriteLine($"# {entryKv.Key.Description.Replace("\n", "\n# ")}");
  90. writer.WriteLine($"{entryKv.Key.Key} = {entryKv.Value}");
  91. }
  92. writer.WriteLine();
  93. }
  94. }
  95. }
  96. public ConfigWrapper<T> Wrap<T>(ConfigDefinition configDefinition, T defaultValue = default(T))
  97. {
  98. if (!Cache.ContainsKey(configDefinition))
  99. {
  100. Cache.Add(configDefinition, TomlTypeConverter.ConvertToString(defaultValue));
  101. Save();
  102. }
  103. else
  104. {
  105. var original = Cache.Keys.First(x => x.Equals(configDefinition));
  106. if (original.Description != configDefinition.Description)
  107. {
  108. original.Description = configDefinition.Description;
  109. Save();
  110. }
  111. }
  112. return new ConfigWrapper<T>(this, configDefinition);
  113. }
  114. public ConfigWrapper<T> Wrap<T>(string section, string key, string description = null, T defaultValue = default(T))
  115. => Wrap<T>(new ConfigDefinition(section, key, description), defaultValue);
  116. }
  117. }