Skip to content

Index

core

Core logic — subprocess runners and semver computation.

GitIdentity

Bases: BaseModel

A git author identity.

Source code in packages/axm-git/src/axm_git/core/identity.py
Python
class GitIdentity(BaseModel):  # type: ignore[explicit-any]  # pydantic BaseModel exposes Any in its API
    """A git author identity."""

    name: str
    email: str

GitProfileConfig

Bases: BaseModel

Full git-profiles.toml configuration.

Source code in packages/axm-git/src/axm_git/core/identity.py
Python
class GitProfileConfig(BaseModel):  # type: ignore[explicit-any]  # pydantic BaseModel exposes Any in its API
    """Full git-profiles.toml configuration."""

    default: GitIdentity
    profiles: dict[str, GitIdentity] = {}
    schedule: Schedule = Schedule()
    workspace_paths: list[Path] = []
    timezone: str = "Europe/Paris"

attempt_commit_with_autofix_retry(cmd, files, git_root, first_result, *, working_dir=None)

Re-stage + retry cmd once when a commit hook auto-fixed files.

Detection is on the combined stdout+stderr of first_result: when the canonical "files were modified" marker is present, the modified files are captured (git diff --name-only before re-staging), the spec files are re-staged via the subdir-aware resolver, and cmd is retried once. Otherwise first_result is returned unchanged.

Source code in packages/axm-git/src/axm_git/core/commit_spec.py
Python
def attempt_commit_with_autofix_retry(
    cmd: list[str],
    files: list[str],
    git_root: Path,
    first_result: _GitResultLike,
    *,
    working_dir: Path | None = None,
) -> AutofixRetry:
    """Re-stage + retry *cmd* once when a commit hook auto-fixed files.

    Detection is on the combined stdout+stderr of *first_result*: when the
    canonical ``"files were modified"`` marker is present, the modified
    files are captured (``git diff --name-only`` *before* re-staging), the
    spec *files* are re-staged via the subdir-aware resolver, and *cmd* is
    retried once.  Otherwise *first_result* is returned unchanged.
    """
    if first_result.returncode == 0:
        return AutofixRetry(result=first_result, retried=False, auto_fixed=[])

    output = first_result.stdout + first_result.stderr
    if AUTOFIX_MARKER not in output:
        return AutofixRetry(result=first_result, retried=False, auto_fixed=[])

    logger.warning("Commit hook auto-fixed files, re-staging and retrying")
    diff = run_git(["diff", "--name-only"], git_root)
    auto_fixed = [f for f in diff.stdout.strip().splitlines() if f.strip()]

    restage_err = stage_spec_files(files, git_root, working_dir=working_dir)
    if restage_err:
        failed = cast(
            "_GitResultLike",
            SimpleNamespace(returncode=1, stdout="", stderr=restage_err),
        )
        return AutofixRetry(result=failed, retried=True, auto_fixed=auto_fixed)

    retried = run_git(cmd, git_root)
    return AutofixRetry(result=retried, retried=True, auto_fixed=auto_fixed)

author_args(identity)

Build --author arguments for a git command.

Source code in packages/axm-git/src/axm_git/core/identity.py
Python
def author_args(identity: GitIdentity | None) -> list[str]:
    """Build ``--author`` arguments for a git command."""
    if identity is None:
        return []
    return ["--author", f"{identity.name} <{identity.email}>"]

build_commit_result(git_root, message, identity, warnings)

Build a successful commit :class:HookResult.

Reads the current HEAD short hash and assembles the result dict with optional identity and warning fields.

Source code in packages/axm-git/src/axm_git/core/commit_spec.py
Python
def build_commit_result(
    git_root: Path,
    message: str,
    identity: GitIdentity | None,
    warnings: list[str],
) -> HookResult:
    """Build a successful commit :class:`HookResult`.

    Reads the current HEAD short hash and assembles the result dict
    with optional identity and warning fields.
    """
    hash_result = run_git(["rev-parse", "--short", "HEAD"], git_root)
    result_kw: dict[str, Any] = {  # type: ignore[explicit-any]  # heterogeneous metadata payload for HookResult.ok(**metadata: Any)
        "commit": hash_result.stdout.strip(),
        "message": message,
    }
    if identity:
        result_kw["author_name"] = identity.name
        result_kw["author_email"] = identity.email
    if warnings:
        result_kw["warnings"] = warnings
    return HookResult.ok(**result_kw)

load_config(config_path=None)

Load and validate a git-profiles TOML config file.

File-absent returns None silently. File-present-but-malformed returns None and emits a WARNING referencing path and the exception class. After successful parse, also warns when schedule.rules is non-empty but workspace_paths is empty (governance config is configured but cannot apply).

Source code in packages/axm-git/src/axm_git/core/identity.py
Python
def load_config(config_path: Path | None = None) -> GitProfileConfig | None:
    """Load and validate a git-profiles TOML config file.

    File-absent returns ``None`` silently. File-present-but-malformed
    returns ``None`` and emits a ``WARNING`` referencing *path* and the
    exception class. After successful parse, also warns when
    ``schedule.rules`` is non-empty but ``workspace_paths`` is empty
    (governance config is configured but cannot apply).
    """
    path = config_path or _DEFAULT_CONFIG_PATH
    try:
        data = path.read_bytes()
    except FileNotFoundError:
        return None
    except OSError as exc:
        logger.warning(
            "Cannot read git-profiles config at %s: %s", path, exc.__class__.__name__
        )
        return None
    if not data:
        return None
    try:
        parsed: dict[str, object] = tomllib.loads(data.decode())
        config = GitProfileConfig.model_validate(parsed)
    except (tomllib.TOMLDecodeError, ValueError, KeyError) as exc:
        logger.warning(
            "Invalid git-profiles config at %s: %s", path, exc.__class__.__name__
        )
        return None
    if config.schedule.rules and not config.workspace_paths:
        logger.warning(
            "git-profiles config at %s defines schedule.rules but "
            "workspace_paths is empty — schedule is inert",
            path,
        )
    return config

resolve_identity(workspace_path, *, now=None, profile_override=None, config_path=None)

Resolve the git identity for the given workspace.

Returns None when no config is available or an unknown profile is requested via profile_override. An unknown profile_override (a typo, or a request against an empty profile set) emits a WARNING naming the requested profile and the available ones before falling back to None — observability, not a hard failure.

Source code in packages/axm-git/src/axm_git/core/identity.py
Python
def resolve_identity(
    workspace_path: Path,
    *,
    now: datetime | None = None,
    profile_override: str | None = None,
    config_path: Path | None = None,
) -> GitIdentity | None:
    """Resolve the git identity for the given workspace.

    Returns ``None`` when no config is available or an unknown profile
    is requested via *profile_override*. An unknown *profile_override*
    (a typo, or a request against an empty profile set) emits a
    ``WARNING`` naming the requested profile and the available ones
    before falling back to ``None`` — observability, not a hard failure.
    """
    config = load_config(config_path)
    if config is None:
        return None

    override = resolve_by_override(config, profile_override)
    if profile_override is not None:
        return override

    tz = ZoneInfo(config.timezone)
    if now is None:
        effective_now = datetime.now(tz=tz)
    elif now.tzinfo is None:
        effective_now = now
    else:
        effective_now = now.astimezone(tz)
    return resolve_by_schedule(config, workspace_path, effective_now) or config.default

retry_commit_on_autofix(files, cmd, git_root, first_result, *, working_dir=None)

Hook-facing wrapper: return only the retried GitResult.

Thin adapter over :func:attempt_commit_with_autofix_retry for callers that only need the final result object (the commit-phase hook).

Source code in packages/axm-git/src/axm_git/core/commit_spec.py
Python
def retry_commit_on_autofix(
    files: list[str],
    cmd: list[str],
    git_root: Path,
    first_result: _GitResultLike,
    *,
    working_dir: Path | None = None,
) -> _GitResultLike:
    """Hook-facing wrapper: return only the retried GitResult.

    Thin adapter over :func:`attempt_commit_with_autofix_retry` for callers
    that only need the final result object (the commit-phase hook).
    """
    return attempt_commit_with_autofix_retry(
        cmd, files, git_root, first_result, working_dir=working_dir
    ).result

validate_commit_spec(spec)

Validate a commit_spec dict (pure; stricter merged contract).

Requires a non-empty message AND a non-empty files list — the stricter of the two prior per-surface validators. Returns (spec, error_message) where spec is None when an error is set; each surface wraps the error string in its own result type.

Source code in packages/axm-git/src/axm_git/core/commit_spec.py
Python
def validate_commit_spec(
    spec: dict[str, object] | None,
) -> tuple[dict[str, object] | None, str | None]:
    """Validate a ``commit_spec`` dict (pure; stricter merged contract).

    Requires a non-empty ``message`` AND a non-empty ``files`` list — the
    stricter of the two prior per-surface validators.  Returns
    ``(spec, error_message)`` where *spec* is ``None`` when an error is set;
    each surface wraps the error string in its own result type.
    """
    if not spec:
        return None, "from_outputs=True but no commit_spec in context"
    if not isinstance(spec, dict):
        return None, "commit_spec must be a dict"
    missing = _REQUIRED_SPEC_KEYS - set(spec)
    if missing:
        return None, (
            f"commit_spec missing {', '.join(repr(k) for k in sorted(missing))}"
        )
    if not spec.get("files"):
        return None, "empty files list"
    if not spec.get("message"):
        return None, "empty message"
    return spec, None