Skip to content

Agent skill that turns natural language, code, Terraform/K8s, SQL, OpenAPI, AsyncAPI, Protobuf and GraphQL sources into editable, tested draw.io architecture diagrams: incremental sync, multi-view projection, drift diff, CI architecture tests, whiteboard derasterize, interactive HTML/PPTX/Mermaid exports.

fix(protoimports): comments in the tokenizer, html-safe labels, detection order

Agents365-aia12b3a9190cb
diff --git a/skills/drawio-skill/scripts/diagramctl.py b/skills/drawio-skill/scripts/diagramctl.py
index 963a75d..a813c71 100644
--- a/skills/drawio-skill/scripts/diagramctl.py
+++ b/skills/drawio-skill/scripts/diagramctl.py
@@ -81,8 +81,6 @@ def emit(value, output=None):
def detect_source(path):
p = Path(path)
if p.is_dir():
- if list(p.rglob("*.proto")):
- return "proto"
if list(p.rglob("*.tf")):
return "terraform"
if (p / "Cargo.toml").exists():
@@ -93,6 +91,10 @@ def detect_source(path):
return "javascript"
if (p / ".github" / "workflows").exists() or (p / ".gitlab-ci.yml").exists():
return "ci"
+ # Last, because a .proto file is often one schema inside a project whose
+ # own language markers above describe the repository better.
+ if list(p.rglob("*.proto")):
+ return "proto"
return "python"
suffix = p.suffix.lower()
if suffix == ".proto":
diff --git a/skills/drawio-skill/scripts/protoimports.py b/skills/drawio-skill/scripts/protoimports.py
index d22b339..97ee2bf 100755
--- a/skills/drawio-skill/scripts/protoimports.py
+++ b/skills/drawio-skill/scripts/protoimports.py
@@ -53,6 +53,7 @@ SCALAR_TYPES = {
TOKEN_RE = re.compile(
r"""
(?P<STRING>"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')
+ | (?P<COMMENT>//[^\n]*|/\*[\s\S]*?\*/)
| (?P<NUM>-?[0-9]+(?:\.[0-9]+)?)
| (?P<IDENT>[A-Za-z_][A-Za-z0-9_.]*)
| (?P<SYM>[{}();=<>:,\[\]])
@@ -71,26 +72,18 @@ class Token:
self.line = line
-def strip_comments(text):
- def repl_block(m):
- return "\n" * m.group(0).count("\n")
-
- text = re.sub(r"/\*.*?\*/", repl_block, text, flags=re.DOTALL)
- text = re.sub(r"//[^\n]*", "", text)
- return text
-
-
def tokenize(text):
tokens = []
line = 1
pos = 0
- text = strip_comments(text)
+ # Comments are matched by the tokenizer rather than stripped up front, so a
+ # `//` or `/*` inside a string literal (a URL, say) stays part of the string.
for m in TOKEN_RE.finditer(text):
kind = m.lastgroup
val = m.group()
line += text[pos:m.start()].count("\n")
pos = m.start()
- if kind != "WS":
+ if kind not in ("WS", "COMMENT"):
tokens.append(Token(kind, val, line))
line += val.count("\n")
pos = m.end()
@@ -345,6 +338,20 @@ def parse_proto(text, file_path=""):
}
+def esc(text):
+ """Escape HTML metacharacters for draw.io's html=1 labels.
+
+ Without it a field type such as `map<string, Item>` is swallowed as an
+ unknown HTML tag when draw.io renders the label.
+ """
+ return (
+ text.replace("&", "&amp;")
+ .replace("<", "&lt;")
+ .replace(">", "&gt;")
+ .replace('"', "&quot;")
+ )
+
+
def compute_dimensions(lines):
width = max(160, -(-max(7 * len(l) + 30 for l in lines) // 10) * 10)
height = max(50, -(-(30 + 18 * len(lines)) // 10) * 10)
@@ -431,7 +438,7 @@ def build(proto_data_list, group=False, direction="TB"):
w, h = compute_dimensions(lines)
node = {
"id": s["id"],
- "label": "\n".join(lines),
+ "label": esc("\n".join(lines)),
"style": SERVICE_STYLE,
"width": w,
"height": h,
@@ -461,7 +468,7 @@ def build(proto_data_list, group=False, direction="TB"):
w, h = compute_dimensions(lines)
node = {
"id": m["id"],
- "label": "\n".join(lines),
+ "label": esc("\n".join(lines)),
"style": MESSAGE_STYLE,
"width": w,
"height": h,
@@ -488,7 +495,7 @@ def build(proto_data_list, group=False, direction="TB"):
w, h = compute_dimensions(lines)
node = {
"id": e["id"],
- "label": "\n".join(lines),
+ "label": esc("\n".join(lines)),
"style": ENUM_STYLE,
"width": w,
"height": h,
@@ -521,12 +528,14 @@ def main():
parsed_list = []
for fpath in files:
+ # pi-lens-ignore: ast-grep:unchecked-throwing-call-python
with open(fpath, encoding="utf-8", errors="replace") as fh:
parsed_list.append(parse_proto(fh.read(), file_path=fpath))
graph = build(parsed_list, group=args.group, direction=args.direction)
text = json.dumps(graph, indent=2, ensure_ascii=False)
if args.output:
+ # pi-lens-ignore: ast-grep:unchecked-throwing-call-python
with open(args.output, "w", encoding="utf-8") as fh:
fh.write(text)
sys.stderr.write(f"wrote {args.output}\n")
diff --git a/tests/test_protoimports.py b/tests/test_protoimports.py
index 8a53a86..f98f709 100644
--- a/tests/test_protoimports.py
+++ b/tests/test_protoimports.py
@@ -9,10 +9,25 @@ import unittest
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SCRIPT = os.path.join(ROOT, "skills", "drawio-skill", "scripts", "protoimports.py")
DIAGRAMCTL = os.path.join(ROOT, "skills", "drawio-skill", "scripts", "diagramctl.py")
+sys.path.insert(0, os.path.dirname(DIAGRAMCTL))
+
+
+def load_bundled(name):
+ """Load a bundled script by path (the scripts directory is not a package)."""
+ path = os.path.join(os.path.dirname(DIAGRAMCTL), name + ".py")
+ spec = importlib.util.spec_from_file_location(name, path)
+ assert spec is not None and spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+diagramctl = load_bundled("diagramctl")
def load_importer():
spec = importlib.util.spec_from_file_location("protoimports", SCRIPT)
+ assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
@@ -127,6 +142,50 @@ class TestProtoImports(unittest.TestCase):
self.assertIn(("shop.Cart", "shop.Cart.State"), pairs)
self.assertIn(("shop.Cart", "shop.Cart.Item"), pairs)
+ def test_comments_do_not_swallow_string_literals(self):
+ # A "//" inside a string used to be stripped as a comment, which also
+ # removed the brace that closed the message and dropped the rest of the
+ # file (URLs in options/defaults are the realistic case).
+ proto = '''
+ syntax = "proto3";
+ package demo;
+
+ /* block comment */
+ message Req { string url = 1 [default = "https://example.com/a"]; }
+ message Resp { string ok = 1; } // trailing comment
+ service DemoService { rpc Get (Req) returns (Resp); }
+ '''
+ parsed = self.importer.parse_proto(proto, "demo.proto")
+ self.assertEqual(["Req", "Resp"], [m["name"] for m in parsed["messages"]])
+ self.assertEqual(["DemoService"], [s["name"] for s in parsed["services"]])
+ # Line numbers stay accurate across the block and trailing comments.
+ self.assertEqual([6, 7], [m["line"] for m in parsed["messages"]])
+
+ def test_map_types_survive_html_label_rendering(self):
+ proto = '''
+ syntax = "proto3";
+ package shop;
+ message Cart { map<string, Item> items = 1; }
+ message Item { string sku = 1; }
+ '''
+ parsed = self.importer.parse_proto(proto, "shop.proto")
+ graph = self.importer.build([parsed])
+ label = next(n for n in graph["nodes"] if n["id"] == "shop.Cart")["label"]
+ self.assertIn("items: map&lt;string, Item&gt;", label)
+
+ def test_directory_detection_keeps_project_language_markers(self):
+ with tempfile.TemporaryDirectory() as td:
+ with open(os.path.join(td, "go.mod"), "w", encoding="utf-8") as f:
+ f.write("module example.com/svc\n")
+ with open(os.path.join(td, "svc.proto"), "w", encoding="utf-8") as f:
+ f.write('syntax = "proto3";\nmessage A {}\n')
+ self.assertEqual("go", diagramctl.detect_source(td))
+
+ with tempfile.TemporaryDirectory() as td:
+ with open(os.path.join(td, "svc.proto"), "w", encoding="utf-8") as f:
+ f.write('syntax = "proto3";\nmessage A {}\n')
+ self.assertEqual("proto", diagramctl.detect_source(td))
+
def test_cli_reads_file_and_directory(self):
with tempfile.TemporaryDirectory() as td:
p1 = os.path.join(td, "user.proto")