Files
ScadaBridge/src/ScadaLink.CLI/Commands/AuditCommandHelpers.cs
T
2026-05-20 21:55:38 -04:00

73 lines
2.7 KiB
C#

using System.CommandLine;
using System.CommandLine.Parsing;
namespace ScadaLink.CLI.Commands;
/// <summary>
/// Resolved Management API connection details for an <c>audit</c> subcommand, or an
/// error describing why resolution failed.
/// </summary>
public sealed class AuditConnection
{
public string? Url { get; init; }
public string? Username { get; init; }
public string? Password { get; init; }
public string? Error { get; init; }
public string? ErrorCode { get; init; }
public static AuditConnection Fail(string error, string code)
=> new() { Error = error, ErrorCode = code };
}
/// <summary>
/// Connection/format resolution shared by the <c>audit</c> subcommands. Mirrors the URL
/// and credential precedence used by <see cref="CommandHelpers"/> (command line → config
/// file / environment), but produces a raw <see cref="ManagementHttpClient"/> target
/// because the audit endpoints are plain REST resources rather than <c>POST /management</c>
/// command-envelope calls.
/// </summary>
public static class AuditCommandHelpers
{
public static AuditConnection ResolveConnection(
ParseResult result,
Option<string> urlOption,
Option<string> usernameOption,
Option<string> passwordOption)
{
var config = CliConfig.Load();
var url = result.GetValue(urlOption);
if (string.IsNullOrWhiteSpace(url))
url = config.ManagementUrl;
if (string.IsNullOrWhiteSpace(url))
{
return AuditConnection.Fail(
"No management URL specified. Use --url, set SCADALINK_MANAGEMENT_URL, or add 'managementUrl' to ~/.scadalink/config.json.",
"NO_URL");
}
if (!CommandHelpers.IsValidManagementUrl(url))
{
return AuditConnection.Fail(
$"Invalid management URL '{url}'. Expected an absolute http/https URL (e.g. http://localhost:9001).",
"INVALID_URL");
}
var username = CommandHelpers.ResolveCredential(result.GetValue(usernameOption), config.Username);
var password = CommandHelpers.ResolveCredential(result.GetValue(passwordOption), config.Password);
if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
{
return AuditConnection.Fail(
"Credentials required. Use --username/--password or set SCADALINK_USERNAME/SCADALINK_PASSWORD.",
"NO_CREDENTIALS");
}
return new AuditConnection { Url = url, Username = username, Password = password };
}
public static string ResolveFormat(ParseResult result, Option<string> formatOption)
=> CommandHelpers.ResolveFormat(result, formatOption, CliConfig.Load());
}