diff --git a/PLCSharpWpf/Models/ProjectBatch.cs b/PLCSharpWpf/Models/ProjectBatch.cs new file mode 100644 index 0000000..632c972 --- /dev/null +++ b/PLCSharpWpf/Models/ProjectBatch.cs @@ -0,0 +1,203 @@ +using Microsoft.EntityFrameworkCore; +using PLCSharp.VVMs.Recipe; +using PLCSharp.VVMs.Workflows; +using System.IO; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.Json.Serialization; + +namespace PLCSharp.Models; + +public sealed record ProjectBatch(List Steps, List Workflows, string[] ChangedFiles, Guid? UndoOf = null) +{ + public bool Compiled => Steps.All(s => s.Status == "pending") && Workflows.All(f => f.Compiled); + [JsonIgnore] internal Dictionary From { get; init; } + [JsonIgnore] internal Dictionary To { get; init; } + [JsonIgnore] internal Dictionary OriginalBytes { get; init; } + [JsonIgnore] internal List Rows { get; init; } +} + +public sealed partial class ProjectDirectory +{ + internal ProjectBatch PlanBatch(JsonArray operations) + { + if (operations == null || operations.Count == 0) throw new ArgumentException("批次不能为空。"); + var temp = Directory.CreateTempSubdirectory("plcsharp-preview-"); + try + { + foreach (var (path, value) in baseline) + { + string full = ProjectFile(temp.FullName, path); + Directory.CreateDirectory(Path.GetDirectoryName(full)); + File.WriteAllText(full, value); + } + using var stage = Open(temp.FullName); + var before = stage.BatchRows(); + var aliases = new Dictionary(); + var preview = new ProjectChanges(); + var steps = new List(); + foreach (var input in operations) + { + var args = input.DeepClone().AsObject(); + void Resolve(JsonObject obj, string key) + { + if (obj?[key] is JsonValue v && v.TryGetValue(out var s) && s.StartsWith('$')) + obj[key] = aliases.TryGetValue(s[1..], out var id) ? id.ToString() : throw new ArgumentException($"未知批次对象 {s}"); + } + Resolve(args, "id"); + foreach (string field in new[]{"RecipeID","RobotID","FuncID"}) Resolve(args["properties"]?.AsObject(), field); + var operation = (string)args["action"] == "rename" ? "previewObjectRename" : "previewObjectEdit"; + var result = preview.Execute(stage, operation, args, false); + var draft = preview.PendingOrInvalid(Guid.Parse((string)result["DraftId"])); + steps.Add(draft); + if (draft.Status == "invalid") break; + if ((string)args["alias"] is string alias && !aliases.TryAdd(alias,draft.ObjectId)) throw new ArgumentException("批次别名重复。"); + if (draft.Edit != null) stage.ApplyObjectEdit(draft.Edit); + else stage.ApplyRename(draft.Rename); + } + var paths = baseline.Keys.Union(stage.baseline.Keys).Where(p => baseline.GetValueOrDefault(p) != stage.baseline.GetValueOrDefault(p)).ToArray(); + var after = stage.BatchRows(); + var rows = new List(); + foreach (var key in before.Keys.Union(after.Keys)) + { + var old = before.GetValueOrDefault(key); + var next = after.GetValueOrDefault(key); + if (JsonNode.DeepEquals(old,next)) continue; + rows.Add(new(old == null ? "create" : next == null ? "delete" : "update",key.Kind,key.Id,"",old,next,[],[],[],[])); + } + var flows = steps.SelectMany(s => s.Edit?.Workflows ?? s.Rename.Scripts.Select(f => new CheckedFlow(f.Id,f.Name,f.Path,f.Review.Compiled,f.Review.Diagnostics)).ToList()) + .GroupBy(f=>f.Id).Select(g=>g.Last()).ToList(); + foreach (var flow in flows.ToArray()) + { + if (after.GetValueOrDefault(("Workflows",flow.Id)) is not { } row) continue; + var check = WorkflowScriptReview.Create(flow.Id, (string)row["Code"], (string)row["Code"]); + flows[flows.IndexOf(flow)] = flow with { Compiled = check.Compiled, Diagnostics = check.Diagnostics }; + } + return new(steps,flows,paths) { From = new(baseline), To = new(stage.baseline), Rows = rows, + OriginalBytes = paths.Where(baseline.ContainsKey).ToDictionary(p=>p,p=>File.ReadAllBytes(ProjectFile(Root,p))) }; + } + finally { temp.Delete(true); } + } + + private Dictionary<(string Kind, Guid Id),JsonObject> BatchRows() + { + var rows = new Dictionary<(string,Guid),JsonObject>(); + foreach (var recipe in Recipes) + { + rows.Add(("Recipes",recipe.ID),RecipeRow(recipe)); + foreach (var flow in Flows(recipe.ID)) rows.Add(("Workflows",flow.ID),FlowRow(flow)); + } + foreach (var (group,tables) in ProjectConfiguration.Groups) + { + var doc = JsonNode.Parse(configuration[ConfigPath(group)]); + foreach (var table in tables) + foreach (var row in doc[table].AsArray()) rows.Add((table,Guid.Parse((string)row["ID"])),row.AsObject()); + } + return rows; + } + + internal ProjectBatch UndoBatch(Guid id, ProjectBatch batch) + { + CheckBatchState(batch.To); + var restoredFlows = new List(); + foreach (var flow in batch.Workflows) + { + if (!batch.From.TryGetValue(flow.Path, out var code)) continue; + var review = WorkflowScriptReview.Create(flow.Id, batch.To.GetValueOrDefault(flow.Path), code); + restoredFlows.Add(flow with { Compiled = review.Compiled, Diagnostics = review.Diagnostics }); + } + return batch with { From = batch.To, To = batch.From, UndoOf = id, Workflows = restoredFlows, + Rows = batch.Rows.AsEnumerable().Reverse().Select(e=>e with { Before=e.After, After=e.Before, + Action=e.Action=="update"?"update":e.Action=="create"?"delete":"create" }).ToList() }; + } + + private void CheckBatchState(Dictionary expected) + { + if (!baseline.OrderBy(p=>p.Key).SequenceEqual(expected.OrderBy(p=>p.Key))) + throw new ProjectConflictException("工程已经改变,请重新预览整批操作。"); + } + + internal void ApplyBatch(ProjectBatch batch) + { + lock (Data.Sync) + { + CheckBatchState(batch.From); + var previousManifest = JsonSerializer.Deserialize(batch.From["project.json"], Json); + if (!Recipes.Select(r => r.ID).SequenceEqual(previousManifest.Recipes) || DefaultRecipeId != previousManifest.DefaultRecipeId) + throw new ProjectConflictException("配方列表有未保存修改。"); + foreach (var rid in previousManifest.Recipes) + { + var order = JsonSerializer.Deserialize(batch.From[RecipePath(rid)], Json).Workflows; + if (!Flows(rid).Select(f => f.ID).SequenceEqual(order.Select(f => f.Id))) + throw new ProjectConflictException("工作流列表有未保存修改。"); + } + var current = BatchRows(); + var configRows = batch.Rows.Where(r=>r.Kind is not ("Workflows" or "Recipes")).ToList(); + var touched = configRows.Select(r=>(r.Kind,r.Id)).ToHashSet(); + var tracked = Data.ChangeTracker.Entries().Where(e=>e.Metadata.FindProperty("ID")?.ClrType==typeof(Guid) && + touched.Contains((e.Metadata.GetTableName(),(Guid)e.Property("ID").CurrentValue))).ToArray(); + if (tracked.Any(e=>e.State!=EntityState.Unchanged) || batch.Rows.Any(r=>!JsonNode.DeepEquals(current.GetValueOrDefault((r.Kind,r.Id)),r.Before))) + throw new ProjectConflictException("批次涉及的对象有未保存修改。"); + var flowRows = batch.Rows.Where(r=>r.Kind=="Workflows").ToList(); + var gates = flowRows.Where(r=>r.Before!=null).Select(r=>(Flows(Guid.Parse((string)r.Before["RecipeID"])).Single(f=>f.ID==r.Id), + (string)r.Before["Code"], (string)(r.After??r.Before)["Code"])).ToArray(); + Workflow.SaveReviewedBatch(gates, () => + { + using var tx = Data.Database.BeginTransaction(); + foreach (var row in configRows) + { + if (row.After == null) + { + if (Data.Database.ExecuteSqlRaw($"DELETE FROM \"{row.Kind}\" WHERE ID = {{0}}",row.Id)!=1) + throw new ProjectConflictException("配置记录已改变。"); + } + else ProjectConfiguration.Restore(Data,[row.Kind],new(){[row.Kind]=new JsonArray(row.After.DeepClone())},row.Before!=null); + } + var expectedBytes = batch.UndoOf.HasValue ? batch.ChangedFiles.Where(batch.From.ContainsKey) + .ToDictionary(p=>p,p=>Encoding.UTF8.GetBytes(batch.From[p])) : batch.OriginalBytes; + WriteFiles(Root,new(batch.To),batch.From.Keys.Union(batch.To.Keys).ToArray(),tx.Commit, + batch.UndoOf.HasValue ? batch.OriginalBytes : null, expectedBytes); + foreach (var entry in tracked) entry.Reload(); + foreach (string path in configuration.Keys.ToList()) configuration[path]=baseline[path]; + var manifest=JsonSerializer.Deserialize(baseline["project.json"],Json); + DefaultRecipeId=manifest.DefaultRecipeId; + foreach (var row in flowRows) + { + var collection=Flows(Guid.Parse((string)(row.After??row.Before)["RecipeID"])); + var flow=collection.SingleOrDefault(f=>f.ID==row.Id); + if (row.After==null) { flow.Stop(); collection.Remove(flow); continue; } + var a=row.After; + bool add=flow==null; + flow??=new Workflow { ID=row.Id, RecipeID=Guid.Parse((string)a["RecipeID"]) }; + flow.Name=(string)a["Name"]; flow.Comment=(string)a["Comment"]; flow.Code=(string)a["Code"]; + flow.CycleDelayTime=(double)a["CycleDelayTime"]; flow.AutomaticExecution=(bool)a["AutomaticExecution"]; flow.Prompt=""; + if (add) collection.Add(flow); + } + foreach (var row in batch.Rows.Where(r=>r.Kind=="Recipes")) + { + var recipe=Recipes.SingleOrDefault(r=>r.ID==row.Id); + if(row.After==null) { Recipes.Remove(recipe); workflows.Remove(row.Id); continue; } + bool add=recipe==null; + recipe??=new Recipe { ID=row.Id }; + recipe.Name=(string)row.After["Name"]; recipe.Comment=(string)row.After["Comment"]; recipe.Prompt=""; + if(add) Recipes.Add(recipe); + } + for(int i=0;ir.ID==rid)); + if(index!=i) Recipes.Move(index,i); + var list=Flows(rid); + var order=JsonSerializer.Deserialize(baseline[RecipePath(rid)],Json).Workflows; + for(int j=0;jf.ID==order[j].Id)); + if(at!=j) list.Move(at,j); + } + } + }); + } + } +} + diff --git a/PLCSharpWpf/Models/ProjectChanges.cs b/PLCSharpWpf/Models/ProjectChanges.cs index 87586d7..e6090d8 100644 --- a/PLCSharpWpf/Models/ProjectChanges.cs +++ b/PLCSharpWpf/Models/ProjectChanges.cs @@ -7,14 +7,16 @@ using System.Text.Json.Nodes; namespace PLCSharp.Models; public sealed record ProjectChange(Guid DraftId, Guid ProjectId, string Kind, Guid ObjectId, Guid RecipeId, - string Name, string Path, string Before, string After, string Revision, string Status, WorkflowScriptReview Review = null, ProjectRename Rename = null, ObjectEdit Edit = null); + string Name, string Path, string Before, string After, string Revision, string Status, WorkflowScriptReview Review = null, ProjectRename Rename = null, ObjectEdit Edit = null, ProjectBatch Batch = null); public sealed class ProjectChanges { private readonly Dictionary drafts = new(); + internal ProjectChange PendingOrInvalid(Guid id) => drafts[id]; + public ProjectChange PendingScript(Guid id) => - drafts.TryGetValue(id, out var draft) && (draft.Review != null || draft.Rename != null || draft.Edit != null) && draft.Status == "pending" ? draft : null; + drafts.TryGetValue(id, out var draft) && (draft.Review != null || draft.Rename != null || draft.Edit != null || draft.Batch != null) && draft.Status == "pending" ? draft : null; private JsonNode Remember(ProjectChange change) { @@ -26,6 +28,16 @@ public sealed class ProjectChanges public JsonNode Execute(ProjectDirectory project, string operation, JsonObject args, bool allowWrite, Func confirm = null) { + ProjectBatch batch = null; + if (operation == "previewBatch") batch = project.PlanBatch(args["operations"]?.AsArray()); + if (operation == "previewUndo" && drafts.TryGetValue(Guid.Parse((string)args["draftId"]), out var originalBatch) && originalBatch.Batch != null) + { + if (originalBatch.ProjectId != project.Id || originalBatch.Status != "saved" || originalBatch.Batch.UndoOf.HasValue) + throw new ProjectConflictException("该批次不能撤销。"); + batch = project.UndoBatch(originalBatch.DraftId, originalBatch.Batch); + } + if (batch != null) return Remember(new(Guid.NewGuid(), project.Id, "Batch", Guid.Empty, Guid.Empty, "工程修改", "project.json", + null, null, project.Revision("project.json"), batch.Compiled ? "pending" : "invalid", Batch: batch)); ObjectEdit edit = null; if (operation == "previewObjectEdit") edit = project.PlanObjectEdit((string)args["action"], (string)args["kind"], @@ -112,13 +124,21 @@ public sealed class ProjectChanges if (operation == "apply" && draft.Status == "pending") { if (!allowWrite) throw new InvalidOperationException("Start the MCP server with --allow-write to apply a preview."); - if ((draft.Review != null || draft.Rename != null || draft.Edit != null) && confirm == null) throw new InvalidOperationException("脚本修改需要用户确认。"); + if ((draft.Review != null || draft.Rename != null || draft.Edit != null || draft.Batch != null) && confirm == null) throw new InvalidOperationException("脚本修改需要用户确认。"); if (confirm != null && !confirm(draft)) draft = draft with { Status = "rejected" }; else { try { - if (draft.Edit != null) + if (draft.Batch != null) + { + var prior = draft.Batch.UndoOf; + if (prior.HasValue && (!drafts.TryGetValue(prior.Value, out var savedBatch) || savedBatch.Status != "saved")) + throw new ProjectConflictException("原批次已经撤销或已过期。"); + project.ApplyBatch(draft.Batch); + if (prior.HasValue) drafts[prior.Value] = drafts[prior.Value] with { Status = "undone" }; + } + else if (draft.Edit != null) { if (draft.Edit.UndoOf is Guid source && (!drafts.TryGetValue(source, out var orig) || orig.Status != "saved")) throw new ProjectConflictException("原操作已经撤销。"); diff --git a/PLCSharpWpf/Models/ProjectDirectory.cs b/PLCSharpWpf/Models/ProjectDirectory.cs index d3d8fd0..480d17d 100644 --- a/PLCSharpWpf/Models/ProjectDirectory.cs +++ b/PLCSharpWpf/Models/ProjectDirectory.cs @@ -210,7 +210,8 @@ public sealed partial class ProjectDirectory : IDisposable WriteFiles(root, Files()); } - private void WriteFiles(string root, Dictionary files, string[] scope = null, Action finalize = null) + private void WriteFiles(string root, Dictionary files, string[] scope = null, Action finalize = null, + Dictionary exactBytes = null, Dictionary expectedBytes = null) { Directory.CreateDirectory(root); // Serialize writers and detect edits made after this instance opened the project. @@ -225,7 +226,7 @@ public sealed partial class ProjectDirectory : IDisposable var full = ProjectFile(root, path); var disk = File.Exists(full) ? File.ReadAllText(full) : null; previous.TryGetValue(path, out var original); - if (disk != original) + if (disk != original || expectedBytes != null && expectedBytes.TryGetValue(path, out var bytes) && !File.ReadAllBytes(full).SequenceEqual(bytes)) throw new IOException($"文件已在外部修改,请重新打开工程:{path}"); } @@ -242,7 +243,8 @@ public sealed partial class ProjectDirectory : IDisposable if (previous.TryGetValue(path, out var old) && old == value) continue; var temp = Path.Combine(stage, path); Directory.CreateDirectory(Path.GetDirectoryName(temp)); - File.WriteAllText(temp, value); + if (exactBytes != null && exactBytes.TryGetValue(path, out var exact)) File.WriteAllBytes(temp, exact); + else File.WriteAllText(temp, value); } foreach (var path in paths) { diff --git a/Tests/PLCSharp.Tests/ProjectBatchTests.cs b/Tests/PLCSharp.Tests/ProjectBatchTests.cs new file mode 100644 index 0000000..e37b97e --- /dev/null +++ b/Tests/PLCSharp.Tests/ProjectBatchTests.cs @@ -0,0 +1,68 @@ +using PLCSharp.Models; +using System.IO; +using System.Text; +using System.Text.Json.Nodes; + +namespace PLCSharp.Tests; + +public class ProjectBatchTests +{ + [Fact] + public void BatchIsReviewedOnceAndRestoresOriginalBytes() + { + var dir = Directory.CreateTempSubdirectory(); + try + { + using (var fresh = ProjectDirectory.New()) fresh.Save(dir.FullName); + var path = Path.Combine(dir.FullName, "project.json"); + File.WriteAllText(path, File.ReadAllText(path), new UTF8Encoding(true)); + using var p = ProjectDirectory.Open(dir.FullName); + var changes = new ProjectChanges(); + var confirmations = 0; + JsonNode Call(string op, JsonObject args, bool accept = true) => + changes.Execute(p, op, args, true, draft => { confirmations++; return accept; }); + Dictionary Files() => Directory.GetFiles(dir.FullName, "*", SearchOption.AllDirectories).ToDictionary(f => f, File.ReadAllBytes); + void Same(Dictionary original) + { + var now = Files(); + Assert.Equal(original.Keys.Order(), now.Keys.Order()); + foreach (var (file, bytes) in original) Assert.Equal(bytes, now[file]); + } + var original = Files(); + var args = JsonNode.Parse(""" + {"operations":[{"action":"create","kind":"Recipes","alias":"r","properties":{"Name":"试产"}}, + {"action":"create","kind":"Workflows","alias":"w","properties":{"RecipeID":"$r","Name":"检测"}}, + {"action":"update","kind":"Workflows","id":"$w","properties":{"Comment":"验收"}}]} + """)!.AsObject(); + var batch = Call("previewBatch", args); + Same(original); + Assert.Equal(0, confirmations); + var key = new JsonObject { ["draftId"] = (string)batch["DraftId"]! }; + Assert.Equal("rejected", (string)Call("apply", key, false)["Status"]!); + Same(original); + key["draftId"] = (string)Call("previewBatch", args)["DraftId"]!; + Assert.Equal("saved", (string)Call("apply", key)["Status"]!); + Call("apply", key); + Assert.Equal(2, confirmations); + using (var copy = ProjectDirectory.Open(dir.FullName)) + Assert.Equal("验收", copy.Flows(copy.Recipes.Single(r => r.Name == "试产").ID).Single().Comment); + var undo = Call("previewUndo", key); + Call("apply", new() { ["draftId"] = (string)undo["DraftId"]! }); + Assert.Equal(3, confirmations); + Same(original); + var bad = args.DeepClone().AsObject(); + bad["operations"]![2]!["properties"] = new JsonObject { ["Code"] = "bad C#" }; + var invalid = Call("previewBatch", bad); + Assert.Equal("invalid", (string)invalid["Status"]!); + Assert.Throws(() => Call("apply", new() { ["draftId"] = (string)invalid["DraftId"]! })); + Same(original); + var stale = Call("previewBatch", args); + File.AppendAllText(path, " "); + var external = Files(); + Assert.ThrowsAny(() => Call("apply", new() { ["draftId"] = (string)stale["DraftId"]! })); + Same(external); + } + finally { dir.Delete(true); } + } +} +