Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions concore_cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,21 @@ Stops all running concore processes. Prompts for confirmation before proceeding.
concore stop
```

### `concore graph <workflow_file>`

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 <format>` - `mermaid` (default) or `dot` (Graphviz)
- `-o, --output <file>` - 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**
Expand Down
33 changes: 33 additions & 0 deletions concore_cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__
Expand Down Expand Up @@ -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"""
Expand Down
77 changes: 77 additions & 0 deletions concore_cli/commands/graph.py
Original file line number Diff line number Diff line change
@@ -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)")
77 changes: 77 additions & 0 deletions tests/test_graph_command.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
from click.testing import CliRunner

from concore_cli.cli import cli

GRAPH = """<?xml version="1.0" encoding="UTF-8"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:y="http://www.yworks.com/xml/graphml">
<graph id="G" edgedefault="directed">
<node id="n0"><data key="d0"><y:NodeLabel>CZ:controller.py</y:NodeLabel></data></node>
<node id="n1"><data key="d0"><y:NodeLabel>OUT:</y:NodeLabel></data></node>
<node id="n2"><data key="d0"><y:NodeLabel>say "hi":x.py</y:NodeLabel></data></node>
<edge id="e0" source="n0" target="n1"><data key="d1"><y:EdgeLabel>0x1000_u</y:EdgeLabel></data></edge>
<edge id="e1" source="n1" target="n2"><data key="d1"><y:EdgeLabel>VCY</y:EdgeLabel></data></edge>
<edge id="e2" source="n2" target="n0"></edge>
<edge id="e3" source="n0" target="missing"></edge>
</graph>
</graphml>
"""


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("<html></html>", 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
Loading