mirror of
https://github.com/kevinveenbirkenbach/computer-playbook.git
synced 2026-11-11 05:06:36 +00:00
Extends ``[tool.ruff.lint].select`` with six additional rule families:
``RUF`` (ruff-specific), ``SIM`` (flake8-simplify), ``C4``
(flake8-comprehensions), ``PERF`` (perflint), ``RET`` (flake8-return),
``PIE`` (flake8-pie). Adds ``RUF001/002/003`` to ``ignore`` because
those exist for homoglyph-attack detection, not English typography —
the project uses em/en-dashes and ``ℹ`` as a UI-hint glyph in CLI help
output deliberately.
Auto-fixed (~225, mechanical & behavior-preserving)
====================================================
- RUF005: ``a + [b]`` → ``[*a, b]``
- C408: ``dict(k=v)`` → ``{"k": v}``
- C420: ``dict.fromkeys(seq)`` shape simplifications
- SIM103/SIM110/SIM118: truthy-return / dict-key / dict-method
idiom simplifications
- RET504/RET505: drop unneeded final assigns / ``else`` after
``return``
- PIE810: combine ``str.startswith(a) or .startswith(b)``
into one call with a tuple
- RUF010: ``f"{str(x)}"`` → ``f"{x\!s}"``
- RUF100: removed unused ``# noqa`` directives that
became stale (mostly old ``# noqa: E402``
markers that ruff's smart E402 implementation
no longer flags after ``sys.path`` shims)
- RUF015 / RUF013 / RUF022 / RUF046 / RUF059: misc small wins
- I001: re-sorted import blocks where the new
imports above shifted them
Hand-fixed (~140, scripted where mechanical)
============================================
PERF401 (42): scripted AST rewrite of
``for x in iter: target.append(expr)`` (with optional ``if`` guard)
→ ``target.extend(expr for x in iter [if cond])``.
``list.extend(genexp)`` consumes the generator immediately, so the
rewrite is semantically equivalent to the original eager loop.
SIM117 (41): scripted AST combiner for nested ``with`` blocks where
the inner is the only statement of the outer (38 sites). The remaining
3 multi-line ``patch.object(...)`` chains were combined by hand using
the parenthesised ``with (\\n A,\\n B,\\n):`` form.
SIM102 (14): scripted AST combiner for nested ``if`` (10 sites). The
remaining 4 carry an inline ``# noqa: SIM102`` with rationale —
combining would either change semantics (the outer body has siblings
beyond the inner ``if``, e.g. ``cli/encrypt/inventory/__main__.py``
where ``encrypted_value = …`` runs regardless of ``ask_confirmation``)
or hurt readability (long literal whitelists).
RUF012 (9): annotated mutable class attributes with ``ClassVar[…]``
and added ``from typing import ClassVar``.
SIM105 (6): ``try/except: pass`` → ``with contextlib.suppress(…):``
with the necessary ``import contextlib`` added. Verified on
``utils/templating.py`` (3 occurrences in a ``finally`` block) —
cleanup behaviour is identical.
SIM115 (4): wrapped ``tempfile.NamedTemporaryFile(..., delete=False)``
call patterns in a ``with`` block; ``delete=False`` keeps the file
on disk after the block, so callers' ``return f.name`` still works.
PERF402, PERF403, B007, SIM108, SIM103: 5 misc fixes (loop→list-copy,
loop→dict-comprehension, unused-loop-var rename, ternary, return
expression).
Verification
============
- ``ruff check .`` → All checks passed
- ``ruff format --check .`` → 894 files already formatted
- 1621 unit tests → all pass
- Integration suite: 44 baseline failures, 1 skipped (unchanged)
- Sample-audited PERF401 rewrites in ``resolver.py``, ``inventory.py``,
``cache/files.py``, ``ressources/__main__.py``; SIM117 in
``test_main.py``; SIM105 in ``utils/templating.py``; SIM102 noqa
rationales in ``cli/encrypt/inventory/__main__.py``.
182 files changed, +993 / −960. With this and the prior strict-rule
commit the branch satisfies 11 ruff rule families end-to-end.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
183 lines
6.1 KiB
Python
183 lines
6.1 KiB
Python
from __future__ import annotations
|
|
|
|
import os
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
import unittest.mock
|
|
from pathlib import Path
|
|
|
|
from utils.annotations.summarize import (
|
|
Annotation,
|
|
main,
|
|
parse_log,
|
|
parse_props,
|
|
render_markdown,
|
|
)
|
|
|
|
|
|
class TestParseProps(unittest.TestCase):
|
|
def test_single_prop(self) -> None:
|
|
self.assertEqual(parse_props("title=Foo"), {"title": "Foo"})
|
|
|
|
def test_multiple_props(self) -> None:
|
|
result = parse_props("title=My Title,file=foo.py,line=42")
|
|
self.assertEqual(result, {"title": "My Title", "file": "foo.py", "line": "42"})
|
|
|
|
def test_empty_string(self) -> None:
|
|
self.assertEqual(parse_props(""), {})
|
|
|
|
def test_none_like_empty(self) -> None:
|
|
self.assertEqual(parse_props(""), {})
|
|
|
|
|
|
class TestParseLog(unittest.TestCase):
|
|
def _write_log(self, content: str) -> Path:
|
|
with tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False) as f:
|
|
f.write(content)
|
|
return Path(f.name)
|
|
|
|
def test_parses_warning(self) -> None:
|
|
p = self._write_log("::warning title=T,file=f.py,line=3::bad thing\n")
|
|
result = parse_log(p)
|
|
self.assertEqual(len(result), 1)
|
|
a = result[0]
|
|
self.assertEqual(a.level, "warning")
|
|
self.assertEqual(a.title, "T")
|
|
self.assertEqual(a.file, "f.py")
|
|
self.assertEqual(a.line, 3)
|
|
self.assertEqual(a.message, "bad thing")
|
|
|
|
def test_parses_error(self) -> None:
|
|
p = self._write_log("::error title=Oops::something broke\n")
|
|
result = parse_log(p)
|
|
self.assertEqual(len(result), 1)
|
|
self.assertEqual(result[0].level, "error")
|
|
self.assertEqual(result[0].title, "Oops")
|
|
|
|
def test_parses_notice(self) -> None:
|
|
p = self._write_log("::notice::just info\n")
|
|
result = parse_log(p)
|
|
self.assertEqual(len(result), 1)
|
|
self.assertEqual(result[0].level, "notice")
|
|
self.assertIsNone(result[0].title)
|
|
|
|
def test_ignores_non_annotation_lines(self) -> None:
|
|
p = self._write_log("regular output\nsome other line\n")
|
|
self.assertEqual(parse_log(p), [])
|
|
|
|
def test_mixed_log(self) -> None:
|
|
content = (
|
|
"build started\n"
|
|
"::warning title=W::warn msg\n"
|
|
"some output\n"
|
|
"::error::err msg\n"
|
|
)
|
|
p = self._write_log(content)
|
|
result = parse_log(p)
|
|
self.assertEqual(len(result), 2)
|
|
self.assertEqual(result[0].level, "warning")
|
|
self.assertEqual(result[1].level, "error")
|
|
|
|
def test_multiple_annotations(self) -> None:
|
|
lines = "\n".join(f"::warning::msg {i}" for i in range(15))
|
|
p = self._write_log(lines)
|
|
self.assertEqual(len(parse_log(p)), 15)
|
|
|
|
|
|
class TestRenderMarkdown(unittest.TestCase):
|
|
def test_empty_returns_no_annotations_message(self) -> None:
|
|
md = render_markdown([], "My Title")
|
|
self.assertIn("My Title", md)
|
|
self.assertIn("No annotations found", md)
|
|
|
|
def test_warning_section_present(self) -> None:
|
|
annotations = [Annotation(level="warning", message="watch out", title="T")]
|
|
md = render_markdown(annotations, "Summary")
|
|
self.assertIn("Warnings", md)
|
|
self.assertIn("watch out", md)
|
|
self.assertIn("🟡", md)
|
|
|
|
def test_error_section_present(self) -> None:
|
|
annotations = [Annotation(level="error", message="broken")]
|
|
md = render_markdown(annotations, "Summary")
|
|
self.assertIn("Errors", md)
|
|
self.assertIn("🔴", md)
|
|
|
|
def test_notice_section_present(self) -> None:
|
|
annotations = [Annotation(level="notice", message="fyi")]
|
|
md = render_markdown(annotations, "Summary")
|
|
self.assertIn("Notices", md)
|
|
self.assertIn("🔵", md)
|
|
|
|
def test_file_with_line_shown_as_colon_path(self) -> None:
|
|
annotations = [Annotation(level="warning", message="x", file="a.py", line=7)]
|
|
md = render_markdown(annotations, "S")
|
|
self.assertIn("a.py:7", md)
|
|
|
|
def test_pipe_in_message_escaped(self) -> None:
|
|
annotations = [Annotation(level="warning", message="a|b")]
|
|
md = render_markdown(annotations, "S")
|
|
self.assertIn("a\\|b", md)
|
|
|
|
def test_count_in_heading(self) -> None:
|
|
annotations = [
|
|
Annotation(level="warning", message="w1"),
|
|
Annotation(level="warning", message="w2"),
|
|
]
|
|
md = render_markdown(annotations, "S")
|
|
self.assertIn("Warnings (2)", md)
|
|
|
|
def test_order_error_warning_notice(self) -> None:
|
|
annotations = [
|
|
Annotation(level="notice", message="n"),
|
|
Annotation(level="warning", message="w"),
|
|
Annotation(level="error", message="e"),
|
|
]
|
|
md = render_markdown(annotations, "S")
|
|
error_pos = md.index("Errors")
|
|
warning_pos = md.index("Warnings")
|
|
notice_pos = md.index("Notices")
|
|
self.assertLess(error_pos, warning_pos)
|
|
self.assertLess(warning_pos, notice_pos)
|
|
|
|
|
|
class TestMain(unittest.TestCase):
|
|
def test_writes_to_github_step_summary(self) -> None:
|
|
with tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False) as log:
|
|
log.write("::warning title=T::msg\n")
|
|
log_path = log.name
|
|
|
|
with tempfile.NamedTemporaryFile(
|
|
mode="w", suffix=".md", delete=False
|
|
) as summary:
|
|
summary_path = summary.name
|
|
|
|
old_argv = sys.argv
|
|
try:
|
|
sys.argv = ["summarize", log_path, "Test Title"]
|
|
with unittest.mock.patch.dict(
|
|
os.environ, {"GITHUB_STEP_SUMMARY": summary_path}
|
|
):
|
|
main()
|
|
finally:
|
|
sys.argv = old_argv
|
|
|
|
content = Path(summary_path).read_text()
|
|
self.assertIn("Test Title", content)
|
|
self.assertIn("msg", content)
|
|
|
|
def test_exits_without_args(self) -> None:
|
|
old_argv = sys.argv
|
|
sys.argv = ["summarize"]
|
|
try:
|
|
with self.assertRaises(SystemExit) as cm:
|
|
main()
|
|
self.assertEqual(cm.exception.code, 1)
|
|
finally:
|
|
sys.argv = old_argv
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|