Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes #3359. Updates Unit Tests to do CM.Reset #3360

Merged
merged 4 commits into from
Mar 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions Terminal.Gui/Configuration/ConfigProperty.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public bool Apply ()
{
if (PropertyInfo?.GetValue (null) is { })
{
PropertyInfo?.SetValue (null, DeepMemberwiseCopy (PropertyValue, PropertyInfo?.GetValue (null)));
PropertyInfo?.SetValue (null, DeepMemberWiseCopy (PropertyValue, PropertyInfo?.GetValue (null)));
}
}
catch (TargetInvocationException tie)
Expand Down Expand Up @@ -82,9 +82,9 @@ public bool Apply ()
/// <returns></returns>
public static string GetJsonPropertyName (PropertyInfo pi)
{
var jpna = pi.GetCustomAttribute (typeof (JsonPropertyNameAttribute)) as JsonPropertyNameAttribute;
var attr = pi.GetCustomAttribute (typeof (JsonPropertyNameAttribute)) as JsonPropertyNameAttribute;

return jpna?.Name ?? pi.Name;
return attr?.Name ?? pi.Name;
}

/// <summary>
Expand Down Expand Up @@ -118,7 +118,7 @@ public static string GetJsonPropertyName (PropertyInfo pi)

if (PropertyValue is { })
{
PropertyValue = DeepMemberwiseCopy (source, PropertyValue);
PropertyValue = DeepMemberWiseCopy (source, PropertyValue);
}
else
{
Expand Down
64 changes: 33 additions & 31 deletions Terminal.Gui/Configuration/ConfigurationManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
global using CM = Terminal.Gui.ConfigurationManager;
using System.Collections;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Text.Encodings.Web;
using System.Text.Json;
Expand Down Expand Up @@ -33,19 +34,19 @@ namespace Terminal.Gui;
/// Settings are applied using the following precedence (higher precedence settings overwrite lower precedence
/// settings):
/// <para>
/// 1. Application configuration found in the users's home directory (<c>~/.tui/appname.config.json</c>) --
/// 1. Application configuration found in the users' home directory (<c>~/.tui/appname.config.json</c>) --
/// Highest precedence
/// </para>
/// <para>
/// 2. Application configuration found in the directory the app was launched from (
/// <c>./.tui/appname.config.json</c>).
/// </para>
/// <para>3. Application configuration found in the applications's resources (<c>Resources/config.json</c>).</para>
/// <para>3. Application configuration found in the applications' resources (<c>Resources/config.json</c>).</para>
/// <para>4. Global configuration found in the user's home directory (<c>~/.tui/config.json</c>).</para>
/// <para>5. Global configuration found in the directory the app was launched from (<c>./.tui/config.json</c>).</para>
/// <para>
/// 6. Global configuration in <c>Terminal.Gui.dll</c>'s resources (<c>Terminal.Gui.Resources.config.json</c>) --
/// Lowest Precidence.
/// Lowest Precedence.
/// </para>
/// </summary>
public static class ConfigurationManager
Expand Down Expand Up @@ -82,8 +83,10 @@ public enum ConfigLocations
/// <see cref="ConfigurationManager"/> to get and set the property's value.
/// </summary>
/// <remarks>Is <see langword="null"/> until <see cref="Initialize"/> is called.</remarks>
[SuppressMessage ("Style", "IDE1006:Naming Styles", Justification = "<Pending>")]
internal static Dictionary<string, ConfigProperty>? _allConfigProperties;

[SuppressMessage ("Style", "IDE1006:Naming Styles", Justification = "<Pending>")]
internal static readonly JsonSerializerOptions _serializerOptions = new ()
{
ReadCommentHandling = JsonCommentHandling.Skip,
Expand All @@ -104,8 +107,10 @@ public enum ConfigLocations
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};

internal static StringBuilder jsonErrors = new ();
[SuppressMessage ("Style", "IDE1006:Naming Styles", Justification = "<Pending>")]
internal static StringBuilder _jsonErrors = new ();

[SuppressMessage ("Style", "IDE1006:Naming Styles", Justification = "<Pending>")]
private static readonly string _configFilename = "config.json";

/// <summary>The backing property for <see cref="Settings"/>.</summary>
Expand Down Expand Up @@ -280,7 +285,7 @@ public static void Load (bool reset = false)
public static void OnApplied ()
{
Debug.WriteLine ("ConfigurationManager.OnApplied()");
Applied?.Invoke (null, new ConfigurationManagerEventArgs ());
Applied?.Invoke (null, new ());

// TODO: Refactor ConfigurationManager to not use an event handler for this.
// Instead, have it call a method on any class appropriately attributed
Expand All @@ -294,18 +299,18 @@ public static void OnApplied ()
public static void OnUpdated ()
{
Debug.WriteLine (@"ConfigurationManager.OnApplied()");
Updated?.Invoke (null, new ConfigurationManagerEventArgs ());
Updated?.Invoke (null, new ());
}

/// <summary>Prints any Json deserialization errors that occurred during deserialization to the console.</summary>
public static void PrintJsonErrors ()
{
if (jsonErrors.Length > 0)
if (_jsonErrors.Length > 0)
{
Console.WriteLine (
@"Terminal.Gui ConfigurationManager encountered the following errors while deserializing configuration files:"
);
Console.WriteLine (jsonErrors.ToString ());
Console.WriteLine (_jsonErrors.ToString ());
}
}

Expand All @@ -326,9 +331,9 @@ public static void Reset ()

ClearJsonErrors ();

Settings = new SettingsScope ();
Settings = new ();
ThemeManager.Reset ();
AppSettings = new AppScope ();
AppSettings = new ();

// To enable some unit tests, we only load from resources if the flag is set
if (Locations.HasFlag (ConfigLocations.DefaultOnly))
Expand All @@ -350,23 +355,20 @@ public static void Reset ()
internal static void AddJsonError (string error)
{
Debug.WriteLine ($"ConfigurationManager: {error}");
jsonErrors.AppendLine (error);
_jsonErrors.AppendLine (error);
}

/// <summary>
/// System.Text.Json does not support copying a deserialized object to an existing instance. To work around this,
/// we implement a 'deep, memberwise copy' method.
/// we implement a 'deep, member-wise copy' method.
/// </summary>
/// <remarks>TOOD: When System.Text.Json implements `PopulateObject` revisit https://github.com/dotnet/corefx/issues/37627</remarks>
/// <param name="source"></param>
/// <param name="destination"></param>
/// <returns><paramref name="destination"/> updated from <paramref name="source"/></returns>
internal static object? DeepMemberwiseCopy (object? source, object? destination)
internal static object? DeepMemberWiseCopy (object? source, object? destination)
{
if (destination is null)
{
throw new ArgumentNullException (nameof (destination));
}
ArgumentNullException.ThrowIfNull (destination);

if (source is null)
{
Expand Down Expand Up @@ -406,7 +408,7 @@ internal static void AddJsonError (string error)
if (((IDictionary)destination).Contains (srcKey))
{
((IDictionary)destination) [srcKey] =
DeepMemberwiseCopy (((IDictionary)source) [srcKey], ((IDictionary)destination) [srcKey]);
DeepMemberWiseCopy (((IDictionary)source) [srcKey], ((IDictionary)destination) [srcKey]);
}
else
{
Expand Down Expand Up @@ -438,7 +440,7 @@ where destProp.CanWrite
if (destVal is { })
{
// Recurse
destProp.SetValue (destination, DeepMemberwiseCopy (sourceVal, destVal));
destProp.SetValue (destination, DeepMemberWiseCopy (sourceVal, destVal));
}
else
{
Expand Down Expand Up @@ -478,7 +480,7 @@ internal static void GetHardCodedDefaults ()
throw new InvalidOperationException ("Initialize must be called first.");
}

Settings = new SettingsScope ();
Settings = new ();
ThemeManager.GetHardCodedDefaults ();
AppSettings?.RetrieveValues ();

Expand All @@ -494,7 +496,7 @@ internal static void GetHardCodedDefaults ()
/// </summary>
internal static void Initialize ()
{
_allConfigProperties = new Dictionary<string, ConfigProperty> ();
_allConfigProperties = new ();
_settings = null;

Dictionary<string, Type> classesWithConfigProps = new (StringComparer.InvariantCultureIgnoreCase);
Expand Down Expand Up @@ -549,18 +551,18 @@ where type.GetProperties ()
scp.OmitClassName
? ConfigProperty.GetJsonPropertyName (p)
: $"{p.DeclaringType?.Name}.{p.Name}",
new ConfigProperty { PropertyInfo = p, PropertyValue = null }
new() { PropertyInfo = p, PropertyValue = null }
);
}
else
{
throw new Exception (
$"Property {
p.Name
} in class {
p.DeclaringType?.Name
} is not static. All SerializableConfigurationProperty properties must be static."
);
throw new (
$"Property {
p.Name
} in class {
p.DeclaringType?.Name
} is not static. All SerializableConfigurationProperty properties must be static."
);
}
}
}
Expand All @@ -576,7 +578,7 @@ where type.GetProperties ()

//_allConfigProperties.ToList ().ForEach (x => Debug.WriteLine ($" Property: {x.Key}"));

AppSettings = new AppScope ();
AppSettings = new ();
}

/// <summary>Creates a JSON document with the configuration specified.</summary>
Expand All @@ -602,5 +604,5 @@ internal static Stream ToStream ()
return stream;
}

private static void ClearJsonErrors () { jsonErrors.Clear (); }
private static void ClearJsonErrors () { _jsonErrors.Clear (); }
}
3 changes: 3 additions & 0 deletions Terminal.sln.DotSettings
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,9 @@
<s:Boolean x:Key="/Default/CodeStyle/EditorConfig/ShowEditorConfigStatusBarIndicator/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/EditorConfig/SyncToVisualStudio/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/Naming/CSharpNaming/ApplyAutoDetectedRules/@EntryValue">False</s:Boolean>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=PrivateStaticReadonly/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="_" Suffix="" Style="aaBb" /&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=PublicFields/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="_" Suffix="" Style="aaBb" /&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=StaticReadonly/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="_" Suffix="" Style="aaBb" /&gt;</s:String>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpKeepExistingMigration/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpPlaceEmbeddedOnSameLineMigration/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpUseContinuousIndentInsideBracesMigration/@EntryIndexedValue">True</s:Boolean>
Expand Down
Loading
Loading