Project: pygitweb

9f80683 """Project actions: run named scripts from ``pyproject.toml`` or ``actions.toml``.
Also discovers mise tasks (when ``mise`` is installed) as a dual-source catalog.
"""
from __future__ import annotations
9f80683 import json
053f925 import os
9f80683 import shutil
053f925 import subprocess
import tomllib
from abc import abstractmethod
from dataclasses import dataclass
from pathlib import Path
9f80683 from typing import Literal
053f925
from abcreg import AnnotatedABC # type: ignore[import-untyped]
_TOOL_TABLE = "pgt"
_ACTIONS_KEY = "actions"
966394d _ACTIONS_FILE = "actions.toml"
_DEFAULT_SET_NAME = "default"
_FLAT_FILE_SET_NAME = "actions"
9f80683 _MISE_SET_NAME = "mise"
_MISE_CONFIG_NAMES = ("mise.toml", ".mise.toml")
ActionSource = Literal["pgt", "mise"]
053f925
@dataclass(frozen=True, slots=True)
class ActionSpec:
73c9c30 name: str
script: str
args: tuple[str, ...] = ()
9f80683 source: ActionSource = "pgt"
description: str = ""
8ac8a11 depends: tuple[str, ...] = ()
hide: bool = False
966394d
@dataclass(frozen=True, slots=True)
class ActionSet:
73c9c30 """A named group of actions the TUI can cycle through."""
966394d
73c9c30 name: str
specs: tuple[ActionSpec, ...]
053f925
8ac8a11 def catalog_registry(sets: list[ActionSet]) -> dict[str, ActionSpec]:
"""Flat name → spec map across sets (last set wins on duplicate names)."""
registry: dict[str, ActionSpec] = {}
for action_set in sets:
for spec in action_set.specs:
registry[spec.name] = spec
return registry
def visible_specs(specs: list[ActionSpec] | tuple[ActionSpec, ...]) -> list[ActionSpec]:
return [spec for spec in specs if not spec.hide]
053f925 class Action(AnnotatedABC):
73c9c30 """Run a named project action and return ``(ok, message)``."""
053f925
73c9c30 @abstractmethod
def action(self, name: str) -> tuple[bool, str]: ...
053f925
def find_project_root(start: Path) -> Path | None:
9f80683 """Walk upward for ``pyproject.toml``, else ``actions.toml`` / mise config."""
73c9c30 current = start.resolve()
9f80683 fallback: Path | None = None
73c9c30 for path in [current, *current.parents]:
if (path / "pyproject.toml").is_file():
return path
9f80683 if fallback is None and ((path / _ACTIONS_FILE).is_file() or _has_mise_config(path)):
fallback = path
return fallback
def _has_mise_config(path: Path) -> bool:
return any((path / name).is_file() for name in _MISE_CONFIG_NAMES)
053f925
def load_action_specs(project_root: Path) -> list[ActionSpec]:
73c9c30 """Read ``[tool.pgt].actions`` from the project's ``pyproject.toml``."""
pgt = _pyproject_pgt(project_root)
if pgt is None:
return []
raw = pgt.get(_ACTIONS_KEY)
if raw is None:
return []
return _parse_actions(raw, where="[tool.pgt].actions")
966394d
def load_action_sets(project_root: Path) -> list[ActionSet]:
73c9c30 """Load action sets from ``pyproject.toml`` and a root ``actions.toml``.
966394d
73c9c30 ``[tool.pgt].actions`` is one set (named ``default``, or ``[tool.pgt].name``).
``[tool.pgt.sets.<name>]`` tables are further sets. ``actions.toml`` may repeat
8ac8a11 that shape, and each other top-level table is also a set. Action entries may
also set ``description``, ``depends``, and ``hide``.
966394d
73c9c30 .. code-block:: toml
966394d
73c9c30 [quality]
actions = [
{ name = "lint", script = "scripts/lint.py" },
]
"""
sets = [*_pyproject_sets(project_root), *_actions_file_sets(project_root)]
seen: set[str] = set()
for action_set in sets:
if action_set.name in seen:
raise ValueError(f"Duplicate action set name: {action_set.name}")
seen.add(action_set.name)
8ac8a11 _validate_depends(sets)
73c9c30 return sets
966394d
9f80683 def mise_available() -> bool:
return shutil.which("mise") is not None
def load_mise_action_specs(project_root: Path) -> list[ActionSpec]:
"""List non-hidden project mise tasks via ``mise tasks ls --json``.
Returns an empty list when mise is missing, fails, or reports no tasks.
"""
if not mise_available():
return []
try:
proc = subprocess.run(
["mise", "tasks", "ls", "--json", "--no-global"],
cwd=project_root,
capture_output=True,
text=True,
check=False,
)
except OSError:
return []
if proc.returncode != 0:
return []
try:
raw = json.loads(proc.stdout or "[]")
except json.JSONDecodeError:
return []
if not isinstance(raw, list):
return []
specs: list[ActionSpec] = []
for entry in raw:
spec = _mise_task_to_spec(entry)
if spec is not None:
specs.append(spec)
return specs
def _mise_task_to_spec(entry: object) -> ActionSpec | None:
if not isinstance(entry, dict):
return None
if entry.get("hide") is True:
return None
name = entry.get("name")
if not isinstance(name, str) or not name.strip():
return None
description = entry.get("description")
desc = description.strip() if isinstance(description, str) else ""
file_value = entry.get("file")
script = file_value.strip() if isinstance(file_value, str) else ""
8ac8a11 return ActionSpec(
name=name.strip(),
script=script,
source="mise",
description=desc,
depends=_mise_depends(entry.get("depends")),
)
def _mise_depends(raw: object) -> tuple[str, ...]:
"""Accept only simple string depends from mise JSON; ignore richer forms."""
if isinstance(raw, str) and raw.strip():
return (raw.strip(),)
if isinstance(raw, list):
names: list[str] = []
for item in raw:
if isinstance(item, str) and item.strip():
names.append(item.strip())
else:
return ()
return tuple(names)
return ()
9f80683
def load_action_catalog(project_root: Path) -> list[ActionSet]:
"""Load pgt action sets, then append a ``mise`` set when mise tasks exist."""
sets = load_action_sets(project_root)
mise_specs = load_mise_action_specs(project_root)
if not mise_specs:
return sets
if any(action_set.name == _MISE_SET_NAME for action_set in sets):
raise ValueError(f"Duplicate action set name: {_MISE_SET_NAME}")
8ac8a11 catalog = [*sets, ActionSet(name=_MISE_SET_NAME, specs=tuple(mise_specs))]
_validate_depends(catalog)
return catalog
9f80683
def run_mise_task(project_root: Path, name: str, args: tuple[str, ...] = ()) -> tuple[bool, str]:
"""Run ``mise run <name>`` in ``project_root`` and return ``(ok, message)``."""
if not mise_available():
return False, "mise not found on PATH"
cmd = ["mise", "run", name]
if args:
cmd.extend(["--", *args])
try:
proc = subprocess.run(
cmd,
cwd=project_root,
capture_output=True,
text=True,
check=False,
)
except OSError as exc:
return False, str(exc)
output = _result_message(proc.stdout, proc.stderr)
if proc.returncode == 0:
return True, output or "ok"
if output:
return False, output
return False, f"exit {proc.returncode}"
8ac8a11 def run_action(
project_root: Path,
spec: ActionSpec,
*,
registry: dict[str, ActionSpec] | None = None,
_stack: tuple[str, ...] = (),
) -> tuple[bool, str]:
"""Run one catalog entry, including ``depends``, dispatching by ``spec.source``.
Mise-sourced entries delegate depends to ``mise run`` itself. pgt entries resolve
``depends`` from ``registry`` (defaulting to ``{spec.name: spec}``).
"""
9f80683 if spec.source == "mise":
return run_mise_task(project_root, spec.name, spec.args)
8ac8a11 names = registry if registry is not None else {spec.name: spec}
if spec.name in _stack:
cycle = " -> ".join([*_stack, spec.name])
return False, f"Circular depends: {cycle}"
for dep_name in spec.depends:
dep = names.get(dep_name)
if dep is None:
return False, f"Unknown depends: {dep_name}"
ok, message = run_action(
project_root,
dep,
registry=names,
_stack=(*_stack, spec.name),
)
if not ok:
return False, message
9f80683 return run_action_script(project_root, spec.script, spec.args)
8ac8a11 def _validate_depends(sets: list[ActionSet]) -> None:
"""When any action declares ``depends``, action names must be unique and resolve."""
has_depends = any(spec.depends for action_set in sets for spec in action_set.specs)
if not has_depends:
return
owners: dict[str, str] = {}
for action_set in sets:
for spec in action_set.specs:
prior = owners.get(spec.name)
if prior is not None:
raise ValueError(
f"Duplicate action name {spec.name!r} in sets {prior!r} and {action_set.name!r} "
"(unique names required when depends is used)"
)
owners[spec.name] = action_set.name
for action_set in sets:
for spec in action_set.specs:
for dep in spec.depends:
if dep not in owners:
raise ValueError(f"Unknown depends {dep!r} on action {spec.name!r}")
966394d def _pyproject_pgt(project_root: Path) -> dict[str, object] | None:
73c9c30 pyproject = project_root / "pyproject.toml"
if not pyproject.is_file():
return None
data = tomllib.loads(pyproject.read_text(encoding="utf-8"))
tool = data.get("tool")
if not isinstance(tool, dict):
return None
pgt = tool.get(_TOOL_TABLE)
if not isinstance(pgt, dict):
return None
return pgt
966394d
def _pyproject_sets(project_root: Path) -> list[ActionSet]:
73c9c30 pgt = _pyproject_pgt(project_root)
if pgt is None:
return []
sets: list[ActionSet] = []
flat = _parse_flat_set(
pgt,
default_name=_DEFAULT_SET_NAME,
actions_where="[tool.pgt].actions",
name_where="[tool.pgt].name",
)
if flat is not None:
sets.append(flat)
raw_sets = pgt.get("sets")
if raw_sets is not None:
sets.extend(_parse_named_tables(raw_sets, where="[tool.pgt].sets"))
return sets
053f925
966394d def _actions_file_sets(project_root: Path) -> list[ActionSet]:
73c9c30 path = project_root / _ACTIONS_FILE
if not path.is_file():
return []
data = tomllib.loads(path.read_text(encoding="utf-8"))
if not isinstance(data, dict):
raise ValueError("actions.toml must be a table")
sets: list[ActionSet] = []
actions_value = data.get(_ACTIONS_KEY)
consumed = {"name"}
if isinstance(actions_value, list):
consumed.add(_ACTIONS_KEY)
flat = _parse_flat_set(
data,
default_name=_FLAT_FILE_SET_NAME,
actions_where="actions.toml actions",
name_where="actions.toml name",
)
if flat is not None:
sets.append(flat)
elif "name" in data:
raise ValueError("actions.toml 'name' requires an 'actions' array")
for key, value in data.items():
if key in consumed:
continue
if not isinstance(key, str) or not key.strip():
raise ValueError("actions.toml set name must be a non-empty string")
if not isinstance(value, dict):
raise ValueError(f"actions.toml unexpected key {key!r}")
specs = _specs_from_set_table(value, where=f"actions.toml [{key.strip()}]")
if specs:
sets.append(ActionSet(name=key.strip(), specs=specs))
return sets
966394d
def _parse_flat_set(
73c9c30 data: dict[str, object],
*,
default_name: str,
actions_where: str,
name_where: str,
966394d ) -> ActionSet | None:
73c9c30 if _ACTIONS_KEY not in data:
if "name" in data:
raise ValueError(f"{name_where} requires 'actions'")
return None
raw_name = data.get("name", default_name)
if not isinstance(raw_name, str) or not raw_name.strip():
raise ValueError(f"{name_where} must be a non-empty string")
specs = tuple(_parse_actions(data[_ACTIONS_KEY], where=actions_where))
if not specs:
return None
return ActionSet(name=raw_name.strip(), specs=specs)
966394d
def _parse_named_tables(raw: object, *, where: str) -> list[ActionSet]:
73c9c30 if not isinstance(raw, dict):
raise ValueError(f"{where} must be a table of action sets")
sets: list[ActionSet] = []
for key, value in raw.items():
if not isinstance(key, str) or not key.strip():
raise ValueError(f"{where} set name must be a non-empty string")
if not isinstance(value, dict):
raise ValueError(f"{where}.{key} must be a table")
name = key.strip()
specs = _specs_from_set_table(value, where=f"{where}.{name}")
if specs:
sets.append(ActionSet(name=name, specs=specs))
return sets
966394d
def _specs_from_set_table(value: dict[str, object], *, where: str) -> tuple[ActionSpec, ...]:
73c9c30 if _ACTIONS_KEY not in value:
raise ValueError(f"{where} missing 'actions'")
return tuple(_parse_actions(value[_ACTIONS_KEY], where=f"{where}.actions"))
966394d
def _parse_actions(raw: object, *, where: str) -> list[ActionSpec]:
73c9c30 if not isinstance(raw, list):
raise ValueError(f"{where} must be an array of name/script entries")
specs: list[ActionSpec] = []
for index, entry in enumerate(raw):
specs.append(_parse_action_entry(entry, where=f"{where}[{index}]"))
return specs
053f925
966394d def _parse_action_entry(entry: object, *, where: str) -> ActionSpec:
73c9c30 if isinstance(entry, dict):
name = entry.get("name")
script = entry.get("script")
if not isinstance(name, str) or not name.strip():
raise ValueError(f"{where} missing string 'name'")
if not isinstance(script, str) or not script.strip():
raise ValueError(f"{where} missing string 'script'")
8ac8a11 return ActionSpec(
name=name.strip(),
script=script.strip(),
args=_parse_args(entry.get("args"), where=where),
description=_parse_description(entry.get("description"), where=where),
depends=_parse_depends(entry.get("depends"), where=where),
hide=_parse_hide(entry.get("hide"), where=where),
)
73c9c30 if isinstance(entry, list) and len(entry) == 2:
name, script = entry
if not isinstance(name, str) or not name.strip():
raise ValueError(f"{where} name must be a non-empty string")
if not isinstance(script, str) or not script.strip():
raise ValueError(f"{where} script must be a non-empty string")
return ActionSpec(name=name.strip(), script=script.strip())
raise ValueError(f"{where} must be {{name=..., script=...}} or [name, script]")
966394d
def _parse_args(raw: object, *, where: str) -> tuple[str, ...]:
73c9c30 if raw is None:
return ()
if not isinstance(raw, list):
raise ValueError(f"{where} 'args' must be an array of strings")
args: list[str] = []
for index, item in enumerate(raw):
if not isinstance(item, str) or item == "":
raise ValueError(f"{where} args[{index}] must be a non-empty string")
args.append(item)
return tuple(args)
053f925
8ac8a11 def _parse_depends(raw: object, *, where: str) -> tuple[str, ...]:
if raw is None:
return ()
if isinstance(raw, str):
name = raw.strip()
if not name:
raise ValueError(f"{where} 'depends' string must be non-empty")
return (name,)
if not isinstance(raw, list):
raise ValueError(f"{where} 'depends' must be a string or array of strings")
depends: list[str] = []
for index, item in enumerate(raw):
if not isinstance(item, str) or not item.strip():
raise ValueError(f"{where} depends[{index}] must be a non-empty string")
depends.append(item.strip())
return tuple(depends)
def _parse_description(raw: object, *, where: str) -> str:
if raw is None:
return ""
if not isinstance(raw, str):
raise ValueError(f"{where} 'description' must be a string")
return raw.strip()
def _parse_hide(raw: object, *, where: str) -> bool:
if raw is None:
return False
if not isinstance(raw, bool):
raise ValueError(f"{where} 'hide' must be a boolean")
return raw
053f925 def project_venv_python(project_root: Path) -> Path | None:
73c9c30 candidate = project_root / ".venv" / "bin" / "python"
if candidate.is_file():
return candidate
windows = project_root / ".venv" / "Scripts" / "python.exe"
if windows.is_file():
return windows
return None
053f925
966394d def run_action_script(project_root: Path, script: str, args: tuple[str, ...] = ()) -> tuple[bool, str]:
73c9c30 """Execute ``script`` inside the project's ``.venv`` and return ``(ok, message)``."""
raw_script = Path(script)
script_path = raw_script.resolve() if raw_script.is_absolute() else (project_root / raw_script).resolve()
if not script_path.is_file():
return False, f"Script not found: {script_path}"
venv_python = project_venv_python(project_root)
if venv_python is None:
return False, f"Project venv not found under {project_root / '.venv'}"
venv_dir = venv_python.parent.parent
venv_bin = venv_python.parent
env = os.environ.copy()
env["VIRTUAL_ENV"] = str(venv_dir)
env["PATH"] = f"{venv_bin}{os.pathsep}{env.get('PATH', '')}"
env.pop("PYTHONHOME", None)
if script_path.suffix == ".py":
cmd = [str(venv_python), str(script_path), *args]
elif os.access(script_path, os.X_OK):
cmd = [str(script_path), *args]
else:
cmd = ["bash", str(script_path), *args]
proc = subprocess.run(
cmd,
cwd=project_root,
capture_output=True,
text=True,
env=env,
check=False,
)
output = _result_message(proc.stdout, proc.stderr)
if proc.returncode == 0:
return True, output or "ok"
if output:
return False, output
return False, f"exit {proc.returncode}"
053f925
def _result_message(stdout: str, stderr: str) -> str:
73c9c30 text = (stdout or "").strip() or (stderr or "").strip()
if not text:
return ""
lines = text.splitlines()
return lines[-1] if lines else text
053f925
@Action.register
class ProjectActions:
73c9c30 """Default action runner backed by ``[tool.pgt].actions``.
966394d
73c9c30 Pass ``specs`` to run one set loaded by :func:`load_action_sets`.
8ac8a11 Pass ``registry`` so ``depends`` can resolve names outside that set.
73c9c30 """
053f925
8ac8a11 def __init__(
self,
project_root: Path,
specs: list[ActionSpec] | None = None,
*,
registry: dict[str, ActionSpec] | None = None,
) -> None:
73c9c30 self._root = project_root.resolve()
8ac8a11 loaded = specs if specs is not None else load_action_specs(self._root)
self._specs = {spec.name: spec for spec in loaded}
self._registry = dict(self._specs) if registry is None else dict(registry)
053f925
73c9c30 @property
def specs(self) -> list[ActionSpec]:
return list(self._specs.values())
053f925
73c9c30 def action(self, name: str) -> tuple[bool, str]:
spec = self._specs.get(name)
if spec is None:
return False, f"Unknown action: {name}"
8ac8a11 return run_action(self._root, spec, registry=self._registry)
053f925
def project_actions(project_root: Path) -> ProjectActions:
73c9c30 return ProjectActions(project_root)