Repository navigation
Show CLI help before importing delivery backends #1523
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| """Argument parsing shared by the console script and CLI module.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import argparse | ||
| import io | ||
| import sys | ||
|
|
||
| WAIT_TIMEOUT = 1800.0 | ||
|
|
||
|
|
||
| def _wait_seconds(value: str) -> float: | ||
| from math import isfinite | ||
|
|
||
| try: | ||
| seconds = float(value) | ||
| if isfinite(seconds) and seconds >= 0: | ||
| return seconds | ||
| except ValueError: | ||
| pass | ||
| raise argparse.ArgumentTypeError("expected a finite, nonnegative number of seconds") | ||
|
|
||
|
|
||
| def _config_path(value: str): | ||
| from pathlib import Path | ||
|
|
||
| return Path(value) | ||
|
|
||
|
|
||
| def build_parser() -> argparse.ArgumentParser: | ||
| parser = argparse.ArgumentParser( | ||
| prog="loopzero", description="One task, one branch, one draft PR, one review, one merge." | ||
| ) | ||
| parser.add_argument( | ||
| "--config", type=_config_path, default=None, help="path to workflow.toml (default: repo root)" | ||
| ) | ||
| parser.add_argument("--version", action=_VersionAction, nargs=0, help="show program's version number and exit") | ||
| sub = parser.add_subparsers(dest="command", required=True) | ||
| start = sub.add_parser("start", help="create an owned worktree and branch for <slug>") | ||
| start.add_argument("slug") | ||
| sub.add_parser("check", help="run the configured checks in the sandbox") | ||
| sub.add_parser("pr", help="push and open or refresh the draft PR") | ||
| review = sub.add_parser("review", help="run native review and post one canonical review") | ||
| review.add_argument( | ||
| "--repost", action="store_true", help="post the saved review for HEAD without a model" | ||
| ) | ||
| review.add_argument("--model", help="reviewer model override for a fresh review") | ||
| review.add_argument("--effort", help="reviewer effort override for a fresh review") | ||
| ready = sub.add_parser( | ||
| "ready", help="compute readiness and mark the PR ready; --wait polls required checks" | ||
| ) | ||
| merge = sub.add_parser( | ||
| "merge", help="recheck readiness, merge and clean up; --wait waits for checks and landing" | ||
| ) | ||
| for waiter, what in ((ready, "required checks on this head"), (merge, "required checks and the landed merge")): | ||
| waiter.add_argument( | ||
| "--wait", nargs="?", const=WAIT_TIMEOUT, type=_wait_seconds, metavar="SECONDS", | ||
| help=f"wait for {what} (default {WAIT_TIMEOUT:.0f}s); exit 3 on timeout", | ||
| ) | ||
| merge.add_argument( | ||
| "--cancel", action="store_true", help="request removal from the configured Mergify queue" | ||
| ) | ||
| resolve = sub.add_parser( | ||
| "resolve", usage='%(prog)s [<finding-id> "<reply>"]', | ||
| help="list open findings, or reply to one and resolve it", | ||
| ) | ||
| resolve.add_argument("finding", nargs="?", help="finding id from the list (8 hex digits)") | ||
| resolve.add_argument("reply", nargs="?", default="", help="what changed, e.g. the fix commit") | ||
| sub.add_parser("status", help="show where this branch is in the sequence") | ||
| return parser | ||
|
|
||
|
|
||
| def _version() -> str: | ||
| """Package version plus the pinned source revision when installed from Git.""" | ||
| import json | ||
| from importlib.metadata import distribution | ||
|
|
||
| dist = distribution("loopzero") | ||
| try: | ||
| commit = json.loads(dist.read_text("direct_url.json") or "{}")["vcs_info"]["commit_id"] | ||
| except (KeyError, TypeError, json.JSONDecodeError): | ||
| commit = "unknown revision (not installed from a Git URL)" | ||
| return f"loopzero {dist.version} {commit}" | ||
|
|
||
|
|
||
| class _VersionAction(argparse.Action): | ||
| def __call__(self, parser, _namespace, _values, _option_string=None): | ||
| print(_version()) | ||
| parser.exit() | ||
|
|
||
|
|
||
| def parse_args(parser: argparse.ArgumentParser, argv: list[str] | None) -> argparse.Namespace: | ||
| # Progress lines must precede the stderr verdict when both go to one file. | ||
| if isinstance(sys.stdout, io.TextIOWrapper): | ||
| sys.stdout.reconfigure(line_buffering=True) | ||
| args = parser.parse_args(argv) | ||
| if args.command == "resolve" and args.finding is not None and not args.reply.strip(): | ||
| parser.error('expected resolve [<finding-id> "<reply>"] with a nonblank reply for a finding') | ||
| if args.command == "review" and args.repost: | ||
| conflicts = [f"--{name}" for name in ("model", "effort") if getattr(args, name) is not None] | ||
| if conflicts: | ||
| parser.error(f"review --repost cannot be combined with {' or '.join(conflicts)}") | ||
| return args |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| """Console entry point. Load delivery commands only after parsing.""" | ||
|
|
||
| from loopzero._cli_args import build_parser, parse_args | ||
|
|
||
|
|
||
| def main(argv: list[str] | None = None) -> int: | ||
| args = parse_args(build_parser(), argv) | ||
| from loopzero.cli import _run | ||
|
|
||
| return _run(args) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,14 +2,17 @@ | |
|
|
||
| from __future__ import annotations | ||
|
|
||
| from loopzero._cli_args import build_parser, parse_args | ||
|
|
||
| # Module execution parses help and version before loading delivery code. | ||
| if __name__ == "__main__": | ||
| _module_args = parse_args(build_parser(), None) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. suggestion: Under |
||
|
|
||
| import argparse | ||
| import dataclasses | ||
| import fcntl | ||
| import hashlib | ||
| import importlib.metadata | ||
| import io | ||
| import json | ||
| import math | ||
| import os | ||
| import shlex | ||
| import random | ||
|
|
@@ -37,7 +40,7 @@ | |
| # --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. | ||
| WAIT_INTERVAL, WAIT_TIMEOUT, MISSING_RUN_GRACE = 30.0, 1800.0, 120.0 | ||
| WAIT_INTERVAL, MISSING_RUN_GRACE = 30.0, 120.0 | ||
| STALE_VERDICT_GRACE, MAX_REVIEW_CLOCK_SKEW = 900.0, 30.0 | ||
| PUSH_TIMEOUT = 600.0 # consumer pre-push hooks (lint, tests) routinely exceed GIT_TIMEOUT | ||
| NEXT_WAIT = "next: loopzero ready --wait" # named at the moment of need; agents hand-roll polls otherwise | ||
|
|
@@ -1739,92 +1742,14 @@ def _print_mergify_status(config: Config, pr: github.PR, readiness: github.Readi | |
| # --------------------------------------------------------------------------- entry point | ||
|
|
||
|
|
||
| def _wait_seconds(value: str) -> float: | ||
| try: | ||
| seconds = float(value) | ||
| if math.isfinite(seconds) and seconds >= 0: | ||
| return seconds | ||
| except ValueError: | ||
| pass | ||
| raise argparse.ArgumentTypeError("expected a finite, nonnegative number of seconds") | ||
|
|
||
|
|
||
| def build_parser() -> argparse.ArgumentParser: | ||
| parser = argparse.ArgumentParser( | ||
| prog="loopzero", description="One task, one branch, one draft PR, one review, one merge." | ||
| ) | ||
| parser.add_argument( | ||
| "--config", type=Path, default=None, help="path to workflow.toml (default: repo root)" | ||
| ) | ||
| parser.add_argument("--version", action="version", version=_version()) | ||
| sub = parser.add_subparsers(dest="command", required=True) | ||
| start = sub.add_parser("start", help="create an owned worktree and branch for <slug>") | ||
| start.add_argument("slug") | ||
| start.set_defaults(func=cmd_start) | ||
| sub.add_parser("check", help="run the configured checks in the sandbox").set_defaults( | ||
| func=cmd_check | ||
| ) | ||
| sub.add_parser("pr", help="push and open or refresh the draft PR").set_defaults(func=cmd_pr) | ||
| review = sub.add_parser("review", help="run native review and post one canonical review") | ||
| review.add_argument( | ||
| "--repost", action="store_true", help="post the saved review for HEAD without a model" | ||
| ) | ||
| review.add_argument("--model", help="reviewer model override for a fresh review") | ||
| review.add_argument("--effort", help="reviewer effort override for a fresh review") | ||
| review.set_defaults(func=cmd_review) | ||
| ready = sub.add_parser( | ||
| "ready", help="compute readiness and mark the PR ready; --wait polls required checks" | ||
| ) | ||
| merge = sub.add_parser( | ||
| "merge", help="recheck readiness, merge and clean up; --wait waits for checks and landing" | ||
| ) | ||
| for waiter, what in ((ready, "required checks on this head"), (merge, "required checks and the landed merge")): | ||
| waiter.add_argument( | ||
| "--wait", nargs="?", const=WAIT_TIMEOUT, type=_wait_seconds, metavar="SECONDS", | ||
| help=f"wait for {what} (default {WAIT_TIMEOUT:.0f}s); exit 3 on timeout", | ||
| ) | ||
| merge.add_argument( | ||
| "--cancel", action="store_true", help="request removal from the configured Mergify queue" | ||
| ) | ||
| ready.set_defaults(func=cmd_ready) | ||
| merge.set_defaults(func=cmd_merge) | ||
| resolve = sub.add_parser( | ||
| "resolve", usage='%(prog)s [<finding-id> "<reply>"]', | ||
| help="list open findings, or reply to one and resolve it", | ||
| ) | ||
| resolve.add_argument("finding", nargs="?", help="finding id from the list (8 hex digits)") | ||
| resolve.add_argument("reply", nargs="?", default="", help="what changed, e.g. the fix commit") | ||
| resolve.set_defaults(func=cmd_resolve) | ||
| status = sub.add_parser("status", help="show where this branch is in the sequence") | ||
| status.set_defaults(func=cmd_status) | ||
| return parser | ||
|
|
||
|
|
||
| def _version() -> str: | ||
| """Package version plus the pinned source revision when installed from Git.""" | ||
| dist = importlib.metadata.distribution("loopzero") | ||
| try: | ||
| commit = json.loads(dist.read_text("direct_url.json") or "{}")["vcs_info"]["commit_id"] | ||
| except (KeyError, TypeError, json.JSONDecodeError): | ||
| commit = "unknown revision (not installed from a Git URL)" | ||
| return f"loopzero {dist.version} {commit}" | ||
| def main(argv: list[str] | None = None) -> int: | ||
| return _run(parse_args(build_parser(), argv)) | ||
|
|
||
|
|
||
| def main(argv: list[str] | None = None) -> int: | ||
| # Progress lines must precede the stderr verdict when both go to one file. | ||
| if isinstance(sys.stdout, io.TextIOWrapper): | ||
| sys.stdout.reconfigure(line_buffering=True) | ||
| parser = build_parser() | ||
| args = parser.parse_args(argv) | ||
| if args.command == "resolve" and args.finding is not None and not args.reply.strip(): | ||
| parser.error('expected resolve [<finding-id> "<reply>"] with a nonblank reply for a finding') | ||
| if args.command == "review" and args.repost: | ||
| conflicts = [f"--{name}" for name in ("model", "effort") if getattr(args, name) is not None] | ||
| if conflicts: | ||
| parser.error(f"review --repost cannot be combined with {' or '.join(conflicts)}") | ||
| def _run(args: argparse.Namespace) -> int: | ||
| try: | ||
| with _proc.unwind_on_sigterm(): | ||
| return args.func(args) | ||
| return globals()[f"cmd_{args.command}"](args) | ||
| except IndependentReviewerUnavailable as exc: | ||
| print(f"loopzero {args.command}: {exc}", file=sys.stderr) | ||
| return 4 | ||
|
|
@@ -1845,4 +1770,4 @@ def _one_line(exc: BaseException) -> str: | |
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| sys.exit(main()) | ||
| sys.exit(_run(_module_args)) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -1123,10 +1123,9 @@ def test_pr_accepts_angle_brackets_and_sublists_as_filled_text(wt: Path) -> None | |
|
|
||
|
|
||
| def test_progress_output_precedes_the_stderr_verdict_in_one_file(tmp_path: Path) -> None: | ||
| script = ("import argparse, sys\nfrom loopzero import cli\np = argparse.ArgumentParser()\n" | ||
| "def wait(args):\n print('waiting')\n raise cli.CliError('dequeued')\n" | ||
| "p.set_defaults(func=wait, command='merge')\ncli.build_parser = lambda: p\n" | ||
| "sys.exit(cli.main([]))\n") | ||
| script = ("import sys\nfrom loopzero import cli\ndef wait(args):\n" | ||
| " print('waiting')\n raise cli.CliError('dequeued')\n" | ||
| "cli.cmd_merge = wait\nsys.exit(cli.main(['merge']))\n") | ||
| with (tmp_path / "log").open("w") as log: | ||
| subprocess.run([sys.executable, "-c", script], stdout=log, stderr=subprocess.STDOUT, check=False) | ||
| assert (tmp_path / "log").read_text().splitlines() == ["waiting", "loopzero merge: dequeued"] | ||
|
|
@@ -1259,11 +1258,12 @@ def test_pr_refuses_to_overwrite_a_pr_head_it_has_never_seen( | |
| assert git(origin, "rev-parse", "refs/heads/lz/t1").strip() == pushed | ||
|
|
||
|
|
||
| def test_version_names_the_installed_revision(capsys) -> None: | ||
| with pytest.raises(SystemExit) as stop: | ||
| cli.main(["--version"]) | ||
| out = capsys.readouterr().out | ||
| assert stop.value.code == 0 and re.fullmatch(r"loopzero \S+ .+\n", out), out | ||
| @pytest.mark.parametrize("flag, pattern", [("--version", r"loopzero \S+ .+\n\Z"), ("--help", r"usage: loopzero ")]) | ||
| def test_cli_info_leaves_delivery_backends_unloaded(flag, pattern): | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. suggestion: Nothing tests the console-script entry point ( Acceptance requires the console script's help and version output to stay the same and help to load no backends. The rewritten test only runs |
||
| for entry in (("-m", "loopzero.cli"), ("-c", "from loopzero._cli_entry import main; main()")): | ||
| done = subprocess.run([sys.executable, "-X", "importtime", *entry, flag], capture_output=True, text=True) | ||
| assert done.returncode == 0 and re.match(pattern, done.stdout), done | ||
| assert not re.search(r"loopzero\.(github|mergify|runners|sandbox)\b", done.stderr) | ||
|
|
||
|
|
||
| def test_pr_refuses_dirty(wt: Path, gh: FakeGh, capsys) -> None: | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.