SourcesManager.cs 8.3 KB

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