Source code for GUIBRUSHR.scripts.check_yaml_online

# GUIBRUSHR/scripts/check_yaml_online.py
"""
Online YAML change checker for GUIBRUSHR.
Detects whether configuration YAML files have been updated
in the remote repository (Git clone) or on PyPI (pip install).
"""

import importlib.metadata
import json
import subprocess
import urllib.request
from pathlib import Path

PACKAGE_NAME = "guibrushr"

YAML_FILENAMES = [
    "condensed.yaml",
    "general.yaml",
    "graphics.yaml",
    "hybrid_elements.yaml",
    "molecules.yaml",
    "parameters.yaml",
]

# ── Helpers ───────────────────────────────────────────────────────────────────

def _get_yaml_dir() -> Path:
    return Path(__file__).parent.parent.resolve() / "Files" / "Configuration_Yaml"

def _get_repo_root() -> Path | None:
    result = subprocess.run(
        ["git", "rev-parse", "--show-toplevel"],
        capture_output=True, text=True
    )
    return Path(result.stdout.strip()) if result.returncode == 0 else None

# ── Git mode ──────────────────────────────────────────────────────────────────

def _check_git(repo_root: Path) -> None:
    branch = subprocess.run(
        ["git", "rev-parse", "--abbrev-ref", "HEAD"],
        capture_output=True, text=True, cwd=repo_root
    ).stdout.strip()

    print(f" Fetching from origin/{branch}...")
    fetch = subprocess.run(
        ["git", "fetch", "origin", branch],
        capture_output=True, text=True, cwd=repo_root
    )
    if fetch.returncode != 0:
        print(f"\n ✗ Fetch failed: {fetch.stderr.strip()}\n")
        return

    yaml_dir = _get_yaml_dir()
    try:
        rel_yaml_dir = yaml_dir.relative_to(repo_root)
    except ValueError:
        print(" ✗ YAML directory is not inside the Git repository.\n")
        return

    changed = []
    for name in YAML_FILENAMES:
        rel_path = str(rel_yaml_dir / name)
        result = subprocess.run(
            ["git", "diff", "--name-only", "HEAD", f"origin/{branch}", "--", rel_path],
            capture_output=True, text=True, cwd=repo_root
        )
        if result.stdout.strip():
            changed.append(name)

    if changed:
        print(f"\n{len(changed)} YAML file(s) were modified in the remote repository:\n")
        for name in changed:
            print(f"    • {name}")
        print("\n → Run 'guibrushr-backup-yaml' to save your local version before pulling.")
        print(" → Then run 'git pull': remote files will overwrite local ones.\n")
    else:
        print("\n ✓ No changes to YAML files in the remote repository.\n")

# ── PyPI mode ─────────────────────────────────────────────────────────────────

def _check_pypi() -> None:
    try:
        installed = importlib.metadata.version(PACKAGE_NAME)
    except importlib.metadata.PackageNotFoundError:
        print(f"\n ✗ Package '{PACKAGE_NAME}' not found in the current environment.\n")
        return

    print(f" Installed version : {installed}")
    print(" Checking PyPI for latest version...")

    try:
        url = f"https://pypi.org/pypi/{PACKAGE_NAME}/json"
        with urllib.request.urlopen(url, timeout=8) as response:
            data = json.loads(response.read())
        latest = data["info"]["version"]
    except Exception as e:
        print(f"\n ✗ Could not reach PyPI: {e}\n")
        return

    print(f" Latest on PyPI     : {latest}\n")

    if installed == latest:
        print(" ✓ You are up to date. No YAML changes expected.\n")
    else:
        print(f" ⚠  A new version is available: {latest}")
        print("    Configuration YAML files may have been updated.")
        print("\n → Run 'guibrushr-backup-yaml' to save your local YAML files.")
        print(f" → Then: pip install --upgrade {PACKAGE_NAME}\n")

# ── Main ──────────────────────────────────────────────────────────────────────

[docs] def check_yaml_online_cli(): print("\n" + "=" * 50) print("GUIBRUSHR - Online YAML Change Checker") print("=" * 50 + "\n") repo_root = _get_repo_root() if repo_root is not None: print(f" Mode: Git repository ({repo_root})\n") _check_git(repo_root) else: print(" Mode: pip installation\n") _check_pypi()
if __name__ == "__main__": check_yaml_online_cli()