Config.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text.RegularExpressions;
  5. using BepInEx.Common;
  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(Common.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. {
  59. return value;
  60. }
  61. else
  62. {
  63. SetEntry(key, defaultValue, section);
  64. return defaultValue;
  65. }
  66. }
  67. /// <summary>
  68. /// Reloads the config from disk. Unwritten changes are lost.
  69. /// </summary>
  70. public static void ReloadConfig()
  71. {
  72. cache.Clear();
  73. string currentSection = "";
  74. foreach (string rawLine in File.ReadAllLines(configPath))
  75. {
  76. string line = rawLine.Trim();
  77. bool commentIndex = line.StartsWith(";") || line.StartsWith("#");
  78. if (commentIndex) //trim comment
  79. continue;
  80. if (line.StartsWith("[") && line.EndsWith("]")) //section
  81. {
  82. currentSection = line.Substring(1, line.Length - 2);
  83. continue;
  84. }
  85. string[] split = line.Split('='); //actual config line
  86. if (split.Length != 2)
  87. continue; //empty/invalid line
  88. if (!cache.ContainsKey(currentSection))
  89. cache[currentSection] = new Dictionary<string, string>();
  90. cache[currentSection][split[0]] = split[1];
  91. }
  92. RaiseConfigReloaded();
  93. }
  94. /// <summary>
  95. /// Writes the config to disk.
  96. /// </summary>
  97. public static void SaveConfig()
  98. {
  99. using (StreamWriter writer = new StreamWriter(File.Create(configPath), System.Text.Encoding.UTF8))
  100. foreach (var sectionKv in cache)
  101. {
  102. writer.WriteLine($"[{sectionKv.Key}]");
  103. foreach (var entryKv in sectionKv.Value)
  104. writer.WriteLine($"{entryKv.Key}={entryKv.Value}");
  105. writer.WriteLine();
  106. }
  107. }
  108. /// <summary>
  109. /// Sets the value of the key in the config.
  110. /// </summary>
  111. /// <param name="key">The key to set the value to.</param>
  112. /// <param name="value">The value to set.</param>
  113. public static void SetEntry(string key, string value, string section = "")
  114. {
  115. key = Sanitize(key);
  116. if (section.IsNullOrWhiteSpace())
  117. section = "Global";
  118. else
  119. section = Sanitize(section);
  120. Dictionary<string, string> subdict;
  121. if (!cache.TryGetValue(section, out subdict))
  122. {
  123. subdict = new Dictionary<string, string>();
  124. cache[section] = subdict;
  125. }
  126. subdict[key] = value;
  127. if (SaveOnConfigSet)
  128. SaveConfig();
  129. }
  130. /// <summary>
  131. /// Returns wether a value is currently set.
  132. /// </summary>
  133. /// <param name="key">The key to check against</param>
  134. /// <param name="section">The section to check in</param>
  135. /// <returns>True if the key is present</returns>
  136. public static bool HasEntry(string key, string section = "")
  137. {
  138. key = Sanitize(key);
  139. if (section.IsNullOrWhiteSpace())
  140. section = "Global";
  141. else
  142. section = Sanitize(section);
  143. return cache.ContainsKey(section) && cache[section].ContainsKey(key);
  144. }
  145. /// <summary>
  146. /// Removes a value from the config.
  147. /// </summary>
  148. /// <param name="key">The key to remove</param>
  149. /// <param name="section">The section to remove from</param>
  150. /// <returns>True if the key was removed</returns>
  151. public static bool UnsetEntry(string key, string section = "")
  152. {
  153. key = Sanitize(key);
  154. if (section.IsNullOrWhiteSpace())
  155. section = "Global";
  156. else
  157. section = Sanitize(section);
  158. if (!HasEntry(key, section))
  159. return false;
  160. cache[section].Remove(key);
  161. return true;
  162. }
  163. public static string Sanitize(string key)
  164. {
  165. return sanitizeKeyRegex.Replace(key, "_");
  166. }
  167. #region Extensions
  168. public static string GetEntry(this BaseUnityPlugin plugin, string key, string defaultValue = "")
  169. {
  170. return GetEntry(key, defaultValue, TypeLoader.GetMetadata(plugin).GUID);
  171. }
  172. public static void SetEntry(this BaseUnityPlugin plugin, string key, string value)
  173. {
  174. SetEntry(key, value, TypeLoader.GetMetadata(plugin).GUID);
  175. }
  176. public static bool HasEntry(this BaseUnityPlugin plugin, string key)
  177. {
  178. return HasEntry(key, TypeLoader.GetMetadata(plugin).GUID);
  179. }
  180. #endregion Extensions
  181. }
  182. }