using Microsoft.CodeAnalysis.CSharp; using Microsoft.EntityFrameworkCore; using System.IO; using Microsoft.CodeAnalysis.Text; using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Serialization; namespace PLCSharp.Models; public sealed record RenamedScript(Guid Id, string Name, string Path, string Before, string After, WorkflowScriptReview Review); public sealed record VariableRename(Guid VariableId, Guid RecipeId, string OldName, string NewName, List Scripts, JsonArray ManualReferences, JsonArray ScanDiagnostics) { public bool Compiled => Scripts.All(s => s.Review.Compiled) && ScanDiagnostics.Count == 0; [JsonIgnore] internal string Scope { get; init; } [JsonIgnore] internal string OriginalVariables { get; init; } [JsonIgnore] internal string SavedScope { get; set; } [JsonIgnore] internal string SavedVariables { get; set; } public Guid? UndoOf { get; init; } } public sealed partial class ProjectDirectory { internal const string VariablesPath = "configuration/variables.json"; internal string RenameScope(Guid recipe) { var inputs = Flows(recipe).OrderBy(w => w.ID).Select(w => new { w.ID, w.Code }); return Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(inputs))); } internal void CheckVariableName(Guid recipe, Guid id, string oldName, string newName) { if (string.IsNullOrWhiteSpace(newName) || newName != newName.Trim() || newName == oldName) throw new ArgumentException("请输入不同的新名称,首尾不能有空白。"); var rows = Data.Variables.Where(v => v.RecipeID == recipe).ToList(); if (!rows.Any(v => v.ID == id && v.Name == oldName) || rows.Any(v => v.ID != id && (v.Name == oldName || v.Name == newName))) throw new ProjectConflictException("变量已更改或配方内存在重名。"); } internal VariableRename PlanRename(Guid id, string newName) { var variable = Data.Variables.Single(v => v.ID == id); CheckVariableName(variable.RecipeID, id, variable.Name, newName); var analysis = WorkflowReferences.Find(this, "Variables", id.ToString(), forRename: true); var hits = analysis["hits"].AsArray(); 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"])) { var flow = Flows(variable.RecipeID).Single(w => w.ID == group.Key); 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(variable.RecipeID, flow.ID), flow.Code, next, WorkflowScriptReview.Create(flow.ID, flow.Code, next))); } return new(id, variable.RecipeID, variable.Name, newName, edits, manual, analysis["diagnostics"].AsArray()) { Scope = RenameScope(variable.RecipeID), OriginalVariables = baseline[VariablesPath] }; } internal VariableRename PlanUndo(Guid operationId, VariableRename saved) { if (saved.SavedScope != RenameScope(saved.RecipeId) || saved.SavedVariables != baseline[VariablesPath]) throw new ProjectConflictException("保存后配方脚本或变量文件已改变,无法安全撤销。"); CheckVariableName(saved.RecipeId, saved.VariableId, 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.VariableId, saved.RecipeId, saved.NewName, saved.OldName, inverse, saved.ManualReferences, new JsonArray()) { UndoOf = operationId, Scope = saved.SavedScope, OriginalVariables = saved.SavedVariables, SavedVariables = saved.OriginalVariables }; } internal void ApplyRename(VariableRename plan) { lock (Data.Sync) { CheckVariableName(plan.RecipeId, plan.VariableId, plan.OldName, plan.NewName); if (RenameScope(plan.RecipeId) != plan.Scope || baseline[VariablesPath] != plan.OriginalVariables) throw new ProjectConflictException("变量或工作流已经改变,请重新预览。"); var files = new Dictionary(baseline); var variables = JsonNode.Parse(files[VariablesPath]); var row = variables["Variables"].AsArray().Single(v => Guid.Parse((string)v["ID"]) == plan.VariableId); if ((string)row["Name"] != plan.OldName) throw new ProjectConflictException("变量名有未保存的编辑,请先保存或还原。"); row["Name"] = plan.NewName; files[VariablesPath] = plan.UndoOf.HasValue ? plan.SavedVariables : Serialize(variables); var recipePath = RecipePath(plan.RecipeId); var flows = Flows(plan.RecipeId); var persisted = JsonNode.Parse(files[recipePath])["workflows"].AsArray().Select(w => Guid.Parse((string)w["id"])); if (!persisted.ToHashSet().SetEquals(flows.Select(w => w.ID))) throw new ProjectConflictException("请先保存工作流列表。"); var scope = new List { VariablesPath, recipePath, "project.json" }; foreach (var flow in flows) scope.Add(ScriptPath(plan.RecipeId, flow.ID)); foreach (var script in plan.Scripts) { if (files[script.Path] != script.Before) throw new ProjectConflictException($"工作流 {script.Name} 存在未保存编辑。"); files[script.Path] = script.After; } // Hold each affected workflow's execution gate through the single multi-file commit. void Commit(int index) { if (index < plan.Scripts.Count) { var script = plan.Scripts[index]; flows.Single(w => w.ID == script.Id).SaveReviewedCode(script.Before, script.After, () => Commit(index + 1)); return; } using var transaction = Data.Database.BeginTransaction(); if (Data.Variables.Where(v => v.ID == plan.VariableId && v.Name == plan.OldName) .ExecuteUpdate(s => s.SetProperty(v => v.Name, plan.NewName)) != 1) throw new ProjectConflictException("变量已发生变化。"); try { WriteFiles(Root, files, scope.ToArray()); } catch (IOException) when (scope.Any(path => !File.Exists(ProjectFile(Root, path)) || File.ReadAllText(ProjectFile(Root, path)) != baseline[path])) { throw new ProjectConflictException("工程文件已从外部修改,请重新打开并预览。"); } transaction.Commit(); configuration[VariablesPath] = files[VariablesPath]; var variable = Data.Variables.Local.Single(v => v.ID == plan.VariableId); variable.Name = plan.NewName; Data.Entry(variable).Property(v => v.Name).OriginalValue = plan.NewName; } Commit(0); plan.SavedScope = RenameScope(plan.RecipeId); plan.SavedVariables = files[VariablesPath]; } } }