Project: pygitweb

8fa7f0b """Project actions: run named tasks from ``pyproject.toml`` or ``actions.toml``.
04f3c66 Groups are named action sets (TUI tabs). Within a set, ``depends`` run in parallel
8fa7f0b and ``run`` steps run in order (mise-style orchestration). Task bodies use mise
``file`` / ``run`` (not pgt-only ``script``); invocation args are CLI/runtime only.
9f80683 """
from __future__ import annotations
9f80683 import json
053f925 import os
bae6568 import re
9f80683 import shutil
053f925 import subprocess
import tomllib
from abc import abstractmethod
bae6568 from collections.abc import Callable, Mapping
04f3c66 from concurrent.futures import ThreadPoolExecutor, as_completed
053f925 from dataclasses import dataclass
from pathlib import Path
9f80683 from typing import Literal
053f925
from abcreg import AnnotatedABC # type: ignore[import-untyped]
bae6568 from pygittools.tasks.args_parser import (
ParseError,
SpecParseError,
parse_argv,
parse_usage_spec,
render_help,
to_usage_env,
)
_USAGE_ENV_PREFIX = re.compile(r"^usage_")
053f925 _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"]
04f3c66 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
053f925
@dataclass(frozen=True, slots=True)
class ActionSpec:
73c9c30 name: str
8fa7f0b file: str = ""
73c9c30 args: tuple[str, ...] = ()
9f80683 source: ActionSource = "pgt"
description: str = ""
8ac8a11 depends: tuple[str, ...] = ()
04f3c66 run: tuple[RunStep, ...] = ()
8ac8a11 hide: bool = False
bae6568 usage: str = ""
raw_args: 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]:
04f3c66 """Flat name → spec map. The same action name in two sets is an error."""
8ac8a11 registry: dict[str, ActionSpec] = {}
04f3c66 owners: dict[str, str] = {}
8ac8a11 for action_set in sets:
for spec in action_set.specs:
04f3c66 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
8ac8a11 registry[spec.name] = spec
return registry
04f3c66 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
8ac8a11 def visible_specs(specs: list[ActionSpec] | tuple[ActionSpec, ...]) -> list[ActionSpec]:
return [spec for spec in specs if not spec.hide]
04f3c66 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]
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
04f3c66 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.
966394d
73c9c30 .. code-block:: toml
966394d
04f3c66 [tool.pgt.sets.quality]
actions = [
8fa7f0b { name = "lint", file = "scripts/lint.py" },
04f3c66 { name = "check", run = [{ task = "lint" }] },
]
73c9c30 """
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)
04f3c66 _ensure_unique_action_names(list(action_set.specs), where=f"action set {action_set.name!r}")
_validate_action_refs(list(action_set.specs))
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")
8fa7f0b file_path = file_value.strip() if isinstance(file_value, str) else ""
8ac8a11 return ActionSpec(
name=name.strip(),
8fa7f0b file=file_path,
8ac8a11 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]:
04f3c66 """Load pgt action sets for the TUI (mise is not shown as a group)."""
return load_action_sets(project_root)
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,
04f3c66 on_action: ActionProgress | None = None,
8ac8a11 _stack: tuple[str, ...] = (),
) -> tuple[bool, str]:
04f3c66 """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``.
8ac8a11
04f3c66 For pgt entries: ``depends`` run in parallel, then ``run`` steps in order, then
8fa7f0b ``file`` if set. Mise-sourced entries delegate to ``mise run``.
8ac8a11 """
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}"
04f3c66 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
bae6568
usage_env, forward_args, early = _resolve_usage(spec)
if early is not None:
return early
04f3c66 last_message = message
for step in spec.run:
bae6568 ok, message = _run_step(
project_root,
step,
registry=names,
stack=stack,
on_action=on_action,
environ=usage_env,
)
8ac8a11 if not ok:
return False, message
04f3c66 last_message = message
8fa7f0b if not spec.file:
04f3c66 return True, last_message
8fa7f0b return run_action_file(project_root, spec.file, forward_args, environ=usage_env)
bae6568
def _resolve_usage(
spec: ActionSpec,
*,
environ: Mapping[str, str] | None = None,
) -> tuple[dict[str, str], tuple[str, ...], tuple[bool, str] | None]:
8fa7f0b """Build env + file argv for one action from runtime ``spec.args``.
bae6568
Returns ``(env, forward_args, early_result)``. When ``early_result`` is set,
8fa7f0b the caller should return it without running the action body. Task-level
baked-in args are not part of the schema; use ``usage`` defaults instead.
bae6568 """
base = dict(environ if environ is not None else os.environ)
if not spec.raw_args:
base = {k: v for k, v in base.items() if not _USAGE_ENV_PREFIX.match(k)}
usage_text = spec.usage.strip()
if not usage_text:
return base, spec.args, None
try:
usage_spec = parse_usage_spec(usage_text, description=spec.description, name=spec.name)
except SpecParseError:
# Invalid usage: task still runs without argument parsing (mise behavior).
return base, spec.args, None
if not usage_spec.args and not usage_spec.flags:
return base, spec.args, None
try:
parsed = parse_argv(usage_spec, spec.args, environ=base)
except ParseError as exc:
return base, (), (False, str(exc))
if parsed.help_requested:
return base, (), (True, render_help(usage_spec).rstrip())
env = dict(base)
env.update(to_usage_env(parsed.values))
return env, (), None
9f80683
04f3c66 def _run_step(
project_root: Path,
step: RunStep,
*,
registry: dict[str, ActionSpec],
stack: tuple[str, ...],
on_action: ActionProgress | None,
bae6568 environ: Mapping[str, str] | None = None,
04f3c66 ) -> tuple[bool, str]:
if isinstance(step, str):
bae6568 return _run_shell_command(project_root, step, environ=environ)
04f3c66 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
bae6568 def _run_shell_command(
project_root: Path,
command: str,
*,
environ: Mapping[str, str] | None = None,
) -> tuple[bool, str]:
env = dict(environ if environ is not None else os.environ)
04f3c66 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}")
8ac8a11
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):
04f3c66 raise ValueError(f"{where} must be an array of action entries")
73c9c30 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")
if not isinstance(name, str) or not name.strip():
raise ValueError(f"{where} missing string 'name'")
8fa7f0b if "script" in entry:
raise ValueError(f"{where} uses 'script'; use mise 'file' (or 'run') instead")
if "args" in entry:
raise ValueError(f"{where} uses task-level 'args'; set defaults in 'usage' or pass args at invoke time")
04f3c66 depends = _parse_depends(entry.get("depends"), where=where)
run = _parse_run(entry.get("run"), where=where)
8fa7f0b file_path = _parse_file(entry.get("file"), where=where, depends=depends, run=run)
8ac8a11 return ActionSpec(
name=name.strip(),
8fa7f0b file=file_path,
8ac8a11 description=_parse_description(entry.get("description"), where=where),
04f3c66 depends=depends,
run=run,
8ac8a11 hide=_parse_hide(entry.get("hide"), where=where),
bae6568 usage=_parse_usage(entry.get("usage"), where=where),
raw_args=_parse_raw_args(entry.get("raw_args"), where=where),
8ac8a11 )
73c9c30 if isinstance(entry, list) and len(entry) == 2:
8fa7f0b name, file_path = entry
73c9c30 if not isinstance(name, str) or not name.strip():
raise ValueError(f"{where} name must be a non-empty string")
8fa7f0b if not isinstance(file_path, str) or not file_path.strip():
raise ValueError(f"{where} file must be a non-empty string")
return ActionSpec(name=name.strip(), file=file_path.strip())
raise ValueError(f"{where} must be {{name=..., file=...}} or [name, file]")
966394d
8fa7f0b def _parse_file(
04f3c66 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:
8fa7f0b raise ValueError(f"{where} requires 'file', 'depends', or 'run'")
04f3c66 return ""
if not isinstance(raw, str):
8fa7f0b raise ValueError(f"{where} 'file' must be a string")
file_path = raw.strip()
if not file_path:
04f3c66 if not has_body:
8fa7f0b raise ValueError(f"{where} requires 'file', 'depends', or 'run'")
04f3c66 return ""
8fa7f0b return file_path
04f3c66
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=[...]}}")
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
bae6568 def _parse_usage(raw: object, *, where: str) -> str:
if raw is None:
return ""
if not isinstance(raw, str):
raise ValueError(f"{where} 'usage' must be a string")
return raw.strip()
def _parse_raw_args(raw: object, *, where: str) -> bool:
if raw is None:
return False
if not isinstance(raw, bool):
raise ValueError(f"{where} 'raw_args' 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
8fa7f0b def run_action_file(
bae6568 project_root: Path,
8fa7f0b file: str,
bae6568 args: tuple[str, ...] = (),
*,
environ: Mapping[str, str] | None = None,
) -> tuple[bool, str]:
8fa7f0b """Execute a mise-style ``file`` task inside the project's ``.venv``."""
raw_file = Path(file)
file_path = raw_file.resolve() if raw_file.is_absolute() else (project_root / raw_file).resolve()
if not file_path.is_file():
return False, f"Script not found: {file_path}"
73c9c30
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
bae6568 env = dict(environ if environ is not None else os.environ)
73c9c30 env["VIRTUAL_ENV"] = str(venv_dir)
env["PATH"] = f"{venv_bin}{os.pathsep}{env.get('PATH', '')}"
env.pop("PYTHONHOME", None)
8fa7f0b if file_path.suffix == ".py":
cmd = [str(venv_python), str(file_path), *args]
elif os.access(file_path, os.X_OK):
cmd = [str(file_path), *args]
73c9c30 else:
8fa7f0b cmd = ["bash", str(file_path), *args]
73c9c30
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
04f3c66 Pass ``specs`` to run a loaded list. Pass ``registry`` so ``depends`` can
resolve names outside that list.
73c9c30 """
053f925
8ac8a11 def __init__(
self,
project_root: Path,
specs: list[ActionSpec] | None = None,
*,
registry: dict[str, ActionSpec] | None = None,
04f3c66 on_action: ActionProgress | None = None,
8ac8a11 ) -> 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)
04f3c66 self._on_action = on_action
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}"
04f3c66 return run_action(self._root, spec, registry=self._registry, on_action=self._on_action)
053f925
def project_actions(project_root: Path) -> ProjectActions:
73c9c30 return ProjectActions(project_root)