f1a7c34b69
Claude-Session: https://claude.ai/code/session_01Y5ef34iUUMjmwnMpL9xgmB
770 lines
38 KiB
C#
770 lines
38 KiB
C#
using System.CommandLine;
|
|
using System.CommandLine.Parsing;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Types;
|
|
|
|
namespace ZB.MOM.WW.ScadaBridge.CLI.Commands;
|
|
|
|
public static class InstanceCommands
|
|
{
|
|
/// <summary>
|
|
/// Builds the instance command and its subcommands.
|
|
/// </summary>
|
|
/// <param name="urlOption">The URL option.</param>
|
|
/// <param name="formatOption">The format option.</param>
|
|
/// <param name="usernameOption">The username option.</param>
|
|
/// <param name="passwordOption">The password option.</param>
|
|
/// <returns>The instance command with all subcommands.</returns>
|
|
public static Command Build(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
|
{
|
|
var command = new Command("instance") { Description = "Manage instances" };
|
|
|
|
command.Add(BuildList(urlOption, formatOption, usernameOption, passwordOption));
|
|
command.Add(BuildGet(urlOption, formatOption, usernameOption, passwordOption));
|
|
command.Add(BuildCreate(urlOption, formatOption, usernameOption, passwordOption));
|
|
command.Add(BuildSetBindings(urlOption, formatOption, usernameOption, passwordOption));
|
|
command.Add(CreateBindModuleCommand(urlOption, formatOption, usernameOption, passwordOption));
|
|
command.Add(BuildSetOverrides(urlOption, formatOption, usernameOption, passwordOption));
|
|
command.Add(BuildImportOverrides(urlOption, formatOption, usernameOption, passwordOption));
|
|
command.Add(BuildAlarmOverride(urlOption, formatOption, usernameOption, passwordOption));
|
|
command.Add(BuildNativeAlarmSourceOverride(urlOption, formatOption, usernameOption, passwordOption));
|
|
command.Add(BuildAttributeOverride(urlOption, formatOption, usernameOption, passwordOption));
|
|
command.Add(BuildSetArea(urlOption, formatOption, usernameOption, passwordOption));
|
|
command.Add(BuildDiff(urlOption, formatOption, usernameOption, passwordOption));
|
|
command.Add(BuildDeploy(urlOption, formatOption, usernameOption, passwordOption));
|
|
command.Add(BuildEnable(urlOption, formatOption, usernameOption, passwordOption));
|
|
command.Add(BuildDisable(urlOption, formatOption, usernameOption, passwordOption));
|
|
command.Add(BuildDelete(urlOption, formatOption, usernameOption, passwordOption));
|
|
|
|
return command;
|
|
}
|
|
|
|
private static Command BuildGet(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
|
{
|
|
var idOption = new Option<int>("--id") { Description = "Instance ID", Required = true };
|
|
var cmd = new Command("get") { Description = "Get an instance by ID" };
|
|
cmd.Add(idOption);
|
|
cmd.SetAction(async (ParseResult result) =>
|
|
{
|
|
var id = result.GetValue(idOption);
|
|
return await CommandHelpers.ExecuteCommandAsync(
|
|
result, urlOption, formatOption, usernameOption, passwordOption, new GetInstanceCommand(id));
|
|
});
|
|
return cmd;
|
|
}
|
|
|
|
private static Command BuildSetBindings(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
|
{
|
|
var idOption = new Option<int>("--id") { Description = "Instance ID", Required = true };
|
|
var bindingsOption = new Option<string>("--bindings")
|
|
{
|
|
Description = "JSON array of binding entries. Each entry is either " +
|
|
"[attributeName, dataConnectionId] or " +
|
|
"[attributeName, dataConnectionId, dataSourceReferenceOverride] " +
|
|
"(the 3rd element overrides the attribute's data-source reference; " +
|
|
"pass null or omit it to use the template default). " +
|
|
"NOTE: this UPSERTS — listed attributes are updated or added, unlisted " +
|
|
"ones keep their binding; omitting the 3rd element on a listed entry " +
|
|
"clears that attribute's previously-set override.",
|
|
Required = true
|
|
};
|
|
|
|
var cmd = new Command("set-bindings") { Description = "Set data connection bindings for an instance" };
|
|
cmd.Add(idOption);
|
|
cmd.Add(bindingsOption);
|
|
cmd.SetAction(async (ParseResult result) =>
|
|
{
|
|
var id = result.GetValue(idOption);
|
|
var bindingsJson = result.GetValue(bindingsOption)!;
|
|
if (!TryParseBindings(bindingsJson, out var bindings, out var error))
|
|
{
|
|
OutputFormatter.WriteError(error!, "INVALID_ARGUMENT");
|
|
return 1;
|
|
}
|
|
return await CommandHelpers.ExecuteCommandAsync(
|
|
result, urlOption, formatOption, usernameOption, passwordOption,
|
|
new SetConnectionBindingsCommand(id, bindings!));
|
|
});
|
|
return cmd;
|
|
}
|
|
|
|
private static Command CreateBindModuleCommand(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
|
{
|
|
var idOption = new Option<int>("--id") { Description = "Instance ID", Required = true };
|
|
var moduleOption = new Option<string>("--module")
|
|
{
|
|
Description = "Module (canonical-name prefix), e.g. RightMESReceiver; use '(instance)' for the instance's direct attributes",
|
|
Required = true
|
|
};
|
|
var connOption = new Option<int>("--connection") { Description = "Data connection ID", Required = true };
|
|
var objectOption = new Option<string>("--object")
|
|
{
|
|
Description = "MxAccess/OPC object path the module's members hang off, e.g. MESReceiver_022 or Left_002.DelmiaReceiver; " +
|
|
"an empty string clears the module's overrides (template defaults apply)",
|
|
Required = true
|
|
};
|
|
var dryRunOption = new Option<bool>("--dry-run") { Description = "Print the resulting bindings without saving" };
|
|
|
|
var cmd = new Command("bind-module")
|
|
{
|
|
Description = "Rebind every member of one composed module to a new object path (upserts only that module's bindings; other modules are untouched)"
|
|
};
|
|
cmd.Add(idOption);
|
|
cmd.Add(moduleOption);
|
|
cmd.Add(connOption);
|
|
cmd.Add(objectOption);
|
|
cmd.Add(dryRunOption);
|
|
cmd.SetAction(async (ParseResult result) =>
|
|
{
|
|
var id = result.GetValue(idOption);
|
|
var module = result.GetValue(moduleOption)!;
|
|
var conn = result.GetValue(connOption);
|
|
var obj = result.GetValue(objectOption);
|
|
var dryRun = result.GetValue(dryRunOption);
|
|
|
|
// Step 1: fetch the instance. The success handler only captures the body so
|
|
// the second round-trip can run as a proper await outside the callback.
|
|
string? instanceJson = null;
|
|
var exit = await CommandHelpers.ExecuteCommandAsync(
|
|
result, urlOption, formatOption, usernameOption, passwordOption,
|
|
new GetInstanceCommand(id),
|
|
onSuccess: json => { instanceJson = json; return 0; });
|
|
if (exit != 0 || instanceJson is null)
|
|
return exit == 0 ? 1 : exit;
|
|
|
|
List<ConnectionBinding> existing;
|
|
try
|
|
{
|
|
existing = ParseExistingBindings(instanceJson);
|
|
}
|
|
catch (System.Text.Json.JsonException ex)
|
|
{
|
|
OutputFormatter.WriteError($"Could not read the instance's connection bindings: {ex.Message}", "INVALID_RESPONSE");
|
|
return 1;
|
|
}
|
|
|
|
// Step 2: rewrite just this module's rows client-side.
|
|
if (!BuildModuleRewrite(existing, module, conn, obj, out var rewritten, out var error))
|
|
{
|
|
OutputFormatter.WriteError(error!, "UNKNOWN_MODULE");
|
|
return 1;
|
|
}
|
|
|
|
if (dryRun)
|
|
{
|
|
OutputFormatter.WriteJson(rewritten);
|
|
return 0;
|
|
}
|
|
|
|
// Step 3: SetConnectionBindings upserts by attribute name, so sending only the
|
|
// module's rows leaves every other module's bindings as they were.
|
|
return await CommandHelpers.ExecuteCommandAsync(
|
|
result, urlOption, formatOption, usernameOption, passwordOption,
|
|
new SetConnectionBindingsCommand(id, rewritten!));
|
|
});
|
|
return cmd;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Pure core of <c>instance bind-module</c>: selects the existing bindings that belong
|
|
/// to <paramref name="module"/> (canonical names starting with <c>{module}.</c>, or
|
|
/// dot-less names for <c>(instance)</c>) and rewrites each override to
|
|
/// <c>{objectPath}.{memberTail}</c> on <paramref name="connectionId"/>. An empty
|
|
/// <paramref name="objectPath"/> clears the override. Only the module's rows are
|
|
/// returned, so the upsert leaves every other module untouched.
|
|
/// </summary>
|
|
/// <param name="existing">The instance's current bindings (from <c>GetInstance</c>).</param>
|
|
/// <param name="module">Module prefix, or <c>(instance)</c> / <c>.</c> for direct attributes.</param>
|
|
/// <param name="connectionId">Data connection to bind the module's members to.</param>
|
|
/// <param name="objectPath">New object path; empty/whitespace clears the overrides.</param>
|
|
/// <param name="rewritten">The module's rewritten bindings, or null on failure.</param>
|
|
/// <param name="error">Descriptive error listing the available modules, or null on success.</param>
|
|
/// <returns>True when at least one binding matched the module; false otherwise.</returns>
|
|
internal static bool BuildModuleRewrite(
|
|
IReadOnlyList<ConnectionBinding> existing,
|
|
string module,
|
|
int connectionId,
|
|
string? objectPath,
|
|
out List<ConnectionBinding>? rewritten,
|
|
out string? error)
|
|
{
|
|
rewritten = null;
|
|
error = null;
|
|
var isInstance = module is "(instance)" or ".";
|
|
var prefix = module + ".";
|
|
var obj = (objectPath ?? string.Empty).Trim().TrimEnd('.');
|
|
|
|
var rows = existing
|
|
.Where(b => isInstance
|
|
? !b.AttributeName.Contains('.')
|
|
: b.AttributeName.StartsWith(prefix, StringComparison.Ordinal))
|
|
.Select(b =>
|
|
{
|
|
var tail = isInstance ? b.AttributeName : b.AttributeName[prefix.Length..];
|
|
return new ConnectionBinding(b.AttributeName, connectionId, obj.Length == 0 ? null : obj + "." + tail);
|
|
})
|
|
.ToList();
|
|
|
|
if (rows.Count == 0)
|
|
{
|
|
var available = existing
|
|
.Select(b => b.AttributeName.Contains('.') ? b.AttributeName[..b.AttributeName.IndexOf('.')] : "(instance)")
|
|
.Distinct()
|
|
.OrderBy(s => s, StringComparer.Ordinal);
|
|
error = $"Instance has no bindings for module '{module}'. Available: {string.Join(", ", available)}. " +
|
|
"A module with no bindings yet must be seeded with 'instance set-bindings' (or bound once in the Central UI).";
|
|
return false;
|
|
}
|
|
|
|
rewritten = rows;
|
|
return true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Reads the <c>connectionBindings</c> array out of a <c>GetInstance</c> response body
|
|
/// (camelCase, as the management API emits it) into typed bindings. A missing or
|
|
/// <c>null</c> array yields an empty list; malformed JSON throws
|
|
/// <see cref="System.Text.Json.JsonException"/> for the caller to report.
|
|
/// </summary>
|
|
/// <param name="json">The <c>GetInstance</c> success body.</param>
|
|
/// <returns>The instance's current bindings.</returns>
|
|
internal static List<ConnectionBinding> ParseExistingBindings(string json)
|
|
{
|
|
var result = new List<ConnectionBinding>();
|
|
using var doc = System.Text.Json.JsonDocument.Parse(json);
|
|
if (doc.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object
|
|
|| !doc.RootElement.TryGetProperty("connectionBindings", out var array)
|
|
|| array.ValueKind != System.Text.Json.JsonValueKind.Array)
|
|
return result;
|
|
|
|
foreach (var item in array.EnumerateArray())
|
|
{
|
|
if (item.ValueKind != System.Text.Json.JsonValueKind.Object) continue;
|
|
if (!item.TryGetProperty("attributeName", out var nameEl) || nameEl.ValueKind != System.Text.Json.JsonValueKind.String) continue;
|
|
if (!item.TryGetProperty("dataConnectionId", out var connEl) || !connEl.TryGetInt32(out var connectionId)) continue;
|
|
string? overrideRef = null;
|
|
if (item.TryGetProperty("dataSourceReferenceOverride", out var ovEl) && ovEl.ValueKind == System.Text.Json.JsonValueKind.String)
|
|
overrideRef = ovEl.GetString();
|
|
result.Add(new ConnectionBinding(nameEl.GetString()!, connectionId, overrideRef));
|
|
}
|
|
return result;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Parses the <c>--bindings</c> argument — a JSON array of binding entries — into a
|
|
/// typed list. Each entry is either a two-element
|
|
/// <c>[attributeName, dataConnectionId]</c> pair or a three-element
|
|
/// <c>[attributeName, dataConnectionId, dataSourceReferenceOverride]</c> triple. The
|
|
/// optional third element carries the per-instance data-source reference override
|
|
/// (<see cref="ConnectionBinding.DataSourceReferenceOverride"/>); a JSON
|
|
/// <c>null</c> (or an omitted third element) leaves it unset so the template default
|
|
/// applies. Returns <c>false</c> with a descriptive <paramref name="error"/> instead
|
|
/// of throwing when the JSON is malformed, an entry has the wrong arity, or an
|
|
/// element has the wrong type.
|
|
/// </summary>
|
|
/// <param name="json">The JSON string to parse.</param>
|
|
/// <param name="bindings">The parsed bindings list, or null if parsing fails.</param>
|
|
/// <param name="error">The error message if parsing fails, or null on success.</param>
|
|
/// <returns>True if parsing succeeded; false otherwise.</returns>
|
|
internal static bool TryParseBindings(
|
|
string json,
|
|
out List<ConnectionBinding>? bindings,
|
|
out string? error)
|
|
{
|
|
bindings = null;
|
|
error = null;
|
|
try
|
|
{
|
|
var pairs = System.Text.Json.JsonSerializer
|
|
.Deserialize<List<List<System.Text.Json.JsonElement>>>(json);
|
|
if (pairs == null)
|
|
{
|
|
error = "Bindings JSON must be a non-null array of "
|
|
+ "[attributeName, dataConnectionId] or "
|
|
+ "[attributeName, dataConnectionId, dataSourceReferenceOverride] entries.";
|
|
return false;
|
|
}
|
|
|
|
var result = new List<ConnectionBinding>(pairs.Count);
|
|
foreach (var pair in pairs)
|
|
{
|
|
if (pair.Count is not (2 or 3))
|
|
{
|
|
error = "Each binding must be a [attributeName, dataConnectionId] pair, "
|
|
+ "optionally with a third dataSourceReferenceOverride element.";
|
|
return false;
|
|
}
|
|
if (pair[0].ValueKind != System.Text.Json.JsonValueKind.String)
|
|
{
|
|
error = "The first element of each binding (attributeName) must be a string.";
|
|
return false;
|
|
}
|
|
if (pair[1].ValueKind != System.Text.Json.JsonValueKind.Number
|
|
|| !pair[1].TryGetInt32(out var connectionId))
|
|
{
|
|
error = "The second element of each binding (dataConnectionId) must be an integer.";
|
|
return false;
|
|
}
|
|
|
|
string? referenceOverride = null;
|
|
if (pair.Count == 3)
|
|
{
|
|
var third = pair[2];
|
|
if (third.ValueKind == System.Text.Json.JsonValueKind.String)
|
|
{
|
|
referenceOverride = third.GetString();
|
|
}
|
|
else if (third.ValueKind != System.Text.Json.JsonValueKind.Null)
|
|
{
|
|
error = "The third element of each binding (dataSourceReferenceOverride) "
|
|
+ "must be a string or null.";
|
|
return false;
|
|
}
|
|
}
|
|
|
|
result.Add(new ConnectionBinding(pair[0].GetString()!, connectionId, referenceOverride));
|
|
}
|
|
|
|
bindings = result;
|
|
return true;
|
|
}
|
|
catch (System.Text.Json.JsonException ex)
|
|
{
|
|
error = $"Invalid bindings JSON: {ex.Message}";
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Parses the <c>--overrides</c> argument — a JSON object of
|
|
/// <c>attributeName -> value</c> pairs — into a typed dictionary. Returns
|
|
/// <c>false</c> with a descriptive <paramref name="error"/> instead of throwing
|
|
/// when the JSON is malformed or null.
|
|
/// </summary>
|
|
/// <param name="json">The JSON string to parse.</param>
|
|
/// <param name="overrides">The parsed overrides dictionary, or null if parsing fails.</param>
|
|
/// <param name="error">The error message if parsing fails, or null on success.</param>
|
|
/// <returns>True if parsing succeeded; false otherwise.</returns>
|
|
internal static bool TryParseOverrides(
|
|
string json,
|
|
out Dictionary<string, string?>? overrides,
|
|
out string? error)
|
|
{
|
|
overrides = null;
|
|
error = null;
|
|
try
|
|
{
|
|
var parsed = System.Text.Json.JsonSerializer
|
|
.Deserialize<Dictionary<string, string?>>(json);
|
|
if (parsed == null)
|
|
{
|
|
error = "Overrides JSON must be a non-null object of attribute name -> value pairs.";
|
|
return false;
|
|
}
|
|
overrides = parsed;
|
|
return true;
|
|
}
|
|
catch (System.Text.Json.JsonException ex)
|
|
{
|
|
error = $"Invalid overrides JSON: {ex.Message}";
|
|
return false;
|
|
}
|
|
}
|
|
|
|
private static Command BuildList(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
|
{
|
|
var siteIdOption = new Option<int?>("--site-id") { Description = "Filter by site ID" };
|
|
var templateIdOption = new Option<int?>("--template-id") { Description = "Filter by template ID" };
|
|
var searchOption = new Option<string?>("--search") { Description = "Search term" };
|
|
var skipOption = new Option<int>("--skip") { Description = "Offset paging: number of items to skip (default 0)" };
|
|
var takeOption = new Option<int?>("--take") { Description = "Offset paging: max items to return (1..1000; omit for unlimited)" };
|
|
|
|
var cmd = new Command("list") { Description = "List instances" };
|
|
cmd.Add(siteIdOption);
|
|
cmd.Add(templateIdOption);
|
|
cmd.Add(searchOption);
|
|
cmd.Add(skipOption);
|
|
cmd.Add(takeOption);
|
|
cmd.SetAction(async (ParseResult result) =>
|
|
{
|
|
var siteId = result.GetValue(siteIdOption);
|
|
var templateId = result.GetValue(templateIdOption);
|
|
var search = result.GetValue(searchOption);
|
|
var skip = result.GetValue(skipOption);
|
|
var take = result.GetValue(takeOption);
|
|
return await CommandHelpers.ExecuteCommandAsync(
|
|
result, urlOption, formatOption, usernameOption, passwordOption,
|
|
new ListInstancesCommand(siteId, templateId, search, skip, take));
|
|
});
|
|
return cmd;
|
|
}
|
|
|
|
private static Command BuildCreate(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
|
{
|
|
var nameOption = new Option<string>("--name") { Description = "Unique instance name", Required = true };
|
|
var templateIdOption = new Option<int>("--template-id") { Description = "Template ID", Required = true };
|
|
var siteIdOption = new Option<int>("--site-id") { Description = "Site ID", Required = true };
|
|
var areaIdOption = new Option<int?>("--area-id") { Description = "Area ID" };
|
|
|
|
var cmd = new Command("create") { Description = "Create a new instance" };
|
|
cmd.Add(nameOption);
|
|
cmd.Add(templateIdOption);
|
|
cmd.Add(siteIdOption);
|
|
cmd.Add(areaIdOption);
|
|
cmd.SetAction(async (ParseResult result) =>
|
|
{
|
|
var name = result.GetValue(nameOption)!;
|
|
var templateId = result.GetValue(templateIdOption);
|
|
var siteId = result.GetValue(siteIdOption);
|
|
var areaId = result.GetValue(areaIdOption);
|
|
return await CommandHelpers.ExecuteCommandAsync(
|
|
result, urlOption, formatOption, usernameOption, passwordOption,
|
|
new CreateInstanceCommand(name, templateId, siteId, areaId));
|
|
});
|
|
return cmd;
|
|
}
|
|
|
|
private static Command BuildDeploy(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
|
{
|
|
var idOption = new Option<int>("--id") { Description = "Instance ID", Required = true };
|
|
var cmd = new Command("deploy") { Description = "Deploy an instance" };
|
|
cmd.Add(idOption);
|
|
cmd.SetAction(async (ParseResult result) =>
|
|
{
|
|
var id = result.GetValue(idOption);
|
|
return await CommandHelpers.ExecuteCommandAsync(
|
|
result, urlOption, formatOption, usernameOption, passwordOption, new MgmtDeployInstanceCommand(id));
|
|
});
|
|
return cmd;
|
|
}
|
|
|
|
private static Command BuildEnable(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
|
{
|
|
var idOption = new Option<int>("--id") { Description = "Instance ID", Required = true };
|
|
var cmd = new Command("enable") { Description = "Enable an instance" };
|
|
cmd.Add(idOption);
|
|
cmd.SetAction(async (ParseResult result) =>
|
|
{
|
|
var id = result.GetValue(idOption);
|
|
return await CommandHelpers.ExecuteCommandAsync(
|
|
result, urlOption, formatOption, usernameOption, passwordOption, new MgmtEnableInstanceCommand(id));
|
|
});
|
|
return cmd;
|
|
}
|
|
|
|
private static Command BuildDisable(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
|
{
|
|
var idOption = new Option<int>("--id") { Description = "Instance ID", Required = true };
|
|
var cmd = new Command("disable") { Description = "Disable an instance" };
|
|
cmd.Add(idOption);
|
|
cmd.SetAction(async (ParseResult result) =>
|
|
{
|
|
var id = result.GetValue(idOption);
|
|
return await CommandHelpers.ExecuteCommandAsync(
|
|
result, urlOption, formatOption, usernameOption, passwordOption, new MgmtDisableInstanceCommand(id));
|
|
});
|
|
return cmd;
|
|
}
|
|
|
|
private static Command BuildDelete(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
|
{
|
|
var idOption = new Option<int>("--id") { Description = "Instance ID", Required = true };
|
|
var cmd = new Command("delete") { Description = "Delete an instance" };
|
|
cmd.Add(idOption);
|
|
cmd.SetAction(async (ParseResult result) =>
|
|
{
|
|
var id = result.GetValue(idOption);
|
|
return await CommandHelpers.ExecuteCommandAsync(
|
|
result, urlOption, formatOption, usernameOption, passwordOption, new MgmtDeleteInstanceCommand(id));
|
|
});
|
|
return cmd;
|
|
}
|
|
|
|
private static Command BuildSetOverrides(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
|
{
|
|
var idOption = new Option<int>("--id") { Description = "Instance ID", Required = true };
|
|
var overridesOption = new Option<string>("--overrides") { Description = "JSON object of attribute name -> value pairs, e.g. {\"Speed\": \"100\", \"Mode\": null}", Required = true };
|
|
|
|
var cmd = new Command("set-overrides") { Description = "Set attribute overrides for an instance" };
|
|
cmd.Add(idOption);
|
|
cmd.Add(overridesOption);
|
|
cmd.SetAction(async (ParseResult result) =>
|
|
{
|
|
var id = result.GetValue(idOption);
|
|
var overridesJson = result.GetValue(overridesOption)!;
|
|
if (!TryParseOverrides(overridesJson, out var overrides, out var error))
|
|
{
|
|
OutputFormatter.WriteError(error!, "INVALID_ARGUMENT");
|
|
return 1;
|
|
}
|
|
return await CommandHelpers.ExecuteCommandAsync(
|
|
result, urlOption, formatOption, usernameOption, passwordOption,
|
|
new SetInstanceOverridesCommand(id, overrides!));
|
|
});
|
|
return cmd;
|
|
}
|
|
|
|
private static Command BuildImportOverrides(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
|
{
|
|
var idOption = new Option<int>("--id") { Description = "Instance ID", Required = true };
|
|
var fileOption = new Option<string>("--file") { Description = "Path to the override CSV file (columns: AttributeName,Value,ElementType)", Required = true };
|
|
|
|
var cmd = new Command("import-overrides") { Description = "Apply attribute overrides from a CSV file" };
|
|
cmd.Add(idOption);
|
|
cmd.Add(fileOption);
|
|
cmd.SetAction(async (ParseResult result) =>
|
|
{
|
|
var id = result.GetValue(idOption);
|
|
var filePath = result.GetValue(fileOption)!;
|
|
|
|
string csvText;
|
|
try
|
|
{
|
|
csvText = File.ReadAllText(filePath);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
OutputFormatter.WriteError($"Cannot read file '{filePath}': {ex.Message}", "FILE_READ_ERROR");
|
|
return 1;
|
|
}
|
|
|
|
var parseResult = OverrideCsvParser.Parse(csvText);
|
|
if (parseResult.Errors.Count > 0)
|
|
{
|
|
foreach (var error in parseResult.Errors)
|
|
OutputFormatter.WriteError(error, "INVALID_CSV");
|
|
return 1;
|
|
}
|
|
|
|
var overrides = parseResult.Rows.ToDictionary(r => r.AttributeName, r => r.Value);
|
|
return await CommandHelpers.ExecuteCommandAsync(
|
|
result, urlOption, formatOption, usernameOption, passwordOption,
|
|
new SetInstanceOverridesCommand(id, overrides));
|
|
});
|
|
return cmd;
|
|
}
|
|
|
|
private static Command BuildAlarmOverride(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
|
{
|
|
var group = new Command("alarm-override") { Description = "Manage per-instance alarm overrides" };
|
|
|
|
// set
|
|
var setIdOption = new Option<int>("--instance-id") { Description = "Instance ID", Required = true };
|
|
var setAlarmOption = new Option<string>("--alarm") { Description = "Alarm canonical name (e.g., 'TempLevels' or 'Pump.TempSensor.Heat')", Required = true };
|
|
var setConfigOption = new Option<string?>("--trigger-config") { Description = "JSON override for TriggerConfiguration (HiLo: partial merge; others: whole-replace)" };
|
|
var setPriorityOption = new Option<int?>("--priority") { Description = "Priority override (0-1000)" };
|
|
var setMesReportableOption = new Option<bool?>("--mes-reportable") { Description = "MES-reportable override: true or false; omit to inherit the template value" };
|
|
var setCmd = new Command("set") { Description = "Set (upsert) an alarm override on an instance" };
|
|
setCmd.Add(setIdOption); setCmd.Add(setAlarmOption); setCmd.Add(setConfigOption); setCmd.Add(setPriorityOption); setCmd.Add(setMesReportableOption);
|
|
setCmd.SetAction(async (ParseResult result) =>
|
|
{
|
|
return await CommandHelpers.ExecuteCommandAsync(
|
|
result, urlOption, formatOption, usernameOption, passwordOption,
|
|
new SetInstanceAlarmOverrideCommand(
|
|
result.GetValue(setIdOption),
|
|
result.GetValue(setAlarmOption)!,
|
|
result.GetValue(setConfigOption),
|
|
result.GetValue(setPriorityOption),
|
|
result.GetValue(setMesReportableOption)));
|
|
});
|
|
group.Add(setCmd);
|
|
|
|
// delete
|
|
var delIdOption = new Option<int>("--instance-id") { Description = "Instance ID", Required = true };
|
|
var delAlarmOption = new Option<string>("--alarm") { Description = "Alarm canonical name", Required = true };
|
|
var delCmd = new Command("delete") { Description = "Remove an alarm override on an instance" };
|
|
delCmd.Add(delIdOption); delCmd.Add(delAlarmOption);
|
|
delCmd.SetAction(async (ParseResult result) =>
|
|
{
|
|
return await CommandHelpers.ExecuteCommandAsync(
|
|
result, urlOption, formatOption, usernameOption, passwordOption,
|
|
new DeleteInstanceAlarmOverrideCommand(
|
|
result.GetValue(delIdOption),
|
|
result.GetValue(delAlarmOption)!));
|
|
});
|
|
group.Add(delCmd);
|
|
|
|
// list
|
|
var listIdOption = new Option<int>("--instance-id") { Description = "Instance ID", Required = true };
|
|
var listCmd = new Command("list") { Description = "List all alarm overrides for an instance" };
|
|
listCmd.Add(listIdOption);
|
|
listCmd.SetAction(async (ParseResult result) =>
|
|
{
|
|
return await CommandHelpers.ExecuteCommandAsync(
|
|
result, urlOption, formatOption, usernameOption, passwordOption,
|
|
new ListInstanceAlarmOverridesCommand(result.GetValue(listIdOption)));
|
|
});
|
|
group.Add(listCmd);
|
|
|
|
return group;
|
|
}
|
|
|
|
private static Command BuildDeleteAttributeOverride(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
|
{
|
|
var idOption = new Option<int>("--instance-id") { Description = "Instance ID", Required = true };
|
|
var attributeOption = new Option<string>("--attribute") { Description = "Canonical attribute name (for example Module.Value)", Required = true };
|
|
var cmd = new Command("delete") { Description = "Remove one attribute override and restore the inherited value" };
|
|
cmd.Add(idOption);
|
|
cmd.Add(attributeOption);
|
|
cmd.SetAction(async (ParseResult result) =>
|
|
{
|
|
return await CommandHelpers.ExecuteCommandAsync(
|
|
result, urlOption, formatOption, usernameOption, passwordOption,
|
|
new DeleteInstanceAttributeOverrideCommand(result.GetValue(idOption), result.GetValue(attributeOption)!));
|
|
});
|
|
return cmd;
|
|
}
|
|
|
|
private static Command BuildAttributeOverride(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
|
{
|
|
var group = new Command("attribute-override") { Description = "Manage individual instance attribute overrides" };
|
|
group.Add(BuildDeleteAttributeOverride(urlOption, formatOption, usernameOption, passwordOption));
|
|
return group;
|
|
}
|
|
|
|
private static Command BuildListNativeAlarmSourceOverrides(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
|
{
|
|
var idOption = new Option<int>("--instance-id") { Description = "Instance ID", Required = true };
|
|
var cmd = new Command("list") { Description = "List native alarm source overrides for an instance" };
|
|
cmd.Add(idOption);
|
|
cmd.SetAction(async (ParseResult result) =>
|
|
{
|
|
return await CommandHelpers.ExecuteCommandAsync(
|
|
result, urlOption, formatOption, usernameOption, passwordOption,
|
|
new ListInstanceNativeAlarmSourceOverridesCommand(result.GetValue(idOption)));
|
|
});
|
|
return cmd;
|
|
}
|
|
|
|
private static Command BuildNativeAlarmSourceOverride(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
|
{
|
|
var group = new Command("native-alarm-source")
|
|
{
|
|
Description = "Manage per-instance native alarm source overrides (retarget an inherited binding; blank = inherited)"
|
|
};
|
|
|
|
group.Add(BuildListNativeAlarmSourceOverrides(urlOption, formatOption, usernameOption, passwordOption));
|
|
|
|
// set
|
|
var setIdOption = new Option<int>("--instance-id") { Description = "Instance ID", Required = true };
|
|
var setSourceOption = new Option<string>("--source") { Description = "Source binding canonical name (e.g. 'Pressure' or 'Module.Pressure')", Required = true };
|
|
var setConnectionOption = new Option<string?>("--connection") { Description = "Connection name override (blank = inherited)" };
|
|
var setSourceRefOption = new Option<string?>("--source-ref") { Description = "Source reference override (blank = inherited)" };
|
|
var setFilterOption = new Option<string?>("--filter") { Description = "Condition filter override (blank = inherited)" };
|
|
var setCmd = new Command("set") { Description = "Set (upsert) a native alarm source override on an instance" };
|
|
setCmd.Add(setIdOption); setCmd.Add(setSourceOption); setCmd.Add(setConnectionOption);
|
|
setCmd.Add(setSourceRefOption); setCmd.Add(setFilterOption);
|
|
setCmd.SetAction(async (ParseResult result) =>
|
|
{
|
|
return await CommandHelpers.ExecuteCommandAsync(
|
|
result, urlOption, formatOption, usernameOption, passwordOption,
|
|
new SetInstanceNativeAlarmSourceOverrideCommand(
|
|
result.GetValue(setIdOption),
|
|
result.GetValue(setSourceOption)!,
|
|
result.GetValue(setConnectionOption),
|
|
result.GetValue(setSourceRefOption),
|
|
result.GetValue(setFilterOption)));
|
|
});
|
|
group.Add(setCmd);
|
|
|
|
// clear
|
|
var clearIdOption = new Option<int>("--instance-id") { Description = "Instance ID", Required = true };
|
|
var clearSourceOption = new Option<string>("--source") { Description = "Source binding canonical name", Required = true };
|
|
var clearCmd = new Command("clear") { Description = "Clear a native alarm source override on an instance (revert to inherited)" };
|
|
clearCmd.Add(clearIdOption); clearCmd.Add(clearSourceOption);
|
|
clearCmd.SetAction(async (ParseResult result) =>
|
|
{
|
|
return await CommandHelpers.ExecuteCommandAsync(
|
|
result, urlOption, formatOption, usernameOption, passwordOption,
|
|
new DeleteInstanceNativeAlarmSourceOverrideCommand(
|
|
result.GetValue(clearIdOption),
|
|
result.GetValue(clearSourceOption)!));
|
|
});
|
|
group.Add(clearCmd);
|
|
|
|
// import (CSV bulk apply — parity with `instance import-overrides`)
|
|
var importIdOption = new Option<int>("--instance-id") { Description = "Instance ID", Required = true };
|
|
var importFileOption = new Option<string>("--file")
|
|
{
|
|
Description = "Path to the override CSV file (columns: SourceName,Connection,SourceReference,Filter; blank field = inherited)",
|
|
Required = true
|
|
};
|
|
var importCmd = new Command("import")
|
|
{
|
|
Description = "Apply native alarm source overrides from a CSV file (all-or-nothing)"
|
|
};
|
|
importCmd.Add(importIdOption);
|
|
importCmd.Add(importFileOption);
|
|
importCmd.SetAction(async (ParseResult result) =>
|
|
{
|
|
var id = result.GetValue(importIdOption);
|
|
var filePath = result.GetValue(importFileOption)!;
|
|
|
|
string csvText;
|
|
try
|
|
{
|
|
csvText = File.ReadAllText(filePath);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
OutputFormatter.WriteError($"Cannot read file '{filePath}': {ex.Message}", "FILE_READ_ERROR");
|
|
return 1;
|
|
}
|
|
|
|
var parseResult = NativeAlarmSourceOverrideCsvParser.Parse(csvText);
|
|
if (parseResult.Errors.Count > 0)
|
|
{
|
|
foreach (var error in parseResult.Errors)
|
|
OutputFormatter.WriteError(error, "INVALID_CSV");
|
|
return 1;
|
|
}
|
|
|
|
var overrides = parseResult.Rows
|
|
.Select(r => new NativeAlarmSourceOverrideEntry(
|
|
r.SourceName, r.Connection, r.SourceReference, r.Filter))
|
|
.ToList();
|
|
return await CommandHelpers.ExecuteCommandAsync(
|
|
result, urlOption, formatOption, usernameOption, passwordOption,
|
|
new SetInstanceNativeAlarmSourceOverridesCommand(id, overrides));
|
|
});
|
|
group.Add(importCmd);
|
|
|
|
return group;
|
|
}
|
|
|
|
private static Command BuildSetArea(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
|
{
|
|
var idOption = new Option<int>("--id") { Description = "Instance ID", Required = true };
|
|
var areaIdOption = new Option<int?>("--area-id") { Description = "Area ID (omit to clear area assignment)" };
|
|
|
|
var cmd = new Command("set-area") { Description = "Reassign an instance to a different area" };
|
|
cmd.Add(idOption);
|
|
cmd.Add(areaIdOption);
|
|
cmd.SetAction(async (ParseResult result) =>
|
|
{
|
|
var id = result.GetValue(idOption);
|
|
var areaId = result.GetValue(areaIdOption);
|
|
return await CommandHelpers.ExecuteCommandAsync(
|
|
result, urlOption, formatOption, usernameOption, passwordOption,
|
|
new SetInstanceAreaCommand(id, areaId));
|
|
});
|
|
return cmd;
|
|
}
|
|
|
|
private static Command BuildDiff(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
|
{
|
|
var idOption = new Option<int>("--id") { Description = "Instance ID", Required = true };
|
|
|
|
var cmd = new Command("diff") { Description = "Show deployment diff (deployed vs current template)" };
|
|
cmd.Add(idOption);
|
|
cmd.SetAction(async (ParseResult result) =>
|
|
{
|
|
var id = result.GetValue(idOption);
|
|
return await CommandHelpers.ExecuteCommandAsync(
|
|
result, urlOption, formatOption, usernameOption, passwordOption,
|
|
new GetDeploymentDiffCommand(id));
|
|
});
|
|
return cmd;
|
|
}
|
|
}
|