2025-11-26 22:38:04 -06:00
|
|
|
using System.Text.RegularExpressions;
|
2025-11-26 01:09:52 -06:00
|
|
|
using LANCommander.SDK.PowerShell;
|
|
|
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
|
|
|
|
|
|
namespace LANCommander.Launcher.Services.PowerShell;
|
|
|
|
|
|
|
|
|
|
public class ScriptDebugger : IScriptDebugger
|
|
|
|
|
{
|
2025-12-10 20:55:38 -06:00
|
|
|
public Func<IScriptDebugContext, Task>? OnDebugStart;
|
|
|
|
|
public Func<IScriptDebugContext, Task>? OnDebugBreak;
|
|
|
|
|
public Func<IScriptDebugContext, Task>? OnDebugEnd;
|
|
|
|
|
public Func<LogLevel, string, Task>? OnOutput;
|
2025-11-26 01:09:52 -06:00
|
|
|
|
2025-11-26 22:38:04 -06:00
|
|
|
private static readonly Regex TokenRegex = new(@"\{[^}]+\}", RegexOptions.Compiled);
|
|
|
|
|
|
2025-12-10 20:55:38 -06:00
|
|
|
public Task StartAsync(IScriptDebugContext context)
|
2025-11-26 01:09:52 -06:00
|
|
|
{
|
2025-12-10 20:55:38 -06:00
|
|
|
return OnDebugStart is null
|
|
|
|
|
? Task.CompletedTask
|
|
|
|
|
: OnDebugStart(context);
|
2025-11-26 01:09:52 -06:00
|
|
|
}
|
|
|
|
|
|
2025-12-10 20:55:38 -06:00
|
|
|
public Task EndAsync(IScriptDebugContext context)
|
2025-11-26 01:09:52 -06:00
|
|
|
{
|
2025-12-10 20:55:38 -06:00
|
|
|
return OnDebugEnd is null
|
|
|
|
|
? Task.CompletedTask
|
|
|
|
|
: OnDebugEnd(context);
|
2025-11-26 01:09:52 -06:00
|
|
|
}
|
|
|
|
|
|
2025-12-10 20:55:38 -06:00
|
|
|
public Task BreakAsync(IScriptDebugContext context)
|
2025-11-26 01:09:52 -06:00
|
|
|
{
|
2025-12-10 20:55:38 -06:00
|
|
|
return OnDebugBreak is null
|
|
|
|
|
? Task.CompletedTask
|
|
|
|
|
: OnDebugBreak(context);
|
2025-11-26 01:09:52 -06:00
|
|
|
}
|
|
|
|
|
|
2025-12-10 20:55:38 -06:00
|
|
|
public Task OutputAsync(IScriptDebugContext context, LogLevel level, string message, params object[] args)
|
2025-11-26 01:09:52 -06:00
|
|
|
{
|
2025-12-10 20:55:38 -06:00
|
|
|
if (OnOutput is null)
|
|
|
|
|
return Task.CompletedTask;
|
|
|
|
|
|
|
|
|
|
return OnOutput(level, Format(message, args));
|
2025-11-26 22:38:04 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private string Format(string template, object?[] args)
|
|
|
|
|
{
|
|
|
|
|
if (args == null || args.Length == 0)
|
|
|
|
|
return template;
|
|
|
|
|
|
|
|
|
|
int i = 0;
|
|
|
|
|
|
|
|
|
|
return TokenRegex.Replace(template, _ =>
|
|
|
|
|
i < args.Length ? args[i++]?.ToString() ?? string.Empty : string.Empty);
|
2025-11-26 01:09:52 -06:00
|
|
|
}
|
|
|
|
|
}
|