Plan scoped object mutations with impact analysis and transactional byte-exact undo
This commit is contained in:
parent
dcd2d13d9f
commit
9f22a36a0b
290
PLCSharpWpf/Models/ObjectEdit.cs
Normal file
290
PLCSharpWpf/Models/ObjectEdit.cs
Normal file
@ -0,0 +1,290 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace PLCSharp.Models;
|
||||
|
||||
public sealed record CheckedFlow(Guid Id, string Name, string Path, bool Compiled, List<ScriptDiagnostic> Diagnostics);
|
||||
public sealed record ObjectEdit(string Action, string Kind, Guid Id, string Path, JsonObject Before, JsonObject After,
|
||||
JsonArray WorkflowReferences, JsonArray ConfigReferences, JsonArray ManualReferences, List<CheckedFlow> Workflows)
|
||||
{
|
||||
public bool Compiled => Workflows.All(f => f.Compiled);
|
||||
public Guid? UndoOf { get; init; }
|
||||
[JsonIgnore] internal string Source { get; init; }
|
||||
[JsonIgnore] internal string Destination { get; init; }
|
||||
[JsonIgnore] internal string Scope { get; init; }
|
||||
[JsonIgnore] internal string SavedScope { get; set; }
|
||||
}
|
||||
|
||||
public sealed partial class ProjectDirectory
|
||||
{
|
||||
internal static string ObjectGroup(string kind) => kind switch
|
||||
{
|
||||
"Variables" => "variables", "AxisPoints" or "RobotPoints" => "points",
|
||||
"Controllers" or "Axes" or "DI" or "DQ" or "Cylinders" or "Robots" or "Connects" or "Cameras" => "hardware",
|
||||
_ => throw new ArgumentException("请选择配方变量、点位或硬件配置对象。")
|
||||
};
|
||||
|
||||
private string ObjectScope() => Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new
|
||||
{
|
||||
files = baseline.OrderBy(k => k.Key), scripts = RenameScope(Guid.Empty)
|
||||
})));
|
||||
|
||||
internal static object MaterializeObject(IEntityType entity, JsonObject row)
|
||||
{
|
||||
var item = Activator.CreateInstance(entity.ClrType);
|
||||
foreach (var p in entity.GetProperties())
|
||||
{
|
||||
var node = row[p.GetColumnName()];
|
||||
object value;
|
||||
if (node == null)
|
||||
{
|
||||
if (!p.IsNullable) throw new ArgumentException($"{p.GetColumnName()} 不能为空。");
|
||||
value = null;
|
||||
}
|
||||
else if (ProjectConfiguration.IsJson(p))
|
||||
{
|
||||
if (node is not (JsonObject or JsonArray)) throw new ArgumentException($"{p.GetColumnName()} 需要对象或数组。");
|
||||
value = node.ToJsonString();
|
||||
}
|
||||
else if (p.ClrType == typeof(bool))
|
||||
value = node.GetValueKind() switch
|
||||
{
|
||||
JsonValueKind.True => true, JsonValueKind.False => false,
|
||||
JsonValueKind.Number when (int)node is 0 or 1 => (int)node == 1,
|
||||
_ => throw new ArgumentException($"{p.GetColumnName()} 需要布尔值。")
|
||||
};
|
||||
else
|
||||
{
|
||||
value = node.Deserialize(p.ClrType);
|
||||
if (p.ClrType.IsEnum && !Enum.IsDefined(p.ClrType, value)) throw new ArgumentException($"{p.GetColumnName()} 枚举值无效。");
|
||||
}
|
||||
p.PropertyInfo.SetValue(item, value);
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
internal static JsonObject ObjectRow(IEntityType entity, object instance)
|
||||
{
|
||||
var row = new JsonObject();
|
||||
foreach (var p in entity.GetProperties())
|
||||
row[p.GetColumnName()] = p.PropertyInfo.GetValue(instance) switch
|
||||
{
|
||||
null => null, Guid g => g.ToString("D").ToUpperInvariant(), bool b => b ? 1 : 0,
|
||||
string s when ProjectConfiguration.IsJson(p) => JsonNode.Parse(s),
|
||||
var val => JsonSerializer.SerializeToNode(val)
|
||||
};
|
||||
return row;
|
||||
}
|
||||
|
||||
private static void MergeProperties(JsonObject target, JsonObject patch)
|
||||
{
|
||||
foreach (var (key, value) in patch)
|
||||
{
|
||||
if (target[key] is JsonObject child && value is JsonObject delta) MergeProperties(child, delta);
|
||||
else target[key] = value?.DeepClone();
|
||||
}
|
||||
}
|
||||
|
||||
internal ObjectEdit PlanObjectEdit(string action, string kind, Guid? objectId, JsonObject properties)
|
||||
{
|
||||
if (action is not ("create" or "update" or "delete")) throw new ArgumentException("请选择 create、update 或 delete。");
|
||||
bool create = action == "create";
|
||||
if (create == objectId.HasValue || (action == "delete" ? properties?.Count > 0 : properties == null))
|
||||
throw new ArgumentException("新增时由工程分配 ID;修改和删除需要对象 ID。");
|
||||
var id = objectId ?? Guid.NewGuid();
|
||||
var path = ConfigPath(ObjectGroup(kind));
|
||||
var doc = JsonNode.Parse(baseline[path]);
|
||||
var rows = doc[kind].AsArray();
|
||||
var before = rows.SingleOrDefault(r => Guid.Parse((string)r["ID"]) == id)?.AsObject();
|
||||
if (!create && before == null) throw new ArgumentException("找不到工程对象。");
|
||||
var entity = ProjectConfiguration.Entity(Data, kind);
|
||||
JsonObject after = null;
|
||||
if (action != "delete")
|
||||
{
|
||||
after = before?.DeepClone().AsObject() ?? ObjectRow(entity, Activator.CreateInstance(entity.ClrType));
|
||||
after["ID"] = id.ToString("D").ToUpperInvariant();
|
||||
foreach (var (key, _) in properties)
|
||||
if (!after.ContainsKey(key) || key == "ID" || !create && key is "Name" or "RecipeID" or "RobotID")
|
||||
throw new ArgumentException($"不能通过属性修改 {key}。名称请使用重命名工具。");
|
||||
MergeProperties(after, properties);
|
||||
var normalized = ObjectRow(entity, MaterializeObject(entity, after));
|
||||
foreach (var p in entity.GetProperties())
|
||||
{
|
||||
var key = p.GetColumnName();
|
||||
if (!properties.ContainsKey(key)) continue;
|
||||
if (ProjectConfiguration.IsJson(p)) CheckSuppliedFields(after[key], normalized[key], key);
|
||||
after[key] = normalized[key]?.DeepClone();
|
||||
}
|
||||
ValidateObject(kind, rows, id, before, after);
|
||||
if (JsonNode.DeepEquals(before, after)) throw new ArgumentException("属性没有变化。");
|
||||
}
|
||||
if (create) rows.Add(after.DeepClone());
|
||||
else if (after == null) rows.Remove(before);
|
||||
else rows[rows.IndexOf(before)] = after.DeepClone();
|
||||
return InspectEdit(action, kind, id, path, before, after, baseline[path], Serialize(doc));
|
||||
}
|
||||
|
||||
private static void CheckSuppliedFields(JsonNode supplied, JsonNode actual, string path)
|
||||
{
|
||||
if (supplied is JsonObject obj && actual is JsonObject result)
|
||||
{
|
||||
foreach (var (key, child) in obj)
|
||||
{
|
||||
if (!result.ContainsKey(key)) throw new ArgumentException($"未知字段 {path}.{key}");
|
||||
CheckSuppliedFields(child, result[key], path + "." + key);
|
||||
}
|
||||
}
|
||||
else if (supplied is JsonArray array && actual is JsonArray saved && array.Count == saved.Count)
|
||||
{
|
||||
for (int i = 0; i < array.Count; i++) CheckSuppliedFields(array[i], saved[i], $"{path}[{i}]");
|
||||
}
|
||||
else if (!JsonNode.DeepEquals(supplied, actual)) throw new ArgumentException($"字段值无法保存:{path}");
|
||||
}
|
||||
|
||||
private void ValidateObject(string kind, JsonArray rows, Guid id, JsonObject before, JsonObject after)
|
||||
{
|
||||
bool Changed(string key) => before == null || !JsonNode.DeepEquals(before[key], after[key]);
|
||||
bool Other(JsonNode r) => Guid.Parse((string)r["ID"]) != id;
|
||||
if (after.ContainsKey("RecipeID") && !Recipes.Any(r => r.ID == Guid.Parse((string)after["RecipeID"])))
|
||||
throw new ArgumentException("所属配方不存在。");
|
||||
if (kind == "RobotPoints")
|
||||
{
|
||||
var owner = Guid.Parse((string)after["RobotID"]);
|
||||
if (!Data.Robots.Any(r => r.ID == owner)) throw new ArgumentException("所属机器人不存在。");
|
||||
}
|
||||
if (kind == "Controllers" && rows.Any(Other)) throw new ArgumentException("工程只能配置一个运动控制器。");
|
||||
if (after.ContainsKey("Name") && Changed("Name"))
|
||||
{
|
||||
var name = (string)after["Name"];
|
||||
if (string.IsNullOrWhiteSpace(name) || name != name.Trim() || rows.Any(r => Other(r) && (string)r["Name"] == name &&
|
||||
(string)r["RecipeID"] == (string)after["RecipeID"] && (string)r["RobotID"] == (string)after["RobotID"]))
|
||||
throw new ArgumentException("名称为空、带首尾空白或在所属范围内重名。");
|
||||
}
|
||||
var address = kind switch { "Axes" => "AxisNo", "DI" or "DQ" => "Number", _ => null };
|
||||
if (address != null && Changed(address) && rows.Any(r => Other(r) && JsonNode.DeepEquals(r[address], after[address])))
|
||||
throw new ArgumentException($"{address} 在同类设备中重复。");
|
||||
foreach (var (key, value) in after)
|
||||
{
|
||||
if (!Changed(key) || value is not JsonValue field || !field.TryGetValue<string>(out var name) || string.IsNullOrEmpty(name)) continue;
|
||||
var table = kind switch
|
||||
{
|
||||
"AxisPoints" when AxisNameFields["AxisPoints"].Contains(key) => "Axes",
|
||||
"Cylinders" when key is "InA" or "InB" => "DI",
|
||||
"Cylinders" when key is "OutA" or "OutB" => "DQ", _ => null
|
||||
};
|
||||
if (table != null && !JsonNode.Parse(baseline[ConfigPath("hardware")])[table].AsArray().Any(r => (string)r["Name"] == name))
|
||||
throw new ArgumentException($"{key} 引用的 {table} 名称不存在:{name}");
|
||||
}
|
||||
}
|
||||
|
||||
internal ObjectEdit UndoObject(Guid operation, ObjectEdit saved)
|
||||
{
|
||||
if (saved.SavedScope != ObjectScope()) throw new ProjectConflictException("工程在保存后已改变,无法撤销。");
|
||||
var inverse = saved.Action switch { "create" => "delete", "delete" => "create", _ => "update" };
|
||||
return InspectEdit(inverse, saved.Kind, saved.Id, saved.Path, saved.After, saved.Before, saved.Destination, saved.Source)
|
||||
with { UndoOf = operation };
|
||||
}
|
||||
|
||||
internal void ApplyObjectEdit(ObjectEdit edit)
|
||||
{
|
||||
lock (Data.Sync)
|
||||
{
|
||||
if (ObjectScope() != edit.Scope || baseline[edit.Path] != edit.Source)
|
||||
throw new ProjectConflictException("配置或脚本已改变,请重新预览。");
|
||||
var current = ProjectConfiguration.Capture(Data, [edit.Kind], false)[edit.Kind].AsArray()
|
||||
.SingleOrDefault(r => Guid.Parse((string)r["ID"]) == edit.Id);
|
||||
if (!JsonNode.DeepEquals(current, edit.Before)) throw new ProjectConflictException("运行工程的对象已改变。");
|
||||
var entity = ProjectConfiguration.Entity(Data, edit.Kind);
|
||||
var tracked = Data.ChangeTracker.Entries().FirstOrDefault(e => e.Metadata == entity && (Guid)e.Property("ID").CurrentValue == edit.Id);
|
||||
if (tracked != null && tracked.State != EntityState.Unchanged) throw new ProjectConflictException("请先保存对象的编辑。");
|
||||
var files = new Dictionary<string, string>(baseline) { [edit.Path] = edit.Destination };
|
||||
using var tx = Data.Database.BeginTransaction();
|
||||
if (edit.After != null)
|
||||
ProjectConfiguration.Restore(Data, [edit.Kind], new JsonObject { [edit.Kind] = new JsonArray(edit.After.DeepClone()) }, edit.Before != null);
|
||||
else
|
||||
{
|
||||
// ObjectGroup validates the table against the fixed project schema.
|
||||
if (Data.Database.ExecuteSqlRaw($"DELETE FROM \"{edit.Kind}\" WHERE ID = {{0}}", edit.Id) != 1)
|
||||
throw new ProjectConflictException("对象已删除。");
|
||||
}
|
||||
WriteFiles(Root, files, baseline.Keys.ToArray(), tx.Commit);
|
||||
if (tracked != null)
|
||||
{
|
||||
if (edit.After == null) tracked.State = EntityState.Detached;
|
||||
else tracked.Reload();
|
||||
}
|
||||
configuration[edit.Path] = edit.Destination;
|
||||
edit.SavedScope = ObjectScope();
|
||||
}
|
||||
}
|
||||
|
||||
private ObjectEdit InspectEdit(string action, string kind, Guid id, string path, JsonObject before, JsonObject after, string source, string destination)
|
||||
{
|
||||
var row = before ?? after;
|
||||
var analysis = Models.WorkflowReferences.Find(this, kind, id.ToString(), forRename: true, candidate: row);
|
||||
var hits = analysis["hits"].AsArray();
|
||||
var confirmed = new JsonArray();
|
||||
var manual = new JsonArray();
|
||||
foreach (var hit in hits) ((string)hit["confidence"] == "confirmed" ? confirmed : manual).Add(hit.DeepClone());
|
||||
var flows = new List<CheckedFlow>();
|
||||
foreach (var group in hits.GroupBy(h => (Recipe: (Guid)h["recipeId"], Flow: (Guid)h["workflowId"])))
|
||||
{
|
||||
var flow = Flows(group.Key.Recipe).Single(w => w.ID == group.Key.Flow);
|
||||
var review = WorkflowScriptReview.Create(flow.ID, flow.Code, flow.Code);
|
||||
flows.Add(new(flow.ID, flow.Name, (string)group.First()["path"], review.Compiled, review.Diagnostics));
|
||||
}
|
||||
foreach (var error in analysis["diagnostics"].AsArray())
|
||||
{
|
||||
var script = (string)error["path"];
|
||||
if (flows.Any(f => f.Path == script)) continue;
|
||||
var flowId = Guid.Parse(System.IO.Path.GetFileNameWithoutExtension(script));
|
||||
var flow = Recipes.SelectMany(r => Flows(r.ID)).Single(w => w.ID == flowId);
|
||||
var review = WorkflowScriptReview.Create(flow.ID, flow.Code, flow.Code);
|
||||
flows.Add(new(flow.ID, flow.Name, script, review.Compiled, review.Diagnostics));
|
||||
}
|
||||
return new(action, kind, id, path, before, after, confirmed, ConfigurationLinks(kind, row), manual, flows)
|
||||
{ Source = source, Destination = destination, Scope = ObjectScope() };
|
||||
}
|
||||
|
||||
private JsonArray ConfigurationLinks(string kind, JsonObject target)
|
||||
{
|
||||
var result = new JsonArray();
|
||||
var name = (string)target["Name"];
|
||||
foreach (var (group, tables) in ProjectConfiguration.Groups)
|
||||
{
|
||||
var path = ConfigPath(group);
|
||||
var doc = JsonNode.Parse(baseline[path]);
|
||||
foreach (var table in tables)
|
||||
foreach (var row in doc[table].AsArray())
|
||||
{
|
||||
void Add(string field) => result.Add(new JsonObject { ["path"] = path, ["table"] = table,
|
||||
["id"] = (string)row["ID"], ["name"] = (string)row["Name"], ["field"] = field });
|
||||
if (kind == "Controllers" && table is "Axes" or "DI" or "DQ") Add("Controller");
|
||||
if (kind == "Robots" && table is "RobotPoints" or "RobotMatrices" &&
|
||||
string.Equals((string)target["ID"], (string)row["RobotID"], StringComparison.OrdinalIgnoreCase)) Add("RobotID");
|
||||
if (string.IsNullOrEmpty(name)) continue;
|
||||
string[] fields = kind switch
|
||||
{
|
||||
"Axes" when AxisNameFields.TryGetValue(table, out var links) => links,
|
||||
"DI" or "DQ" when table == "Cylinders" => CylinderFields(kind),
|
||||
"AxisPoints" when table == "Matrices" && SamePointScope(target, row) => MatrixPointFields,
|
||||
"RobotPoints" when table == "RobotMatrices" && SamePointScope(target, row) => MatrixPointFields,
|
||||
_ => []
|
||||
};
|
||||
foreach (var field in fields) if ((string)row[field] == name) Add(field);
|
||||
if (kind == "Cameras" && table == "VisionFunctions")
|
||||
{
|
||||
var steps = row["VisionFlows"].AsArray();
|
||||
for (int i = 0; i < steps.Count; i++)
|
||||
if ((int)steps[i]["Type"] == (int)PLCSharp.VVMs.Vision.VisionFlowType.拍照 &&
|
||||
(string)steps[i]["StringParams"]?["Camera"] == name) Add($"VisionFlows[{i}].StringParams.Camera");
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@ -21,7 +21,7 @@ internal static class ProjectConfiguration
|
||||
["interface"] = ["CanvasConfigs", "CustomControls"]
|
||||
};
|
||||
|
||||
private static IEntityType Entity(DatasContext db, string table) =>
|
||||
internal static IEntityType Entity(DatasContext db, string table) =>
|
||||
db.Model.GetEntityTypes().Single(e => e.GetTableName() == table);
|
||||
|
||||
private static string Quote(string identifier) => "\"" + identifier.Replace("\"", "\"\"") + "\"";
|
||||
@ -61,7 +61,7 @@ internal static class ProjectConfiguration
|
||||
return document;
|
||||
}
|
||||
|
||||
private static bool IsJson(IProperty property) => property.ClrType == typeof(string)
|
||||
internal static bool IsJson(IProperty property) => property.ClrType == typeof(string)
|
||||
&& property.Name.StartsWith("Serialized", StringComparison.Ordinal);
|
||||
|
||||
private static void EmbedImageInputs(JsonNode flows)
|
||||
@ -76,7 +76,7 @@ internal static class ProjectConfiguration
|
||||
}
|
||||
}
|
||||
|
||||
internal static void Restore(DatasContext db, string[] tables, JsonObject document)
|
||||
internal static void Restore(DatasContext db, string[] tables, JsonObject document, bool update = false)
|
||||
{
|
||||
foreach (var table in tables)
|
||||
{
|
||||
@ -88,6 +88,13 @@ internal static class ProjectConfiguration
|
||||
var columns = string.Join(", ", fields.Select(p => Quote(p.GetColumnName())));
|
||||
var parameters = fields.Select((p, i) => "$p" + i).ToArray();
|
||||
insert.CommandText = $"INSERT INTO {Quote(table)} ({columns}) VALUES ({string.Join(", ", parameters)})";
|
||||
if (update)
|
||||
{
|
||||
var key = entity.FindPrimaryKey().Properties.Single();
|
||||
var assignments = fields.Select((p, i) => (p, i)).Where(x => x.p != key)
|
||||
.Select(x => $"{Quote(x.p.GetColumnName())}={parameters[x.i]}");
|
||||
insert.CommandText = $"UPDATE {Quote(table)} SET {string.Join(", ", assignments)} WHERE {Quote(key.GetColumnName())}={parameters[Array.IndexOf(fields, key)]}";
|
||||
}
|
||||
foreach (var name in parameters)
|
||||
{
|
||||
var parameter = insert.CreateParameter();
|
||||
@ -110,8 +117,8 @@ internal static class ProjectConfiguration
|
||||
else raw = value.GetValueKind() switch
|
||||
{
|
||||
JsonValueKind.String => (string)value,
|
||||
JsonValueKind.Number when value.AsValue().TryGetValue<long>(out var n) => n,
|
||||
JsonValueKind.Number => (double)value,
|
||||
JsonValueKind.Number when long.TryParse(value.ToJsonString(), System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var n) => n,
|
||||
JsonValueKind.Number => value.Deserialize<double>(),
|
||||
_ => throw new InvalidDataException($"{table}.{p.Name} 类型无效。")
|
||||
};
|
||||
// SQLite stores EF GUID keys in upper-case text.
|
||||
@ -119,7 +126,7 @@ internal static class ProjectConfiguration
|
||||
}
|
||||
insert.Parameters[i].Value = raw;
|
||||
}
|
||||
insert.ExecuteNonQuery();
|
||||
if (insert.ExecuteNonQuery() != 1) throw new ProjectConflictException($"{table} 对象已改变。");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -28,19 +28,19 @@ internal static class WorkflowReferences
|
||||
.Select(p => MetadataReference.CreateFromFile(p)).ToArray();
|
||||
});
|
||||
|
||||
internal static JsonNode Find(ProjectDirectory project, string kind, string id, bool forRename = false, NestedName nested = null, string memberName = null)
|
||||
internal static JsonNode Find(ProjectDirectory project, string kind, string id, bool forRename = false, NestedName nested = null, string memberName = null, JsonNode candidate = null)
|
||||
{
|
||||
var targetType = kind switch { "Variables" => typeof(Variable), "SystemVariables" => typeof(SystemVariable),
|
||||
"VisionFunctions" => typeof(VisionFunction), "DI" => typeof(DI), "DQ" => typeof(DQ), "Axes" => typeof(Axis), "AxisPoints" => typeof(AxisPoint), "RobotPoints" => typeof(RobotPoint),
|
||||
"Cylinders" => typeof(Cylinder), "Robots" => typeof(Robot), "Connects" => typeof(Connect),
|
||||
"Controllers" => typeof(Controller), "Cylinders" => typeof(Cylinder), "Robots" => typeof(Robot), "Connects" => typeof(Connect),
|
||||
"Cameras" => typeof(PLCSharp.VVMs.Vision.Camera.CameraBase), "ImageDatas" => typeof(ImageData), "LocalImageDatas" => typeof(LocalImageData),
|
||||
"ControlMeasurements" => typeof(PLCSharp.VVMs.Homepage.TableControl.RangeValue), "VisionLocalVariables" => typeof(LocalVariableItem),
|
||||
"InterpolationSegments" => typeof(Interpolation), "InterpolationPoints" => typeof(InterpolationPoint),
|
||||
"Recipes" => typeof(PLCSharp.VVMs.Recipe.Recipe), "CustomControls" => typeof(PLCSharp.VVMs.Homepage.CustomControl),
|
||||
"Matrices" => typeof(Matrix), "RobotMatrices" => typeof(RobotMatrix), "InterpolationGroups" => typeof(InterpolationGroup),
|
||||
"Workflows" => typeof(Workflow), _ => throw new ArgumentException("Unsupported reference target.") };
|
||||
var target = ProjectInspection.Query(project, "get", new() { ["kind"] = nested?.Table ?? kind, ["id"] = id });
|
||||
bool projectWide = kind is "Axes" or "DI" or "DQ" or "Cylinders" or "Robots" or "Connects" or "Cameras" or "Recipes";
|
||||
var target = candidate ?? ProjectInspection.Query(project, "get", new() { ["kind"] = nested?.Table ?? kind, ["id"] = id });
|
||||
bool projectWide = kind is "Controllers" or "Axes" or "DI" or "DQ" or "Cylinders" or "Robots" or "Connects" or "Cameras" or "Recipes";
|
||||
var recipeId = projectWide ? Guid.Empty : Guid.Parse((string)target["RecipeID"]);
|
||||
var name = nested == null ? (string)target["Name"] : memberName;
|
||||
var uniqueOwner = nested != null && ProjectConfiguration.Capture(project.Data, [nested.Table], false)[nested.Table].AsArray()
|
||||
@ -71,6 +71,30 @@ internal static class WorkflowReferences
|
||||
column = position.Character + 1, start = value.SpanStart, length = value.Span.Length, expression = location.ToString(),
|
||||
confidence = !constant.HasValue ? "dynamic" : bound ? "confirmed" : "possible" });
|
||||
}
|
||||
if (candidate != null)
|
||||
{
|
||||
// Indexing, iteration and predicates on a collection may select an object at runtime.
|
||||
var collectionName = kind == "RobotPoints" ? "Points" : kind;
|
||||
foreach (var access in root.DescendantNodes().OfType<MemberAccessExpressionSyntax>())
|
||||
{
|
||||
if (model.GetSymbolInfo(access).Symbol is not IPropertySymbol property) continue;
|
||||
bool singleton = kind == "Controllers" && property.Name == nameof(ControllersModel.Controller) &&
|
||||
property.ContainingType.ToDisplayString() == typeof(ControllersModel).FullName;
|
||||
bool collection = property.Name == collectionName && property.Type is INamedTypeSymbol list &&
|
||||
list.TypeArguments.Length == 1 && list.TypeArguments[0].ToDisplayString() == targetType.FullName;
|
||||
if (!singleton && !collection) continue;
|
||||
var invocation = access.Parent?.Parent as InvocationExpressionSyntax;
|
||||
if (collection && invocation?.ArgumentList.Arguments.Count == 1 &&
|
||||
invocation.ArgumentList.Arguments[0].Expression is SimpleLambdaExpressionSyntax lambda &&
|
||||
lambda.Body is BinaryExpressionSyntax eq && eq.IsKind(SyntaxKind.EqualsExpression) &&
|
||||
new[] { eq.Left, eq.Right }.Any(e => model.GetSymbolInfo(e).Symbol is IPropertySymbol { Name: "Name" } n &&
|
||||
n.ContainingType.ToDisplayString() == targetType.FullName)) continue;
|
||||
var position = access.GetLocation().GetLineSpan().StartLinePosition;
|
||||
hits.Add(new { recipeId = recipe.ID, workflowId = workflow.ID, workflow.Name, path, line = position.Line + 1,
|
||||
column = position.Character + 1, expression = (invocation as SyntaxNode ?? access.Parent ?? access).ToString(),
|
||||
confidence = singleton ? "confirmed" : "dynamic" });
|
||||
}
|
||||
}
|
||||
// Return null when the receiver cannot be tied to a configured robot.
|
||||
bool? IsTargetRobot(ExpressionSyntax receiver)
|
||||
{
|
||||
|
||||
52
Tests/PLCSharp.Tests/ObjectEditTests.cs
Normal file
52
Tests/PLCSharp.Tests/ObjectEditTests.cs
Normal file
@ -0,0 +1,52 @@
|
||||
using PLCSharp.Models;
|
||||
using System.IO;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace PLCSharp.Tests;
|
||||
|
||||
public class ObjectEditTests
|
||||
{
|
||||
[Fact]
|
||||
public void EverySupportedTableCreatesUpdatesDeletesAndUndoesEachSnapshot()
|
||||
{
|
||||
var dir = Directory.CreateTempSubdirectory();
|
||||
try
|
||||
{
|
||||
using var p = ProjectDirectory.New();
|
||||
p.Save(dir.FullName);
|
||||
var robot = p.PlanObjectEdit("create", "Robots", null, new() { ["Name"] = "Parent" });
|
||||
p.ApplyObjectEdit(robot);
|
||||
foreach (var kind in new[] { "Variables", "Controllers", "Axes", "DI", "DQ", "Cylinders", "Robots", "Connects", "Cameras", "AxisPoints", "RobotPoints" })
|
||||
{
|
||||
JsonObject fields = new();
|
||||
if (kind != "Controllers") fields["Name"] = "QA";
|
||||
if (kind is "Variables" or "AxisPoints" or "RobotPoints") fields["RecipeID"] = p.DefaultRecipeId.ToString();
|
||||
if (kind == "RobotPoints") fields["RobotID"] = robot.Id.ToString();
|
||||
string path = Path.Combine(dir.FullName, "configuration", ProjectDirectory.ObjectGroup(kind) + ".json");
|
||||
var original = File.ReadAllBytes(path);
|
||||
var add = p.PlanObjectEdit("create", kind, null, fields);
|
||||
Assert.Equal(original, File.ReadAllBytes(path));
|
||||
p.ApplyObjectEdit(add);
|
||||
var added = File.ReadAllBytes(path);
|
||||
JsonObject patch = kind switch
|
||||
{
|
||||
"DI" or "DQ" => new() { ["LineNumber"] = "Q9" },
|
||||
"AxisPoints" or "RobotPoints" => new() { ["X"] = 3.5 },
|
||||
_ => new() { ["Comment"] = "inspection" }
|
||||
};
|
||||
var update = p.PlanObjectEdit("update", kind, add.Id, patch);
|
||||
p.ApplyObjectEdit(update);
|
||||
var changed = File.ReadAllBytes(path);
|
||||
var remove = p.PlanObjectEdit("delete", kind, add.Id, null);
|
||||
p.ApplyObjectEdit(remove);
|
||||
p.ApplyObjectEdit(p.UndoObject(Guid.NewGuid(), remove));
|
||||
Assert.Equal(changed, File.ReadAllBytes(path));
|
||||
p.ApplyObjectEdit(p.UndoObject(Guid.NewGuid(), update));
|
||||
Assert.Equal(added, File.ReadAllBytes(path));
|
||||
p.ApplyObjectEdit(p.UndoObject(Guid.NewGuid(), add));
|
||||
Assert.Equal(original, File.ReadAllBytes(path));
|
||||
}
|
||||
}
|
||||
finally { dir.Delete(true); }
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user