SourcesManager.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. #nullable enable
  2. using System.Diagnostics;
  3. using System.Diagnostics.CodeAnalysis;
  4. using System.Reflection;
  5. using System.Text.Json;
  6. namespace Terminal.Gui.Configuration;
  7. /// <summary>
  8. /// Manages the <see cref="ConfigurationManager"/> Sources and provides the API for loading them. Source is a location where a configuration can be stored. Sources are defined in <see cref="ConfigLocations"/>.
  9. /// </summary>
  10. public class SourcesManager
  11. {
  12. /// <summary>
  13. /// Provides a map from each of the <see cref="ConfigLocations"/> to file system and resource paths that have been loaded by <see cref="ConfigurationManager"/>.
  14. /// </summary>
  15. public Dictionary<ConfigLocations, string> Sources { get; } = new ();
  16. /// <summary>INTERNAL: Loads <paramref name="stream"/> into the specified <see cref="SettingsScope"/>.</summary>
  17. /// <param name="settingsScope">The Settings Scope object that <paramref name="stream"/> will be loaded into.</param>
  18. /// <param name="stream">Json document to update the settings with.</param>
  19. /// <param name="source">The source (filename/resource name) the Json document was read from.</param>
  20. /// <param name="location">The Config Location corresponding to <paramref name="source"/></param>
  21. /// <returns><see langword="true"/> if the settingsScope was updated.</returns>
  22. [RequiresUnreferencedCode ("AOT")]
  23. [RequiresDynamicCode ("AOT")]
  24. internal bool Load (SettingsScope? settingsScope, Stream stream, string source, ConfigLocations location)
  25. {
  26. if (settingsScope is null)
  27. {
  28. return false;
  29. }
  30. // Update the existing settings with the new settings.
  31. try
  32. {
  33. #if DEBUG
  34. string? json = new StreamReader (stream).ReadToEnd ();
  35. stream.Position = 0;
  36. Debug.Assert (json != null, "json != null");
  37. #endif
  38. SettingsScope? scope = JsonSerializer.Deserialize (stream, typeof (SettingsScope), ConfigurationManager.SerializerContext.Options) as SettingsScope;
  39. settingsScope.UpdateFrom (scope!);
  40. ConfigurationManager.OnUpdated ();
  41. AddSource (location, source);
  42. Logging.Trace ($"Read configuration from \"{source}\" - ConfigLocation: {location}");
  43. return true;
  44. }
  45. catch (JsonException e)
  46. {
  47. if (ConfigurationManager.ThrowOnJsonErrors ?? false)
  48. {
  49. throw;
  50. }
  51. ConfigurationManager.AddJsonError ($"Error reading {source}: {e.Message}");
  52. }
  53. return false;
  54. }
  55. internal void AddSource (ConfigLocations location, string source)
  56. {
  57. if (!Sources.TryAdd (location, source))
  58. {
  59. //Logging.Warning ($"{location} has already been added to Sources.");
  60. Sources [location] = source;
  61. }
  62. }
  63. /// <summary>INTERNAL: Loads the `config.json` file a <paramref name="filePath"/> into the specified <see cref="SettingsScope"/>.</summary>
  64. /// <param name="settingsScope">The Settings Scope object that <paramref name="filePath"/> will be loaded into.</param>
  65. /// <param name="filePath">Json document to update the settings with.</param>
  66. /// <param name="location">The Config Location corresponding to <paramref name="filePath"/></param>
  67. /// <returns><see langword="true"/> if the settingsScope was updated.</returns>
  68. [RequiresUnreferencedCode ("AOT")]
  69. [RequiresDynamicCode ("AOT")]
  70. internal bool Load (SettingsScope? settingsScope, string filePath, ConfigLocations location)
  71. {
  72. string realPath = filePath.Replace ("~", Environment.GetFolderPath (Environment.SpecialFolder.UserProfile));
  73. if (!File.Exists (realPath))
  74. {
  75. //Logging.Warning ($"\"{realPath}\" does not exist.");
  76. // Always add the source even if it doesn't exist.
  77. AddSource (location, filePath);
  78. return true;
  79. }
  80. int retryCount = 0;
  81. // Sometimes when the config file is written by an external agent, the change notification comes
  82. // before the file is closed. This works around that.
  83. while (retryCount < 2)
  84. {
  85. try
  86. {
  87. FileStream? stream = File.OpenRead (realPath);
  88. bool ret = Load (settingsScope, stream, filePath, location);
  89. stream.Close ();
  90. stream.Dispose ();
  91. return ret;
  92. }
  93. catch (IOException ioe)
  94. {
  95. Logging.Warning ($"{ioe.Message}. Retrying...");
  96. Task.Delay (100);
  97. retryCount++;
  98. }
  99. }
  100. return false;
  101. }
  102. /// <summary>INTERNAL: Loads the Json document in <paramref name="json"/> into the specified <see cref="SettingsScope"/>.</summary>
  103. /// <param name="settingsScope">The Settings Scope object that <paramref name="json"/> will be loaded into.</param>
  104. /// <param name="json">Json document to update the settings with.</param>
  105. /// <param name="source">The source (filename/resource name) the Json document was read from.</param>
  106. /// <param name="location">The Config Location corresponding to <paramref name="json"/></param>
  107. /// <returns><see langword="true"/> if the settingsScope was updated.</returns>
  108. [RequiresUnreferencedCode ("AOT")]
  109. [RequiresDynamicCode ("AOT")]
  110. internal bool Load (SettingsScope? settingsScope, string? json, string source, ConfigLocations location)
  111. {
  112. Debug.Assert (location != ConfigLocations.All);
  113. if (string.IsNullOrEmpty (json))
  114. {
  115. return false;
  116. }
  117. var stream = new MemoryStream ();
  118. var writer = new StreamWriter (stream);
  119. writer.Write (json);
  120. writer.Flush ();
  121. stream.Position = 0;
  122. return Load (settingsScope, stream, source, location);
  123. }
  124. /// <summary>INTERNAL: Loads the Json document from the resource named <paramref name="resourceName"/> from <paramref name="assembly"/> into the specified <see cref="SettingsScope"/>.</summary>
  125. /// <param name="settingsScope">The Settings Scope object that <paramref name="resourceName"/> will be loaded into.</param>
  126. /// <param name="assembly">The assembly containing the resource.</param>
  127. /// <param name="resourceName">The name of the resource containing the Json document was read from.</param>
  128. /// <param name="location">The Config Location corresponding to <paramref name="resourceName"/></param>
  129. /// <returns><see langword="true"/> if the settingsScope was updated.</returns>
  130. [RequiresUnreferencedCode ("AOT")]
  131. [RequiresDynamicCode ("AOT")]
  132. internal bool Load (SettingsScope? settingsScope, Assembly assembly, string resourceName, ConfigLocations location)
  133. {
  134. if (string.IsNullOrEmpty (resourceName))
  135. {
  136. Logging.Warning ($"{resourceName} must not be null or empty.");
  137. return false;
  138. }
  139. using Stream? stream = assembly.GetManifestResourceStream (resourceName);
  140. if (stream is null)
  141. {
  142. Logging.Warning ($"Resource \"{resourceName}\" does not exist in \"{assembly.GetName ().Name}\".");
  143. return false;
  144. }
  145. return Load (settingsScope, stream, $"resource://[{assembly.GetName ().Name}]/{resourceName}", location);
  146. }
  147. /// <summary>
  148. /// INTERNAL: Returns a JSON document with the configuration specified.
  149. /// </summary>
  150. /// <param name="scope"></param>
  151. [RequiresUnreferencedCode ("AOT")]
  152. [RequiresDynamicCode ("AOT")]
  153. internal string ToJson (SettingsScope? scope)
  154. {
  155. //Logging.Debug ("ConfigurationManager.ToJson()");
  156. return JsonSerializer.Serialize (scope, typeof (SettingsScope), ConfigurationManager.SerializerContext);
  157. }
  158. /// <summary>
  159. /// INTERNAL: Returns a stream with the configuration specified.
  160. /// </summary>
  161. /// <param name="scope"></param>
  162. [RequiresUnreferencedCode ("AOT")]
  163. [RequiresDynamicCode ("AOT")]
  164. internal Stream ToStream (SettingsScope? scope)
  165. {
  166. string json = JsonSerializer.Serialize (scope, typeof (SettingsScope), ConfigurationManager.SerializerContext);
  167. // turn it into a stream
  168. var stream = new MemoryStream ();
  169. var writer = new StreamWriter (stream);
  170. writer.Write (json);
  171. writer.Flush ();
  172. stream.Position = 0;
  173. return stream;
  174. }
  175. }