Refactor hot reload system to improve event handling & monitor delete events as well

This commit is contained in:
Thorsten Sommer 2025-06-01 20:54:25 +02:00
parent 7903f13a93
commit 85fcb4a6c8
Signed by: tsommer
GPG Key ID: 371BBA77A02C0108

View File

@ -15,12 +15,26 @@ public static partial class PluginFactory
LOG.LogInformation($"Start hot reloading plugins for path '{HOT_RELOAD_WATCHER.Path}'."); LOG.LogInformation($"Start hot reloading plugins for path '{HOT_RELOAD_WATCHER.Path}'.");
try try
{ {
var messageBus = Program.SERVICE_PROVIDER.GetRequiredService<MessageBus>();
HOT_RELOAD_WATCHER.IncludeSubdirectories = true; HOT_RELOAD_WATCHER.IncludeSubdirectories = true;
HOT_RELOAD_WATCHER.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName; HOT_RELOAD_WATCHER.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;
HOT_RELOAD_WATCHER.Filter = "*.lua"; HOT_RELOAD_WATCHER.Filter = "*.lua";
HOT_RELOAD_WATCHER.Changed += async (_, args) => HOT_RELOAD_WATCHER.Changed += HotReloadEventHandler;
HOT_RELOAD_WATCHER.Deleted += HotReloadEventHandler;
HOT_RELOAD_WATCHER.EnableRaisingEvents = true;
}
catch (Exception e)
{
LOG.LogError(e, "Error while setting up hot reloading.");
}
finally
{
LOG.LogInformation("Hot reloading plugins set up.");
}
}
private static async void HotReloadEventHandler(object _, FileSystemEventArgs args)
{
try
{ {
var changeType = args.ChangeType.ToString().ToLowerInvariant(); var changeType = args.ChangeType.ToString().ToLowerInvariant();
if (!await HOT_RELOAD_SEMAPHORE.WaitAsync(0)) if (!await HOT_RELOAD_SEMAPHORE.WaitAsync(0))
@ -33,23 +47,16 @@ public static partial class PluginFactory
{ {
LOG.LogInformation($"File changed ({changeType}): {args.FullPath}. Reloading plugins..."); LOG.LogInformation($"File changed ({changeType}): {args.FullPath}. Reloading plugins...");
await LoadAll(); await LoadAll();
await messageBus.SendMessage<bool>(null, Event.PLUGINS_RELOADED); await MessageBus.INSTANCE.SendMessage<bool>(null, Event.PLUGINS_RELOADED);
} }
finally finally
{ {
HOT_RELOAD_SEMAPHORE.Release(); HOT_RELOAD_SEMAPHORE.Release();
} }
};
HOT_RELOAD_WATCHER.EnableRaisingEvents = true;
} }
catch (Exception e) catch (Exception e)
{ {
LOG.LogError(e, "Error while setting up hot reloading."); LOG.LogError(e, $"Error while handling hot reload event for file '{args.FullPath}' with change type '{args.ChangeType}'.");
}
finally
{
LOG.LogInformation("Hot reloading plugins set up.");
} }
} }
} }