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
9 changes: 9 additions & 0 deletions concore_cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,15 @@ my-workflow/
└── README.md # Project documentation
```

### `concore add-node <project_dir> --lang <language>`

Adds a starter node to an existing project: a source stub in `src/` and a matching (unconnected) node in `workflow.graphml`. Languages: `python`, `cpp`, `octave`, `verilog`, `java` (the same stubs `concore init --interactive` creates). If the default file name is taken it uses the next free one (`script2.py`, `Script2.java`), and the node is placed below the existing nodes. Connect it to the others in yEd afterwards.

**Example:**
```bash
concore add-node my-project --lang cpp
```

### `concore build <workflow_file>`

Compiles a concore workflow GraphML file into executable scripts (POSIX, Windows, or Docker).
Expand Down
19 changes: 19 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.add_node import LANGUAGES, add_node
from .commands.doctor import doctor_check
from .commands.setup import setup_concore
from . import __version__
Expand Down Expand Up @@ -181,6 +182,24 @@ def watch(study_dir, interval, once):
sys.exit(1)


@cli.command("add-node")
@click.argument("project_dir", type=click.Path(exists=True, file_okay=False))
@click.option(
"--lang",
"-l",
required=True,
type=click.Choice(LANGUAGES),
help="Language of the new node",
)
def add_node_command(project_dir, lang):
"""Add a starter node (source file + workflow entry) to an existing project"""
try:
add_node(project_dir, lang, console)
except Exception as e:
console.print(f"[red]Error:[/red] {str(e)}")
sys.exit(1)


@cli.command()
def doctor():
"""Check system readiness for running concore studies"""
Expand Down
94 changes: 94 additions & 0 deletions concore_cli/commands/add_node.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import re
from pathlib import Path

from rich.panel import Panel

from .init import GRAPHML_NODE, LANGUAGE_NODES

LANGUAGES = tuple(LANGUAGE_NODES)

NODE_KEY_RE = re.compile(r"<key\b[^>]*>")
NODE_ID_RE = re.compile(r'<node\b[^>]*\bid="([^"]*)"')
LABEL_RE = re.compile(r"<y:NodeLabel[^>]*>([^<]*)</y:NodeLabel>")
Y_RE = re.compile(r'<y:Geometry\b[^>]*\by="(-?[0-9.]+)"')


def _nodegraphics_key(text):
for tag in NODE_KEY_RE.findall(text):
if 'for="node"' in tag and 'yfiles.type="nodegraphics"' in tag:
match = re.search(r'\bid="([^"]*)"', tag)
if match:
return match.group(1)
return None


def _pick_filename(default_filename, src_path, used_files):
stem, dot, ext = default_filename.rpartition(".")
candidate, n = default_filename, 1
while (src_path / candidate).exists() or candidate in used_files:
n += 1
candidate = f"{stem}{n}{dot}{ext}"
return candidate


def _pick_index(node_ids, labels):
i = 1
while f"n{i}" in node_ids or any(lab.startswith(f"N{i}:") for lab in labels):
i += 1
return i


def add_node(project_dir, lang, console):
project_path = Path(project_dir)
workflow = project_path / "workflow.graphml"
if not workflow.is_file():
raise FileNotFoundError(f"No workflow.graphml in '{project_dir}'")
if lang not in LANGUAGE_NODES:
raise ValueError(f"Unsupported language '{lang}'")

# Read bytes so a CRLF file keeps its line endings (read_text would convert them).
text = workflow.read_bytes().decode("utf-8")
newline = "\r\n" if "\r\n" in text else "\n"

key_id = _nodegraphics_key(text)
if key_id is None:
raise ValueError("workflow.graphml has no node graphics key to attach to")
close = text.rfind("</graph>")
if close == -1:
raise ValueError("workflow.graphml has no </graph> element")

info = LANGUAGE_NODES[lang]
src_path = project_path / "src"
labels = [m.strip() for m in LABEL_RE.findall(text)]
used_files = {lab.split(":", 1)[1] for lab in labels if ":" in lab}
filename = _pick_filename(info["filename"], src_path, used_files)
idx = _pick_index(set(NODE_ID_RE.findall(text)), labels)
ys = [float(y) for y in Y_RE.findall(text)]
y = int(max(ys) + 100) if ys else 100

stub = info["stub"]
if lang == "java":
class_name = Path(filename).stem
stub = stub.replace("public class Script", f"public class {class_name}")

node_xml = GRAPHML_NODE.format(
idx=idx, y=y, color=info["color"], filename=filename
).replace('key="d6"', f'key="{key_id}"')
node_xml = node_xml.replace("\n", newline)

src_path.mkdir(exist_ok=True)
(src_path / filename).write_text(stub, encoding="utf-8")

line_start = text.rfind(newline, 0, close) + len(newline)
updated = text[:line_start] + node_xml + newline + text[line_start:]
workflow.write_bytes(updated.encode("utf-8"))

console.print(
Panel.fit(
f"[green]✓[/green] Added node N{idx}: {filename}\n\n"
f" src/{filename}\n"
f" workflow.graphml (unconnected — connect it in yEd)",
title="Success",
border_style="green",
)
)
93 changes: 93 additions & 0 deletions tests/test_add_node_command.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import re

import pytest
from click.testing import CliRunner

from concore_cli.cli import cli


@pytest.fixture
def project(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
result = CliRunner().invoke(cli, ["init", "proj"])
assert result.exit_code == 0, result.output
return tmp_path / "proj"


def _labels(project):
text = (project / "workflow.graphml").read_text(encoding="utf-8")
return re.findall(r"<y:NodeLabel[^>]*>([^<]*)</y:NodeLabel>", text)


def test_add_node_adds_source_and_graph_entry(project):
result = CliRunner().invoke(cli, ["add-node", str(project), "--lang", "cpp"])
assert result.exit_code == 0, result.output
assert (
(project / "src" / "script.cpp")
.read_text()
.startswith('#include "concore.hpp"')
)
assert _labels(project) == ["N1:script.py", "N2:script.cpp"]


def test_add_node_picks_unused_names(project):
for _ in range(2):
result = CliRunner().invoke(cli, ["add-node", str(project), "--lang", "python"])
assert result.exit_code == 0, result.output
assert _labels(project) == ["N1:script.py", "N2:script2.py", "N3:script3.py"]
assert (project / "src" / "script2.py").is_file()
assert (project / "src" / "script3.py").is_file()


def test_add_node_renames_java_class_to_match_file(project):
for _ in range(2):
CliRunner().invoke(cli, ["add-node", str(project), "--lang", "java"])
assert "public class Script {" in (project / "src" / "Script.java").read_text()
second = (project / "src" / "Script2.java").read_text()
assert "public class Script2 {" in second
assert "public class Script {" not in second


def test_added_node_is_placed_below_existing_nodes(project):
CliRunner().invoke(cli, ["add-node", str(project), "--lang", "octave"])
text = (project / "workflow.graphml").read_text(encoding="utf-8")
ys = [int(y) for y in re.findall(r'<y:Geometry[^>]*\by="(\d+)"', text)]
assert ys == [100, 200]


def test_add_node_uses_the_files_own_graphics_key_and_line_endings(project):
wf = project / "workflow.graphml"
text = wf.read_text(encoding="utf-8").replace('"d6"', '"d4"').replace("\n", "\r\n")
wf.write_bytes(text.encode("utf-8"))
result = CliRunner().invoke(cli, ["add-node", str(project), "--lang", "verilog"])
assert result.exit_code == 0, result.output
data = wf.read_bytes().decode("utf-8")
assert data.count('<data key="d4">') == 2
assert 'key="d6"' not in data
assert "\r\n" in data and "\n" not in data.replace("\r\n", "")


def test_workflow_still_validates_after_adding_nodes(project):
CliRunner().invoke(cli, ["add-node", str(project), "--lang", "cpp"])
result = CliRunner().invoke(
cli,
[
"validate",
str(project / "workflow.graphml"),
"--source",
str(project / "src"),
],
)
assert "has no filename" not in result.output
assert "Missing source file" not in result.output


def test_add_node_requires_a_project(tmp_path):
result = CliRunner().invoke(cli, ["add-node", str(tmp_path), "--lang", "python"])
assert result.exit_code == 1
assert "No workflow.graphml" in result.output


def test_add_node_rejects_unknown_language(project):
result = CliRunner().invoke(cli, ["add-node", str(project), "--lang", "cobol"])
assert result.exit_code != 0
Loading