Skip to content

Commit

Permalink
Adding SerializeIgnore support
Browse files Browse the repository at this point in the history
  • Loading branch information
rube200 committed Mar 4, 2024
1 parent 08eff02 commit cab5931
Showing 1 changed file with 49 additions and 21 deletions.
70 changes: 49 additions & 21 deletions framework/OpenMod.Core/Persistence/YamlDataStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
using OpenMod.Core.Helpers;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
using YamlDotNet.Serialization.TypeInspectors;

namespace OpenMod.Core.Persistence
{
Expand Down Expand Up @@ -63,9 +64,11 @@ public class YamlDataStore : IDataStore, IDisposable

var serializerBuilder = new SerializerBuilder()
.WithNamingConvention(CamelCaseNamingConvention.Instance)
.WithTypeInspector(i => new SerializableIgnoreInspector(i))
.DisableAliases();
var deserializerBuilder = new DeserializerBuilder()
.WithNamingConvention(CamelCaseNamingConvention.Instance)
.WithTypeInspector(i => new SerializableIgnoreInspector(i))
.IgnoreUnmatchedProperties();

foreach(var converter in options.Value.Converters)
Expand Down Expand Up @@ -198,7 +201,7 @@ private async Task ChangeEventHandler(FileSystemEventArgs a)
var fileHash = BitConverter.ToString(sha.ComputeHash(fileStream));

// Ensure that we are actually writing different data
// otherwise the file change watcher won't trigger and result in desycned write counter state
// otherwise the file change watcher won't trigger and result in desynced write counter state
if (string.Equals(fileHash, contentHash, StringComparison.Ordinal))
{
return Task.CompletedTask;
Expand Down Expand Up @@ -270,7 +273,7 @@ public Task<bool> ExistsAsync(string key)
// when reading from a FileSystemWatcher's event.
//
// Similar: https://stackoverflow.com/q/49551278
var encodedData = await Retry.DoAsync(() => File.ReadAllBytes((filePath)), TimeSpan.FromMilliseconds(1), 5);
var encodedData = await Retry.DoAsync(() => File.ReadAllBytes(filePath), TimeSpan.FromMilliseconds(1), 5);

using var sha = new SHA256Managed();
var contentHash = BitConverter.ToString(sha.ComputeHash(encodedData));
Expand Down Expand Up @@ -379,16 +382,15 @@ private void RegisterKnownKey(string key)
// Will add a change watcher that logs detected file changes
m_KnownKeys.Add(key);

if (m_LogOnChange && !m_WatchedFiles.Contains(key) && m_Runtime != null)
{
m_WatchedFiles.Add(key);
if (!m_LogOnChange || m_WatchedFiles.Contains(key) || m_Runtime == null)
return;

AddChangeWatcher(key, m_Runtime!, () =>
{
m_Logger.LogInformation("Reloaded {Prefix}{Key}{Suffix}.yaml",
m_Prefix ?? string.Empty, key, m_Suffix ?? string.Empty);
});
}
m_WatchedFiles.Add(key);
AddChangeWatcher(key, m_Runtime!, () =>
{
m_Logger.LogInformation("Reloaded {Prefix}{Key}{Suffix}.yaml",
m_Prefix ?? string.Empty, key, m_Suffix ?? string.Empty);
});
}

protected virtual string GetFilePathForKey(string key)
Expand All @@ -398,6 +400,12 @@ protected virtual string GetFilePathForKey(string key)

private void IncrementWriteCounter(string key)
{
#if NETSTANDARD2_1
if (!m_WriteCounter.TryAdd(key, 1))
{
m_WriteCounter[key]++;
}
#else
if (!m_WriteCounter.ContainsKey(key))
{
m_WriteCounter.Add(key, 1);
Expand All @@ -406,6 +414,7 @@ private void IncrementWriteCounter(string key)
{
m_WriteCounter[key]++;
}
#endif
}

private bool DecrementWriteCounter(string key)
Expand All @@ -415,18 +424,19 @@ private bool DecrementWriteCounter(string key)
return true;
}

if (m_WriteCounter[key] == 0)
#pragma warning disable IDE0066 // Convert switch to expression
// ReSharper disable once ConvertSwitchStatementToSwitchExpression
switch (m_WriteCounter[key])
{
return true;
case 0:
return true;
case < 0:
// race condition? can only happen if called outside lock
throw new InvalidOperationException("DecrementWriteCounter has become negative");
default:
return m_WriteCounter[key]-- == 0;
}

if (m_WriteCounter[key] < 0)
{
// race condition? can only happen if called outside lock
throw new InvalidOperationException("DecrementWriteCounter has become negative");
}

return m_WriteCounter[key]-- == 0;
#pragma warning restore IDE0066 // Convert switch to expression
}

public void Dispose()
Expand Down Expand Up @@ -454,5 +464,23 @@ public RegisteredChangeListener(IOpenModComponent component, string key, Action

public Action Callback { get; }
}

//Note we could try use AttributeOverride, but they are processed after YamlIgnoreAttribute
//So if we add YamlIgnoreAttribute they will be ignored
public class SerializableIgnoreInspector : TypeInspectorSkeleton
{
private readonly ITypeInspector m_InnerTypeDescriptor;

public SerializableIgnoreInspector(ITypeInspector typeInspector)
{
m_InnerTypeDescriptor = typeInspector;
}

public override IEnumerable<IPropertyDescriptor> GetProperties(Type type, object? container)
{
var inspectorProps = m_InnerTypeDescriptor.GetProperties(type, container);
return inspectorProps.Where(inspectProp => inspectProp.GetCustomAttribute<SerializeIgnoreAttribute>() == null);
}
}
}
}

0 comments on commit cab5931

Please sign in to comment.