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.
Python agent-skillsarchitecturearchitecture-diagramasyncapibpmnc4-modelclaude-codediagramdiagrams-as-codedrawioflowchartgithub-actionsgraphqlimage-to-diagramkubernetesmcp-serverprotobufsysmlterraformuml
feat: IaC importers — Terraform/K8s manifests to architecture diagrams with official cloud icons (#51)
Agents365.ai3d8acbcc4fa8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 012079f..b8f739c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,26 @@ All notable changes to **drawio-skill** are documented here. The format is basedon [Keep a Changelog](https://keepachangelog.com/), and the project followssemantic-ish versioning (the `version:` field in `skills/drawio-skill/SKILL.md`).+## [1.15.0] — 2026-07-02+### Added+- **IaC → architecture diagram.** Two new importers feed autolayout:+ - `tfimports.py` parses Terraform `.tf` files (regex + brace matching, no+ HCL dependency) into a resource-reference graph. Each resource type is+ resolved to its **official cloud icon** via the bundled shape index —+ AWS `aws4`, Azure `azure2`, GCP icon sets — with a ~45-entry curated+ query table and strict tag-AND matching (a partial match falls back to a+ plain box rather than another vendor's icon). `--group` boxes resources+ by service; `--no-icons` for plain boxes.+ - `k8simports.py` parses Kubernetes manifests (JSON incl. `kind: List`+ stdlib-only; YAML via PyYAML) and derives Ingress→Service,+ Service→workload (selector match), workload→ConfigMap/Secret/PVC and+ HPA→target edges, with official `mxgraph.kubernetes` kind icons+ (25 kinds). `--group` boxes objects by namespace.+- `autolayout.py`: graph-level `ranksep`/`nodesep` passthrough (icon labels+ render below the shape and need wider spacing — the IaC importers emit+ these automatically) and `\n` in labels now renders as a line break.+- Test coverage for both importers and the autolayout additions (suite now 38).+## [1.14.0] — 2026-06-03### Added- `aiicons.py` resolves common RAG/LLM **data-store brands** (Qdrant, Redis,diff --git a/README.md b/README.mdindex 34f9031..72bab39 100644--- a/README.md+++ b/README.md@@ -24,6 +24,7 @@ A skill that turns natural-language descriptions into `.drawio` XML and exports- **6 diagram type presets** — ERD, UML Class, Sequence, Architecture, ML/Deep Learning, Flowchart- **Visualize a codebase** — extract and auto-lay-out the structure of a Python / JS-TS / Go / Rust project (import graphs) or a Python class hierarchy — Graphviz placement, transitive reduction, nested module containers+- **IaC → architecture diagram** — turn **Terraform** configs or **Kubernetes** manifests into an architecture diagram where every resource renders as its **official AWS / Azure / GCP / K8s icon**, edges derived from actual references (role ARNs, selectors, volume mounts)- **Search 10,000+ official shapes** — resolve the exact AWS / Azure / GCP / Cisco / Kubernetes / UML / BPMN icon style instead of guessing (no more blank-box `shape=mxgraph.*` typos)- **AI / LLM brand logos** — 321 logos (OpenAI, Claude, Gemini, Mistral, Llama, Ollama, LangChain…) that draw.io has none of, for LLM-app architecture diagrams- **Self-check + auto-fix** — reads its own PNG output and auto-fixes overlaps, clipped labels, stacked edges, and more (up to 2 rounds)@@ -140,13 +141,17 @@ python3 scripts/rustimports.py ./crate --group -o graph.json# Python class-inheritance hierarchypython3 scripts/pyclasses.py mypackage --group -o graph.json+# Infrastructure as Code — official cloud icons resolved automatically+python3 scripts/tfimports.py ./infra -o graph.json # Terraform → AWS/Azure/GCP icons+python3 scripts/k8simports.py ./manifests -o graph.json # K8s YAML/JSON → kind icons+# any extractor → auto-layout → editable .drawiopython3 scripts/autolayout.py graph.json -o diagram.drawio```| Piece | What it does ||---|---|-| **5 extractors** | import graphs for **Python · JS/TS · Go · Rust**, plus **Python class inheritance** |+| **7 extractors** | import graphs for **Python · JS/TS · Go · Rust**, **Python class inheritance**, plus **Terraform** and **Kubernetes** resource graphs with official cloud icons || **Auto-layout** | Graphviz places nodes and routes orthogonal edges *around* them — removes the manual-coordinate ceiling for large graphs || **Transitive reduction** | drops edges implied by a longer path, turning a dense hairball into a traceable graph (asyncio: 149 → 46 edges) || **Nested containers** | `--group` boxes modules by sub-package, nested for deep package trees |@@ -232,6 +237,7 @@ Behind the scenes: **check dependencies → plan layout → generate `.drawio` X| Iterative review loop | ❌ manual re-prompt | ✅ targeted edits, 5-round safety valve || Diagram type presets | ❌ | ✅ 6 presets (ERD, UML, Seq, Arch, ML, Flow) || Visualize a codebase | ❌ | ✅ import graphs (Py/JS/Go/Rust) + class diagrams |+| IaC → architecture diagram | ❌ | ✅ Terraform / K8s manifests → official cloud icons || Auto-layout for large graphs | ❌ hand-places, overlaps | ✅ Graphviz placement, ortho routing, nested containers || Structural validation | ❌ | ✅ deterministic `.drawio` linter || Official shape search | ❌ guesses, blank boxes | ✅ exact style for 10k+ AWS/Azure/GCP/UML shapes |diff --git a/README_CN.md b/README_CN.mdindex 5259dc7..c8f608a 100644--- a/README_CN.md+++ b/README_CN.md@@ -24,6 +24,7 @@- **6 种图表类型预设** —— ER 图、UML 类图、序列图、架构图、ML/深度学习、流程图- **可视化代码库** —— 提取并自动布局一个 Python / JS-TS / Go / Rust 项目的结构(导入关系图)或 Python 类继承层级 —— Graphviz 布点、传递约简、按子包嵌套的容器+- **IaC → 架构图** —— 把 **Terraform** 配置或 **Kubernetes** manifest 直接变成架构图,每个资源渲染为**官方 AWS / Azure / GCP / K8s 图标**,连线来自真实引用(role ARN、selector、volume 挂载)- **搜索 10,000+ 个官方形状** —— 直接拿到 AWS / Azure / GCP / Cisco / Kubernetes / UML / BPMN 图标的精确 style,不靠猜(杜绝 `shape=mxgraph.*` 拼错变空白框)- **AI / LLM 品牌图标** —— 321 个 draw.io 自身没有的 logo(OpenAI、Claude、Gemini、Mistral、Llama、Ollama、LangChain……),专为 LLM 应用架构图准备- **自检 + 自动修复** —— 读取自己导出的 PNG,自动修复重叠、截断标签、连线堆叠等问题(最多 2 轮)@@ -138,13 +139,17 @@ python3 scripts/rustimports.py ./crate --group -o graph.json# Python 类继承层级python3 scripts/pyclasses.py mypackage --group -o graph.json+# 基础设施即代码 —— 自动解析官方云图标+python3 scripts/tfimports.py ./infra -o graph.json # Terraform → AWS/Azure/GCP 图标+python3 scripts/k8simports.py ./manifests -o graph.json # K8s YAML/JSON → kind 图标+# 任一提取器 → 自动布局 → 可编辑的 .drawiopython3 scripts/autolayout.py graph.json -o diagram.drawio```| 组件 | 作用 ||---|---|-| **5 个提取器** | **Python · JS/TS · Go · Rust** 的导入关系图,外加 **Python 类继承** |+| **7 个提取器** | **Python · JS/TS · Go · Rust** 的导入关系图、**Python 类继承**,外加 **Terraform** 和 **Kubernetes** 资源图(自动配官方云图标) || **自动布局** | Graphviz 自动布点,正交连线**绕开**节点 —— 大图不再需要手动摆坐标 || **传递约简** | 删掉被更长路径蕴含的边,把密集的"毛线团"变成可读图(asyncio:149 → 46 条边) || **嵌套容器** | `--group` 按子包给模块分框,深层包树自动嵌套 |@@ -230,6 +235,7 @@ Skill 会提取配色、形状、字体和连线风格,渲染预览图,**确| 迭代审查循环 | ❌ 需手动重新提问 | ✅ 定向编辑,5 轮安全阀 || 图表类型预设 | ❌ | ✅ 6 种(ERD、UML、序列、架构、ML、流程) || 可视化代码库 | ❌ | ✅ 导入关系图(Py/JS/Go/Rust)+ 类图 |+| IaC → 架构图 | ❌ | ✅ Terraform / K8s manifest → 官方云图标 || 大图自动布局 | ❌ 手动摆放、易重叠 | ✅ Graphviz 布点、正交路由、嵌套容器 || 结构校验 | ❌ | ✅ 确定性 `.drawio` linter || 官方形状搜索 | ❌ 靠猜、变空白框 | ✅ 1 万+ AWS/Azure/GCP/UML 形状的精确 style |diff --git a/skills/drawio-skill/SKILL.md b/skills/drawio-skill/SKILL.mdindex 406fbef..0b3ca4b 100644--- a/skills/drawio-skill/SKILL.md+++ b/skills/drawio-skill/SKILL.md@@ -1,12 +1,12 @@---name: drawio-skill-version: 1.14.0-description: Use when the user requests diagrams, flowcharts, architecture diagrams, ER diagrams, UML / sequence / class diagrams, network topology, ML/DL model figures (Transformer/CNN/LSTM), mind maps, or any visualization. Also use proactively when explaining systems with 3+ components, complex data flows, or relationships that benefit from visual representation. Best suited when the diagram needs custom styling, rich shape vocabulary, swimlanes, or exportable images (PNG/SVG/PDF/JPG). Generates .drawio XML and exports locally via the native draw.io desktop CLI.+version: 1.15.0+description: Use when the user requests diagrams, flowcharts, architecture diagrams, ER diagrams, UML / sequence / class diagrams, network topology, cloud architecture from Terraform or Kubernetes manifests, ML/DL model figures (Transformer/CNN/LSTM), mind maps, or any visualization. Also use proactively when explaining systems with 3+ components, complex data flows, or relationships that benefit from visual representation. Best suited when the diagram needs custom styling, rich shape vocabulary, swimlanes, or exportable images (PNG/SVG/PDF/JPG). Generates .drawio XML and exports locally via the native draw.io desktop CLI.license: MIThomepage: https://github.com/Agents365-ai/drawio-skillcompatibility: Requires draw.io desktop app CLI on PATH (macOS/Linux/Windows). Self-check step requires a vision-enabled model (e.g., Claude Sonnet/Opus); gracefully skipped if unavailable. Optional auto-layout (scripts/autolayout.py) needs Graphviz (dot).platforms: [macos, linux, windows]-metadata: {"openclaw":{"requires":{"anyBins":["draw.io","drawio"]},"emoji":"📐","os":["darwin","linux","win32"],"install":[{"id":"brew-drawio","kind":"brew","formula":"drawio","bins":["drawio"],"label":"Install draw.io via Homebrew","os":["darwin"]},{"id":"brew-graphviz","kind":"brew","formula":"graphviz","bins":["dot"],"label":"Install Graphviz for optional autolayout.py","os":["darwin"],"optional":true}]},"hermes":{"tags":["drawio","diagram","flowchart","architecture","visualization","uml"],"category":"design","requires_tools":["drawio","draw.io"],"related_skills":["mermaid","excalidraw","plantuml"]},"author":"Agents365-ai","version":"1.14.0"}+metadata: {"openclaw":{"requires":{"anyBins":["draw.io","drawio"]},"emoji":"📐","os":["darwin","linux","win32"],"install":[{"id":"brew-drawio","kind":"brew","formula":"drawio","bins":["drawio"],"label":"Install draw.io via Homebrew","os":["darwin"]},{"id":"brew-graphviz","kind":"brew","formula":"graphviz","bins":["dot"],"label":"Install Graphviz for optional autolayout.py","os":["darwin"],"optional":true}]},"hermes":{"tags":["drawio","diagram","flowchart","architecture","visualization","uml"],"category":"design","requires_tools":["drawio","draw.io"],"related_skills":["mermaid","excalidraw","plantuml"]},"author":"Agents365-ai","version":"1.15.0"}---# Draw.io Diagrams@@ -45,6 +45,7 @@ When the workflow references one of these, read it on demand — none of them ne| `references/autolayout.md` | The diagram is large or layout-heavy (dependency/call graph, code structure, >~15 nodes) and you want Graphviz to place nodes + route edges instead of hand-placing coordinates || `scripts/pyimports.py` · `jsimports.py` · `goimports.py` · `rustimports.py` | The user wants to visualize a **Python, JS/TS, Go, or Rust project** structure — extracts the import graph (transitive-reduced, optional `--group` containers, nested by sub-package) for autolayout || `scripts/pyclasses.py` | The user wants a **Python class hierarchy / class diagram** — extracts classes + inheritance edges (boxed by module with `--group`) for autolayout |+| `scripts/tfimports.py` · `k8simports.py` | The user wants to visualize **Terraform or Kubernetes infrastructure** — extracts the resource/object reference graph with each node resolved to its **official cloud icon** (AWS/Azure/GCP via the shape index, K8s kind icons) for autolayout || `scripts/validate.py` | You generated a `.drawio` (especially via autolayout or for a large hand-placed diagram) and want a fast deterministic structural lint (dangling edges, dup/reserved ids, broken parents, overlaps) before the vision self-check |## Prerequisites@@ -95,7 +96,7 @@ When a preset loads successfully, mention it in the first line of the reply: *"U1. **Check deps** — **resolve which name the binary has on this system** and use that name verbatim in every subsequent command in this workflow. Try in order: (a) `drawio --version` (the canonical name for Homebrew cask, jgraph `.deb`/`.rpm`, Arch AUR), (b) `draw.io --version` (older builds, some custom symlinks, some distro packages), (c) macOS `.app` direct: `/Applications/draw.io.app/Contents/MacOS/draw.io --version`, (d) Windows: `"C:\Program Files\draw.io\draw.io.exe" --version`. The first one that prints a version is your binary; remember the exact path/name and substitute it for `drawio` in every export command below. **Do not copy the example commands verbatim if your binary is named differently** — the examples use `drawio` only because it's the most common. On macOS-Homebrew, `drawio` is just a thin wrapper script that execs `/Applications/draw.io.app/Contents/MacOS/draw.io` — they run the same engine, so candidate (c) is only needed when the `drawio` wrapper is absent (e.g. the app was installed by drag-and-drop without the cask).2. **Plan** — identify shapes, relationships, layout (LR or TB), group by tier/layer-3. **Generate** — write `.drawio` XML file to disk. Hand-place coordinates for small/styled diagrams. **For large or layout-heavy diagrams (dependency/call graphs, code structure, >~15 nodes), don't hand-place** — describe the graph as JSON and run `python3 <this-skill-dir>/scripts/autolayout.py graph.json -o <name>.drawio` to compute node positions + orthogonal edge routing via Graphviz (see `references/autolayout.md`). For a **Python / JS-TS / Go / Rust project**, the matching importer (`scripts/pyimports.py`, `jsimports.py`, `goimports.py`, or `rustimports.py`) extracts the import graph (transitive-reduced; add `--group` to box modules by sub-package, nested for deep trees) ready for autolayout; for a **Python class hierarchy**, `scripts/pyclasses.py` extracts classes + inheritance instead. For complex architecture diagrams with many visible edge labels, give labels `labelBackgroundColor=#ffffff;fontSize=11` and use edge geometry `x`/`y` offsets plus `<mxPoint as="offset" />` to move long labels into nearby whitespace instead of relying on draw.io's default midpoint placement. After generating any `.drawio`, run `python3 <this-skill-dir>/scripts/validate.py <name>.drawio` for a fast structural lint (dangling edges, dup ids, overlaps) before exporting. Default output dir is the user's working dir; if the user specified an output path or directory (e.g. `./artifacts/`, `docs/images/`), use that instead — `mkdir -p` the target dir first. Apply the same dir choice to PNG/SVG/PDF exports in steps 4 and 7.+3. **Generate** — write `.drawio` XML file to disk. Hand-place coordinates for small/styled diagrams. **For large or layout-heavy diagrams (dependency/call graphs, code structure, >~15 nodes), don't hand-place** — describe the graph as JSON and run `python3 <this-skill-dir>/scripts/autolayout.py graph.json -o <name>.drawio` to compute node positions + orthogonal edge routing via Graphviz (see `references/autolayout.md`). For a **Python / JS-TS / Go / Rust project**, the matching importer (`scripts/pyimports.py`, `jsimports.py`, `goimports.py`, or `rustimports.py`) extracts the import graph (transitive-reduced; add `--group` to box modules by sub-package, nested for deep trees) ready for autolayout; for a **Python class hierarchy**, `scripts/pyclasses.py` extracts classes + inheritance instead; for **Terraform** (`scripts/tfimports.py <dir>`) or **Kubernetes manifests** (`scripts/k8simports.py <dir>`), the importer extracts the resource/object reference graph and resolves every node to its official cloud icon (AWS/Azure/GCP/K8s) automatically. For complex architecture diagrams with many visible edge labels, give labels `labelBackgroundColor=#ffffff;fontSize=11` and use edge geometry `x`/`y` offsets plus `<mxPoint as="offset" />` to move long labels into nearby whitespace instead of relying on draw.io's default midpoint placement. After generating any `.drawio`, run `python3 <this-skill-dir>/scripts/validate.py <name>.drawio` for a fast structural lint (dangling edges, dup ids, overlaps) before exporting. Default output dir is the user's working dir; if the user specified an output path or directory (e.g. `./artifacts/`, `docs/images/`), use that instead — `mkdir -p` the target dir first. Apply the same dir choice to PNG/SVG/PDF exports in steps 4 and 7.4. **Export draft** — run CLI to produce a preview PNG. **Do NOT pass `-e`** at this step — the embedded `zTXt mxGraphModel` chunk it adds causes vision APIs (Claude included) to return 400 "Could not process image" in step 5. **Cap the preview width with `--width 2000` (not `-s 2`)** — Claude's vision API rejects images larger than 2576×2576px with "Unable to resize image — dimensions exceed the 2576x2576px limit", and `-s 2` on a medium-or-larger diagram easily overshoots that ceiling. Save the clean preview as `<name>.png` (single extension). Embedding and full-resolution scale are for the final export only (step 7).5. **Self-check** — use the agent's built-in vision capability to read the exported PNG, catch obvious issues, auto-fix before showing user (requires a vision-enabled model such as Claude Sonnet/Opus). If reading the PNG returns a 400 / "Could not process image" error, you almost certainly exported with `-e` by mistake — re-export without `-e` and retry once. If it still fails, skip self-check and continue to step 6.6. **Review loop** — show image to user, collect feedback, apply targeted XML edits, re-export, repeat until approveddiff --git a/skills/drawio-skill/references/autolayout.md b/skills/drawio-skill/references/autolayout.mdindex 5cbed0f..eaad9d6 100644--- a/skills/drawio-skill/references/autolayout.md+++ b/skills/drawio-skill/references/autolayout.md@@ -86,30 +86,36 @@ python3 <this-skill-dir>/scripts/validate.py diagram.drawioIt catches dangling edge endpoints, duplicate/reserved ids, broken parent references (errors), plus off-grid/negative geometry and overlapping sibling nodes (warnings) — without launching draw.io. Exit status is non-zero on any error (or any warning with `--strict`), so it can gate the workflow. Auto-layout output should always pass clean; a failure means a malformed input graph (e.g. an edge referencing a missing node id).-## Importers — visualize code structure+## Importers — visualize code & infrastructure-Bundled importers turn a codebase into a graph JSON ready for autolayout, so "visualize this project" is a two-step pipeline:+Bundled importers turn a codebase or an IaC configuration into a graph JSON ready for autolayout, so "visualize this project" is a two-step pipeline:-| Language | Script | Node = | Edge = |+| Source | Script | Node = | Edge = ||---|---|---|---|| Python | `scripts/pyimports.py <dir>` | module / package (`ast`) | intra-project `import` / `from` || JS / TS | `scripts/jsimports.py <dir>` | source file (`.ts/.tsx/.js/.jsx/.mjs/.cjs`) | resolved relative `import`/`export from`/`require()`/`import()` || Go | `scripts/goimports.py <dir>` | package (directory, via `go.mod`) | intra-module package import || Rust | `scripts/rustimports.py <dir>` | module (`.rs` file / `mod`) | intra-crate `use crate::` / `super::` / `self::` || Python (classes) | `scripts/pyclasses.py <dir>` | class (`ast`) | subclass → base (inheritance) |+| Terraform | `scripts/tfimports.py <dir>` | `resource` / `module` block, rendered as its **official AWS/Azure/GCP icon** | cross-resource reference (`aws_iam_role.x.arn`, `${...}`, `depends_on`) |+| Kubernetes | `scripts/k8simports.py <dir>` | manifest object (kind/name), rendered as its **official K8s kind icon** | Ingress→Service, Service→workload (selector), workload→ConfigMap/Secret/PVC, HPA→target |```bashpython3 <this-skill-dir>/scripts/pyimports.py myproject -o graph.jsonpython3 <this-skill-dir>/scripts/autolayout.py graph.json -o diagram.drawio```-Each keeps only **intra-project** edges (third-party/stdlib imports are ignored), shortens node labels (drops the shared package/module/directory prefix; ids stay fully qualified), and shares the same flags: `--direction TB|LR` (default `TB`), `--group`, `--no-reduce`.+Each code importer keeps only **intra-project** edges (third-party/stdlib imports are ignored), shortens node labels (drops the shared package/module/directory prefix; ids stay fully qualified), and shares the same flags: `--direction TB|LR` (default `TB`), `--group`, `--no-reduce`. The IaC importers share `--direction` and `--group` and add `--no-icons`.- **Python** (`pyimports.py`): if the directory is itself a package (`__init__.py` present), module names are package-qualified so the project's own absolute imports resolve; nested subpackages (`pkg.sub.mod`) are handled.- **JS/TS** (`jsimports.py`): resolution is path-based (tries the source extensions and directory `index` files); `node_modules` and bare specifiers are skipped. Scanning is regex-based, not a full parser.- **Go** (`goimports.py`): reads the `module` path from `go.mod`; each directory of `.go` files is one package; `*_test.go` and `vendor/` are skipped.- **Rust** (`rustimports.py`): each `.rs` file is a module (`mod.rs`/`main.rs`/`lib.rs` name the enclosing module); edges come from `use` paths rooted at `crate::`/`super::`/`self::` (brace groups expanded). `std`/external crates and `target/` are skipped. Regex-based — inline `mod { … }` blocks aren't split out, and 2015-edition bare intra-crate paths aren't resolved.- **Python classes** (`pyclasses.py`): a finer granularity — one node per class, edges from each subclass to the project base classes it extends, so the result is an auto-generated class hierarchy. Bases are matched by name (preferring the same module); external bases (`object`, third-party) are ignored. With `--group`, classes are boxed by their module, so a deep package tree nests naturally. Inheritance only — function-level call graphs are out of scope (static call resolution in Python is unreliable).+- **Terraform** (`tfimports.py`): parses `.tf` files directly (regex + brace matching, no HCL library). Each resource type is resolved to its official icon through the bundled shape index — AWS `aws4` set, Azure `azure2` set, GCP icon set — with a curated query table for the ~45 most common types and strict tag-AND matching so a partial match never lands on the wrong vendor's icon; unresolvable types fall back to a plain box labeled `name` + type (`--no-icons` forces boxes for all). `--group` boxes resources by service (`aws_s3_* → s3`). Data sources, variables, locals and providers are ignored; heredocs with unbalanced braces are the known parse limit.+- **Kubernetes** (`k8simports.py`): accepts one or more manifest files or a directory. JSON (including `kind: List`, i.e. `kubectl get ... -o json` output) parses with the stdlib alone; `.yaml`/`.yml` needs PyYAML. Kind icons come from the official `mxgraph.kubernetes` set (25 kinds mapped). Edges land only on objects present in the manifest set, matched within the same namespace. `--group` boxes objects by namespace. No `--no-reduce` flag — reference edges are sparse and never reduced.++Both IaC importers emit `ranksep`/`nodesep` in the graph JSON automatically (icon labels render *below* the shape, so rows need extra separation).**Density reduction is on by default** — this is the key to a readable result. Real import graphs are dense (asyncio: 33 modules / ~149 edges); without reduction they render as a hairball. Every importer applies **transitive reduction** (Graphviz `tred` — drops edges already implied by a longer path), which on asyncio cuts ~149 edges to ~46 and turns the hairball into a clean, traceable diagram. Pass `--no-reduce` to keep every edge.diff --git a/skills/drawio-skill/scripts/autolayout.py b/skills/drawio-skill/scripts/autolayout.pyindex 47ce4dc..1aa7961 100644--- a/skills/drawio-skill/scripts/autolayout.py+++ b/skills/drawio-skill/scripts/autolayout.py@@ -70,7 +70,9 @@ GROUP_PAD = 24def attr(value):- return escape(str(value), {'"': """})+ # Newlines in labels become 
 so draw.io renders a line break (a raw+ # newline inside an XML attribute is normalized to a space by parsers).+ return escape(str(value), {'"': """, "\n": "
"})def dot_quote(value):@@ -113,9 +115,12 @@ def group_tree(nodes):def build_dot(graph):rankdir = "LR" if str(graph.get("direction", "TB")).upper() == "LR" else "TB"+ # Optional graph-level spacing (inches). Icon nodes render their label below+ # the shape, so importers emitting icons ask for extra rank/node separation.+ sep = "".join(f" {k}={float(graph[k]):.2f};" for k in ("ranksep", "nodesep") if k in graph)# splines=ortho makes dot route edges as orthogonal polylines; we replay# those bends as draw.io waypoints so edges go around nodes, not through them.- lines = [f"digraph G {{ rankdir={rankdir}; splines=ortho; node [shape=box fixedsize=true];"]+ lines = [f"digraph G {{ rankdir={rankdir};{sep} splines=ortho; node [shape=box fixedsize=true];"]# Group nodes into (possibly nested) clusters so dot keeps each group# together; a node's first appearance fixes its cluster, so list members# before the size attributes. The cluster margin reserves room for thediff --git a/skills/drawio-skill/scripts/k8simports.py b/skills/drawio-skill/scripts/k8simports.pynew file mode 100644index 0000000..35fd7fb--- /dev/null+++ b/skills/drawio-skill/scripts/k8simports.py@@ -0,0 +1,238 @@+#!/usr/bin/env python3+"""Extract a Kubernetes manifest set's object graph as autolayout graph JSON.++Reads manifest files (a directory, or explicit .yaml/.yml/.json paths), maps+each object kind to its official draw.io Kubernetes icon (mxgraph.kubernetes+set, resolved from the bundled shape index), and derives the reference edges+that make an architecture readable:++ Ingress -> Service (spec backend service names)+ Service -> workload (selector labels match the pod template)+ workload -> ConfigMap/Secret (env / envFrom / volumes)+ workload -> PVC (persistentVolumeClaim volumes)+ HPA -> target workload (scaleTargetRef)++Workloads: Deployment, StatefulSet, DaemonSet, ReplicaSet, Job, CronJob, Pod.+Edges only land on objects that are themselves in the manifest set. The output+feeds autolayout.py:++ python3 k8simports.py ./manifests -o graph.json+ python3 autolayout.py graph.json -o cluster.drawio++JSON input (single object, or a `kind: List` as produced by+`kubectl get ... -o json`) parses with the stdlib alone; .yaml/.yml files+need PyYAML (`pip install pyyaml`).++Usage: python3 k8simports.py <dir-or-manifest...> [-o graph.json]+ [--direction TB|LR] [--group] [--no-icons]+"""+import argparse+import glob+import gzip+import json+import os+import re+import sys++# Object kind -> prIcon name inside the mxgraph.kubernetes.icon2 shape set.+KIND_ICON = {+ "ClusterRole": "c-role", "ClusterRoleBinding": "crb", "ConfigMap": "cm",+ "CronJob": "cronjob", "CustomResourceDefinition": "crd", "DaemonSet": "ds",+ "Deployment": "deploy", "Endpoints": "ep", "HorizontalPodAutoscaler": "hpa",+ "Ingress": "ing", "Job": "job", "Namespace": "ns", "NetworkPolicy": "netpol",+ "Node": "node", "PersistentVolume": "pv", "PersistentVolumeClaim": "pvc",+ "Pod": "pod", "ReplicaSet": "rs", "Role": "role", "RoleBinding": "rb",+ "Secret": "secret", "Service": "svc", "ServiceAccount": "sa",+ "StatefulSet": "sts", "StorageClass": "sc",+}+WORKLOADS = {"Deployment", "StatefulSet", "DaemonSet", "ReplicaSet", "Job", "CronJob", "Pod"}+_INDEX = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "data",+ "shape-index.json.gz")+++def icon_styles():+ """prIcon name -> (style, w, h) from the bundled official shape index."""+ with gzip.open(_INDEX, "rt", encoding="utf-8") as f:+ shapes = json.load(f)+ out = {}+ for s in shapes:+ st = s["style"]+ m = re.search(r"prIcon=([\w-]+)", st)+ # Skip the kubernetesLabel=1 variants (they paint the kind name into+ # the icon; our node label already names the object below it).+ if "mxgraph.kubernetes.icon2" in st and m and "kubernetesLabel" not in st:+ out.setdefault(m.group(1), (st, s["w"], s["h"]))+ return out+++def load_manifests(paths):+ """Parse all given files into a list of k8s objects."""+ files = []+ for p in paths:+ if os.path.isdir(p):+ for ext in ("yaml", "yml", "json"):+ files.extend(glob.glob(os.path.join(p, "**", f"*.{ext}"), recursive=True))+ else:+ files.append(p)+ objs = []+ for path in sorted(set(files)):+ with open(path, encoding="utf-8") as f:+ text = f.read()+ if path.endswith(".json"):+ docs = [json.loads(text)]+ else:+ try:+ import yaml+ except ImportError:+ sys.exit(f"error: {path} is YAML but PyYAML is not installed "+ "(pip install pyyaml) — or feed JSON from `kubectl get ... -o json`")+ docs = list(yaml.safe_load_all(text))+ for doc in docs:+ if not isinstance(doc, dict):+ continue+ if doc.get("kind") == "List":+ objs.extend(i for i in doc.get("items", []) if isinstance(i, dict))+ else:+ objs.append(doc)+ return [o for o in objs if o.get("kind") and o.get("metadata", {}).get("name")]+++def pod_spec(obj):+ spec = obj.get("spec") or {}+ if obj["kind"] == "Pod":+ return spec+ if obj["kind"] == "CronJob":+ spec = (spec.get("jobTemplate") or {}).get("spec") or {}+ return (spec.get("template") or {}).get("spec") or {}+++def pod_labels(obj):+ if obj["kind"] == "Pod":+ return (obj.get("metadata") or {}).get("labels") or {}+ spec = obj.get("spec") or {}+ if obj["kind"] == "CronJob":+ spec = (spec.get("jobTemplate") or {}).get("spec") or {}+ return ((spec.get("template") or {}).get("metadata") or {}).get("labels") or {}+++def mounted_refs(pspec):+ """(kind, name) pairs a pod spec references via env/envFrom/volumes."""+ refs = set()+ for c in (pspec.get("containers") or []) + (pspec.get("initContainers") or []):+ for e in c.get("env") or []:+ vf = e.get("valueFrom") or {}+ for key, kind in (("configMapKeyRef", "ConfigMap"), ("secretKeyRef", "Secret")):+ if vf.get(key, {}).get("name"):+ refs.add((kind, vf[key]["name"]))+ for e in c.get("envFrom") or []:+ for key, kind in (("configMapRef", "ConfigMap"), ("secretRef", "Secret")):+ if e.get(key, {}).get("name"):+ refs.add((kind, e[key]["name"]))+ for v in pspec.get("volumes") or []:+ if v.get("configMap", {}).get("name"):+ refs.add(("ConfigMap", v["configMap"]["name"]))+ if v.get("secret", {}).get("secretName"):+ refs.add(("Secret", v["secret"]["secretName"]))+ if v.get("persistentVolumeClaim", {}).get("claimName"):+ refs.add(("PersistentVolumeClaim", v["persistentVolumeClaim"]["claimName"]))+ return refs+++def ingress_backends(obj):+ """Service names referenced by an Ingress (networking.k8s.io/v1 + legacy)."""+ names, stack = set(), [obj.get("spec") or {}]+ while stack:+ cur = stack.pop()+ if isinstance(cur, dict):+ svc = cur.get("service")+ if isinstance(svc, dict) and svc.get("name"):+ names.add(svc["name"])+ if isinstance(cur.get("serviceName"), str):+ names.add(cur["serviceName"])+ stack.extend(cur.values())+ elif isinstance(cur, list):+ stack.extend(cur)+ return names+++def main():+ ap = argparse.ArgumentParser(description="Kubernetes manifests -> autolayout graph JSON.")+ ap.add_argument("paths", nargs="+", help="manifest files and/or directories")+ ap.add_argument("-o", "--output", help="output JSON path (default: stdout)")+ ap.add_argument("--direction", default="TB", choices=["TB", "LR"])+ ap.add_argument("--group", action="store_true", help="group objects by namespace")+ ap.add_argument("--no-icons", action="store_true",+ help="plain boxes instead of official Kubernetes icons")+ args = ap.parse_args()++ objs = load_manifests(args.paths)+ if not objs:+ sys.exit("error: no Kubernetes objects found (need kind + metadata.name)")++ def key(obj):+ meta = obj.get("metadata") or {}+ return (meta.get("namespace") or "", obj["kind"], meta["name"])++ by_key = {key(o): o for o in objs}+ icons = {} if args.no_icons else icon_styles()++ edges = set()+ for k, obj in by_key.items():+ ns, kind, _ = k++ def link(tkind, tname):+ if (ns, tkind, tname) in by_key and (ns, tkind, tname) != k:+ edges.add((k, (ns, tkind, tname)))++ if kind == "Ingress":+ for svc in ingress_backends(obj):+ link("Service", svc)+ elif kind == "Service":+ sel = (obj.get("spec") or {}).get("selector") or {}+ if sel:+ for tk, target in by_key.items():+ if (tk[0] == ns and tk[1] in WORKLOADS+ and sel.items() <= pod_labels(target).items()):+ edges.add((k, tk))+ elif kind in WORKLOADS:+ for tkind, tname in mounted_refs(pod_spec(obj)):+ link(tkind, tname)+ elif kind == "HorizontalPodAutoscaler":+ ref = (obj.get("spec") or {}).get("scaleTargetRef") or {}+ if ref.get("kind") and ref.get("name"):+ link(ref["kind"], ref["name"])++ def nid(k):+ ns, kind, name = k+ return f"{ns + '/' if ns else ''}{kind}/{name}"++ nodes = []+ for k in by_key:+ ns, kind, name = k+ node = {"id": nid(k), "label": name}+ icon = icons.get(KIND_ICON.get(kind, ""))+ if icon:+ node.update(style=icon[0], width=icon[1], height=icon[2])+ else:+ node["label"] = f"{name}\n{kind}"+ if args.group and ns:+ node["group"] = ns+ nodes.append(node)++ graph = {"direction": args.direction, "nodes": nodes,+ "edges": [{"source": nid(s), "target": nid(t)} for s, t in sorted(edges)]}+ if icons:+ # Icon labels render below the shape — reserve extra layout spacing.+ graph.update(ranksep=0.7, nodesep=0.6)+ text = json.dumps(graph, indent=2)+ if args.output:+ with open(args.output, "w", encoding="utf-8") as f:+ f.write(text)+ sys.stderr.write(f"wrote {args.output}\n")+ else:+ sys.stdout.write(text)+ sys.stderr.write(f"{len(nodes)} objects, {len(edges)} edges\n")+++if __name__ == "__main__":+ main()diff --git a/skills/drawio-skill/scripts/tfimports.py b/skills/drawio-skill/scripts/tfimports.pynew file mode 100644index 0000000..13a4d2a--- /dev/null+++ b/skills/drawio-skill/scripts/tfimports.py@@ -0,0 +1,262 @@+#!/usr/bin/env python3+"""Extract a Terraform configuration's resource graph as autolayout graph JSON.++Parses ``.tf`` files with a small regex + brace-matching pass (no HCL library+needed), builds resource-reference edges (``aws_iam_role.lambda.arn`` inside+another resource's body -> edge), and resolves each resource type to its+official draw.io cloud icon via the bundled shape index — AWS (aws4 set),+Azure (azure2 set) and GCP (Google Cloud icon set). The output feeds+autolayout.py:++ python3 tfimports.py ./infra -o graph.json+ python3 autolayout.py graph.json -o infra.drawio++Nodes are the ``resource`` and ``module`` blocks declared in the scanned files;+data sources, variables, locals and providers are ignored. A reference is any+``type.name`` / ``module.name`` token in a resource body that matches a+declared node — attribute chains (``aws_s3_bucket.logs.arn``), ``"${...}"``+interpolations and ``depends_on`` entries all count. Transitive reduction+(Graphviz ``tred``) keeps big graphs readable; ``--no-reduce`` keeps every+edge. Heredoc bodies with unbalanced braces are the one known parse limit.++Usage: python3 tfimports.py <dir-or-file.tf> [-o graph.json]+ [--direction TB|LR] [--group] [--no-reduce] [--no-icons]+"""+import argparse+import glob+import importlib.util+import json+import os+import re+import subprocess+import sys++# provider prefix of the resource type -> (icon query prefix, style predicate).+# The predicate pins results to the modern shape set for that cloud — a bare+# keyword search happily returns another vendor's icon (e.g. "kubernetes+# deployment" -> Azure Arc), so set filtering is what makes resolution safe.+PROVIDERS = {+ "aws": ("aws", lambda st: "mxgraph.aws4" in st),+ "azurerm": ("azure", lambda st: "img/lib/azure2" in st),+ "azuread": ("azure", lambda st: "img/lib/azure2" in st),+ "google": ("gcp", lambda st: "editableCssRules" in st),+}++# Resource types whose derived query ("aws lambda function") misses or mis-hits+# the intended icon; values are the query that finds it. Keep alphabetical.+QUERY_OVERRIDES = {+ "aws_alb": "aws elastic load balancing",+ "aws_apigatewayv2_api": "aws api gateway",+ "aws_autoscaling_group": "aws ec2 auto scaling",+ "aws_cloudwatch_log_group": "aws cloudwatch",+ "aws_db_instance": "aws rds",+ "aws_dynamodb_table": "aws dynamodb",+ "aws_ecr_repository": "aws elastic container registry",+ "aws_ecs_cluster": "aws elastic container service",+ "aws_ecs_service": "aws elastic container service",+ "aws_ecs_task_definition": "aws elastic container service",+ "aws_efs_file_system": "aws elastic file system",+ "aws_eks_cluster": "aws elastic kubernetes service",+ "aws_elasticache_cluster": "aws elasticache",+ "aws_iam_policy": "aws identity and access management",+ "aws_instance": "aws ec2",+ "aws_kms_key": "aws key management service",+ "aws_lambda_function": "aws lambda",+ "aws_lb": "aws elastic load balancing",+ "aws_rds_cluster": "aws aurora",+ "aws_s3_bucket": "aws simple storage service",+ "aws_secretsmanager_secret": "aws secrets manager",+ "aws_sfn_state_machine": "aws step functions",+ "aws_sns_topic": "aws simple notification service",+ "aws_sqs_queue": "aws simple queue service",+ "azurerm_app_service": "azure app services",+ "azurerm_application_gateway": "azure application gateways",+ "azurerm_cosmosdb_account": "azure cosmos db",+ "azurerm_kubernetes_cluster": "azure kubernetes services",+ "azurerm_linux_function_app": "azure function apps",+ "azurerm_linux_virtual_machine": "azure virtual machine",+ "azurerm_linux_web_app": "azure app services",+ "azurerm_mssql_database": "azure sql database",+ "azurerm_mssql_server": "azure sql database",+ "azurerm_servicebus_namespace": "azure service bus",+ "azurerm_storage_account": "azure storage accounts",+ "azurerm_virtual_network": "azure virtual networks",+ "azurerm_windows_function_app": "azure function apps",+ "azurerm_windows_virtual_machine": "azure virtual machine",+ "azurerm_windows_web_app": "azure app services",+ "google_cloudfunctions2_function": "gcp cloud functions",+ "google_cloudfunctions_function": "gcp cloud functions",+ "google_compute_instance": "gcp compute engine",+ "google_container_cluster": "gcp kubernetes engine",+ "google_redis_instance": "gcp memorystore",+ "google_sql_database_instance": "gcp cloud sql",+ "google_storage_bucket": "gcp cloud storage",+}++_COMMENT = re.compile(r"/\*.*?\*/|(?:#|//)[^\n]*", re.S)+_BLOCK = re.compile(r'^[ \t]*(resource|module)[ \t]+"([\w.-]+)"(?:[ \t]+"([\w.-]+)")?[ \t]*\{', re.M)+_REF = re.compile(r"\b([a-z][a-z0-9_]*\.[A-Za-z_][A-Za-z0-9_-]*)")+++def parse_blocks(text):+ """Yield (kind, label1, label2, body) for resource/module blocks."""+ text = _COMMENT.sub("", text)+ for m in _BLOCK.finditer(text):+ depth, i = 1, m.end()+ while i < len(text) and depth:+ if text[i] == "{":+ depth += 1+ elif text[i] == "}":+ depth -= 1+ i += 1+ yield m.group(1), m.group(2), m.group(3), text[m.end():i - 1]+++def load_shapesearch():+ path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "shapesearch.py")+ spec = importlib.util.spec_from_file_location("shapesearch", path)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++class IconResolver:+ """Resolve a Terraform resource type to an official draw.io icon style."""++ def __init__(self):+ import gzip+ self.ss = load_shapesearch()+ with gzip.open(self.ss.INDEX, "rt", encoding="utf-8") as f:+ self.shapes = json.load(f)+ self.tag_map = self.ss.build_tag_map(self.shapes)+ self.cache = {}++ def _and_styles(self, words):+ """Style strings of shapes whose tags match EVERY query word.+ shapesearch.search() falls back to scored OR matching when the AND set+ is empty — fine interactively, but here a partial match means a visibly+ wrong icon, so results outside this set are rejected and the caller's+ back-off handles the miss (a plain box beats a wrong icon)."""+ idxs = None+ for t in words:+ exact, phonetic = self.ss.match_term(self.tag_map, t)+ s = exact | phonetic+ idxs = s if idxs is None else idxs & s+ if not idxs:+ return set()+ return {self.shapes[i]["style"] for i in idxs}++ def resolve(self, rtype):+ if rtype in self.cache:+ return self.cache[rtype]+ provider = rtype.split("_", 1)[0]+ hit = None+ if provider in PROVIDERS:+ prefix, want = PROVIDERS[provider]+ words = (QUERY_OVERRIDES.get(rtype) or+ f"{prefix} {rtype.split('_', 1)[1].replace('_', ' ')}").split()+ # Back off one trailing word at a time: "aws lambda event source+ # mapping" eventually matches on "aws lambda".+ while len(words) > 1 and hit is None:+ allowed = self._and_styles(words)+ good = [r for r in+ self.ss.search(self.shapes, self.tag_map, " ".join(words), 40)+ if r["style"] in allowed and want(r["style"])+ and "group" not in r["style"].lower()]+ # Prefer aws4 service icons (resIcon=) over scenario glyphs.+ hit = next((r for r in good if "resIcon=" in r["style"]), None) or \+ (good[0] if good else None)+ words = words[:-1]+ if hit and max(hit["w"], hit["h"]) < 44:+ # Some sets (GCP) ship tiny nominal sizes; scale up so the icon+ # is not dwarfed by its label. aspect=fixed keeps the ratio.+ f = 48 / max(hit["w"], hit["h"])+ hit = dict(hit, w=round(hit["w"] * f), h=round(hit["h"] * f))+ self.cache[rtype] = hit+ return hit+++def transitive_reduce(nodes, edges):+ """Drop edges implied by a longer path, via Graphviz `tred`."""+ idx = {n: i for i, n in enumerate(nodes)}+ dot = "digraph{" + "".join(f"{idx[s]}->{idx[t]};" for s, t in edges) + "}"+ try:+ out = subprocess.run(["tred"], input=dot, capture_output=True,+ text=True, check=True).stdout+ except (FileNotFoundError, subprocess.CalledProcessError) as exc:+ sys.stderr.write(f"warning: tred unavailable, keeping all edges ({exc})\n")+ return edges+ rev = {i: n for n, i in idx.items()}+ return [(rev[int(a)], rev[int(b)]) for a, b in re.findall(r"(\d+)\s*->\s*(\d+)", out)]+++def main():+ ap = argparse.ArgumentParser(description="Terraform resource graph -> autolayout graph JSON.")+ ap.add_argument("path", help=".tf file or directory containing .tf files")+ ap.add_argument("-o", "--output", help="output JSON path (default: stdout)")+ ap.add_argument("--direction", default="TB", choices=["TB", "LR"])+ ap.add_argument("--group", action="store_true",+ help="group resources into containers by service (aws_s3_* -> s3)")+ ap.add_argument("--no-reduce", action="store_true",+ help="keep every edge (skip transitive reduction)")+ ap.add_argument("--no-icons", action="store_true",+ help="plain boxes instead of official cloud icons")+ args = ap.parse_args()++ files = ([args.path] if os.path.isfile(args.path)+ else sorted(glob.glob(os.path.join(args.path, "**", "*.tf"), recursive=True)))+ blocks = []+ for path in files:+ with open(path, encoding="utf-8") as f:+ blocks.extend(parse_blocks(f.read()))+ if not blocks:+ sys.exit(f"error: no resource/module blocks found under {args.path}")++ declared = {} # node id -> (rtype or None, name, body)+ for kind, l1, l2, body in blocks:+ nid = f"{l1}.{l2}" if kind == "resource" else f"module.{l1}"+ declared[nid] = (l1 if kind == "resource" else None, l2 or l1, body)++ edges = sorted({(nid, ref) for nid, (_, _, body) in declared.items()+ for ref in _REF.findall(body) if ref in declared and ref != nid})+ raw = len(edges)+ if not args.no_reduce:+ edges = transitive_reduce(list(declared), edges)++ resolver = None if args.no_icons else IconResolver()+ unmatched = []+ nodes = []+ for nid, (rtype, name, _) in declared.items():+ node = {"id": nid, "label": name}+ icon = resolver.resolve(rtype) if resolver and rtype else None+ if icon:+ node.update(style=icon["style"], width=icon["w"], height=icon["h"])+ else:+ # No icon: keep the type visible on the box (second line).+ node["label"] = f"{name}\n{rtype}" if rtype else f"module {name}"+ if rtype:+ unmatched.append(rtype)+ if args.group and rtype and "_" in rtype:+ node["group"] = rtype.split("_")[1]+ nodes.append(node)++ graph = {"direction": args.direction, "nodes": nodes,+ "edges": [{"source": s, "target": t} for s, t in edges]}+ if resolver:+ # Icon labels render below the shape — reserve extra layout spacing.+ graph.update(ranksep=0.7, nodesep=0.6)+ text = json.dumps(graph, indent=2)+ if args.output:+ with open(args.output, "w", encoding="utf-8") as f:+ f.write(text)+ sys.stderr.write(f"wrote {args.output}\n")+ else:+ sys.stdout.write(text)+ note = "" if args.no_reduce else f" (reduced from {raw})"+ sys.stderr.write(f"{len(nodes)} nodes, {len(edges)} edges{note}\n")+ if unmatched:+ sys.stderr.write("no icon for: " + ", ".join(sorted(set(unmatched))) + "\n")+++if __name__ == "__main__":+ main()diff --git a/tests/test_scripts.py b/tests/test_scripts.pyindex d09a889..6c13f1d 100644--- a/tests/test_scripts.py+++ b/tests/test_scripts.py@@ -172,6 +172,20 @@ class TestAutolayoutColor(unittest.TestCase):self.assertNotIn("fillColor=#d5e8d4", out) # no group tintself.assertIn("fillColor=#ff0000", out) # explicit style still wins+ def test_graph_level_spacing(self):+ # Importers emitting icon nodes ask for extra separation (labels render+ # below the shape); the keys pass straight through to dot.+ dot = self.m.build_dot({"nodes": [{"id": "a"}], "edges": [],+ "ranksep": 0.7, "nodesep": 0.6})+ self.assertIn("ranksep=0.70;", dot)+ self.assertIn("nodesep=0.60;", dot)++ def test_label_newline_becomes_entity(self):+ out = self.m.to_drawio(+ {"direction": "TB", "nodes": [{"id": "n", "label": "one\ntwo"}],+ "edges": []}, 5, {"n": (1, 1)}, {}, color=True)+ self.assertIn("one
two", out)+def test_escapes_special_chars(self):# Ids/edges with a quote or backslash must be escaped in the DOT input# (else they corrupt the Graphviz source); a style with a quote must be@@ -418,6 +432,70 @@ class TestImportersCli(unittest.TestCase):self.assertEqual(graph["edges"][0],{"source": "example.com/m/a", "target": "example.com/m/b"})+ def test_tfimports_edge_and_icons(self):+ # Node ids are type.name; the lambda resolves to an official aws4 icon+ # and the referenced role becomes an edge.+ with tempfile.TemporaryDirectory() as d:+ self._write(os.path.join(d, "main.tf"),+ 'resource "aws_lambda_function" "fn" {\n'+ ' role = aws_iam_role.exec.arn # comment\n'+ '}\n'+ 'resource "aws_iam_role" "exec" {\n'+ ' name = "exec"\n'+ '}\n')+ r = run("tfimports.py", d, "--no-reduce")+ graph = json.loads(r.stdout)+ ids = {n["id"] for n in graph["nodes"]}+ self.assertEqual(ids, {"aws_lambda_function.fn", "aws_iam_role.exec"})+ self.assertEqual(graph["edges"], [{"source": "aws_lambda_function.fn",+ "target": "aws_iam_role.exec"}])+ fn = next(n for n in graph["nodes"] if n["id"] == "aws_lambda_function.fn")+ self.assertIn("mxgraph.aws4", fn["style"])+ self.assertEqual(graph["ranksep"], 0.7) # icon labels need spacing++ def test_tfimports_no_icons(self):+ # Without icons the type stays visible on the box (two-line label).+ with tempfile.TemporaryDirectory() as d:+ self._write(os.path.join(d, "main.tf"),+ 'resource "aws_s3_bucket" "logs" {}\n')+ graph = json.loads(run("tfimports.py", d, "--no-icons").stdout)+ self.assertEqual(graph["nodes"][0]["label"], "logs\naws_s3_bucket")+ self.assertNotIn("style", graph["nodes"][0])++ K8S_LIST = {"kind": "List", "items": [+ {"apiVersion": "v1", "kind": "Service",+ "metadata": {"name": "web", "namespace": "shop"},+ "spec": {"selector": {"app": "web"}}},+ {"apiVersion": "apps/v1", "kind": "Deployment",+ "metadata": {"name": "web", "namespace": "shop"},+ "spec": {"template": {"metadata": {"labels": {"app": "web", "tier": "fe"}},+ "spec": {"containers": [+ {"name": "web", "image": "nginx",+ "envFrom": [{"configMapRef": {"name": "cfg"}}]}]}}}},+ {"apiVersion": "v1", "kind": "ConfigMap",+ "metadata": {"name": "cfg", "namespace": "shop"}},+ ]}++ def test_k8simports_json(self):+ # JSON input needs no PyYAML; selector match and configMap ref -> edges.+ with tempfile.TemporaryDirectory() as d:+ self._write(os.path.join(d, "all.json"), json.dumps(self.K8S_LIST))+ graph = json.loads(run("k8simports.py", d).stdout)+ ids = {n["id"] for n in graph["nodes"]}+ self.assertEqual(ids, {"shop/Service/web", "shop/Deployment/web",+ "shop/ConfigMap/cfg"})+ edges = {(e["source"], e["target"]) for e in graph["edges"]}+ self.assertEqual(edges, {("shop/Service/web", "shop/Deployment/web"),+ ("shop/Deployment/web", "shop/ConfigMap/cfg")})+ svc = next(n for n in graph["nodes"] if n["id"] == "shop/Service/web")+ self.assertIn("mxgraph.kubernetes", svc["style"])++ def test_k8simports_group_by_namespace(self):+ with tempfile.TemporaryDirectory() as d:+ self._write(os.path.join(d, "all.json"), json.dumps(self.K8S_LIST))+ graph = json.loads(run("k8simports.py", d, "--group").stdout)+ self.assertTrue(all(n["group"] == "shop" for n in graph["nodes"]))+def test_rustimports_edge(self):# Node ids are module paths (no crate-root file, so just a, b).with tempfile.TemporaryDirectory() as d: