Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
Trojaner committed Jan 17, 2021
1 parent 536571f commit 5e31264
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 1 deletion.
2 changes: 1 addition & 1 deletion framework/OpenMod.Core/Commands/CommandStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ public async Task InvalidateAsync()
}

await m_CommandDataStore.SetRegisteredCommandsAsync(commandsData);
m_Logger.LogDebug($"InvalidateAsync: Loaded {commands.Count} commands.");
m_Logger.LogInformation($"Loaded {commands.Count} commands.");
}

public async Task<IReadOnlyCollection<ICommandRegistration>> GetCommandsAsync()
Expand Down
3 changes: 3 additions & 0 deletions framework/OpenMod.Core/Persistence/YamlDataStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,13 @@ public YamlDataStore(DataStoreCreationParameters parameters)

m_Serializer = new SerializerBuilder()
.WithNamingConvention(CamelCaseNamingConvention.Instance)
.WithTypeConverter(new YamlNullableEnumTypeConverter())
.Build();

m_Deserializer = new DeserializerBuilder()
.WithNamingConvention(CamelCaseNamingConvention.Instance)
.IgnoreUnmatchedProperties()
.WithTypeConverter(new YamlNullableEnumTypeConverter())
.Build();

m_ChangeListeners = new List<KeyValuePair<IOpenModComponent, Action>>();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
using System;
using OpenMod.API;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;

namespace OpenMod.Core.Persistence
{
/// Fixes an issue introduced in YamlDotNet 9.1
/// https://github.com/aaubry/YamlDotNet/issues/544
[OpenModInternal]
public class YamlNullableEnumTypeConverter : IYamlTypeConverter
{
public bool Accepts(Type type)
{
return Nullable.GetUnderlyingType(type)?.IsEnum ?? false;
}

public object ReadYaml(IParser parser, Type type)
{
type = Nullable.GetUnderlyingType(type) ?? throw new ArgumentException("Expected nullable enum type for ReadYaml");
var scalar = parser.Consume<Scalar>();

if (string.IsNullOrWhiteSpace(scalar.Value))
{
return null;
}

try
{
return Enum.Parse(type, scalar.Value);
}
catch(Exception ex)
{
throw new Exception($"Invalid value: \"{scalar.Value}\" for {type.Name}", ex);
}
}

public void WriteYaml(IEmitter emitter, object value, Type type)
{
type = Nullable.GetUnderlyingType(type) ?? throw new ArgumentException("Expected nullable enum type for WriteYaml");

if (value != null)
{
var toWrite = Enum.GetName(type, value) ?? throw new InvalidOperationException($"Invalid value {value} for enum: {type}");
emitter.Emit(new Scalar(null, null, toWrite, ScalarStyle.Any, true, false));
}
}
}
}

0 comments on commit 5e31264

Please sign in to comment.