from __future__ import annotations

from ..errors import GitCommandError, GitRunError
from ..run import run


class GitPullArgsError(GitCommandError):
    """Raised when `git pull` with arbitrary args fails."""


def pull_args(
    args: list[str] | None = None,
    *,
    cwd: str = ".",
    preview: bool = False,
) -> None:
    """
    Execute `git pull` with caller-provided arguments.

    Examples:
      []                          -> git pull
      ["--ff-only"]               -> git pull --ff-only
      ["--rebase"]                -> git pull --rebase
      ["origin", "main"]          -> git pull origin main
    """
    extra = args or []
    try:
        run(["pull", *extra], cwd=cwd, preview=preview)
    except GitRunError as exc:
        details = getattr(exc, "output", None) or getattr(exc, "stderr", None) or ""
        raise GitPullArgsError(
            (
                f"Failed to run `git pull` with args={extra!r} "
                f"in cwd={cwd!r}.\n{details}"
            ).rstrip(),
            cwd=cwd,
        ) from exc
