Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
122 changes: 41 additions & 81 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@
RUNNER_FAILURES = (runners.RunnerMissing, runners.RunnerAuthFailed, runners.RunnerBadOutput)
HANDLED = (LoopZeroError, worktree.WorktreeError, github.GhError, OSError, ValueError)
UNEXPECTED = (KeyError, TypeError)
PAGE = 100
# --wait: poll interval, default timeout, and how long a required check may stay
# missing before GitHub is assumed to have dropped the event for this head.
# Each poll costs several GitHub API calls from a quota shared by every session.
Expand Down Expand Up @@ -151,10 +150,7 @@ def _context(args: argparse.Namespace, *, pin_checks: bool = False) -> tuple[Pat


def _is_ancestor(wt: Path, sha: str, head: str) -> bool:
done = _proc.run(
["git", "merge-base", "--is-ancestor", sha, head],
cwd=wt, env_allowlist=worktree.GIT_ENV, timeout=GIT_TIMEOUT,
)
done = config_mod.run_git(wt, "merge-base", "--is-ancestor", sha, head)
if done.exit_code not in (0, 1):
detail = _proc.tail(done.stderr or done.stdout, 1)
raise CliError(f"git merge-base --is-ancestor failed (exit {done.exit_code}): "
Expand All @@ -164,10 +160,7 @@ def _is_ancestor(wt: Path, sha: str, head: str) -> bool:

def _primary_base(wt: Path, config: Config) -> str:
base = config.trusted_base_revision or config_mod.base_revision(wt, config.base_branch)
done = _proc.run(
["git", "merge-base", base, "HEAD"],
cwd=wt, env_allowlist=worktree.GIT_ENV, timeout=GIT_TIMEOUT,
)
done = config_mod.run_git(wt, "merge-base", base, "HEAD")
if done.exit_code == 0:
return done.stdout.strip()
if done.exit_code != 1:
Expand All @@ -185,9 +178,7 @@ def _require_clean(wt: Path) -> None:

def _require_task_branch(config: Config, branch: str) -> None:
if branch == config.base_branch:
raise CliError(
f"branch {branch!r} is the configured base; use a task branch"
)
raise CliError(f"branch {branch!r} is the configured base; use a task branch")


def _require_pr(config: Config, branch: str, *, allow_merged: bool = False) -> github.PR:
Expand All @@ -213,11 +204,11 @@ def _rest_rows(endpoint: str, what: str) -> list[dict]:
"""Every row of a REST list, oldest first, following pages until a short one."""
rows: list[dict] = []
for page in range(1, 101):
batch = github.api_get(f"{endpoint}?per_page={PAGE}&page={page}")
batch = github.api_get(f"{endpoint}?per_page={github.PAGE}&page={page}")
if not isinstance(batch, list) or not all(isinstance(row, dict) for row in batch):
raise CliError(f"invalid GitHub {what} response")
rows += batch
if len(batch) < PAGE:
if len(batch) < github.PAGE:
return rows
raise CliError(f"GitHub {what} pagination limit exceeded")

Expand Down Expand Up @@ -309,10 +300,7 @@ def _readiness(
report = _load_report(wt)
receipt_problem = _check_report_problem(report, wt, config, head)
if receipt_problem:
result = github.Readiness(
ready=False,
reasons=(*result.reasons, receipt_problem),
)
result = github.Readiness(False, (*result.reasons, receipt_problem))
elif announce_receipt:
_print_receipt(wt, report, "accepted")
if config.merge_strategy == "mergify" and pr.state == "OPEN":
Expand Down Expand Up @@ -536,12 +524,6 @@ def replace(match: re.Match[str]) -> str:
return prefix + content.lstrip("\n")


def _update_pr_checks(wt: Path, head: str, config: Config, pr: github.PR) -> None:
body = _pr_body(wt, head, config, pr.body)
if body != (pr.body or "").replace("\r\n", "\n"):
github.update_body(config.repo, pr.number, body)


_REQUIRED_TASK_LINES = ("Context", "Problem", "Goal")


Expand Down Expand Up @@ -576,24 +558,17 @@ def _append_review(body: str, result: ReviewResult) -> str:


def _refresh_pr_checks(wt: Path, config: Config) -> None:
try:
with _lock_task_state(wt):
_refresh_existing_pr_checks(wt, config)
except OSError as exc:
print(f"note: could not refresh PR checks: {_one_line(exc)}", file=sys.stderr)


def _refresh_existing_pr_checks(wt: Path, config: Config) -> None:
"""Best-effort refresh only when local HEAD is the existing PR head."""
argv = ["git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"]
try:
upstream = _proc.run(argv, cwd=wt, env_allowlist=worktree.GIT_ENV, timeout=GIT_TIMEOUT)
if upstream.exit_code != 0:
return
branch, head = worktree.branch(wt), worktree.head(wt)
pr = github.pr_for_branch(config.repo, branch, open_only=True)
if pr is not None and pr.head_sha == head:
_update_pr_checks(wt, head, config, pr)
with _lock_task_state(wt):
upstream = config_mod.run_git(wt, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}")
if upstream.exit_code == 0:
branch, head = worktree.branch(wt), worktree.head(wt)
pr = github.pr_for_branch(config.repo, branch, open_only=True)
if pr is not None and pr.head_sha == head:
body = _pr_body(wt, head, config, pr.body)
if body != (pr.body or "").replace("\r\n", "\n"):
github.update_body(config.repo, pr.number, body)
except (github.GhError, _proc.ProcTimeout, OSError, ValueError, CliError) as exc:
print(f"note: could not refresh PR checks: {_one_line(exc)}", file=sys.stderr)

Expand All @@ -615,8 +590,7 @@ def _pr_title(wt: Path, branch: str) -> str:

def cmd_start(args: argparse.Namespace) -> int:
root = _toplevel()
argv = ["git", "symbolic-ref", "--quiet", "--short", "HEAD"]
current = _proc.run(argv, cwd=root, env_allowlist=worktree.GIT_ENV, timeout=GIT_TIMEOUT)
current = config_mod.run_git(root, "symbolic-ref", "--quiet", "--short", "HEAD")
if current.stdout.strip().startswith("lz/") or (
current.exit_code == 1 and worktree.is_linked_checkout(root)
):
Expand Down Expand Up @@ -814,16 +788,12 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int:
login.casefold() for login in config.review_publishers
}:
raise CliError("current GitHub login is not a configured review publisher")
reviews = [] if args.repost else _pr_reviews(config.repo, pr.number)
if args.repost:
saved = [kind for kind in ("primary", "delta") if _review_file(wt, head, kind).exists()]
if len(saved) > 1:
raise CliError("multiple saved reviews for HEAD; publication is ambiguous")
if not saved:
reviews = _pr_reviews(config.repo, pr.number)
kind = saved[0] if saved else _decide_kind(
_pr_markers(reviews, head, config.review_publishers, repo=config.repo, number=pr.number), head
)[0]
saved = [kind for kind in ("primary", "delta") if _review_file(wt, head, kind).exists()] if args.repost else []
if len(saved) > 1:
raise CliError("multiple saved reviews for HEAD; publication is ambiguous")
reviews = [] if saved else _pr_reviews(config.repo, pr.number)
if saved:
kind = saved[0]
else:
kind, reviewed = _decide_kind(
_pr_markers(reviews, head, config.review_publishers, repo=config.repo, number=pr.number), head
Expand Down Expand Up @@ -1128,7 +1098,6 @@ def select(family: str) -> Callable[..., ReviewResult]:
try:
try:
result = selected[family](diff=diff)
break
except runners.RunnerPromptTooLong:
chunks = runners.split_diff(diff, config.review_chunk_bytes)
print(
Expand All @@ -1138,7 +1107,7 @@ def select(family: str) -> Callable[..., ReviewResult]:
chunk_results = [selected[family](diff=chunk, chunk=(index, len(chunks)))
for index, chunk in enumerate(chunks, 1)]
result = runners.merge_reviews(chunk_results)
break
break
except RUNNER_FAILURES as exc:
reason, detail, fallback_reason = _review_failure(family, exc)
errors[family] = detail, exc.tail if isinstance(exc, runners.RunnerMalformedOutput) else ""
Expand Down Expand Up @@ -1384,16 +1353,17 @@ def cmd_ready(args: argparse.Namespace) -> int:
return 0


def _required_check_reasons(names: tuple[str, ...], *states: str) -> dict[str, str]:
return {f"required check '{name}' {state}": name for name in names for state in states}


def _draft_checks_waiting(
config: Config, pr: github.PR, readiness: github.Readiness
) -> tuple[str, ...]:
reasons = set(readiness.reasons) - {MERGEABILITY_PENDING}
if not pr.is_draft or not reasons:
return ()
expected: dict[str, str] = {}
for name in config.required_ci:
expected[f"required check '{name}' missing on {pr.head_sha[:12]}"] = name
expected[f"required check '{name}' is skipped"] = name
expected = _required_check_reasons(config.required_ci, f"missing on {pr.head_sha[:12]}", "is skipped")
if not reasons <= expected.keys():
return ()
blocked = {expected[reason] for reason in reasons}
Expand All @@ -1408,9 +1378,8 @@ def _pending_checks(
An explicit ready wait can observe a skipped result left over from draft CI.
"""
states = [f"missing on {pr.head_sha[:12]}", "is pending", *(["is skipped"] if allow_skipped else [])]
waitable = {f"required check '{n}' {state}" for n in config.required_ci for state in states}
waitable.update(readiness.waitable_failures)
waitable.add(MERGEABILITY_PENDING)
waitable = {*_required_check_reasons(config.required_ci, *states),
*readiness.waitable_failures, MERGEABILITY_PENDING}
reasons = readiness.reasons
return reasons if reasons and all(r in waitable for r in reasons) else ()

Expand Down Expand Up @@ -1460,20 +1429,19 @@ def _wait_with_deadline(
allow_merged: bool = False, allow_skipped: bool = False, initial: github.Readiness | None = None,
) -> tuple[github.PR, github.Readiness | None, bool] | None:
started = time.monotonic() if started is None else started
wait = partial(_wait_for_checks, wt, config, pr, timeout, kicked=kicked, started=started,
shown=shown, args=args, allow_merged=allow_merged,
allow_skipped=allow_skipped, initial=initial)
if timeout == 0:
return _wait_for_checks(wt, config, pr, timeout, kicked=kicked, started=started,
shown=shown, args=args, allow_merged=allow_merged,
allow_skipped=allow_skipped, initial=initial)
return wait()
deadline = started + timeout
if time.monotonic() >= deadline:
_print_check_wait_timeout(pr, args)
return None
reported_timeout = False
try:
with github.bounded_reads(deadline, token=None, retry=True):
waited = _wait_for_checks(wt, config, pr, timeout, kicked=kicked, started=started,
shown=shown, args=args, bounded=True, allow_merged=allow_merged,
allow_skipped=allow_skipped, initial=initial)
waited = wait(bounded=True)
reported_timeout = waited is None
except github.ReadDeadline:
if not reported_timeout:
Expand Down Expand Up @@ -1722,6 +1690,9 @@ def _wait_for_mergify(
return None


_FOLLOW_QUEUE = "next: loopzero merge --wait follows the queue, verifies and cleans up"


class _AdmissionDeadline(Exception):
"""The --wait budget expired before a new merge or queue request."""

Expand All @@ -1747,7 +1718,6 @@ def _merge_with_mergify(
confirmed = state is not None
if confirmed and not confirmed_marker:
mergify.mark_confirmed(config.repo, pr.number, pr.head_sha, queue)
confirmed_marker = True
if not confirmed and confirmed_marker:
closed: list[github.GhError] = []
if sha := _mergify_departure(config, pr, queue, closed, confirmed=True):
Expand All @@ -1758,14 +1728,10 @@ def _merge_with_mergify(
if admit_by is not None and time.monotonic() > admit_by:
raise _AdmissionDeadline
mergify.request(config.repo, pr.number, pr.head_sha, queue)
requested = True
if deadline is not None:
return _wait_for_mergify(config, pr, max(0.0, deadline - time.monotonic()), confirmed)
state_name = "confirmed in" if confirmed else "requested from"
print(
f"PR #{pr.number} {state_name} Mergify queue {queue}; "
"next: loopzero merge --wait follows the queue, verifies and cleans up"
)
print(f"PR #{pr.number} {state_name} Mergify queue {queue}; {_FOLLOW_QUEUE}")
return None


Expand Down Expand Up @@ -1797,10 +1763,7 @@ def cmd_merge(args: argparse.Namespace) -> int:
return 3
pr, readiness, _ = waited
if readiness is None:
sha = github.merged_sha(
config.repo, pr.number,
expected_head=pr.head_sha,
)
sha = github.merged_sha(config.repo, pr.number, expected_head=pr.head_sha)
if sha is None:
raise CliError(f"PR #{pr.number} reports MERGED but has no merge commit yet; rerun")
print(f"PR #{pr.number} was already merged as {sha[:12]}; cleaning up")
Expand All @@ -1826,10 +1789,7 @@ def cmd_merge(args: argparse.Namespace) -> int:
print(f"timed out waiting for the merge queue to land PR #{pr.number}")
return 3
if sha is None:
print(
f"PR #{pr.number} is queued for merge into {config.base_branch}; "
"next: loopzero merge --wait follows the queue, verifies and cleans up"
)
print(f"PR #{pr.number} is queued for merge into {config.base_branch}; {_FOLLOW_QUEUE}")
return 0
_cleanup_remote_refs(wt, config, branch, pr.head_sha)
_cleanup(wt, pr)
Expand Down
Loading
Loading