115 lines
6.0 KiB
Python
115 lines
6.0 KiB
Python
"""Prepare a portable sample copy, open it in PLCSharp and enable AI access, then run verify."""
|
|
import argparse
|
|
import json
|
|
from pathlib import Path
|
|
import shutil
|
|
import uuid
|
|
|
|
from mcp_smoke import Client
|
|
|
|
|
|
def prepare(sample, directory):
|
|
shutil.copytree(sample, directory)
|
|
script, = directory.rglob("*.cs")
|
|
source = (
|
|
"using PLCSharp.Models;\nusing PLCSharp.Core.Common;\n"
|
|
f"public class Extension_{script.stem.replace('-', '')} {{\n"
|
|
" public void Run(GlobalModel model, FlowModel flow) {\n"
|
|
' _ = model.GetVariable("计数");\n'
|
|
' _ = model.GetVariable(flow.Step.ToString());\n'
|
|
" }\n}\n"
|
|
)
|
|
script.write_bytes(source.encode("utf-8"))
|
|
|
|
|
|
def prepare_workflow(sample, directory):
|
|
shutil.copytree(sample, directory)
|
|
target_script, = directory.rglob("*.cs")
|
|
manifest = target_script.parent.parent / "recipe.json"
|
|
recipe = json.loads(manifest.read_bytes())
|
|
target, = recipe["workflows"]
|
|
caller = dict(target, id=str(uuid.uuid4()), name="调度", automaticExecution=False)
|
|
recipe["workflows"].append(caller)
|
|
manifest.write_text(json.dumps(recipe, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
source = (
|
|
"using PLCSharp.Models;\nusing PLCSharp.Core.Common;\n"
|
|
f"public class Extension_{caller['id'].replace('-', '')} {{\n"
|
|
" public void Run(GlobalModel model, FlowModel flow) {\n"
|
|
f' _ = model.GetTask("{target["name"]}");\n'
|
|
' _ = model.GetTask(flow.Step.ToString());\n'
|
|
" }\n}\n"
|
|
)
|
|
target_script.with_name(caller["id"] + ".cs").write_bytes(source.encode("utf-8"))
|
|
|
|
|
|
def prepare_point(sample, directory):
|
|
shutil.copytree(sample, directory)
|
|
caller, = (p for p in directory.rglob("*.cs") if 'GetTask("搬运")' in p.read_text(encoding="utf-8"))
|
|
source = caller.read_text(encoding="utf-8").replace("using PLCSharp.Models;", "using PLCSharp.Models; using System.Linq;")
|
|
source = source.replace('_ = model.GetTask("搬运");',
|
|
'_ = model.ControllersModel.AxisPoints.FirstOrDefault(p => p.Name == "定位");')
|
|
source = source.replace('_ = model.GetTask(flow.Step.ToString());',
|
|
'_ = model.ControllersModel.AxisPoints.FirstOrDefault(p => p.Name == flow.Step.ToString());')
|
|
caller.write_bytes(source.encode("utf-8"))
|
|
|
|
|
|
def verify(exe, directory, workflow=False, point=False):
|
|
before = {p: p.read_bytes() for p in directory.rglob("*") if p.is_file()}
|
|
client = Client(exe, directory, "--allow-write")
|
|
try:
|
|
summary = client.call("get_project_summary")
|
|
assert summary["source"] == "editor"
|
|
recipe = summary["DefaultRecipeId"]
|
|
kind, old, new, tool, lookup = (
|
|
("Workflows", "搬运", "工件搬运", "preview_workflow_rename", "GetTask") if workflow else
|
|
("Variables", "计数", "完成计数", "preview_variable_rename", "GetVariable"))
|
|
if point:
|
|
kind, old, new, tool = "AxisPoints", "定位", "装配定位", "preview_point_rename"
|
|
items = client.call("list_objects", kind=kind, recipeId=recipe)["items"]
|
|
target, = (item for item in items if item["name"] == old)
|
|
draft = client.call(tool, id=target["id"], newName=new, **({"kind": kind} if point else {}))
|
|
plan = draft["Rename"]
|
|
script, = plan["Scripts"]
|
|
manual, = plan["ManualReferences"]
|
|
assert draft["Status"] == "pending" and script["Review"]["Compiled"]
|
|
assert manual["confidence"] == "dynamic" and manual["line"] == 6
|
|
replacement = f'p.Name == "{new}"' if point else f'{lookup}("{new}")'
|
|
if point:
|
|
link, = plan["MatrixReferences"]
|
|
assert link["Table"] == "Matrices" and link["Field"] == "StartName"
|
|
assert replacement in script["After"] and manual["expression"] in script["After"]
|
|
print(json.dumps({"source": summary["source"], "dynamic": manual, "compiled": True}, ensure_ascii=False), flush=True)
|
|
assert all(p.read_bytes() == old for p, old in before.items())
|
|
saved = client.call("apply_changes", draftId=draft["DraftId"])
|
|
assert saved["Status"] == "saved"
|
|
assert client.call("get_object", kind=kind, id=target["id"])["Name"] == new
|
|
assert client.call("get_object", kind="Workflows", id=script["Id"])["Code"] == script["After"]
|
|
if point:
|
|
assert client.call("get_object", kind="Matrices", id=link["Id"])["StartName"] == new
|
|
metadata = draft["Path"]
|
|
assert {p for p, old in before.items() if p.read_bytes() != old} == {
|
|
directory / metadata, directory / script["Path"]}
|
|
undo = client.call("preview_undo", draftId=draft["DraftId"])
|
|
assert undo["Rename"]["Compiled"] and undo["Rename"]["UndoOf"] == draft["DraftId"]
|
|
assert client.call("apply_changes", draftId=undo["DraftId"])["Status"] == "saved"
|
|
assert client.call("get_change_status", draftId=draft["DraftId"])["Status"] == "undone"
|
|
assert client.call("get_object", kind=kind, id=target["id"])["Name"] == old
|
|
assert client.call("get_object", kind="Workflows", id=script["Id"])["Code"] == script["Before"]
|
|
assert before == {p: p.read_bytes() for p in directory.rglob("*") if p.is_file()}
|
|
print("PASS: live editor rename, confirmation, undo and byte-for-byte restore.")
|
|
finally:
|
|
client.close()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("mode", choices=["prepare", "verify", "prepare-workflow", "verify-workflow", "prepare-point", "verify-point"])
|
|
parser.add_argument("source", type=Path, help="Sample directory for prepare, MCP executable for verify")
|
|
parser.add_argument("project", type=Path)
|
|
args = parser.parse_args()
|
|
if args.mode.startswith("prepare"):
|
|
{"prepare": prepare, "prepare-workflow": prepare_workflow, "prepare-point": prepare_point}[args.mode](args.source, args.project)
|
|
else:
|
|
verify(args.source, args.project, workflow=args.mode == "verify-workflow", point=args.mode == "verify-point")
|
|
|