SourcesManager.cs 8.3 KB

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