Files
poli0981andClaude Opus 5.5 e7cb14a888 1.4.1: SonarQube Cloud CI analysis with coverage (#7)
Moves SonarQube Cloud from Automatic Analysis to CI-based analysis with
pytest coverage, makes its quality gate part of the required `ci` check,
and fixes what the first CI scan reported on `main`.

## SonarQube Cloud in CI

- `sonar-project.properties` (new) replaces `.sonarcloud.properties`,
which only Automatic Analysis read. Automatic Analysis is off in the
project settings; the two can't run together.
  - The whole repo is analysed as sources, with `tests/` as tests.
- `sonar.python.version=3.14`: the analyzer warns "No explicit support
for version 3.15" and falls back to 3.14 anyway.
  - It reads `coverage.xml` and sets `sonar.qualitygate.wait=true`.
- `ci.yml`:
- `test` runs `pytest --cov` and uploads `coverage.xml` as an artifact
kept 1 day.
- New `sonar` job: `SonarSource/sonarqube-scan-action` v8.3.0, the
latest release (SonarScanner CLI 8.1.0.6389), with full history.
- `sonar.projectVersion` comes from the newest `changelog/*.x.md`
heading, so "new code" on `main` restarts at each release.
- Only its scan step sees `SONAR_TOKEN`. The job runs no project code
and installs nothing.
- Without the token (Dependabot PRs) it skips with a notice and still
passes; `main` is analysed after the merge.
- The `ci` gate now needs `sonar`, so a failed quality gate blocks the
merge.
- `pyproject.toml`: `[tool.coverage.*]` measures `scripts/` with branch
coverage and relative paths, and sets `fail_under = 95`.

## The seven issues the CI scan found on `main`

| Rule | Where | Change |
|---|---|---|
| `githubactions:S8541` ×2 | pip installs in `lint` and `test` |
`--only-binary :all:` |
| `githubactions:S8544` ×2 | same | Hash-locked `requirements-dev.txt`,
compiled from the new `requirements-dev.in` with pip-tools on Python
3.14, installed with `--require-hashes` |
| `pythonsecurity:S8707` | `release_notes.py` | The version must look
like a release tag, and the file name is built from its major number
alone. The changelog directory is no longer a CLI argument;
`release.yml` never passed one. |
| `python:S5332` ×2 | `config.py`, the feed's XML namespaces | Accepted
in `sonar-project.properties` with the reason: they must equal the
feed's `xmlns` values and are never fetched. |

The lock is compiled on Python 3.14 because Dependabot's pip updater
takes the Python version from the lock's header and supports only up to
3.14 (the same setup as free-games-itchio-list).

## Coverage

Coverage of `scripts/` (line and branch) goes from 72 % to 100 %. The
new tests cover:

- `http_client`
- Bluesky, Discord and Mastodon
- `post_to_all`
- the multi-video and empty-window paths of `notify.main`
- `fetch_feed`
- the `release_notes` CLI

Tests still make no network calls.

The new tests also caught a real leak: `http_client` read the body of an
`HTTPError` but never closed it, and that error object is also the open
response. It is now closed.

## Audit, scanners and Dependabot

- zizmor 1.30.0 → 1.31.1. This needs zizmor-action v0.6.4 → v0.7.1,
because v0.6.4 can only run the zizmor releases it ships a lock for.
- New pins, all past the 7-day cooldown and on the same SHAs as the
other poli0981 repos: sonarqube-scan-action v8.3.0, upload-artifact
v7.0.2, download-artifact v8.0.2.
- Left for Dependabot because they are still inside the cooldown
(released 2026-10-19…23): ruff 0.17.2, setup-python v7.1.0,
zizmor-action v0.8.0, coverage 7.17.0, SonarScanner CLI 8.2.0.
- `dependabot.yml` is unchanged:
- the `pip` entry handles the `.in`/lock pair, and the groups still
match everything;
  - the `dependencies` label exists;
  - Dependabot alerts and security updates are on, with 0 open alerts.

## Verification

- Local (Python 3.15.1):
  - ruff is clean;
  - all tests pass with coverage at 100 %;
  - zizmor 1.31.1 reports no findings;
  - the lock installs with `--require-hashes --only-binary :all:`;
  - `release_notes.py v1.4.1` prints the new entry.
- CI on this PR: `lint`, `test`, `security`, `sonar` and `ci` pass. The
scanner log has no warnings, `coverage.xml` is imported, and the quality
gate passes.

## After the merge

- `main`'s first analysis with these settings closes the seven issues
above.
- Tags: `v1.4.0` (878c3eb) was never pushed. `v1.4.1` is yours to sign
and push as well.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 23:26:34 +00:00

122 lines
3.8 KiB
Python

"""
Thin urllib wrapper shared by every platform module.
One request path, one exception type. Callers catch `HttpError` and decide what the
status means for them. The URL is kept on the exception but left out of its message
because several endpoints carry credentials in the path.
"""
from __future__ import annotations
import json
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from config import HTTP_TIMEOUT, USER_AGENT
class HttpError(Exception):
"""Non-2xx response (`status` > 0) or transport failure (`status` == 0)."""
def __init__(self, status: int, body: str, url: str) -> None:
self.status = status
self.body = body
self.url = url
detail = body.strip()[:300]
super().__init__(f"HTTP {status} — {detail}" if status else f"connection error — {detail}")
def _request(
url: str,
*,
data: bytes | None = None,
headers: dict[str, str] | None = None,
method: str | None = None,
timeout: int = HTTP_TIMEOUT,
) -> tuple[bytes, dict[str, str]]:
"""Perform a request. Returns (body, lower-cased response headers)."""
if not url.startswith("https://"):
raise ValueError("Refusing non-HTTPS URL")
req = Request( # noqa: S310 — scheme checked above
url, data=data, headers={"User-Agent": USER_AGENT, **(headers or {})}, method=method
)
try:
with urlopen(req, timeout=timeout) as resp: # noqa: S310
return resp.read(), {k.lower(): v for k, v in resp.headers.items()}
except HTTPError as e:
try:
body = e.read().decode("utf-8", errors="replace")
finally:
e.close() # the error is also the response; leaving it open leaks it
raise HttpError(e.code, body, url) from e
except OSError as e: # URLError, timeouts, connection resets
raise HttpError(0, str(e), url) from e
def _as_dict(body: bytes) -> dict:
"""Parse a JSON body. Empty bodies (e.g. Discord 204) become {}."""
if not body.strip():
return {}
try:
parsed = json.loads(body)
except json.JSONDecodeError:
return {"_raw": body.decode("utf-8", errors="replace")}
return parsed if isinstance(parsed, dict) else {"_data": parsed}
def get_text(url: str, headers: dict[str, str] | None = None, timeout: int = HTTP_TIMEOUT) -> str:
body, _ = _request(url, headers=headers, timeout=timeout)
return body.decode("utf-8", errors="replace")
def get_bytes(
url: str, headers: dict[str, str] | None = None, timeout: int = HTTP_TIMEOUT
) -> tuple[bytes, str]:
"""Returns (body, content-type)."""
body, resp_headers = _request(url, headers=headers, timeout=timeout)
return body, resp_headers.get("content-type", "application/octet-stream")
def post_json(
url: str, payload: dict, headers: dict[str, str] | None = None, timeout: int = HTTP_TIMEOUT
) -> dict:
body, _ = _request(
url,
data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json", **(headers or {})},
method="POST",
timeout=timeout,
)
return _as_dict(body)
def post_form(
url: str, fields: dict, headers: dict[str, str] | None = None, timeout: int = HTTP_TIMEOUT
) -> dict:
body, _ = _request(
url,
data=urlencode(fields).encode("utf-8"),
headers={"Content-Type": "application/x-www-form-urlencoded", **(headers or {})},
method="POST",
timeout=timeout,
)
return _as_dict(body)
def post_bytes(
url: str,
data: bytes,
content_type: str,
headers: dict[str, str] | None = None,
timeout: int = HTTP_TIMEOUT,
) -> dict:
body, _ = _request(
url,
data=data,
headers={"Content-Type": content_type, **(headers or {})},
method="POST",
timeout=timeout,
)
return _as_dict(body)