diff --git a/.envrc-example b/.envrc-example new file mode 100644 index 0000000..3550a30 --- /dev/null +++ b/.envrc-example @@ -0,0 +1 @@ +use flake diff --git a/.gitignore b/.gitignore index 512450e..2b30b53 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,8 @@ .env.* secrets.txt backup.zip +.envrc +.direnv # SSL / ACME Certificates & Keys config/letsencrypt/* @@ -47,4 +49,3 @@ __pycache__/ # Local Bootstrap & Operational Scripts scripts/bootstrap_lldap_users.py scripts/bootstrap_*.py - diff --git a/flake.lock b/flake.lock index 4198690..d1ecdb1 100644 --- a/flake.lock +++ b/flake.lock @@ -2,11 +2,11 @@ "nodes": { "nixpkgs": { "locked": { - "lastModified": 1790046670, - "narHash": "sha256-OJe62m8gZx4xEAQnMcqH1u31/uu4Xf0q2ykAEHZfgrg=", - "rev": "6774f7bc253789b113a4f39285dc0fa100abeacc", + "lastModified": 1790463110, + "narHash": "sha256-VZHcT2wKLkApBCACQ2SH4P1jVZUbbOA7jWAGi1MIViw=", + "rev": "e158d9ed9b51c98974c5e66e1ba1c9e0255fecaa", "type": "tarball", - "url": "https://releases.nixos.org/nixos/unstable/nixos-26.11pre1077996.6774f7bc2537/nixexprs.tar.zst" + "url": "https://releases.nixos.org/nixos/unstable/nixos-26.11pre1080189.e158d9ed9b51/nixexprs.tar.zst" }, "original": { "type": "tarball", @@ -26,11 +26,11 @@ ] }, "locked": { - "lastModified": 1789890976, - "narHash": "sha256-GKwH3zpy7tartuJMG0Rv/xUsdetG1QLmTVv8UKgJLmA=", + "lastModified": 1790498116, + "narHash": "sha256-rs9meAYxW3zzrh43yaW7htrqCD+X9+pupDPHN86fumI=", "owner": "Mic92", "repo": "sops-nix", - "rev": "7214124c20c1542c90deb54af50e2f53ae02711f", + "rev": "5efb5a6f4f5ab192817d28557dd4d650fa14d866", "type": "github" }, "original": { diff --git a/flake.nix b/flake.nix index 69e0d9a..b78b1f0 100644 --- a/flake.nix +++ b/flake.nix @@ -27,9 +27,12 @@ devShells.${system}.default = pkgs.mkShell { buildInputs = with pkgs; [ - python3 - python3Packages.pytest - python3Packages.pyyaml + (python3.withPackages (ps: with ps; [ + pyyaml + types-pyyaml + pytest + ])) + pyright ruff ]; shellHook = '' diff --git a/nixos/configuration.nix b/nixos/configuration.nix index 32b5390..f819bf5 100644 --- a/nixos/configuration.nix +++ b/nixos/configuration.nix @@ -120,7 +120,9 @@ sops age # Python runtime (hard requirement for appctl and gitops_dispatcher.py) - python3 + python3.withPackages(ps: with ps; [ + pyyaml + ]) # Modern shell utilities eza # ls replacement ripgrep # rg — fast grep diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..2915980 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,5 @@ +[tool.pyright] +extraPaths = ["scripts"] +exclude = [ + "scripts/appctl_engine.py", +] diff --git a/scripts/appctl_engine_v2.py b/scripts/appctl_engine_v2.py new file mode 100644 index 0000000..3433e17 --- /dev/null +++ b/scripts/appctl_engine_v2.py @@ -0,0 +1,458 @@ +import os +import subprocess +import sys +from dataclasses import asdict, dataclass, field +from pathlib import Path +from typing import Any + +import yaml + +# Dynamic Environment Paths +CORE_DIR = os.environ.get( + "CORE_DIR", os.path.dirname(os.path.dirname(os.path.abspath(__file__))), +) + +SITES_DIR = os.environ.get( + "SITES_DIR", + os.path.join(os.path.dirname(CORE_DIR), "Sites") + if os.path.isdir(os.path.join(os.path.dirname(CORE_DIR), "Sites")) + else os.path.expanduser("~/Sites"), +) + + +HOMELAB_DOMAIN = os.environ.get("HOMELAB_DOMAIN") or os.environ.get("DOMAIN", "") + + +def validate_environment() -> None: + """Ensure mandatory environment configuration is valid before CLI execution.""" + errors: list[str] = [] + + if not HOMELAB_DOMAIN: + errors.append( + "• Missing 'HOMELAB_DOMAIN' (or 'DOMAIN') environment variable.\n" + " Please export it (e.g. export HOMELAB_DOMAIN='roadtotech.me') or set it in your environment file." + ) + + if not os.path.isdir(CORE_DIR): + errors.append(f"• Core directory not found at: {CORE_DIR}") + + if errors: + print("❌ Environment Validation Failed:\n", file=sys.stderr) + for err in errors: + print(f" {err}", file=sys.stderr) + sys.exit(1) + +class ManifestError(Exception): + pass + +@dataclass +class HomepageConfig: + title: str + group: str = "Applications" + icon: str = "default.png" + container: str = "" + weight: int = 50 + +@dataclass +class SourceConfig: + """Upstream source provenance descriptor.""" + type: str = "git" # "git" + url: str = "" # e.g., "https://git.roadtotech.me/kiskaadee/bitetrack.git" + ref: str = "main" # Branch (e.g. "main"), tag (e.g. "v1.0.0"), or commit SHA + +@dataclass +class App: + name: str # Canonical identified (e.g., "traefik", "jellyfin") + description: str # Human-readable summary for dashboards and CLI info + domain: str # Routing FQDN (e.g., "auth.roadtotech.me") or "internal". + dir_path: str # Filesystem directory (CORE_DIR for Core, or ~/Sites/ for Sites). + + @property + def is_internal(self) -> bool: + """Returns True if the service does not expose a public TLS endpoint.""" + return not self.domain or self.domain == "internal" or self.domain.endswith(".local") or ":" in self.domain + + def to_dict(self) -> dict[str, Any]: + """Serialize for JSON consumption by scripts/appctl""" + data = asdict(self) + data["type"] = getattr(self, "app_type", "app") + return data + +@dataclass +class CoreService(App): + container: str = "" # Target container name inside Core's root docker-compose.yml (e.g., "authelia", "stalwart") + weight: int = 50 # Homepage ordering weight (optional, for dashboard synchronization) + icon: str = "default.png" # Dashboard icon filename + app_type: str = "core_service" + dir_path: str = CORE_DIR + +@dataclass +class SitesApp(App): + dir_name: str = "" # directory name in ~/Sites (e.g., "homelab-vaultwarden") + source: SourceConfig | None = None # Upstream source provenance (optional; None indicates Image-Only workload) + aliases: list[str] = field(default_factory=list) # CLI resolution aliases (e.g., "vw", "vaultwarden") + visible: bool = True # Defines whether the icon is visible in the Homepage Dashboard + auth: bool = True # Authelia protection guard indicator; Defaulting to True is safer + has_compose: bool = False # Whether a docker-compose.yaml exists at ~/Sites/dir_name. + networks: list[str] = field(default_factory=lambda: ["proxy-net"]) # Docker network attachments (def ["proxy-net"]) + env: dict[str, Any] = field(default_factory=dict) # Dynamic environment variable overrides + homepage: HomepageConfig | None = None # Dashboard Card Configuration + manifest_error: str | None = None # Captured syntax/loading errors if app.yaml was malformed/absent + app_type: str = "app" + + + +def load_manifest(manifest_path: str) -> dict[str, Any]: + """Load and parese the app manifest file + + Raises: + FileNotFoundError: if the manifest file does not exist. + ValueError: if YAML object is malformed. + TypeError: If root is not a directory + """ + if not os.path.isfile(manifest_path): + raise FileNotFoundError(f"Manifest file not found at {manifest_path}") + + try: + with open(manifest_path, "r", encoding="utf-8") as file: + manifest_data = yaml.safe_load(file) or {} + except (yaml.YAMLError, OSError) as err: + raise ManifestError(f"YAML parsing failed: {err}") from err + + if not isinstance(manifest_data, dict): + raise ManifestError(f"Invalid manifest root: expected `dict`, got `{type(manifest_data).__name__}`") + + return manifest_data + + + +def sites_app_from_manifest( + + app_dir: str, + manifest: dict[str, Any], + manifest_error: str | None = None +) -> SitesApp: + """Construct and normalize a SitesApp domain model from raw manifest data.""" + raw_dir_name = os.path.basename(app_dir) + canonical_name = str(manifest.get("name") or raw_dir_name.replace("homelab-", "")) + + # Normalize aliases into list[str] + raw_aliases = manifest.get("aliases") or [] + if isinstance(raw_aliases, str): + aliases = [raw_aliases] + elif isinstance(raw_aliases, list): + aliases = [str(alias) for alias in raw_aliases] + else: + aliases = [] + + # Homepage card normalization + homepage_config: HomepageConfig | None = None + raw_hp = manifest.get("homepage") + if isinstance(raw_hp, dict): + homepage_config = HomepageConfig( + title=str(raw_hp.get("title") or canonical_name), + group=str(raw_hp.get("group") or "Applications"), + icon=str(raw_hp.get("icon") or "default.png"), + container=str(raw_hp.get("container") or canonical_name), + weight=int(raw_hp.get("weight", 50)) + ) + has_compose = ( + os.path.isfile(os.path.join(app_dir, "docker-compose.yaml")) or + os.path.isfile(os.path.join(app_dir, "docker-compose.yml")) + ) + + # Manifest Data parsing + raw_desc = manifest.get("description") + app_desc: str = str(raw_desc) if raw_desc is not None else "" + + raw_dom = manifest.get("domain") + app_dom = str(raw_dom) if raw_dom is not None else f"{canonical_name}.{HOMELAB_DOMAIN}" + + app_net = manifest.get("networks") + if not isinstance(app_net, list): + app_net = ["proxy-net"] + + app_env = manifest.get("env") + if not isinstance(app_env, dict): + app_env = {} + + def _as_bool(value: Any, default: bool) -> bool: + if isinstance(value, bool): + return value + return default + + app_vis = _as_bool(manifest.get("visible"), True) + app_auth = _as_bool(manifest.get("auth"), True) + + # Source provenance normalization + source_config: SourceConfig | None = None + raw_source = manifest.get("source") + if isinstance(raw_source, dict): + source_url = str(raw_source.get("url") or "") + allowed_schemes = ("https://", "ssh://", "git@") + if source_url: + if not any(source_url.startswith(s) for s in allowed_schemes): + err = f"Invalid source.url scheme: must start with {', '.join(allowed_schemes)}" + manifest_error = f"{manifest_error}; {err}" if manifest_error else err + else: + source_config = SourceConfig( + type=str(raw_source.get("type") or "git"), + url=source_url, + ref=str(raw_source.get("ref") or "main"), + ) + + return SitesApp( + name=canonical_name, + dir_name=raw_dir_name, + source=source_config, + description=app_desc, + domain=app_dom, + dir_path=app_dir, + has_compose=has_compose, + aliases=aliases, + visible=app_vis, + auth=app_auth, + networks=app_net, + env=app_env, + homepage=homepage_config, + manifest_error=manifest_error, + ) + + + +def get_sites_apps(sites_dir: str | None = None) -> list[SitesApp]: + """ + Scan the given sites directory (defaulting to SITES_DIR) for application. + """ + target_dir = sites_dir or SITES_DIR + apps: list[SitesApp] = [] + if not os.path.isdir(target_dir): + return apps + + for entry in sorted(os.listdir(target_dir)): + app_dir = os.path.join(target_dir, entry) + # skip hidden or null directories + if entry.startswith(".") or not os.path.isdir(app_dir): + continue + manifest_path = os.path.join(app_dir, "app.yaml") + manifest: dict[str, Any] = {} + manifest_error: str | None = None + + if os.path.isfile(manifest_path): + try: + manifest = load_manifest(manifest_path=manifest_path) + except ManifestError as err: + manifest_error = str(err) + apps.append(sites_app_from_manifest(app_dir, manifest, manifest_error)) + + return apps + +def resolve_app( + query: str, + apps: list[SitesApp] | None = None, + sites_dir: str | None = None +) -> SitesApp | None: + + if apps is None: + apps = get_sites_apps(sites_dir= sites_dir if sites_dir is not None else SITES_DIR) + + query_clean = query.strip().lower() + + # 1. Extract match on canonical name + for app in apps: + if app.name.lower() == query_clean: + return app + + # 2. Match on alias + for app in apps: + if any(alias.lower() == query_clean for alias in app.aliases): + return app + + # 3. Match directory name + for app in apps: + if app.dir_name.lower() == query_clean: + return app + # 4. Match stripped 'homelab-' prefix + for app in apps: + if app.dir_name.lower() == f"homelab-{query_clean}": + return app + + return None + +def get_core_services(core_dir: str | None = None) -> list[CoreService]: + """Return the strongly-typed registry of Core platform services.""" + return [ + CoreService( + name="traefik", + domain=f"traefik.{HOMELAB_DOMAIN}", + container="traefik", + description="Edge Reverse Proxy & ACME TLS", + icon="traefik.png", + weight=10, + ), + CoreService( + name="authelia", + domain=f"auth.{HOMELAB_DOMAIN}", + container="authelia", + description="Identity & SSO Access Control", + icon="authelia.png", + weight=20, + ), + CoreService( + name="lldap", + domain=f"users.{HOMELAB_DOMAIN}", + container="lldap", + description="Lightweight LDAP User Directory", + icon="lldap.png", + weight=25, + ), + CoreService( + name="stalwart", + domain=f"mail.{HOMELAB_DOMAIN}", + container="stalwart", + description="All-in-one Mail Server", + icon="email.png", + weight=26, + ), + + CoreService( + name="portainer", + domain=f"portainer.{HOMELAB_DOMAIN}", + container="portainer", + description="Container Management GUI", + icon="portainer.png", + weight=30, + ), + CoreService( + name="dozzle", + domain=f"logs.{HOMELAB_DOMAIN}", + container="dozzle", + description="Real-time Log Viewer", + icon="dozzle.png", + weight=40, + ), + CoreService( + name="socket-proxy", + domain="internal", + container="socket-proxy", + description="Docker Socket Security Proxy", + ), + CoreService( + name="homepage", + domain=f"dashboard.{HOMELAB_DOMAIN}", + container="homepage", + description="Application Dashboard & System Portal", + icon="homepage.png", + weight=5, + ), + CoreService( + name="diun", + domain="internal", + container="diun", + description="Docker Image Update Notifier", + ), + CoreService( + name="watchtower", + domain="internal", + container="watchtower", + description="Automated Container Updates", + ), + ] + + +def get_docker_status( + dir_path: str | Path, + container_name: str | None = None, +) -> str: + """Get container running status for a docker-compose directory or single Core container.""" + try: + if container_name: + inspect_res = subprocess.run( + ["docker", "inspect", "-f", "{{.State.Running}}", container_name], + capture_output=True, + text=True, + check=False, + ) + state = inspect_res.stdout.strip() + if state.lower() == "true": + return "🟢 Running (1)" + return "🔴 Stopped" + + path = Path(dir_path) + if path.exists() and not (path / "docker-compose.yml").is_file() and not (path / "docker-compose.yaml").is_file(): + return "⚪ Not Stack" + + res = subprocess.run( + ["docker", "compose", "ps", "-q"], + cwd=str(path), + capture_output=True, + text=True, + check=False, + ) + container_ids = [c for c in res.stdout.strip().splitlines() if c] + if not container_ids: + return "🔴 Stopped" + + inspect_res = subprocess.run( + ["docker", "inspect", "-f", "{{.State.Running}}"] + container_ids, + capture_output=True, + text=True, + check=False, + ) + running_states = inspect_res.stdout.strip().splitlines() + running_count = sum(1 for s in running_states if s.lower() == "true") + total_count = len(container_ids) + + if running_count == total_count and total_count > 0: + return f"🟢 Running ({running_count})" + elif running_count > 0: + return f"🟡 Degraded ({running_count}/{total_count})" + else: + return "🔴 Stopped" + except (subprocess.SubprocessError, OSError): + return "❓ Unknown" + + +def get_docker_image_revision( + dir_path: str | Path | None = None, + container_name: str | None = None, +) -> str | None: + """Extract `org.opencontainers.image.revision` label from running container.""" + try: + target: str | None = container_name + if not target and dir_path: + res = subprocess.run( + ["docker", "compose", "ps", "-q"], + cwd=str(dir_path), + capture_output=True, + text=True, + check=False, + ) + ids = [c for c in res.stdout.strip().splitlines() if c] + if ids: + target = ids[0] + + if not target: + return None + + inspect_res = subprocess.run( + [ + "docker", + "inspect", + "-f", + '{{ index .Config.Labels "org.opencontainers.image.revision" }}', + target, + ], + capture_output=True, + text=True, + check=False, + ) + revision = inspect_res.stdout.strip() + if revision and revision != "": + return revision + return None + except (subprocess.SubprocessError, OSError): + return None + +def cmd_sync_homepage(args) -> None: + pass diff --git a/scripts/gitops_dispatcher.py b/scripts/gitops_dispatcher.py index fc7857f..d1726e1 100755 --- a/scripts/gitops_dispatcher.py +++ b/scripts/gitops_dispatcher.py @@ -722,6 +722,7 @@ def main(): sys.exit(0 if "Branch mismatch" in reason else 1) logger.info(f"✅ Webhook admission passed: {reason}") + assert target_dir is not None, "admitted deployment must have a valid target directory" commit_sha = payload.get("after", "") if not commit_sha and isinstance(payload.get("head_commit"), dict): commit_sha = payload.get("head_commit", {}).get("id", "") diff --git a/tests/unit/test_appctl_engine_v2.py b/tests/unit/test_appctl_engine_v2.py new file mode 100644 index 0000000..d915316 --- /dev/null +++ b/tests/unit/test_appctl_engine_v2.py @@ -0,0 +1,338 @@ +import sys +from dataclasses import dataclass +from pathlib import Path +from unittest.mock import MagicMock + +import pytest + +# Import appctl engine v2 +CORE_ROOT = Path(__file__).resolve().parent.parent.parent +sys.path.insert(0, str(CORE_ROOT / "scripts")) + +import appctl_engine_v2 as engine + + +@dataclass +class AppFactory: + """Helper class to generate mock app directories and configurations""" + sites_dir: Path + + def create( + self, + dir_name: str, + manifest_yaml: str = "", + has_compose: bool = True, + ) -> Path: + app_dir: Path = self.sites_dir / dir_name + app_dir.mkdir(parents=True, exist_ok=True) + if manifest_yaml: + (app_dir / "app.yaml").write_text(manifest_yaml, encoding="utf-8") + if has_compose: + (app_dir / "docker-compose.yml").write_text("services: {}\n", encoding="utf-8") + return app_dir + +@pytest.fixture +def mock_sites_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + """Fixture that creates an isolated Sites directory and points engine.SITES_DIR to it""" + sites = tmp_path / "Sites" + monkeypatch.setattr(engine, "SITES_DIR", str(sites)) + monkeypatch.setattr(engine, "HOMELAB_DOMAIN", "mydomain.test") + return sites + +@pytest.fixture +def app_factory(mock_sites_dir: Path) -> AppFactory: + """Fixture that provides the AppFactory instance to test""" + return AppFactory(mock_sites_dir) + +@pytest.fixture +def mock_core_dir( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch +) -> Path: + """Fixture that creates an isolated Core directory and points engine.CORE_DIR to it""" + core = tmp_path / "CORE" + core.mkdir(parents=True, exist_ok=True) + return core + +## GREEN TEST: Existing implementation should not break + +def test_resolve_app_hierarchy(app_factory: AppFactory): + """Ensure resolution follows: Canonical Name > Alias > Dir Name > Prefix""" + app_factory.create( + dir_name="homelab-jellyfin", + manifest_yaml=""" + name: media-server + aliases: + - movies + """, + ) + apps = engine.get_sites_apps() + + assert engine.resolve_app("media-server", apps) is not None + assert engine.resolve_app("movies", apps) is not None + assert engine.resolve_app("homelab-jellyfin", apps) is not None + assert engine.resolve_app("unknown", apps) is None + +def test_manifest_data_overrides_default_values(app_factory: AppFactory): + """Ensure app.yaml values successfully override the system defaults""" + app_factory.create( + dir_name="homelab-custom", + manifest_yaml=""" + name: custom-app + domain: custom.roadtotech.local + auth: false + visible: false + networks: + - custom-net + """ + ) + + apps = engine.get_sites_apps() + app = engine.resolve_app("custom-app", apps) + + assert app is not None + assert app.domain == "custom.roadtotech.local" + assert app.auth is False + assert app.networks == ["custom-net"] + +def test_sites_app_normalization(app_factory: AppFactory): + """Ensure missing or badly typed manifest fields are safely normalized""" + app_factory.create( + dir_name="homelab-custom", + manifest_yaml=""" + name: testapp + # Missing domain - should fallback to .roadtotech.me + aliases: single-string-alias # should become a list[str] + auth: "False" # should evaluate based on boolean casting + homepage: + weight: "99" # this should be casted as an int + """ + ) + apps = engine.get_sites_apps() + app = engine.resolve_app("testapp", apps) + + assert app is not None + assert app.name == "testapp" + assert app.domain == "testapp.mydomain.test" + assert app.aliases == ["single-string-alias"] + assert app.auth is True + assert app.homepage is not None + assert app.homepage.weight == 99 + + +def test_sites_app_source_provenance_normalization(app_factory: AppFactory): + """Ensure source provenance block is correctly parsed into SourceConfig""" + # 1. Source-backed app with explicit ref + app_factory.create( + dir_name="homelab-bitetrack", + manifest_yaml=""" + name: bitetrack + source: + type: git + url: https://git.roadtotech.me/kiskaadee/bitetrack.git + ref: v1.2.0 + """ + ) + # 2. Source-backed app with default ref (main) + app_factory.create( + dir_name="homelab-doc2site", + manifest_yaml=""" + name: doc2site + source: + url: https://git.roadtotech.me/kiskaadee/doc2site.git + """ + ) + # 3. Image-only app (no source block) + app_factory.create( + dir_name="homelab-jellyfin", + manifest_yaml=""" + name: jellyfin + """ + ) + + apps = engine.get_sites_apps() + + bitetrack = engine.resolve_app("bitetrack", apps) + assert bitetrack is not None + assert bitetrack.source is not None + assert bitetrack.source.type == "git" + assert bitetrack.source.url == "https://git.roadtotech.me/kiskaadee/bitetrack.git" + assert bitetrack.source.ref == "v1.2.0" + assert bitetrack.to_dict()["source"]["ref"] == "v1.2.0" + + doc2site = engine.resolve_app("doc2site", apps) + assert doc2site is not None + assert doc2site.source is not None + assert doc2site.source.ref == "main" + + jellyfin = engine.resolve_app("jellyfin", apps) + assert jellyfin is not None + assert jellyfin.source is None + assert jellyfin.to_dict()["source"] is None + + # 4. App with illegal source transport (e.g. file://) + app_factory.create( + dir_name="homelab-malformed", + manifest_yaml=""" + name: malformed + source: + url: file:///etc/passwd + """ + ) + apps_updated = engine.get_sites_apps() + malformed = engine.resolve_app("malformed", apps_updated) + assert malformed is not None + assert malformed.source is None + assert malformed.manifest_error is not None + assert "Invalid source.url scheme" in malformed.manifest_error + + +## RED TESTS: TDD Goals for next implementation + +def test_docker_status_parser_running(monkeypatch): + """Ensure get_docker_status reports running compose stack when all containers are running.""" + def mock_run(args, **kwargs): + mock = MagicMock() + if "ps" in args: + mock.stdout = "container123\n" + if "inspect" in args: + mock.stdout = "true\n" + return mock + + monkeypatch.setattr("subprocess.run", mock_run) + + status = engine.get_docker_status("/fake/dir") + assert status == "🟢 Running (1)" + + +def test_docker_status_parser_stopped(monkeypatch): + """Ensure get_docker_status reports stopped when no containers exist.""" + def mock_run(args, **kwargs): + mock = MagicMock() + if "ps" in args: + mock.stdout = "" + return mock + + monkeypatch.setattr("subprocess.run", mock_run) + + status = engine.get_docker_status("/fake/dir") + assert status == "🔴 Stopped" + + +def test_docker_status_parser_degraded(monkeypatch): + """Ensure get_docker_status reports degraded when partial containers are running.""" + def mock_run(args, **kwargs): + mock = MagicMock() + if "ps" in args: + mock.stdout = "c1\nc2\n" + if "inspect" in args: + mock.stdout = "true\nfalse\n" + return mock + + monkeypatch.setattr("subprocess.run", mock_run) + + status = engine.get_docker_status("/fake/dir") + assert status == "🟡 Degraded (1/2)" + + +def test_docker_status_parser_not_stack(tmp_path: Path): + """Ensure get_docker_status reports Not Stack for real directory without compose file.""" + empty_dir = tmp_path / "empty_service" + empty_dir.mkdir() + assert engine.get_docker_status(empty_dir) == "⚪ Not Stack" + + +def test_docker_status_single_container(monkeypatch): + """Ensure get_docker_status inspects single Core container by name.""" + def mock_run(args, **kwargs): + mock = MagicMock() + if "authelia" in args: + mock.stdout = "true\n" + else: + mock.stdout = "false\n" + return mock + + monkeypatch.setattr("subprocess.run", mock_run) + + assert engine.get_docker_status("", container_name="authelia") == "🟢 Running (1)" + assert engine.get_docker_status("", container_name="traefik") == "🔴 Stopped" + + +def test_docker_status_error_handling(monkeypatch): + """Ensure get_docker_status handles subprocess failures gracefully.""" + def mock_err(*args, **kwargs): + raise OSError("Docker socket unreachable") + + monkeypatch.setattr("subprocess.run", mock_err) + assert engine.get_docker_status("/fake/dir") == "❓ Unknown" + + +def test_docker_image_revision_extraction(monkeypatch): + """Ensure get_docker_image_revision extracts org.opencontainers.image.revision.""" + def mock_run(args, **kwargs): + mock = MagicMock() + if "ps" in args: + mock.stdout = "container123\n" + if "inspect" in args: + mock.stdout = "9d82577f489f0d478e465a36077538d0ded16ba5\n" + return mock + + monkeypatch.setattr("subprocess.run", mock_run) + assert engine.get_docker_image_revision("/fake/dir") == "9d82577f489f0d478e465a36077538d0ded16ba5" + + def mock_run_empty(args, **kwargs): + mock = MagicMock() + if "ps" in args: + mock.stdout = "container123\n" + if "inspect" in args: + mock.stdout = "\n" + return mock + + monkeypatch.setattr("subprocess.run", mock_run_empty) + assert engine.get_docker_image_revision("/fake/dir") is None + +@pytest.mark.xfail(reason="TDD in progress: cmd_sync_homepage not yet implemented") +def test_homepage_sync_groups_and_sorts_correctly( + mock_core_dir: Path, + app_factory: AppFactory, + monkeypatch): + """ + TDD Goal: Port `cmd_sync_homepage` to V2 using the new Dataclass structure. + It must group by `homepage.group` and sort by `homepage.weight`. + """ + hp_config_dir = mock_core_dir / "config" / "homepage" + hp_config_dir.mkdir(parents=True, exist_ok=True) + + app_factory.create( + dir_name="homelab-app1", + manifest_yaml=""" + name: App1 + domain: app1.local.test + homepage: + title: App1 + group: Group B + weight: 20 + """ + ) + + app_factory.create( + dir_name="homelab-app2", + manifest_yaml=""" + name: App2 + domain: app2.local.test + homepage: + title: App2 + group: Group A + weight: 10 + """ + ) + + monkeypatch.setattr(engine, "get_core_services", list) + engine.cmd_sync_homepage(["--homepage-dir=" + str(hp_config_dir)]) + + output_file = hp_config_dir / "services.yaml" + assert output_file.exists(), "The services.yaml file must be generated" + + content = output_file.read_text() + assert content.find("- Group A") < content.find("- Group B") # Group A should appear before Group B + assert "App2" in content # App 2 is in the file diff --git a/uv.lock b/uv.lock new file mode 100644 index 0000000..9431a63 --- /dev/null +++ b/uv.lock @@ -0,0 +1,3 @@ +version = 1 +revision = 3 +requires-python = ">=3.11"