Config.cs 6.6 KB

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