Config.cs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. using BepInEx.Common;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Text.RegularExpressions;
  6. namespace BepInEx
  7. {
  8. /// <summary>
  9. /// A helper class to handle persistent data.
  10. /// </summary>
  11. public static class Config
  12. {
  13. private static Dictionary<string, Dictionary<string, string>> cache = new Dictionary<string, Dictionary<string, string>>();
  14. private static string configPath => Path.Combine(Utility.PluginsDirectory, "config.ini");
  15. private static Regex sanitizeKeyRegex = new Regex("[^a-zA-Z0-9]+");
  16. private static void RaiseConfigReloaded()
  17. {
  18. var handler = ConfigReloaded;
  19. if (handler != null)
  20. handler.Invoke();
  21. }
  22. public static event Action ConfigReloaded;
  23. /// <summary>
  24. /// If enabled, writes the config to disk every time a value is set.
  25. /// </summary>
  26. public static bool SaveOnConfigSet { get; set; } = true;
  27. static Config()
  28. {
  29. if (File.Exists(configPath))
  30. {
  31. ReloadConfig();
  32. }
  33. else
  34. {
  35. SaveConfig();
  36. }
  37. }
  38. /// <summary>
  39. /// Returns the value of the key if found, otherwise returns the default value.
  40. /// </summary>
  41. /// <param name="key">The key to search for.</param>
  42. /// <param name="defaultValue">The default value to return if the key is not found.</param>
  43. /// <returns>The value of the key.</returns>
  44. public static string GetEntry(string key, string defaultValue = "", string section = "")
  45. {
  46. key = Sanitize(key);
  47. if (section.IsNullOrWhiteSpace())
  48. section = "Global";
  49. else
  50. section = Sanitize(section);
  51. Dictionary<string, string> subdict;
  52. if (!cache.TryGetValue(section, out subdict))
  53. {
  54. SetEntry(key, defaultValue, section);
  55. return defaultValue;
  56. }
  57. if (subdict.TryGetValue(key, out string value))
  58. return value;
  59. else
  60. {
  61. SetEntry(key, defaultValue, section);
  62. return defaultValue;
  63. }
  64. }
  65. /// <summary>
  66. /// Reloads the config from disk. Unwritten changes are lost.
  67. /// </summary>
  68. public static void ReloadConfig()
  69. {
  70. cache.Clear();
  71. string currentSection = "";
  72. foreach (string rawLine in File.ReadAllLines(configPath))
  73. {
  74. string line = rawLine.Trim();
  75. bool commentIndex = line.StartsWith(";") || line.StartsWith("#");
  76. if (commentIndex) //trim comment
  77. continue;
  78. if (line.StartsWith("[") && line.EndsWith("]")) //section
  79. {
  80. currentSection = line.Substring(1, line.Length - 2);
  81. continue;
  82. }
  83. string[] split = line.Split('='); //actual config line
  84. if (split.Length != 2)
  85. continue; //empty/invalid line
  86. if (!cache.ContainsKey(currentSection))
  87. cache[currentSection] = new Dictionary<string, string>();
  88. cache[currentSection][split[0]] = split[1];
  89. }
  90. RaiseConfigReloaded();
  91. }
  92. /// <summary>
  93. /// Writes the config to disk.
  94. /// </summary>
  95. public static void SaveConfig()
  96. {
  97. using (StreamWriter writer = new StreamWriter(File.Create(configPath), System.Text.Encoding.UTF8))
  98. foreach (var sectionKv in cache)
  99. {
  100. writer.WriteLine($"[{sectionKv.Key}]");
  101. foreach (var entryKv in sectionKv.Value)
  102. writer.WriteLine($"{entryKv.Key}={entryKv.Value}");
  103. writer.WriteLine();
  104. }
  105. }
  106. /// <summary>
  107. /// Sets the value of the key in the config.
  108. /// </summary>
  109. /// <param name="key">The key to set the value to.</param>
  110. /// <param name="value">The value to set.</param>
  111. public static void SetEntry(string key, string value, string section = "")
  112. {
  113. key = Sanitize(key);
  114. if (section.IsNullOrWhiteSpace())
  115. section = "Global";
  116. else
  117. section = Sanitize(section);
  118. Dictionary<string, string> subdict;
  119. if (!cache.TryGetValue(section, out subdict))
  120. {
  121. subdict = new Dictionary<string, string>();
  122. cache[section] = subdict;
  123. }
  124. subdict[key] = value;
  125. if (SaveOnConfigSet)
  126. SaveConfig();
  127. }
  128. /// <summary>
  129. /// Returns wether a value is currently set.
  130. /// </summary>
  131. /// <param name="key">The key to check against</param>
  132. /// <param name="section">The section to check in</param>
  133. /// <returns>True if the key is present</returns>
  134. public static bool HasEntry(string key, string section = "")
  135. {
  136. key = Sanitize(key);
  137. if (section.IsNullOrWhiteSpace())
  138. section = "Global";
  139. else
  140. section = Sanitize(section);
  141. return cache.ContainsKey(section) && cache[section].ContainsKey(key);
  142. }
  143. /// <summary>
  144. /// Removes a value from the config.
  145. /// </summary>
  146. /// <param name="key">The key to remove</param>
  147. /// <param name="section">The section to remove from</param>
  148. /// <returns>True if the key was removed</returns>
  149. public static bool UnsetEntry(string key, string section = "")
  150. {
  151. key = Sanitize(key);
  152. if (section.IsNullOrWhiteSpace())
  153. section = "Global";
  154. else
  155. section = Sanitize(section);
  156. if (!HasEntry(key, section))
  157. return false;
  158. cache[section].Remove(key);
  159. return true;
  160. }
  161. public static string Sanitize(string key)
  162. {
  163. return sanitizeKeyRegex.Replace(key, "_");
  164. }
  165. #region Extensions
  166. public static string GetEntry(this BaseUnityPlugin plugin, string key, string defaultValue = "")
  167. {
  168. return GetEntry(key, defaultValue, plugin.ID);
  169. }
  170. public static void SetEntry(this BaseUnityPlugin plugin, string key, string value)
  171. {
  172. SetEntry(key, value, plugin.ID);
  173. }
  174. public static bool HasEntry(this BaseUnityPlugin plugin, string key)
  175. {
  176. return HasEntry(key, plugin.ID);
  177. }
  178. #endregion Extensions
  179. }
  180. }