From f9be721fb8f740415d5d424b637511f75ff12292 Mon Sep 17 00:00:00 2001 From: yadavchiragg Date: Sun, 15 Nov 2026 20:25:31 +0530 Subject: [PATCH] feat(cli): add 'concore graph' to export a workflow as Mermaid or dot Prints the workflow as a Mermaid flowchart or Graphviz dot graph (or writes it to a file) so it can be pasted into docs. Output verified with mmdc and dot on every bundled workflow. Tests and docs included. --- concore_cli/README.md | 15 +++++++ concore_cli/cli.py | 33 +++++++++++++++ concore_cli/commands/graph.py | 77 +++++++++++++++++++++++++++++++++++ tests/test_graph_command.py | 77 +++++++++++++++++++++++++++++++++++ 4 files changed, 202 insertions(+) create mode 100644 concore_cli/commands/graph.py create mode 100644 tests/test_graph_command.py diff --git a/concore_cli/README.md b/concore_cli/README.md index 78f98b1a..d6a0ead9 100644 --- a/concore_cli/README.md +++ b/concore_cli/README.md @@ -126,6 +126,21 @@ Stops all running concore processes. Prompts for confirmation before proceeding. concore stop ``` +### `concore graph ` + +Prints a workflow as a diagram you can paste into a README or docs. Nodes are shown with their labels and edges with their edge labels. + +**Options:** +- `-f, --format ` - `mermaid` (default) or `dot` (Graphviz) +- `-o, --output ` - Write to a file instead of printing + +**Example:** +```bash +concore graph workflow.graphml +concore graph workflow.graphml -f dot -o workflow.dot +dot -Tsvg workflow.dot -o workflow.svg +``` + ## Development Workflow 1. **Create a new project** diff --git a/concore_cli/cli.py b/concore_cli/cli.py index dc8fca34..92591438 100644 --- a/concore_cli/cli.py +++ b/concore_cli/cli.py @@ -10,6 +10,7 @@ from .commands.stop import stop_all from .commands.inspect import inspect_workflow from .commands.watch import watch_study +from .commands.graph import FORMATS, graph_workflow from .commands.doctor import doctor_check from .commands.setup import setup_concore from . import __version__ @@ -181,6 +182,38 @@ def watch(study_dir, interval, once): sys.exit(1) +@cli.command() +@click.argument("workflow_file", type=click.Path(exists=True)) +@click.option( + "--format", + "-f", + "output_format", + default="mermaid", + show_default=True, + type=click.Choice(FORMATS), + help="Diagram format", +) +@click.option( + "--output", + "-o", + type=click.Path(dir_okay=False), + help="Write to this file instead of printing", +) +def graph(workflow_file, output_format, output): + """Print a workflow as a Mermaid or Graphviz (dot) diagram""" + try: + text = graph_workflow(workflow_file, output_format) + except Exception as e: + console.print(f"[red]Error:[/red] {str(e)}") + sys.exit(1) + if output: + with open(output, "w", encoding="utf-8", newline="\n") as f: + f.write(text) + console.print(f"[green]Wrote[/green] {output}") + else: + click.echo(text, nl=False) + + @cli.command() def doctor(): """Check system readiness for running concore studies""" diff --git a/concore_cli/commands/graph.py b/concore_cli/commands/graph.py new file mode 100644 index 00000000..68759129 --- /dev/null +++ b/concore_cli/commands/graph.py @@ -0,0 +1,77 @@ +from pathlib import Path + +from bs4 import BeautifulSoup + +FORMATS = ("mermaid", "dot") + + +def _text(element, name): + tag = element.find(f"y:{name}") + if tag is None: + tag = element.find(name) + return tag.text.strip() if tag is not None and tag.text else "" + + +def _read_graph(workflow_path): + soup = BeautifulSoup(workflow_path.read_text(encoding="utf-8"), "xml") + if not soup.find("graphml"): + raise ValueError("Not a valid GraphML file") + + names = {} + for node in soup.find_all("node"): + node_id = node.get("id") + if node_id: + names[node_id] = _text(node, "NodeLabel") or node_id + + edges = [] + for edge in soup.find_all("edge"): + source, target = edge.get("source"), edge.get("target") + if source in names and target in names: + edges.append((source, target, _text(edge, "EdgeLabel"))) + return names, edges + + +def _display(label): + # 'CZ:controller.py' stays as is; a port-only node 'IN:' shows as 'IN'. + return label[:-1] if label.endswith(":") and len(label) > 1 else label + + +def _mermaid_quote(text): + return '"' + text.replace('"', "#quot;") + '"' + + +def _dot_quote(text): + return '"' + text.replace("\\", "\\\\").replace('"', '\\"') + '"' + + +def render_mermaid(names, edges): + index = {node_id: f"n{i}" for i, node_id in enumerate(names)} + lines = ["flowchart LR"] + for node_id, label in names.items(): + lines.append(f" {index[node_id]}[{_mermaid_quote(_display(label))}]") + for source, target, label in edges: + arrow = f"-->|{_mermaid_quote(label)}|" if label else "-->" + lines.append(f" {index[source]} {arrow} {index[target]}") + return "\n".join(lines) + "\n" + + +def render_dot(names, edges): + index = {node_id: f"n{i}" for i, node_id in enumerate(names)} + lines = ["digraph concore {", " rankdir=LR;", " node [shape=box];"] + for node_id, label in names.items(): + lines.append(f" {index[node_id]} [label={_dot_quote(_display(label))}];") + for source, target, label in edges: + attr = f" [label={_dot_quote(label)}]" if label else "" + lines.append(f" {index[source]} -> {index[target]}{attr};") + lines.append("}") + return "\n".join(lines) + "\n" + + +def graph_workflow(workflow_file, output_format): + """Return the workflow drawn as Mermaid or Graphviz DOT text.""" + names, edges = _read_graph(Path(workflow_file)) + if output_format == "mermaid": + return render_mermaid(names, edges) + if output_format == "dot": + return render_dot(names, edges) + raise ValueError(f"Unknown format '{output_format}' (use mermaid or dot)") diff --git a/tests/test_graph_command.py b/tests/test_graph_command.py new file mode 100644 index 00000000..64ae4106 --- /dev/null +++ b/tests/test_graph_command.py @@ -0,0 +1,77 @@ +from click.testing import CliRunner + +from concore_cli.cli import cli + +GRAPH = """ + + + CZ:controller.py + OUT: + say "hi":x.py + 0x1000_u + VCY + + + + +""" + + +def _graph(tmp_path): + path = tmp_path / "wf.graphml" + path.write_text(GRAPH, encoding="utf-8") + return str(path) + + +def test_graph_defaults_to_mermaid(tmp_path): + result = CliRunner().invoke(cli, ["graph", _graph(tmp_path)]) + assert result.exit_code == 0 + lines = result.output.splitlines() + assert lines[0] == "flowchart LR" + assert ' n0["CZ:controller.py"]' in lines + assert ' n1["OUT"]' in lines + assert ' n0 -->|"0x1000_u"| n1' in lines + assert " n2 --> n0" in lines + + +def test_graph_mermaid_escapes_quotes(tmp_path): + result = CliRunner().invoke(cli, ["graph", _graph(tmp_path)]) + assert ' n2["say #quot;hi#quot;:x.py"]' in result.output.splitlines() + + +def test_graph_skips_edges_to_unknown_nodes(tmp_path): + result = CliRunner().invoke(cli, ["graph", _graph(tmp_path)]) + assert "missing" not in result.output + assert result.output.count("-->") == 3 + + +def test_graph_dot(tmp_path): + result = CliRunner().invoke(cli, ["graph", _graph(tmp_path), "-f", "dot"]) + assert result.exit_code == 0 + lines = result.output.splitlines() + assert lines[0] == "digraph concore {" + assert lines[-1] == "}" + assert ' n0 [label="CZ:controller.py"];' in lines + assert ' n2 [label="say \\"hi\\":x.py"];' in lines + assert ' n0 -> n1 [label="0x1000_u"];' in lines + assert " n2 -> n0;" in lines + + +def test_graph_writes_output_file(tmp_path): + out = tmp_path / "wf.mmd" + result = CliRunner().invoke(cli, ["graph", _graph(tmp_path), "-o", str(out)]) + assert result.exit_code == 0 + assert out.read_text(encoding="utf-8").startswith("flowchart LR\n") + + +def test_graph_rejects_non_graphml(tmp_path): + bad = tmp_path / "bad.graphml" + bad.write_text("", encoding="utf-8") + result = CliRunner().invoke(cli, ["graph", str(bad)]) + assert result.exit_code == 1 + assert "Not a valid GraphML" in result.output + + +def test_graph_rejects_unknown_format(tmp_path): + result = CliRunner().invoke(cli, ["graph", _graph(tmp_path), "-f", "svg"]) + assert result.exit_code != 0