SourcesManager.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. using System.Collections.Concurrent;
  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 ConcurrentDictionary<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. // ConcurrentDictionary's AddOrUpdate is thread-safe
  58. Sources.AddOrUpdate (location, source, (key, oldValue) => source);
  59. }
  60. /// <summary>INTERNAL: Loads the `config.json` file a <paramref name="filePath"/> into the specified <see cref="SettingsScope"/>.</summary>
  61. /// <param name="settingsScope">The Settings Scope object that <paramref name="filePath"/> will be loaded into.</param>
  62. /// <param name="filePath">Json document to update the settings with.</param>
  63. /// <param name="location">The Config Location corresponding to <paramref name="filePath"/></param>
  64. /// <returns><see langword="true"/> if the settingsScope was updated.</returns>
  65. [RequiresUnreferencedCode ("AOT")]
  66. [RequiresDynamicCode ("AOT")]
  67. internal bool Load (SettingsScope? settingsScope, string filePath, ConfigLocations location)
  68. {
  69. string realPath = filePath.Replace ("~", Environment.GetFolderPath (Environment.SpecialFolder.UserProfile));
  70. if (!File.Exists (realPath))
  71. {
  72. //Logging.Warning ($"\"{realPath}\" does not exist.");
  73. // Always add the source even if it doesn't exist.
  74. AddSource (location, filePath);
  75. return true;
  76. }
  77. int retryCount = 0;
  78. // Sometimes when the config file is written by an external agent, the change notification comes
  79. // before the file is closed. This works around that.
  80. while (retryCount < 2)
  81. {
  82. try
  83. {
  84. FileStream? stream = File.OpenRead (realPath);
  85. bool ret = Load (settingsScope, stream, filePath, location);
  86. stream.Close ();
  87. stream.Dispose ();
  88. return ret;
  89. }
  90. catch (IOException ioe)
  91. {
  92. Logging.Warning ($"{ioe.Message}. Retrying...");
  93. Task.Delay (100);
  94. retryCount++;
  95. }
  96. }
  97. return false;
  98. }
  99. /// <summary>INTERNAL: Loads the Json document in <paramref name="json"/> into the specified <see cref="SettingsScope"/>.</summary>
  100. /// <param name="settingsScope">The Settings Scope object that <paramref name="json"/> will be loaded into.</param>
  101. /// <param name="json">Json document to update the settings with.</param>
  102. /// <param name="source">The source (filename/resource name) the Json document was read from.</param>
  103. /// <param name="location">The Config Location corresponding to <paramref name="json"/></param>
  104. /// <returns><see langword="true"/> if the settingsScope was updated.</returns>
  105. [RequiresUnreferencedCode ("AOT")]
  106. [RequiresDynamicCode ("AOT")]
  107. internal bool Load (SettingsScope? settingsScope, string? json, string source, ConfigLocations location)
  108. {
  109. Debug.Assert (location != ConfigLocations.All);
  110. if (string.IsNullOrEmpty (json))
  111. {
  112. return false;
  113. }
  114. var stream = new MemoryStream ();
  115. var writer = new StreamWriter (stream);
  116. writer.Write (json);
  117. writer.Flush ();
  118. stream.Position = 0;
  119. return Load (settingsScope, stream, source, location);
  120. }
  121. /// <summary>INTERNAL: Loads the Json document from the resource named <paramref name="resourceName"/> from <paramref name="assembly"/> into the specified <see cref="SettingsScope"/>.</summary>
  122. /// <param name="settingsScope">The Settings Scope object that <paramref name="resourceName"/> will be loaded into.</param>
  123. /// <param name="assembly">The assembly containing the resource.</param>
  124. /// <param name="resourceName">The name of the resource containing the Json document was read from.</param>
  125. /// <param name="location">The Config Location corresponding to <paramref name="resourceName"/></param>
  126. /// <returns><see langword="true"/> if the settingsScope was updated.</returns>
  127. [RequiresUnreferencedCode ("AOT")]
  128. [RequiresDynamicCode ("AOT")]
  129. internal bool Load (SettingsScope? settingsScope, Assembly assembly, string resourceName, ConfigLocations location)
  130. {
  131. if (string.IsNullOrEmpty (resourceName))
  132. {
  133. Logging.Warning ($"{resourceName} must not be null or empty.");
  134. return false;
  135. }
  136. using Stream? stream = assembly.GetManifestResourceStream (resourceName);
  137. if (stream is null)
  138. {
  139. Logging.Warning ($"Resource \"{resourceName}\" does not exist in \"{assembly.GetName ().Name}\".");
  140. return false;
  141. }
  142. return Load (settingsScope, stream, $"resource://[{assembly.GetName ().Name}]/{resourceName}", location);
  143. }
  144. /// <summary>
  145. /// INTERNAL: Returns a JSON document with the configuration specified.
  146. /// </summary>
  147. /// <param name="scope"></param>
  148. [RequiresUnreferencedCode ("AOT")]
  149. [RequiresDynamicCode ("AOT")]
  150. internal string ToJson (SettingsScope? scope)
  151. {
  152. //Logging.Debug ("ConfigurationManager.ToJson()");
  153. return JsonSerializer.Serialize (scope, typeof (SettingsScope), ConfigurationManager.SerializerContext);
  154. }
  155. /// <summary>
  156. /// INTERNAL: Returns a stream with the configuration specified.
  157. /// </summary>
  158. /// <param name="scope"></param>
  159. [RequiresUnreferencedCode ("AOT")]
  160. [RequiresDynamicCode ("AOT")]
  161. internal Stream ToStream (SettingsScope? scope)
  162. {
  163. string json = JsonSerializer.Serialize (scope, typeof (SettingsScope), ConfigurationManager.SerializerContext);
  164. // turn it into a stream
  165. var stream = new MemoryStream ();
  166. var writer = new StreamWriter (stream);
  167. writer.Write (json);
  168. writer.Flush ();
  169. stream.Position = 0;
  170. return stream;
  171. }
  172. }