Skip to content
Merged
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
78 changes: 34 additions & 44 deletions src/loopzero/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"review_chunk_bytes": int, "review": dict,
},
}
_REVIEW_SETTINGS = {"model": str, "effort": str, "allowed_efforts": list}


class ConfigError(LoopZeroError):
Expand Down Expand Up @@ -151,64 +152,44 @@ def load_trusted(worktree: Path, *, previous: Config | None = None, refresh: boo

def _build(data: dict[str, Any]) -> Config:
_reject_unknown("top level", data, _SECTIONS)
for section, keys in _SECTIONS.items():
table = data.get(section, {})
if not isinstance(table, dict):
raise ConfigError(f"[{section}] must be a table")
_reject_unknown(f"[{section}]", table, keys)
for key, kind in keys.items():
if key in table and not isinstance(table[key], kind):
raise ConfigError(f"{section}.{key} must be a {kind.__name__}")

repo = data.get("repo", {})
checks = data.get("checks", {})
delivery = data.get("delivery", {})

if "name" not in repo:
sections = {
section: _check_table(section, data.get(section, {}), schema)
for section, schema in _SECTIONS.items()
}
repo, checks, delivery = sections["repo"], sections["checks"], sections["delivery"]

if (name := repo.get("name")) is None:
raise ConfigError("missing required key repo.name (\"owner/name\")")
name = repo["name"]
if name.count("/") != 1 or not all(name.split("/")):
raise ConfigError(f'repo.name must look like "owner/name", got {name!r}')

base = repo.get("base", "main")
if not base:
if not (base := repo.get("base", "main")):
raise ConfigError("repo.base must not be empty")
merge, mergify_queue = _merge_settings(delivery)
reviewers = _strings("delivery.reviewers", delivery.get("reviewers", list(REVIEWER_FAMILIES)))
if not reviewers:
raise ConfigError("delivery.reviewers must list at least one reviewer")
for reviewer in reviewers:
if reviewer not in REVIEWER_FAMILIES:
raise ConfigError(
f"delivery.reviewers entries must be in {REVIEWER_FAMILIES}, got {reviewer!r}"
)
review_chunk_bytes = delivery.get("review_chunk_bytes", 200_000)
if unknown := next((family for family in reviewers if family not in REVIEWER_FAMILIES), None):
raise ConfigError(f"delivery.reviewers entries must be in {REVIEWER_FAMILIES}, got {unknown!r}")
review_chunk_bytes = delivery.get("review_chunk_bytes", Config.review_chunk_bytes)
if isinstance(review_chunk_bytes, bool) or review_chunk_bytes < 4096:
raise ConfigError("delivery.review_chunk_bytes must be an int >= 4096")
review: dict[str, ReviewConfig] = {}
for family, table in delivery.get("review", {}).items():
if family not in REVIEWER_FAMILIES:
raise ConfigError(f"unknown review family delivery.review.{family}")
if not isinstance(table, dict):
raise ConfigError(f"[delivery.review.{family}] must be a table")
label = f"delivery.review.{family}"
_reject_unknown(f"[{label}]", table, ("model", "effort", "allowed_efforts"))
for key in ("model", "effort"):
if key in table and (not isinstance(table[key], str) or not table[key]):
raise ConfigError(f"{label}.{key} must be a non-empty str")
allowed = table.get("allowed_efforts", [])
if not isinstance(allowed, list):
raise ConfigError(f"{label}.allowed_efforts must be a list")
review[family] = ReviewConfig(table.get("model"), table.get("effort"),
_strings(f"{label}.allowed_efforts", allowed))
table = _check_table(label, table, _REVIEW_SETTINGS, nonempty_strings=True)
review[family] = ReviewConfig(
table.get("model"), table.get("effort"), _strings(f"{label}.allowed_efforts", table.get("allowed_efforts", [])),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Line savings partly come from lines longer than the configured 100-character limit

pyproject.toml sets line-length = 100. Lint passes only because ruff selects E4/E7/E9 and not E501, and the checks never run ruff format --check. Even so, several new lines go past the limit: the ReviewConfig(...) argument line here (about 125 chars), the reviewers raise at line 173, the checks.runner walrus line, and the reviewer_ro_paths=_host_paths(...) keyword. Some of the 10 counted lines therefore come from cramming code together, not from sharing logic. Running ruff format would bring the lines back. Smallest fix: wrap these lines within 100 characters, or bind allowed = _strings(...) before ReviewConfig(...). Then confirm the line budget still holds from the real dedupe.

)

commands = _strings("checks.commands", checks.get("commands", []))
if any(not command.strip() for command in commands):
raise ConfigError("checks.commands entries must each be a nonblank command")
kwargs: dict[str, Any] = {}
if "runner" in checks:
runner = _strings("checks.runner", checks["runner"])
if not runner or any(not arg or "\0" in arg for arg in runner):
if not (runner := _strings("checks.runner", checks["runner"])) or any("\0" in arg for arg in runner):
raise ConfigError("checks.runner must be a nonempty argv prefix")
if "/" in runner[0] and not Path(runner[0]).is_absolute():
raise ConfigError("checks.runner executable paths must be absolute")
Expand Down Expand Up @@ -236,10 +217,8 @@ def _build(data: dict[str, Any]) -> Config:
if "runner" in checks and checks["limits"]:
keys = ", ".join(f"checks.limits.{key}" for key in sorted(checks["limits"]))
raise ConfigError(f"{keys} apply only to local checks and cannot be set with checks.runner")
reviewer_ro_paths = _host_paths(
"delivery.reviewer_ro_paths", delivery.get("reviewer_ro_paths", [])
)
return Config(
reviewer_ro_paths=_host_paths("delivery.reviewer_ro_paths", delivery.get("reviewer_ro_paths", [])),
repo=name,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Moving reviewer_ro_paths to the first keyword only works because Python evaluates arguments left to right

The error order is kept because _host_paths is still evaluated before _strings("delivery.review_publishers", ...) inside the Config(...) call. That holds only while the argument stays first. If someone later sorts or regroups the keywords, the order of competing errors changes without any warning. The rest of the call is grouped by field. Consider keeping it as a separate statement, or adding a comment saying the position matters.

base_branch=base,
checks=commands,
Expand All @@ -250,16 +229,14 @@ def _build(data: dict[str, Any]) -> Config:
review_publishers=_strings("delivery.review_publishers",
delivery.get("review_publishers", [])),
review=review,
reviewer_ro_paths=reviewer_ro_paths,
review_chunk_bytes=review_chunk_bytes,
network=checks.get("network", False),
inputs=inputs, env=env, **kwargs,
)


def _merge_settings(delivery: dict[str, Any]) -> tuple[str, str | None]:
merge = delivery.get("merge", "squash")
if merge not in MERGE_STRATEGIES:
if (merge := delivery.get("merge", "squash")) not in MERGE_STRATEGIES:
raise ConfigError(f"delivery.merge must be one of {MERGE_STRATEGIES}, got {merge!r}")
mergify_queue = delivery.get("mergify_queue")
if merge == "mergify":
Expand All @@ -272,9 +249,22 @@ def _merge_settings(delivery: dict[str, Any]) -> tuple[str, str | None]:
return merge, mergify_queue


def _check_table(label: str, table: Any, schema: dict[str, type], *,
nonempty_strings: bool = False) -> dict[str, Any]:
if not isinstance(table, dict):
raise ConfigError(f"[{label}] must be a table")
_reject_unknown(f"[{label}]", table, schema)
for key, kind in schema.items():
if key in table:
nonempty = nonempty_strings and kind is str
if not isinstance(table[key], kind) or (nonempty and not table[key]):
expected = "non-empty str" if nonempty else kind.__name__
raise ConfigError(f"{label}.{key} must be a {expected}")
return table


def _reject_unknown(where: str, table: dict[str, Any], allowed: Any) -> None:
unknown = sorted(set(table) - set(allowed))
if unknown:
if unknown := sorted(set(table) - set(allowed)):
raise ConfigError(f"unknown key(s) in {where}: {', '.join(unknown)}")


Expand Down
Loading