Project: pygitweb
"""Project actions: run named scripts from ``pyproject.toml`` or ``actions.toml``.
Groups are named action sets (TUI tabs). Within a set, ``depends`` run in parallel
and ``run`` steps run in order (mise-style orchestration).
"""
from __future__ import annotations
import json
import os
import shutil
import subprocess
import tomllib
from abc import abstractmethod
from collections.abc import Callable
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
from pathlib import Path
from typing import Literal
from abcreg import AnnotatedABC # type: ignore[import-untyped]
_TOOL_TABLE = "pgt"
_ACTIONS_KEY = "actions"
_ACTIONS_FILE = "actions.toml"
_DEFAULT_SET_NAME = "default"
_FLAT_FILE_SET_NAME = "actions"
_MISE_SET_NAME = "mise"
_MISE_CONFIG_NAMES = ("mise.toml", ".mise.toml")
ActionSource = Literal["pgt", "mise"]
ActionStatus = Literal["running", "success", "failure"]
ActionProgress = Callable[[str, ActionStatus, str], None]
@dataclass(frozen=True, slots=True)
class RunTask:
"""A ``run`` step that invokes one action by name (mise ``{ task = ... }``)."""
task: str
@dataclass(frozen=True, slots=True)
class RunParallel:
"""A ``run`` step that invokes several actions in parallel (mise ``{ tasks = [...] }``)."""
tasks: tuple[str, ...]
RunStep = str | RunTask | RunParallel
@dataclass(frozen=True, slots=True)
class ActionSpec:
name: str
script: str = ""
args: tuple[str, ...] = ()
source: ActionSource = "pgt"
description: str = ""
depends: tuple[str, ...] = ()
run: tuple[RunStep, ...] = ()
hide: bool = False
@dataclass(frozen=True, slots=True)
class ActionSet:
"""A named group of actions the TUI can cycle through."""
name: str
specs: tuple[ActionSpec, ...]
def catalog_registry(sets: list[ActionSet]) -> dict[str, ActionSpec]:
"""Flat name → spec map. The same action name in two sets is an error."""
registry: dict[str, ActionSpec] = {}
owners: dict[str, str] = {}
for action_set in sets:
for spec in action_set.specs:
previous = owners.get(spec.name)
if previous is not None:
raise ValueError(
f"Duplicate action name {spec.name!r} in action sets {previous!r} and {action_set.name!r}"
)
owners[spec.name] = action_set.name
registry[spec.name] = spec
return registry
def set_registry(specs: list[ActionSpec] | tuple[ActionSpec, ...]) -> dict[str, ActionSpec]:
"""Name → spec map for one action set, including hidden actions."""
registry: dict[str, ActionSpec] = {}
for spec in specs:
if spec.name in registry:
raise ValueError(f"Duplicate action name {spec.name!r}")
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]
def referenced_task_names(spec: ActionSpec) -> set[str]:
"""Action names referenced by ``depends`` and ``run`` steps."""
names = set(spec.depends)
for step in spec.run:
if isinstance(step, RunTask):
names.add(step.task)
elif isinstance(step, RunParallel):
names.update(step.tasks)
return names
def root_visible_specs(specs: list[ActionSpec] | tuple[ActionSpec, ...]) -> list[ActionSpec]:
"""Visible actions not referenced by another visible action's depends/run.
Used for ``Run all`` so hubs cover their leaves without double-running.
"""
visible = visible_specs(specs)
referenced = {name for spec in visible for name in referenced_task_names(spec)}
return [spec for spec in visible if spec.name not in referenced]
class Action(AnnotatedABC):
"""Run a named project action and return ``(ok, message)``."""
@abstractmethod
def action(self, name: str) -> tuple[bool, str]: ...
def find_project_root(start: Path) -> Path | None:
"""Walk upward for ``pyproject.toml``, else ``actions.toml`` / mise config."""
current = start.resolve()
fallback: Path | None = None
for path in [current, *current.parents]:
if (path / "pyproject.toml").is_file():
return path
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)
def load_action_specs(project_root: Path) -> list[ActionSpec]:
"""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")
def load_action_sets(project_root: Path) -> list[ActionSet]:
"""Load action sets from ``pyproject.toml`` and a root ``actions.toml``.
``[tool.pgt].actions`` is one set (named ``default``, or ``[tool.pgt].name``).
``[tool.pgt.sets.<name>]`` tables are further sets. ``actions.toml`` may repeat
that shape, and each other top-level table is also a set. Within a set,
``depends`` run in parallel and ``run`` steps run in order.
.. code-block:: toml
[tool.pgt.sets.quality]
actions = [
{ name = "lint", script = "scripts/lint.py" },
{ name = "check", run = [{ task = "lint" }] },
]
"""
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)
_ensure_unique_action_names(list(action_set.specs), where=f"action set {action_set.name!r}")
_validate_action_refs(list(action_set.specs))
return sets
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 ""
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 ()
def load_action_catalog(project_root: Path) -> list[ActionSet]:
"""Load pgt action sets for the TUI (mise is not shown as a group)."""
return load_action_sets(project_root)
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}"
def run_action(
project_root: Path,
spec: ActionSpec,
*,
registry: dict[str, ActionSpec] | None = None,
on_action: ActionProgress | None = None,
_stack: tuple[str, ...] = (),
) -> tuple[bool, str]:
"""Run one catalog entry and report each action that runs, including dependencies."""
if on_action is not None:
on_action(spec.name, "running", "")
ok, message = _execute_action(project_root, spec, registry=registry, on_action=on_action, _stack=_stack)
if on_action is not None:
on_action(spec.name, "success" if ok else "failure", message)
return ok, message
def _execute_action(
project_root: Path,
spec: ActionSpec,
*,
registry: dict[str, ActionSpec] | None,
on_action: ActionProgress | None,
_stack: tuple[str, ...],
) -> tuple[bool, str]:
"""Dispatch one entry by ``spec.source``.
For pgt entries: ``depends`` run in parallel, then ``run`` steps in order, then
``script`` if set. Mise-sourced entries delegate to ``mise run``.
"""
if spec.source == "mise":
return run_mise_task(project_root, spec.name, spec.args)
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}"
stack = (*_stack, spec.name)
ok, message = _run_named_actions_parallel(
project_root,
spec.depends,
registry=names,
stack=stack,
on_action=on_action,
unknown_prefix="Unknown depends",
)
if not ok:
return False, message
last_message = message
for step in spec.run:
ok, message = _run_step(project_root, step, registry=names, stack=stack, on_action=on_action)
if not ok:
return False, message
last_message = message
if not spec.script:
return True, last_message
return run_action_script(project_root, spec.script, spec.args)
def _run_step(
project_root: Path,
step: RunStep,
*,
registry: dict[str, ActionSpec],
stack: tuple[str, ...],
on_action: ActionProgress | None,
) -> tuple[bool, str]:
if isinstance(step, str):
return _run_shell_command(project_root, step)
if isinstance(step, RunTask):
return _run_named_actions_parallel(
project_root,
(step.task,),
registry=registry,
stack=stack,
on_action=on_action,
unknown_prefix="Unknown run task",
)
return _run_named_actions_parallel(
project_root,
step.tasks,
registry=registry,
stack=stack,
on_action=on_action,
unknown_prefix="Unknown run task",
)
def _run_named_actions_parallel(
project_root: Path,
names: tuple[str, ...],
*,
registry: dict[str, ActionSpec],
stack: tuple[str, ...],
on_action: ActionProgress | None,
unknown_prefix: str,
) -> tuple[bool, str]:
if not names:
return True, "ok"
specs: list[ActionSpec] = []
for name in names:
spec = registry.get(name)
if spec is None:
return False, f"{unknown_prefix}: {name}"
specs.append(spec)
if len(specs) == 1:
return run_action(project_root, specs[0], registry=registry, on_action=on_action, _stack=stack)
last_message = "ok"
failures: list[str] = []
with ThreadPoolExecutor(max_workers=len(specs)) as pool:
futures = {
pool.submit(
run_action,
project_root,
spec,
registry=registry,
on_action=on_action,
_stack=stack,
): spec.name
for spec in specs
}
for future in as_completed(futures):
ok, message = future.result()
if ok:
last_message = message
else:
failures.append(f"{futures[future]}: {message}")
if failures:
return False, failures[0]
return True, last_message
def _run_shell_command(project_root: Path, command: str) -> tuple[bool, str]:
env = os.environ.copy()
venv_python = project_venv_python(project_root)
if venv_python is not None:
venv_bin = venv_python.parent
env["VIRTUAL_ENV"] = str(venv_bin.parent)
env["PATH"] = f"{venv_bin}{os.pathsep}{env.get('PATH', '')}"
env.pop("PYTHONHOME", None)
proc = subprocess.run(
["bash", "-c", command],
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}"
def _ensure_unique_action_names(specs: list[ActionSpec], *, where: str) -> None:
seen: set[str] = set()
for spec in specs:
if spec.name in seen:
raise ValueError(f"Duplicate action name {spec.name!r} in {where}")
seen.add(spec.name)
def _validate_action_refs(specs: list[ActionSpec]) -> None:
names = {spec.name for spec in specs}
for spec in specs:
for ref in referenced_task_names(spec):
if ref not in names:
kind = "depends" if ref in spec.depends else "run"
raise ValueError(f"Unknown {kind} {ref!r} on action {spec.name!r}")
def _pyproject_pgt(project_root: Path) -> dict[str, object] | None:
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
def _pyproject_sets(project_root: Path) -> list[ActionSet]:
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
def _actions_file_sets(project_root: Path) -> list[ActionSet]:
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
def _parse_flat_set(
data: dict[str, object],
*,
default_name: str,
actions_where: str,
name_where: str,
) -> ActionSet | None:
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)
def _parse_named_tables(raw: object, *, where: str) -> list[ActionSet]:
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
def _specs_from_set_table(value: dict[str, object], *, where: str) -> tuple[ActionSpec, ...]:
if _ACTIONS_KEY not in value:
raise ValueError(f"{where} missing 'actions'")
return tuple(_parse_actions(value[_ACTIONS_KEY], where=f"{where}.actions"))
def _parse_actions(raw: object, *, where: str) -> list[ActionSpec]:
if not isinstance(raw, list):
raise ValueError(f"{where} must be an array of action entries")
specs: list[ActionSpec] = []
for index, entry in enumerate(raw):
specs.append(_parse_action_entry(entry, where=f"{where}[{index}]"))
return specs
def _parse_action_entry(entry: object, *, where: str) -> ActionSpec:
if isinstance(entry, dict):
name = entry.get("name")
if not isinstance(name, str) or not name.strip():
raise ValueError(f"{where} missing string 'name'")
depends = _parse_depends(entry.get("depends"), where=where)
run = _parse_run(entry.get("run"), where=where)
script = _parse_script(entry.get("script"), where=where, depends=depends, run=run)
return ActionSpec(
name=name.strip(),
script=script,
args=_parse_args(entry.get("args"), where=where),
description=_parse_description(entry.get("description"), where=where),
depends=depends,
run=run,
hide=_parse_hide(entry.get("hide"), where=where),
)
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]")
def _parse_script(
raw: object,
*,
where: str,
depends: tuple[str, ...],
run: tuple[RunStep, ...],
) -> str:
has_body = bool(depends) or bool(run)
if raw is None:
if not has_body:
raise ValueError(f"{where} requires 'script', 'depends', or 'run'")
return ""
if not isinstance(raw, str):
raise ValueError(f"{where} 'script' must be a string")
script = raw.strip()
if not script:
if not has_body:
raise ValueError(f"{where} requires 'script', 'depends', or 'run'")
return ""
return script
def _parse_run(raw: object, *, where: str) -> tuple[RunStep, ...]:
if raw is None:
return ()
if isinstance(raw, str):
command = raw.strip()
if not command:
raise ValueError(f"{where} 'run' string must be non-empty")
return (command,)
if not isinstance(raw, list):
raise ValueError(f"{where} 'run' must be a string or array of steps")
steps: list[RunStep] = []
for index, item in enumerate(raw):
steps.append(_parse_run_step(item, where=f"{where}.run[{index}]"))
if not steps:
raise ValueError(f"{where} 'run' must not be empty")
return tuple(steps)
def _parse_run_step(item: object, *, where: str) -> RunStep:
if isinstance(item, str):
command = item.strip()
if not command:
raise ValueError(f"{where} command must be a non-empty string")
return command
if not isinstance(item, dict):
raise ValueError(f"{where} must be a string, {{task=...}}, or {{tasks=[...]}}")
if "task" in item and "tasks" in item:
raise ValueError(f"{where} cannot set both 'task' and 'tasks'")
if "task" in item:
task = item.get("task")
if not isinstance(task, str) or not task.strip():
raise ValueError(f"{where} 'task' must be a non-empty string")
return RunTask(task=task.strip())
if "tasks" in item:
tasks_raw = item.get("tasks")
if not isinstance(tasks_raw, list) or not tasks_raw:
raise ValueError(f"{where} 'tasks' must be a non-empty array of strings")
tasks: list[str] = []
for index, name in enumerate(tasks_raw):
if not isinstance(name, str) or not name.strip():
raise ValueError(f"{where}.tasks[{index}] must be a non-empty string")
tasks.append(name.strip())
return RunParallel(tasks=tuple(tasks))
raise ValueError(f"{where} must be a string, {{task=...}}, or {{tasks=[...]}}")
def _parse_args(raw: object, *, where: str) -> tuple[str, ...]:
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)
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
def project_venv_python(project_root: Path) -> Path | None:
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
def run_action_script(project_root: Path, script: str, args: tuple[str, ...] = ()) -> tuple[bool, str]:
"""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}"
def _result_message(stdout: str, stderr: str) -> str:
text = (stdout or "").strip() or (stderr or "").strip()
if not text:
return ""
lines = text.splitlines()
return lines[-1] if lines else text
@Action.register
class ProjectActions:
"""Default action runner backed by ``[tool.pgt].actions``.
Pass ``specs`` to run a loaded list. Pass ``registry`` so ``depends`` can
resolve names outside that list.
"""
def __init__(
self,
project_root: Path,
specs: list[ActionSpec] | None = None,
*,
registry: dict[str, ActionSpec] | None = None,
on_action: ActionProgress | None = None,
) -> None:
self._root = project_root.resolve()
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)
self._on_action = on_action
@property
def specs(self) -> list[ActionSpec]:
return list(self._specs.values())
def action(self, name: str) -> tuple[bool, str]:
spec = self._specs.get(name)
if spec is None:
return False, f"Unknown action: {name}"
return run_action(self._root, spec, registry=self._registry, on_action=self._on_action)
def project_actions(project_root: Path) -> ProjectActions:
return ProjectActions(project_root)