From cfb25928cb82d68579afbed2effe42aac7d19b46 Mon Sep 17 00:00:00 2001 From: wanglei Date: Sat, 5 Dec 2026 22:13:44 +0800 Subject: [PATCH] Apply and undo reviewed axis, point and workflow changes across recipes --- PLCSharp.Mcp/ProjectGateway.cs | 2 +- PLCSharp.Mcp/ProjectTools.cs | 6 +- PLCSharpWpf/Models/AxisRename.cs | 106 ++++++++++++++++++ PLCSharpWpf/Models/GlobalModel.Project.cs | 4 +- PLCSharpWpf/Models/PointRename.cs | 3 +- PLCSharpWpf/Models/ProjectChanges.cs | 6 +- PLCSharpWpf/Models/VariableRename.cs | 69 ++++++++---- .../VVMs/Workflows/ScriptReviewWindow.xaml.cs | 5 +- Tests/PLCSharp.Tests/AxisRenameTests.cs | 72 ++++++++++++ 9 files changed, 242 insertions(+), 31 deletions(-) create mode 100644 PLCSharpWpf/Models/AxisRename.cs create mode 100644 Tests/PLCSharp.Tests/AxisRenameTests.cs diff --git a/PLCSharp.Mcp/ProjectGateway.cs b/PLCSharp.Mcp/ProjectGateway.cs index fb43e08..af70ed2 100644 --- a/PLCSharp.Mcp/ProjectGateway.cs +++ b/PLCSharp.Mcp/ProjectGateway.cs @@ -28,7 +28,7 @@ internal sealed class ProjectGateway(string root, bool allowWrite) return ProjectPipe.Call(root, new() { ["operation"] = operation, ["arguments"] = arguments }, () => { using var project = ProjectDirectory.Open(root); - if (operation is "preview" or "previewScript" or "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewUndo" or "apply" or "status") + if (operation is "preview" or "previewScript" or "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewAxisRename" or "previewUndo" or "apply" or "status") return changes.Execute(project, operation, arguments, allowWrite, change => (change.Review == null && change.Rename == null) || approved); return ProjectInspection.Query(project, operation, arguments); }).ToJsonString(); diff --git a/PLCSharp.Mcp/ProjectTools.cs b/PLCSharp.Mcp/ProjectTools.cs index 0cd6fdb..c3fe64b 100644 --- a/PLCSharp.Mcp/ProjectTools.cs +++ b/PLCSharp.Mcp/ProjectTools.cs @@ -11,6 +11,10 @@ internal sealed class ProjectTools(ProjectGateway gateway) public string PreviewVisionFunctionRename(string id, string newName) => gateway.Call("previewVisionRename", new() { ["id"] = id, ["newName"] = newName }); + [McpServerTool(Name = "preview_axis_rename"), Description("Preview a project-wide motion axis rename by ID, including point and interpolation configuration, compiled workflow edits and dynamic references.")] + public string PreviewAxisRename(string id, string newName) => + gateway.Call("previewAxisRename", new() { ["id"] = id, ["newName"] = newName }); + [McpServerTool(Name = "preview_point_rename"), Description("Preview renaming an AxisPoints or RobotPoints ID, including bound workflow and matrix references. Review uncertain and dynamic hits before applying.")] public string PreviewPointRename(string kind, string id, string newName) => gateway.Call("previewPointRename", new() { ["kind"] = kind, ["id"] = id, ["newName"] = newName }); @@ -21,7 +25,7 @@ internal sealed class ProjectTools(ProjectGateway gateway) [McpServerTool(Name = "preview_variable_rename"), Description("Preview renaming a recipe user variable by ID. Compile rewritten workflows, and report dynamic or uncertain references for review. Apply the returned draft ID after review.")] public string PreviewVariableRename(string id, string newName) => gateway.Call("previewRename", new() { ["id"] = id, ["newName"] = newName }); - [McpServerTool(Name = "preview_undo"), Description("Preview reversal of a saved variable, vision function, point or workflow rename from this session. Apply the new draft ID to confirm undo.")] + [McpServerTool(Name = "preview_undo"), Description("Preview reversal of a saved variable, axis, vision function, point or workflow rename from this session. Apply the new draft ID to confirm undo.")] public string PreviewUndo(string draftId) => gateway.Call("previewUndo", new() { ["draftId"] = draftId }); [McpServerTool(Name = "preview_workflow_script"), Description("Preview replacement C# source for a workflow ID. Returns a line diff, Roslyn diagnostics, entry-point validation and draft ID. No code runs. Apply a valid draft with apply_changes; a local WPF confirmation is required.")] diff --git a/PLCSharpWpf/Models/AxisRename.cs b/PLCSharpWpf/Models/AxisRename.cs new file mode 100644 index 0000000..e4acf60 --- /dev/null +++ b/PLCSharpWpf/Models/AxisRename.cs @@ -0,0 +1,106 @@ +using PLCSharp.VVMs.MotionController; +using System.Text.Json.Nodes; + +namespace PLCSharp.Models; + +public sealed partial class ProjectDirectory +{ + private static readonly Dictionary AxisNameFields = new() + { + ["AxisPoints"] = ["AxisXName", "AxisYName", "AxisZName", "AxisUName"], + ["InterpolationGroups"] = ["AxisXName", "AxisYName"] + }; + + private void CheckAxisName(Guid id, string before, string after) + { + if (string.IsNullOrWhiteSpace(before) || string.IsNullOrWhiteSpace(after) || after != after.Trim() || before == after) + throw new ArgumentException("请输入不同的新轴名,首尾不能有空白。"); + if (!Data.Axes.Any(a => a.ID == id && a.Name == before) || + Data.Axes.Any(a => a.ID != id && (a.Name == before || a.Name == after))) + throw new ProjectConflictException("轴已改变或工程内存在重名。"); + } + + private static List AxisLinks(JsonNode document, string before, string after) + { + var links = new List(); + foreach (var (table, fields) in AxisNameFields) + foreach (var row in document[table].AsArray()) + foreach (var field in fields) + { + var value = (string)row[field]; + if (value == after) throw new ProjectConflictException($"点位配置中已有对新轴名的引用:{table}/{row["ID"]}.{field}"); + if (value == before) links.Add(new(table, Guid.Parse((string)row["ID"]), field)); + } + return links; + } + + internal ProjectRename PlanAxisRename(Guid id, string newName) + { + var manifest = JsonNode.Parse(baseline["project.json"]); + var savedRecipes = manifest["recipes"].AsArray().Select(r => Guid.Parse((string)r)).ToHashSet(); + if (!savedRecipes.SetEquals(Recipes.Select(r => r.ID))) + throw new ProjectConflictException("请先保存配方列表,再预览工程轴重命名。"); + var axis = Data.Axes.Single(a => a.ID == id); + CheckAxisName(id, axis.Name, newName); + var points = baseline[ConfigPath("points")]; + return PlanReferences("Axes", id, Guid.Empty, axis.Name, newName) with + { + OriginalPoints = points, + PointReferences = AxisLinks(JsonNode.Parse(points), axis.Name, newName) + }; + } + + private static void UpdateAxisPointsDocument(ProjectRename plan, Dictionary files) + { + var path = ConfigPath("points"); + if (files[path] != plan.OriginalPoints) throw new ProjectConflictException("点位配置已改变,请重新预览。"); + if (plan.PointReferences.Count == 0) return; + var document = JsonNode.Parse(files[path]); + foreach (var reference in plan.PointReferences) + reference.Row(document)[reference.Field] = plan.NewName; + files[path] = plan.UndoOf.HasValue ? plan.SavedPoints : Serialize(document); + } + + internal Action PrepareAxisView(ProjectRename plan, ControllersModel model, Guid recipe) + { + var axis = model.Axes.SingleOrDefault(a => a.ID == plan.ObjectId); + if (axis == null || axis.Name != plan.OldName || + model.Axes.Any(a => a.ID != axis.ID && (a.Name == plan.OldName || a.Name == plan.NewName))) + throw new ProjectConflictException("编辑器运动轴列表已改变,请先保存。"); + + var document = JsonNode.Parse(plan.OriginalPoints); + var expected = plan.PointReferences.Where(f => Guid.Parse((string)f.Row(document)["RecipeID"]) == recipe).ToHashSet(); + var updates = new List(); + void CheckRows(string table, IEnumerable rows) + { + foreach (var row in rows) + { + var entry = Data.Entry(row); + var id = (Guid)entry.Property("ID").CurrentValue; + foreach (var field in AxisNameFields[table]) + { + var property = entry.Property(field); + var value = (string)property.CurrentValue; + if (value == plan.NewName || expected.Remove(new(table, id, field)) != (value == plan.OldName)) + throw new ProjectConflictException("编辑器中的轴名引用已改变,请先保存。"); + if (value == plan.OldName) updates.Add(() => property.CurrentValue = plan.NewName); + } + } + } + CheckRows("AxisPoints", model.AxisPoints); + CheckRows("InterpolationGroups", model.InterpolationGroups); + if (expected.Count != 0) throw new ProjectConflictException("编辑器中的点位或插补组已改变,请先保存。"); + return () => + { + axis.Name = plan.NewName; + foreach (var update in updates) update(); + foreach (var p in model.Matrices.SelectMany(m => m.Points)) + { + if (p.AxisX?.ID == axis.ID) p.AxisXName = plan.NewName; + if (p.AxisY?.ID == axis.ID) p.AxisYName = plan.NewName; + if (p.AxisZ?.ID == axis.ID) p.AxisZName = plan.NewName; + if (p.AxisU?.ID == axis.ID) p.AxisUName = plan.NewName; + } + }; + } +} diff --git a/PLCSharpWpf/Models/GlobalModel.Project.cs b/PLCSharpWpf/Models/GlobalModel.Project.cs index 94a25de..5a3c579 100644 --- a/PLCSharpWpf/Models/GlobalModel.Project.cs +++ b/PLCSharpWpf/Models/GlobalModel.Project.cs @@ -32,7 +32,7 @@ public partial class GlobalModel if (!AllowAiAccess) throw new InvalidOperationException("请在机种配方页面启用 AI 访问。"); string operation = (string)request["operation"]; var args = request["arguments"].AsObject(); - if (operation is "preview" or "previewScript" or "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewUndo" or "apply" or "status") + if (operation is "preview" or "previewScript" or "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewAxisRename" or "previewUndo" or "apply" or "status") { if (operation == "apply" && (ModeState.State.Execute || WorkflowsModel.IsBusy)) throw new InvalidOperationException("运行或切换配方期间无法保存 AI 修改。"); @@ -70,6 +70,8 @@ public partial class GlobalModel updateEditorView = Project.PreparePointView(point, robot.Points, robot.RobotMatrices); } } + if (accepted && change.Rename is { Kind: "Axes" } axis) + updateEditorView = Project.PrepareAxisView(axis, ControllersModel, CurrentRecipe.ID); return accepted; }); if ((string)resultChange["Status"] == "saved") updateEditorView?.Invoke(); diff --git a/PLCSharpWpf/Models/PointRename.cs b/PLCSharpWpf/Models/PointRename.cs index 94914b6..db7ad21 100644 --- a/PLCSharpWpf/Models/PointRename.cs +++ b/PLCSharpWpf/Models/PointRename.cs @@ -11,6 +11,7 @@ public sealed record PointField(string Table, Guid Id, string Field) .Single(row => Guid.Parse((string)row["ID"]) == Id); internal Type EntityType => Table switch { + "Axes" => typeof(Axis), "InterpolationGroups" => typeof(InterpolationGroup), "AxisPoints" => typeof(AxisPoint), "RobotPoints" => typeof(RobotPoint), "Matrices" => typeof(Matrix), "RobotMatrices" => typeof(RobotMatrix), _ => throw new ArgumentException("未知点位配置表。") @@ -68,7 +69,7 @@ public sealed partial class ProjectDirectory } private static IEnumerable PointFields(ProjectRename plan) => - plan.MatrixReferences.Prepend(new(plan.Kind, plan.ObjectId, "Name")); + plan.MatrixReferences.Concat(plan.PointReferences).Prepend(new(plan.Kind, plan.ObjectId, "Name")); private void WritePointFields(ProjectRename plan) { diff --git a/PLCSharpWpf/Models/ProjectChanges.cs b/PLCSharpWpf/Models/ProjectChanges.cs index bd0b5db..f2ac3c0 100644 --- a/PLCSharpWpf/Models/ProjectChanges.cs +++ b/PLCSharpWpf/Models/ProjectChanges.cs @@ -26,10 +26,12 @@ public sealed class ProjectChanges public JsonNode Execute(ProjectDirectory project, string operation, JsonObject args, bool allowWrite, Func confirm = null) { - if (operation is "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewUndo") + if (operation is "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewAxisRename" or "previewUndo") { ProjectRename plan; - if (operation == "previewVisionRename") + if (operation == "previewAxisRename") + plan = project.PlanAxisRename(Guid.Parse((string)args["id"]), (string)args["newName"]); + else if (operation == "previewVisionRename") plan = project.PlanVisionRename(Guid.Parse((string)args["id"]), (string)args["newName"]); else if (operation == "previewPointRename") plan = project.PlanPointRename((string)args["kind"], Guid.Parse((string)args["id"]), (string)args["newName"]); diff --git a/PLCSharpWpf/Models/VariableRename.cs b/PLCSharpWpf/Models/VariableRename.cs index bb62dae..c0a41a5 100644 --- a/PLCSharpWpf/Models/VariableRename.cs +++ b/PLCSharpWpf/Models/VariableRename.cs @@ -22,10 +22,14 @@ public sealed record ProjectRename(Guid ObjectId, Guid RecipeId, string OldName, { "AxisPoints" or "RobotPoints" => "configuration/points.json", "VisionFunctions" => "configuration/vision.json", + "Axes" => "configuration/hardware.json", "Workflows" => $"recipes/{recipe:D}/recipe.json", _ => ProjectDirectory.VariablesPath }; public List MatrixReferences { get; init; } = []; + public List PointReferences { get; init; } = []; + [JsonIgnore] internal string OriginalPoints { get; init; } + [JsonIgnore] internal string SavedPoints { get; set; } [JsonIgnore] internal string RobotScope { get; init; } public bool Compiled => Scripts.All(s => s.Review.Compiled) && ScanDiagnostics.Count == 0; [JsonIgnore] internal string Scope { get; init; } @@ -39,9 +43,12 @@ public sealed partial class ProjectDirectory { internal const string VariablesPath = "configuration/variables.json"; + private IEnumerable RecipeScope(Guid recipe) => + recipe == Guid.Empty ? Recipes.Select(r => r.ID).OrderBy(id => id) : [recipe]; + internal string RenameScope(Guid recipe) { - var inputs = Flows(recipe).OrderBy(w => w.ID).Select(w => new { w.ID, w.Name, w.Code }); + var inputs = RecipeScope(recipe).Select(id => new { id, scripts = Flows(id).OrderBy(w => w.ID).Select(w => new { w.ID, w.Name, w.Code }) }); return Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(inputs))); } @@ -103,14 +110,14 @@ public sealed partial class ProjectDirectory var manual = new JsonArray(); foreach (var hit in hits.Where(h => (string)h["confidence"] != "confirmed")) manual.Add(hit.DeepClone()); var edits = new List(); - foreach (var group in hits.Where(h => (string)h["confidence"] == "confirmed").GroupBy(h => (Guid)h["workflowId"])) + foreach (var group in hits.Where(h => (string)h["confidence"] == "confirmed").GroupBy(h => (Recipe: (Guid)h["recipeId"], Flow: (Guid)h["workflowId"]))) { - var flow = Flows(recipeId).Single(w => w.ID == group.Key); + var flow = Flows(group.Key.Recipe).Single(w => w.ID == group.Key.Flow); string replacement = SymbolDisplay.FormatLiteral(newName, quote: true); var changes = group.Select(h => new TextChange(new TextSpan((int)h["start"], (int)h["length"]), replacement)) .Distinct().OrderBy(c => c.Span.Start); var next = SourceText.From(flow.Code).WithChanges(changes).ToString(); - edits.Add(new(flow.ID, flow.Name, ScriptPath(recipeId, flow.ID), flow.Code, next, + edits.Add(new(flow.ID, flow.Name, ScriptPath(group.Key.Recipe, flow.ID), flow.Code, next, WorkflowScriptReview.Create(flow.ID, flow.Code, next))); } return new(id, recipeId, oldName, newName, edits, manual, analysis["diagnostics"].AsArray()) @@ -118,13 +125,14 @@ public sealed partial class ProjectDirectory } internal ProjectRename PlanUndo(Guid operationId, ProjectRename saved) { - if (saved.SavedScope != RenameScope(saved.RecipeId) || saved.SavedMetadata != baseline[saved.MetadataPath]) + if (saved.SavedScope != RenameScope(saved.RecipeId) || saved.SavedMetadata != baseline[saved.MetadataPath] || + (saved.Kind == "Axes" && saved.SavedPoints != baseline[ConfigPath("points")])) throw new ProjectConflictException("保存后配方脚本或名称文件已改变,无法安全撤销。"); CheckName(saved, saved.NewName, saved.OldName); var inverse = saved.Scripts.Select(s => s with { Before = s.After, After = s.Before, Review = WorkflowScriptReview.Create(s.Id, s.After, s.Before) }).ToList(); return new(saved.ObjectId, saved.RecipeId, saved.NewName, saved.OldName, inverse, - saved.ManualReferences, new JsonArray()) { Kind = saved.Kind, MatrixReferences = saved.MatrixReferences, RobotScope = saved.RobotScope, UndoOf = operationId, Scope = saved.SavedScope, + saved.ManualReferences, new JsonArray()) { Kind = saved.Kind, PointReferences = saved.PointReferences, OriginalPoints = saved.SavedPoints, SavedPoints = saved.OriginalPoints, MatrixReferences = saved.MatrixReferences, RobotScope = saved.RobotScope, UndoOf = operationId, Scope = saved.SavedScope, OriginalMetadata = saved.SavedMetadata, SavedMetadata = saved.OriginalMetadata }; } @@ -132,6 +140,7 @@ public sealed partial class ProjectDirectory { if (plan.Kind == "Workflows") CheckWorkflowName(plan.RecipeId, plan.ObjectId, before, after); else if (plan.Kind == "VisionFunctions") CheckVisionName(plan.RecipeId, plan.ObjectId, before, after); + else if (plan.Kind == "Axes") CheckAxisName(plan.ObjectId, before, after); else if (plan.IsPoint) ValidatePoint(plan, before, after); else CheckVariableName(plan.RecipeId, plan.ObjectId, before, after); } @@ -145,31 +154,42 @@ public sealed partial class ProjectDirectory throw new ProjectConflictException("变量或工作流已经改变,请重新预览。"); var files = new Dictionary(baseline); bool workflowRename = plan.Kind == "Workflows"; - var recipePath = RecipePath(plan.RecipeId); + var metadata = JsonNode.Parse(files[plan.MetadataPath]); var rows = metadata[workflowRename ? "workflows" : plan.Kind].AsArray(); var row = rows.Single(v => Guid.Parse((string)v[workflowRename ? "id" : "ID"]) == plan.ObjectId); var field = workflowRename ? "name" : "Name"; if ((string)row[field] != plan.OldName) throw new ProjectConflictException("名称有未保存的编辑,请先保存或还原。"); - var flows = Flows(plan.RecipeId); - var persisted = JsonNode.Parse(files[recipePath])["workflows"].AsArray() - .ToDictionary(w => Guid.Parse((string)w["id"]), w => (string)w["name"]); - if (flows.Count != persisted.Count || flows.Any(w => !persisted.TryGetValue(w.ID, out var name) || w.Name != name)) - throw new ProjectConflictException("请先保存工作流列表。"); + var scope = new List { "project.json", plan.MetadataPath }; + var scripts = new Dictionary(); + foreach (var recipe in RecipeScope(plan.RecipeId)) + { + var recipePath = RecipePath(recipe); + var flows = Flows(recipe); + var persisted = JsonNode.Parse(files[recipePath])["workflows"].AsArray() + .ToDictionary(w => Guid.Parse((string)w["id"]), w => (string)w["name"]); + if (flows.Count != persisted.Count || flows.Any(w => !persisted.TryGetValue(w.ID, out var name) || w.Name != name)) + throw new ProjectConflictException("请先保存工作流列表。"); + if (recipePath != plan.MetadataPath) scope.Add(recipePath); + foreach (var flow in flows) + { + var path = ScriptPath(recipe, flow.ID); + if (!files.TryGetValue(path, out var code) || code != (flow.Code ?? "")) + throw new ProjectConflictException($"工作流 {flow.Name} 有未保存的编辑,请保存后重新预览。"); + scope.Add(path); + scripts.Add(path, flow); + } + } row[field] = plan.NewName; foreach (var reference in plan.MatrixReferences) reference.Row(metadata)[reference.Field] = plan.NewName; files[plan.MetadataPath] = plan.UndoOf.HasValue ? plan.SavedMetadata : Serialize(metadata); - var scope = new List { recipePath, "project.json" }; - if (!workflowRename) scope.Add(plan.MetadataPath); if (plan.Kind == "RobotPoints") scope.Add(ConfigPath("hardware")); - foreach (var flow in flows) + if (plan.Kind == "Axes") { - var path = ScriptPath(plan.RecipeId, flow.ID); - if (files[path] != (flow.Code ?? "")) - throw new ProjectConflictException($"工作流 {flow.Name} 有未保存的编辑,请保存后重新预览。"); - scope.Add(path); + UpdateAxisPointsDocument(plan, files); + scope.Add(ConfigPath("points")); } foreach (var script in plan.Scripts) { @@ -179,8 +199,8 @@ public sealed partial class ProjectDirectory } // Hold each affected workflow's execution gate through the single multi-file commit. - var updates = plan.Scripts.Select(s => (Flow: flows.Single(w => w.ID == s.Id), s.Before, s.After)).ToArray(); - var targetFlow = workflowRename ? flows.Single(w => w.ID == plan.ObjectId) : null; + var updates = plan.Scripts.Select(s => (Flow: scripts[s.Path], s.Before, s.After)).ToArray(); + var targetFlow = workflowRename ? scripts[ScriptPath(plan.RecipeId, plan.ObjectId)] : null; if (workflowRename && updates.All(edit => edit.Flow != targetFlow)) updates = [.. updates, (targetFlow, targetFlow.Code ?? "", targetFlow.Code ?? "")]; PLCSharp.VVMs.Workflows.Workflow.SaveReviewedBatch(updates, () => @@ -189,7 +209,7 @@ public sealed partial class ProjectDirectory if (plan.Kind == "VisionFunctions" && Data.VisionFunctions.Where(v => v.ID == plan.ObjectId && v.Name == plan.OldName) .ExecuteUpdate(s => s.SetProperty(v => v.Name, plan.NewName)) != 1) throw new ProjectConflictException("视觉功能已发生变化。"); - if (plan.IsPoint) WritePointFields(plan); + if (plan.IsPoint || plan.Kind == "Axes") WritePointFields(plan); if (plan.Kind == "Variables" && Data.Variables.Where(v => v.ID == plan.ObjectId && v.Name == plan.OldName) .ExecuteUpdate(s => s.SetProperty(v => v.Name, plan.NewName)) != 1) throw new ProjectConflictException("变量已发生变化。"); @@ -205,7 +225,9 @@ public sealed partial class ProjectDirectory return; } configuration[plan.MetadataPath] = files[plan.MetadataPath]; - if (plan.IsPoint) + if (plan.Kind == "Axes") + configuration[ConfigPath("points")] = files[ConfigPath("points")]; + if (plan.IsPoint || plan.Kind == "Axes") { AcceptPointFields(plan); return; @@ -221,6 +243,7 @@ public sealed partial class ProjectDirectory variable.Name = plan.NewName; Data.Entry(variable).Property(v => v.Name).OriginalValue = plan.NewName; }); + if (plan.Kind == "Axes") plan.SavedPoints = files[ConfigPath("points")]; plan.SavedScope = RenameScope(plan.RecipeId); plan.SavedMetadata = files[plan.MetadataPath]; } diff --git a/PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml.cs b/PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml.cs index 36f2d69..57c560d 100644 --- a/PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml.cs +++ b/PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml.cs @@ -11,13 +11,14 @@ public partial class ScriptReviewWindow : Window InitializeComponent(); if (change.Rename is { } rename) { - var subject = rename.Kind switch { "VisionFunctions" => "视觉功能", "Workflows" => "工作流", + var subject = rename.Kind switch { "Axes" => "运动轴", "VisionFunctions" => "视觉功能", "Workflows" => "工作流", "AxisPoints" or "RobotPoints" => "点位", _ => "变量" }; Title = $"确认{(rename.UndoOf.HasValue ? "撤销" : "")}{subject}重命名"; WorkflowTitle.Text = $"{rename.OldName} → {rename.NewName}"; Location.Text = System.IO.Path.Combine(root, change.Path); CheckResult.Text = $"已通过编译的工作流:{rename.Scripts.Count},需人工核对的引用:{rename.ManualReferences.Count}"; - CodeDiff.Text = string.Join("\n", rename.MatrixReferences.Select(m => $"{m.Table}/{m.Id} · {m.Field}:{rename.OldName} → {rename.NewName}") + CodeDiff.Text = string.Join("\n", rename.PointReferences.Select(p => $"configuration/points.json · {p.Table}/{p.Id} · {p.Field}:{rename.OldName} → {rename.NewName}") + .Concat(rename.MatrixReferences.Select(m => $"{m.Table}/{m.Id} · {m.Field}:{rename.OldName} → {rename.NewName}")) .Concat(rename.ManualReferences.Select(h => $"待核对 [{h["confidence"]}] {h["path"]}:{h["line"]} {h["expression"]}")) .Concat(rename.Scripts.Select(s => $"\n{s.Path} · {s.Name}\n{s.Review.Diff}"))); diff --git a/Tests/PLCSharp.Tests/AxisRenameTests.cs b/Tests/PLCSharp.Tests/AxisRenameTests.cs new file mode 100644 index 0000000..8aafd0c --- /dev/null +++ b/Tests/PLCSharp.Tests/AxisRenameTests.cs @@ -0,0 +1,72 @@ +using PLCSharp.Models; +using PLCSharp.VVMs.MotionController; +using PLCSharp.VVMs.Recipe; +using PLCSharp.VVMs.Workflows; +using System.IO; + +namespace PLCSharp.Tests; + +public class AxisRenameTests +{ + [Fact] + public void RenameUpdatesReferencesAcrossRecipesAndRejectsStalePointFiles() + { + var root = Directory.CreateTempSubdirectory(); + try + { + using var p = ProjectDirectory.New(); + p.Recipes.Add(new Recipe { Name = "B" }); + var axis = new Axis { Name = "X" }; + p.Data.AddRange(axis, new Axis { Name = "Y" }); + foreach (var recipe in p.Recipes) + { + p.Data.Add(new AxisPoint { RecipeID = recipe.ID, Name = "Home", AxisUName = "X" }); + p.Data.Add(new InterpolationGroup { RecipeID = recipe.ID, AxisYName = "X" }); + var flow = new Workflow { RecipeID = recipe.ID, Name = "Run" }; + flow.Code = $$""" + using System.Linq; + using PLCSharp.Models; + using PLCSharp.Core.Common; + public class Extension_{{flow.ID:N}} { + public void Run(GlobalModel m, FlowModel f) { + _ = m.ControllersModel.Axes.FirstOrDefault(a => a.Name == "X"); + _ = m.ControllersModel.Controller.Axes.FirstOrDefault(a => a.Name == f.Step.ToString()); + _ = m.GetTask("X"); + } + } + """; + p.Flows(recipe.ID).Add(flow); + } + p.Save(root.FullName); + var original = Directory.GetFiles(root.FullName, "*", SearchOption.AllDirectories).ToDictionary(f => f, File.ReadAllBytes); + Assert.ThrowsAny(() => p.PlanAxisRename(axis.ID, "Y")); + var draft = p.PlanAxisRename(axis.ID, "横移轴"); + Assert.True(draft.Compiled); + Assert.Equal(2, draft.Scripts.Count); + Assert.Equal(2, draft.ManualReferences.Count); + Assert.Equal(4, draft.PointReferences.Count); + p.ApplyRename(draft); + using (var reopened = ProjectDirectory.Open(root.FullName)) + { + Assert.Equal("横移轴", reopened.Data.Axes.Find(axis.ID)!.Name); + Assert.All(reopened.Data.AxisPoints, pt => Assert.Equal("横移轴", pt.AxisUName)); + Assert.All(reopened.Data.InterpolationGroups, g => Assert.Equal("横移轴", g.AxisYName)); + foreach (var r in reopened.Recipes) + { + var script = Assert.Single(reopened.Flows(r.ID)).Code; + Assert.Contains("a.Name == \"横移轴\"", script); + Assert.Contains("GetTask(\"X\")", script); + } + } + p.ApplyRename(p.PlanUndo(Guid.NewGuid(), draft)); + Assert.All(original, file => Assert.Equal(file.Value, File.ReadAllBytes(file.Key))); + var stale = p.PlanAxisRename(axis.ID, "横移轴"); + var points = Path.Combine(root.FullName, "configuration", "points.json"); + File.AppendAllText(points, "\n"); + Assert.ThrowsAny(() => p.ApplyRename(stale)); + Assert.Equal("X", axis.Name); + Assert.All(original.Where(f => f.Key != points), file => Assert.Equal(file.Value, File.ReadAllBytes(file.Key))); + } + finally { root.Delete(true); } + } +}