183 lines
10 KiB
C#
183 lines
10 KiB
C#
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 ProjectRename(Guid ObjectId, Guid RecipeId, string OldName, string NewName,
|
|
List<RenamedScript> Scripts, JsonArray ManualReferences, JsonArray ScanDiagnostics)
|
|
{
|
|
public string Kind { get; init; } = "Variables";
|
|
public Guid? VariableId => Kind == "Variables" ? ObjectId : null;
|
|
public string MetadataPath => Kind == "Workflows" ? $"recipes/{RecipeId:D}/recipe.json" : ProjectDirectory.VariablesPath;
|
|
public bool Compiled => Scripts.All(s => s.Review.Compiled) && ScanDiagnostics.Count == 0;
|
|
[JsonIgnore] internal string Scope { get; init; }
|
|
[JsonIgnore] internal string OriginalMetadata { get; init; }
|
|
[JsonIgnore] internal string SavedScope { get; set; }
|
|
[JsonIgnore] internal string SavedMetadata { 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.Name, 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 ProjectRename PlanRename(Guid id, string newName)
|
|
{
|
|
var variable = Data.Variables.Single(v => v.ID == id);
|
|
CheckVariableName(variable.RecipeID, id, variable.Name, newName);
|
|
return PlanReferences("Variables", id, variable.RecipeID, variable.Name, newName);
|
|
}
|
|
|
|
internal ProjectRename PlanWorkflowRename(Guid id, string newName)
|
|
{
|
|
var workflow = Recipes.SelectMany(r => Flows(r.ID)).Single(w => w.ID == id);
|
|
CheckWorkflowName(workflow.RecipeID, id, workflow.Name, newName);
|
|
return PlanReferences("Workflows", id, workflow.RecipeID, workflow.Name, newName);
|
|
}
|
|
|
|
private void CheckWorkflowName(Guid recipeId, Guid id, string oldName, string newName)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(newName) || newName != newName.Trim() || newName == oldName)
|
|
throw new ArgumentException("请输入不同的新名称,首尾不能有空白。");
|
|
var flows = Flows(recipeId);
|
|
if (!flows.Any(w => w.ID == id && w.Name == oldName) ||
|
|
flows.Any(w => w.ID != id && (w.Name == oldName || w.Name == newName)))
|
|
throw new ProjectConflictException("工作流已更改或配方内存在重名。");
|
|
}
|
|
|
|
private ProjectRename PlanReferences(string kind, Guid id, Guid recipeId, string oldName, string newName)
|
|
{
|
|
var analysis = WorkflowReferences.Find(this, kind, 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<RenamedScript>();
|
|
foreach (var group in hits.Where(h => (string)h["confidence"] == "confirmed").GroupBy(h => (Guid)h["workflowId"]))
|
|
{
|
|
var flow = Flows(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(recipeId, flow.ID), flow.Code, next,
|
|
WorkflowScriptReview.Create(flow.ID, flow.Code, next)));
|
|
}
|
|
return new(id, recipeId, oldName, newName, edits, manual, analysis["diagnostics"].AsArray())
|
|
{ Kind = kind, Scope = RenameScope(recipeId), OriginalMetadata = baseline[kind == "Workflows" ? RecipePath(recipeId) : VariablesPath] };
|
|
}
|
|
internal ProjectRename PlanUndo(Guid operationId, ProjectRename saved)
|
|
{
|
|
if (saved.SavedScope != RenameScope(saved.RecipeId) || saved.SavedMetadata != baseline[saved.MetadataPath])
|
|
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, UndoOf = operationId, Scope = saved.SavedScope,
|
|
OriginalMetadata = saved.SavedMetadata, SavedMetadata = saved.OriginalMetadata };
|
|
}
|
|
|
|
private void CheckName(ProjectRename plan, string before, string after)
|
|
{
|
|
if (plan.Kind == "Workflows") CheckWorkflowName(plan.RecipeId, plan.ObjectId, before, after);
|
|
else CheckVariableName(plan.RecipeId, plan.ObjectId, before, after);
|
|
}
|
|
|
|
internal void ApplyRename(ProjectRename plan)
|
|
{
|
|
lock (Data.Sync)
|
|
{
|
|
CheckName(plan, plan.OldName, plan.NewName);
|
|
if (RenameScope(plan.RecipeId) != plan.Scope || baseline[plan.MetadataPath] != plan.OriginalMetadata)
|
|
throw new ProjectConflictException("变量或工作流已经改变,请重新预览。");
|
|
var files = new Dictionary<string, string>(baseline);
|
|
bool workflowRename = plan.Kind == "Workflows";
|
|
var recipePath = RecipePath(plan.RecipeId);
|
|
var metadata = JsonNode.Parse(files[plan.MetadataPath]);
|
|
var rows = metadata[workflowRename ? "workflows" : "Variables"].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("请先保存工作流列表。");
|
|
row[field] = plan.NewName;
|
|
files[plan.MetadataPath] = plan.UndoOf.HasValue ? plan.SavedMetadata : Serialize(metadata);
|
|
var scope = new List<string> { recipePath, "project.json" };
|
|
if (!workflowRename) scope.Add(VariablesPath);
|
|
foreach (var flow in flows)
|
|
{
|
|
var path = ScriptPath(plan.RecipeId, flow.ID);
|
|
if (files[path] != (flow.Code ?? ""))
|
|
throw new ProjectConflictException($"工作流 {flow.Name} 有未保存的编辑,请保存后重新预览。");
|
|
scope.Add(path);
|
|
}
|
|
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.
|
|
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;
|
|
if (workflowRename && updates.All(edit => edit.Flow != targetFlow))
|
|
updates = [.. updates, (targetFlow, targetFlow.Code ?? "", targetFlow.Code ?? "")];
|
|
PLCSharp.VVMs.Workflows.Workflow.SaveReviewedBatch(updates, () =>
|
|
{
|
|
using var transaction = workflowRename ? null : Data.Database.BeginTransaction();
|
|
if (!workflowRename && 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("变量已发生变化。");
|
|
try { WriteFiles(Root, files, scope.ToArray(), transaction == null ? null : transaction.Commit); }
|
|
catch (IOException) when (scope.Any(path => !File.Exists(ProjectFile(Root, path)) ||
|
|
File.ReadAllText(ProjectFile(Root, path)) != baseline[path]))
|
|
{
|
|
throw new ProjectConflictException("工程文件已从外部修改,请重新打开并预览。");
|
|
}
|
|
if (workflowRename)
|
|
{
|
|
targetFlow.SetReviewedName(plan.NewName);
|
|
return;
|
|
}
|
|
configuration[VariablesPath] = files[VariablesPath];
|
|
var variable = Data.Variables.Local.Single(v => v.ID == plan.ObjectId);
|
|
variable.Name = plan.NewName;
|
|
Data.Entry(variable).Property(v => v.Name).OriginalValue = plan.NewName;
|
|
});
|
|
plan.SavedScope = RenameScope(plan.RecipeId);
|
|
plan.SavedMetadata = files[plan.MetadataPath];
|
|
}
|
|
}
|
|
|
|
}
|
|
|