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
21 changes: 6 additions & 15 deletions concore_cli/commands/add_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

from rich.panel import Panel

from .init import GRAPHML_NODE, LANGUAGE_NODES
from .init import GRAPHML_NODE, LANGUAGE_NODES, _free_filename, _stub_for

LANGUAGES = tuple(LANGUAGE_NODES)

Expand All @@ -22,15 +22,6 @@ def _nodegraphics_key(text):
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):
Expand Down Expand Up @@ -61,15 +52,15 @@ def add_node(project_dir, lang, console):
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)
used_stems = {f.rsplit(".", 1)[0].lower() for f in used_files}
if src_path.is_dir():
used_stems |= {p.stem.lower() for p in src_path.iterdir()}
filename = _free_filename(info["filename"], used_stems)
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}")
stub = _stub_for(lang, filename)

node_xml = GRAPHML_NODE.format(
idx=idx, y=y, color=info["color"], filename=filename
Expand Down
43 changes: 36 additions & 7 deletions concore_cli/commands/init.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,17 +234,38 @@ def run_wizard(console):
# ---------------------------------------------------------------------------


def _build_graphml(project_name, selected_langs):
def _free_filename(default_filename, used_stems):
"""Number the default filename until its stem is unused, then claim it."""
# port files are named by stem, so script.m must not sit beside script.py;
# compared case-insensitively, like Windows and macOS file systems
stem, dot, ext = default_filename.rpartition(".")
candidate, n = stem, 1
while candidate.lower() in used_stems:
n += 1
candidate = f"{stem}{n}"
used_stems.add(candidate.lower())
return f"{candidate}{dot}{ext}"


def _stub_for(lang_key, filename):
stub = LANGUAGE_NODES[lang_key]["stub"]
if lang_key == "java":
class_name = Path(filename).stem
stub = stub.replace("public class Script", f"public class {class_name}")
return stub


def _build_graphml(project_name, selected_langs, filenames):
"""Return a GraphML string with one unconnected node per selected language."""
node_blocks = []
for idx, lang_key in enumerate(selected_langs, start=1):
for idx, (lang_key, filename) in enumerate(zip(selected_langs, filenames), start=1):
info = LANGUAGE_NODES[lang_key]
node_blocks.append(
GRAPHML_NODE.format(
idx=idx,
y=100 + (idx - 1) * 100, # stack vertically, 100 px apart
color=info["color"],
filename=info["filename"],
filename=filename,
)
)
return GRAPHML_HEADER.format(
Expand Down Expand Up @@ -284,12 +305,20 @@ def init_project_interactive(name, selected_langs, console):

# workflow.graphml
workflow_file = project_path / "workflow.graphml"
workflow_file.write_text(_build_graphml(name, selected_langs), encoding="utf-8")
used_stems = set()
filenames = [
_free_filename(LANGUAGE_NODES[k]["filename"], used_stems)
for k in selected_langs
]
workflow_file.write_text(
_build_graphml(name, selected_langs, filenames), encoding="utf-8"
)

# one source stub per selected language
for lang_key in selected_langs:
info = LANGUAGE_NODES[lang_key]
(src_path / info["filename"]).write_text(info["stub"], encoding="utf-8")
for lang_key, filename in zip(selected_langs, filenames):
(src_path / filename).write_text(
_stub_for(lang_key, filename), encoding="utf-8"
)

# README
(project_path / "README.md").write_text(
Expand Down
17 changes: 17 additions & 0 deletions concore_cli/commands/validate.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
import os
from pathlib import Path
from bs4 import BeautifulSoup
from rich.panel import Panel
Expand Down Expand Up @@ -69,6 +70,8 @@ def _classify_message(message, bucket_name):
return {"error_type": "node_parse_error"}
if message.startswith("Duplicate node container name:"):
return {"error_type": "duplicate_container_name"}
if message.startswith("Source files share the name"):
return {"error_type": "duplicate_source_stem"}
if message.startswith("Duplicate node label:"):
return {"error_type": "duplicate_node_label"}
if message == "Edge missing source or target":
Expand Down Expand Up @@ -357,6 +360,20 @@ def finalize():
f"used by {', '.join(sorted(labels))}"
)

# port files and docker images are named after the source stem
# (case-insensitive, like Windows and macOS file systems)
stems = {}
for label in node_labels:
source = label.split(":", 1)[1] if ":" in label else ""
if source:
stems.setdefault(os.path.splitext(source)[0].lower(), set()).add(source)
for stem, sources in sorted(stems.items()):
if len(sources) > 1:
errors.append(
f"Source files share the name '{stem}': "
f"{', '.join(sorted(sources))} (rename one of them)"
)

node_ids = {node.get("id") for node in nodes if node.get("id")}
for edge in edges:
source = edge.get("source")
Expand Down
14 changes: 14 additions & 0 deletions mkconcore.py
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,20 @@ def cleanup_script_files():
logging.error(f"Container name '{name}' is used by more than one node: {', '.join(labels)}")
sys.exit(1)

# Port files, Dockerfiles and docker images are named after the source stem,
# so two different sources with one stem (controller.py, controller.m) overwrite each other
# (case-insensitive, like Windows and macOS file systems)
stems = {}
for _label in label_values:
_source = _label.split(':', 1)[1]
if _source:
stems.setdefault(os.path.splitext(_source)[0].lower(), set()).add(_source)
clashes = {stem: sources for stem, sources in stems.items() if len(sources) > 1}
if clashes:
for stem, sources in sorted(clashes.items()):
logging.error(f"Source files {', '.join(sorted(sources))} share the name '{stem}'; rename one of them")
sys.exit(1)

for edge in edges_text:
try:
data = edge.find('data', recursive=False)
Expand Down
43 changes: 36 additions & 7 deletions tests/test_add_node_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@ 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")
(project / "src" / "script2.cpp")
.read_text()
.startswith('#include "concore.hpp"')
)
assert _labels(project) == ["N1:script.py", "N2:script.cpp"]
assert _labels(project) == ["N1:script.py", "N2:script2.cpp"]


def test_add_node_picks_unused_names(project):
Expand All @@ -42,10 +42,11 @@ def test_add_node_picks_unused_names(project):
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
# Script.java would share its port files with script.py on Windows/macOS
assert "public class Script2 {" in (project / "src" / "Script2.java").read_text()
second = (project / "src" / "Script3.java").read_text()
assert "public class Script3 {" in second
assert "public class Script2 {" not in second


def test_added_node_is_placed_below_existing_nodes(project):
Expand All @@ -68,7 +69,8 @@ def test_add_node_uses_the_files_own_graphics_key_and_line_endings(project):


def test_workflow_still_validates_after_adding_nodes(project):
CliRunner().invoke(cli, ["add-node", str(project), "--lang", "cpp"])
for lang in ("cpp", "octave"):
CliRunner().invoke(cli, ["add-node", str(project), "--lang", lang])
result = CliRunner().invoke(
cli,
[
Expand All @@ -80,6 +82,7 @@ def test_workflow_still_validates_after_adding_nodes(project):
)
assert "has no filename" not in result.output
assert "Missing source file" not in result.output
assert "share the name" not in result.output


def test_add_node_requires_a_project(tmp_path):
Expand All @@ -91,3 +94,29 @@ def test_add_node_requires_a_project(tmp_path):
def test_add_node_rejects_unknown_language(project):
result = CliRunner().invoke(cli, ["add-node", str(project), "--lang", "cobol"])
assert result.exit_code != 0


def test_init_wizard_gives_each_language_its_own_stem(tmp_path, monkeypatch):
from concore_cli.commands.init import init_project_interactive

monkeypatch.chdir(tmp_path)
init_project_interactive("proj", ["python", "octave", "java"], _Quiet())
project = tmp_path / "proj"
assert _labels(project) == ["N1:script.py", "N2:script2.m", "N3:Script3.java"]
java = (project / "src" / "Script3.java").read_text()
assert "public class Script3 {" in java
result = CliRunner().invoke(
cli,
[
"validate",
str(project / "workflow.graphml"),
"--source",
str(project / "src"),
],
)
assert "share the name" not in result.output


class _Quiet:
def print(self, *args, **kwargs):
pass
35 changes: 34 additions & 1 deletion tests/test_duplicate_container_names.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def print(self, *args, **kwargs):
def _setup(tmp_path, first, second):
src = tmp_path / "src"
src.mkdir()
for name in ("a.py", "b.py"):
for name in ("a.py", "b.py", "a.m"):
(src / name).write_text("print('x')\n")
wf = tmp_path / "w.graphml"
wf.write_text(GRAPH.format(first=first, second=second))
Expand Down Expand Up @@ -79,3 +79,36 @@ def test_validate_reports_duplicate_container_name(tmp_path):
def test_validate_accepts_distinct_container_names(tmp_path):
wf, src = _setup(tmp_path, "ctrl:a.py", "plant:b.py")
assert validate_workflow(str(wf), str(src), _Console()) is True


def test_mkconcore_rejects_two_sources_with_same_stem(tmp_path):
# a.py and a.m would both write src/a.iport and src/a.oport
wf, src = _setup(tmp_path, "ctrl:a.py", "plant:a.m")
result = _run_mkconcore(tmp_path, wf, src)
assert result.returncode != 0
assert "share the name 'a'" in result.stdout + result.stderr


def test_mkconcore_accepts_one_source_shared_by_two_nodes(tmp_path):
wf, src = _setup(tmp_path, "ctrl:a.py", "plant:a.py")
assert _run_mkconcore(tmp_path, wf, src).returncode == 0


def test_validate_reports_two_sources_with_same_stem(tmp_path):
wf, src = _setup(tmp_path, "ctrl:a.py", "plant:a.m")
console = _Console()
assert validate_workflow(str(wf), str(src), console) is False
assert any("Source files share the name 'a'" in line for line in console.lines)


def test_validate_accepts_one_source_shared_by_two_nodes(tmp_path):
wf, src = _setup(tmp_path, "ctrl:a.py", "plant:a.py")
assert validate_workflow(str(wf), str(src), _Console()) is True


def test_validate_reports_stems_that_differ_only_in_case(tmp_path):
# a.iport and A.iport are one file on Windows and macOS
wf, src = _setup(tmp_path, "ctrl:a.py", "plant:A.m")
console = _Console()
assert validate_workflow(str(wf), str(src), console) is False
assert any("Source files share the name 'a'" in line for line in console.lines)
Loading