fcbuild 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
fcbuild/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """fcbuild: declarative build tool for FreeCAD models."""
2
+
3
+ __version__ = "0.0.1"
fcbuild/cli.py ADDED
@@ -0,0 +1,52 @@
1
+ """Command-line entry point. Subcommands are stubs until the phase that implements them."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from collections.abc import Sequence
8
+ from pathlib import Path
9
+
10
+ from fcbuild import __version__
11
+
12
+ EXIT_OK = 0
13
+ EXIT_FAILURE = 1
14
+ EXIT_USAGE = 2
15
+
16
+ # Subcommand -> phase that implements it, used by the "not implemented" message.
17
+ IMPLEMENTED_IN_PHASE = {"verify": 4, "build": 4, "list": 2, "inspect": 4}
18
+
19
+
20
+ def build_parser() -> argparse.ArgumentParser:
21
+ parser = argparse.ArgumentParser(prog="fcbuild", description="Declarative FreeCAD builds.")
22
+ parser.add_argument("--version", action="version", version=f"fcbuild {__version__}")
23
+ parser.add_argument("--config", type=Path, help="path to fcbuild.yaml (default: search upward)")
24
+ parser.add_argument("--freecad", type=Path, help="path to FreeCADCmd")
25
+
26
+ subcommands = parser.add_subparsers(dest="command", metavar="<command>")
27
+
28
+ verify = subcommands.add_parser("verify", help="check the config against the models")
29
+ verify.add_argument("--level", choices=["schema", "model", "deep"], default="model")
30
+ verify.add_argument("--format", choices=["human", "json", "github"], default="human")
31
+
32
+ build = subcommands.add_parser("build", help="build all outputs, or one build[:variant]")
33
+ build.add_argument("target", nargs="?", help="build or build:variant")
34
+
35
+ subcommands.add_parser("list", help="show the variants x outputs that would be produced")
36
+
37
+ inspect = subcommands.add_parser("inspect", help="dump objects, aliases and VarSet properties")
38
+ inspect.add_argument("source", type=Path, help="an .FCStd file")
39
+
40
+ return parser
41
+
42
+
43
+ def main(argv: Sequence[str] | None = None) -> int:
44
+ parser = build_parser()
45
+ arguments = parser.parse_args(argv)
46
+ if arguments.command is None:
47
+ parser.print_help()
48
+ return EXIT_USAGE
49
+ phase = IMPLEMENTED_IN_PHASE[arguments.command]
50
+ print(f"fcbuild {arguments.command}: not implemented yet (planned for Phase {phase})",
51
+ file=sys.stderr)
52
+ return EXIT_FAILURE
@@ -0,0 +1,64 @@
1
+ """Find a FreeCADCmd executable and read its version (orchestrator side)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ import shutil
8
+ import subprocess
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+
12
+ ENV_VAR = "FCBUILD_FREECAD"
13
+ PATH_NAMES = ("FreeCADCmd", "freecadcmd")
14
+ KNOWN_LOCATIONS = (
15
+ Path("/opt/freecad/usr/bin/FreeCADCmd"),
16
+ Path("/usr/local/bin/FreeCADCmd"),
17
+ Path("/usr/bin/FreeCADCmd"),
18
+ Path("/Applications/FreeCAD.app/Contents/Resources/bin/FreeCADCmd"),
19
+ Path("C:/Program Files/FreeCAD 1.0/bin/FreeCADCmd.exe"),
20
+ )
21
+
22
+
23
+ class FreeCADNotFoundError(RuntimeError):
24
+ """No usable FreeCADCmd could be located."""
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class FreeCADInstall:
29
+ executable: Path
30
+ version: str
31
+ source: str # how it was found: "flag", "env", "path" or "known location"
32
+
33
+
34
+ def locate_freecad(explicit: str | Path | None = None) -> FreeCADInstall:
35
+ """Resolve FreeCADCmd: explicit flag, then FCBUILD_FREECAD, then PATH, then known paths."""
36
+ candidates: list[tuple[str, Path]] = []
37
+ if explicit is not None:
38
+ candidates.append(("flag", Path(explicit)))
39
+ env_value = os.environ.get(ENV_VAR)
40
+ if env_value:
41
+ candidates.append(("env", Path(env_value)))
42
+ for name in PATH_NAMES:
43
+ found = shutil.which(name)
44
+ if found:
45
+ candidates.append(("path", Path(found)))
46
+ candidates.extend(("known location", path) for path in KNOWN_LOCATIONS)
47
+
48
+ for source, path in candidates:
49
+ if path.is_file() and os.access(path, os.X_OK):
50
+ return FreeCADInstall(path, read_version(path), source)
51
+ raise FreeCADNotFoundError(
52
+ f"FreeCADCmd not found. Use --freecad, set {ENV_VAR}, or put it on PATH."
53
+ )
54
+
55
+
56
+ def read_version(executable: Path) -> str:
57
+ """Return the version string such as '1.1.4' from `FreeCADCmd --version`."""
58
+ completed = subprocess.run(
59
+ [str(executable), "--version"], capture_output=True, text=True, timeout=60, check=False
60
+ )
61
+ match = re.search(r"FreeCAD\s+(\d+\.\d+(?:\.\d+)?)", completed.stdout + completed.stderr)
62
+ if match is None:
63
+ raise FreeCADNotFoundError(f"Could not read a version from {executable}")
64
+ return match.group(1)
fcbuild/runner.py ADDED
@@ -0,0 +1,73 @@
1
+ """Launch the FreeCAD worker for one job and collect its result (orchestrator side)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import subprocess
8
+ import tempfile
9
+ from dataclasses import dataclass, field
10
+ from importlib import resources
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ from fcbuild.freecad_locator import FreeCADInstall
15
+
16
+ JOB_ENV_VAR = "FCBUILD_JOB"
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class WorkerOutcome:
21
+ """What came back from one worker process."""
22
+
23
+ ok: bool
24
+ error: str | None
25
+ result: dict[str, Any] = field(default_factory=dict)
26
+ returncode: int = 0
27
+ log: str = ""
28
+
29
+
30
+ def run_job(
31
+ freecad: FreeCADInstall, job: dict[str, Any], timeout_seconds: float = 600
32
+ ) -> WorkerOutcome:
33
+ """Run one job in a fresh FreeCADCmd process.
34
+
35
+ The job path travels in FCBUILD_JOB (FreeCADCmd argument passing is awkward). A worker that
36
+ crashes or times out yields a failed outcome; it never takes this process down.
37
+ """
38
+ with tempfile.TemporaryDirectory(prefix="fcbuild-") as work_dir_name:
39
+ work_dir = Path(work_dir_name)
40
+ job_path = work_dir / "job.json"
41
+ result_path = work_dir / "result.json"
42
+ job_path.write_text(json.dumps({**job, "result_path": str(result_path)}))
43
+
44
+ worker_script = resources.files("fcbuild.worker").joinpath("main.py")
45
+ with resources.as_file(worker_script) as script_path:
46
+ try:
47
+ completed = subprocess.run(
48
+ [str(freecad.executable), str(script_path)],
49
+ env={**os.environ, JOB_ENV_VAR: str(job_path)},
50
+ capture_output=True,
51
+ text=True,
52
+ timeout=timeout_seconds,
53
+ check=False,
54
+ )
55
+ except subprocess.TimeoutExpired:
56
+ return WorkerOutcome(False, f"worker timed out after {timeout_seconds}s")
57
+
58
+ log = completed.stdout + completed.stderr
59
+ if not result_path.is_file():
60
+ return WorkerOutcome(
61
+ False,
62
+ f"worker died without a result (exit code {completed.returncode})",
63
+ returncode=completed.returncode,
64
+ log=log,
65
+ )
66
+ result: dict[str, Any] = json.loads(result_path.read_text())
67
+ return WorkerOutcome(
68
+ ok=bool(result.get("ok")),
69
+ error=result.get("error"),
70
+ result=result,
71
+ returncode=completed.returncode,
72
+ log=log,
73
+ )
File without changes
fcbuild/worker/main.py ADDED
@@ -0,0 +1,95 @@
1
+ """Worker: runs INSIDE FreeCADCmd. Reads the job JSON, does FreeCAD work, writes a result JSON.
2
+
3
+ Phase 1 spike: open a document, set spreadsheet aliases, recompute, export STEP and STL.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import os
10
+ import traceback
11
+ from typing import Any
12
+
13
+
14
+ def apply_spreadsheet_params(doc: Any, params: dict[str, Any]) -> None:
15
+ for path, value in params.items():
16
+ object_name, _, alias = path.partition(".")
17
+ sheet = doc.getObject(object_name)
18
+ if sheet is None:
19
+ raise ValueError(f"object not found: {object_name}")
20
+ cell = sheet.getCellFromAlias(alias)
21
+ if cell is None:
22
+ raise ValueError(f"alias not found on {object_name}: {alias}")
23
+ sheet.set(cell, str(value))
24
+ doc.recompute()
25
+
26
+
27
+ def check_recompute(doc: Any) -> None:
28
+ for obj in doc.Objects:
29
+ if "Invalid" in obj.State or "Error" in obj.State:
30
+ raise RuntimeError(f"{obj.Name}: recompute failed (state {list(obj.State)})")
31
+
32
+
33
+ def get_target(doc: Any, name: str) -> Any:
34
+ matches = doc.getObjectsByLabel(name) or [doc.getObject(name)]
35
+ matches = [match for match in matches if match is not None]
36
+ if len(matches) != 1:
37
+ raise ValueError(f"{name!r} matched {len(matches)} objects")
38
+ target = matches[0]
39
+ shape = getattr(target, "Shape", None)
40
+ if shape is None or shape.isNull() or not shape.isValid():
41
+ raise RuntimeError(f"{name}: missing or invalid shape")
42
+ return target
43
+
44
+
45
+ def export(target: Any, export_spec: dict[str, str], stl_options: dict[str, float]) -> None:
46
+ path, fmt = export_spec["path"], export_spec["format"]
47
+ os.makedirs(os.path.dirname(path), exist_ok=True)
48
+ if fmt == "step":
49
+ import Import
50
+
51
+ Import.export([target], path)
52
+ elif fmt == "stl":
53
+ import Mesh
54
+ import MeshPart
55
+
56
+ mesh = MeshPart.meshFromShape(
57
+ Shape=target.Shape,
58
+ LinearDeflection=stl_options.get("linear_deflection", 0.05),
59
+ AngularDeflection=stl_options.get("angular_deflection", 0.3),
60
+ )
61
+ Mesh.Mesh(mesh).write(path)
62
+ else:
63
+ raise ValueError(f"unsupported format: {fmt}")
64
+
65
+
66
+ def run(job: dict[str, Any]) -> dict[str, Any]:
67
+ import FreeCAD
68
+
69
+ doc = FreeCAD.openDocument(job["source"])
70
+ try:
71
+ apply_spreadsheet_params(doc, job.get("params", {}))
72
+ check_recompute(doc)
73
+ written: list[str] = []
74
+ for export_spec in job["exports"]:
75
+ target = get_target(doc, export_spec["object"])
76
+ export(target, export_spec, job.get("stl", {}))
77
+ written.append(export_spec["path"])
78
+ return {"ok": True, "freecad_version": ".".join(FreeCAD.Version()[:3]), "written": written}
79
+ finally:
80
+ FreeCAD.closeDocument(doc.Name)
81
+
82
+
83
+ def main() -> None:
84
+ with open(os.environ["FCBUILD_JOB"]) as job_file:
85
+ job = json.load(job_file)
86
+ try:
87
+ result = run(job)
88
+ except Exception as error: # noqa: BLE001 - report every failure to the orchestrator
89
+ result = {"ok": False, "error": f"{type(error).__name__}: {error}",
90
+ "traceback": traceback.format_exc()}
91
+ with open(job["result_path"], "w") as result_file:
92
+ json.dump(result, result_file)
93
+
94
+
95
+ main()
@@ -0,0 +1,5 @@
1
+ Metadata-Version: 2.5
2
+ Name: fcbuild
3
+ Version: 0.0.1
4
+ Summary: Declarative build tool for FreeCAD models
5
+ Requires-Python: >=3.10
@@ -0,0 +1,10 @@
1
+ fcbuild/__init__.py,sha256=0RuBr1EcTjDG-RuvMeM6NBqRfRSD0iPYi8Bis8WL26g,81
2
+ fcbuild/cli.py,sha256=YKMRUCOcrUwi3YhFAkWf1e07A_1JEcbgEbzHLZ6SYsU,2068
3
+ fcbuild/freecad_locator.py,sha256=6qirw6YKJfdmoeLr9vVM0GrbtZbaxevyyhD3coC-xYs,2209
4
+ fcbuild/runner.py,sha256=VbyCNmHJyRInE-tZlT9_cZ_NyY0eoESUSJQIkz6Zsnc,2488
5
+ fcbuild/worker/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ fcbuild/worker/main.py,sha256=uaCktA8KYk_FsIhrkXU13TOmyERjwK-hqJmy6C4ze_o,3259
7
+ fcbuild-0.0.1.dist-info/METADATA,sha256=XczrBGt78l6Zx9ryep2osxypGu98IDzXTaIIj9lbAOI,126
8
+ fcbuild-0.0.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
9
+ fcbuild-0.0.1.dist-info/entry_points.txt,sha256=IeS9PH-In5pLvb-XQ6nJfOLktCX08sccnLe1iXnk2VI,45
10
+ fcbuild-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ fcbuild = fcbuild.cli:main