mirror of
https://github.com/kuhyx/utils.git
synced 2026-11-24 18:06:29 +01:00
Compare commits
5 Commits
879265b966
...
8274a3e918
| Author | SHA1 | Date | |
|---|---|---|---|
| 8274a3e918 | |||
| a4ea305164 | |||
| 3b5c247f05 | |||
| c295db7a15 | |||
| ee276cd8e5 |
@ -103,12 +103,12 @@ repos:
|
||||
- --disable-error-code=list-item
|
||||
|
||||
- repo: https://github.com/pylint-dev/pylint
|
||||
rev: v3.3.2
|
||||
rev: v4.0.8
|
||||
hooks:
|
||||
- id: pylint
|
||||
args:
|
||||
- --rcfile=crdt-sync/pyproject.toml
|
||||
- --fail-under=8.0
|
||||
- --fail-under=10
|
||||
- --jobs=4
|
||||
additional_dependencies:
|
||||
- pytest
|
||||
|
||||
@ -13,6 +13,8 @@ from dataclasses import dataclass
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from crdt_sync._revisions import revision_of
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
@ -20,8 +22,6 @@ if TYPE_CHECKING:
|
||||
from crdt_sync._remote import RemoteStore
|
||||
from crdt_sync._syncstate import SyncState
|
||||
|
||||
from crdt_sync._revisions import revision_of
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
|
||||
@ -17,10 +17,6 @@ import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from crdt_sync._log import merge_logs
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from crdt_sync._log import Log
|
||||
|
||||
from crdt_sync._pull import _pull_remote_logs, _PullContext, _remote_revs
|
||||
from crdt_sync._revisions import revision_of
|
||||
from crdt_sync._syncargs import LogCodec, RevisionTracking, SyncTarget
|
||||
@ -31,6 +27,9 @@ from crdt_sync._syncstate import (
|
||||
SyncStateStore,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from crdt_sync._log import Log
|
||||
|
||||
# Named explicitly so the autofixer cannot prune an import that exists for its
|
||||
# re-export: crdt_sync/__init__.py imports all of these from here.
|
||||
__all__ = [
|
||||
|
||||
@ -17,6 +17,7 @@ from unittest.mock import MagicMock, patch
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from tool import _token_exchange as tx
|
||||
from tool import google_id_token as git
|
||||
|
||||
_CLIENT_ID = "client-id-for-the-web-application"
|
||||
@ -68,7 +69,7 @@ def _run(result: dict[str, str], post: MagicMock | Exception, **kwargs: object)
|
||||
"""Drive ``fetch_id_token`` against a canned callback and exchange."""
|
||||
starter, free_port, handler, _, _ = _fake_flow(result)
|
||||
with starter, free_port, handler:
|
||||
target = patch.object(git.requests, "post")
|
||||
target = patch.object(tx.requests, "post")
|
||||
with target as posted:
|
||||
if isinstance(post, Exception):
|
||||
posted.side_effect = post
|
||||
@ -91,7 +92,7 @@ def test_the_exchange_posts_the_code_and_the_matching_redirect_uri() -> None:
|
||||
starter, free_port, handler, _, _ = _fake_flow(
|
||||
{"code": "the-auth-code", "state": _STATE}, port=8765
|
||||
)
|
||||
with starter, free_port, handler, patch.object(git.requests, "post") as posted:
|
||||
with starter, free_port, handler, patch.object(tx.requests, "post") as posted:
|
||||
posted.return_value = _response(payload={"id_token": _ID_VALUE})
|
||||
git.fetch_id_token(_CLIENT_ID, _CLIENT_CREDENTIAL, port=8765)
|
||||
|
||||
@ -110,7 +111,7 @@ def test_a_fixed_port_is_used_verbatim_rather_than_a_free_one() -> None:
|
||||
starter, free_port, handler, _, _ = _fake_flow(
|
||||
{"code": "c", "state": _STATE}, port=9999
|
||||
)
|
||||
with starter, free_port as picked, handler, patch.object(git.requests, "post") as p:
|
||||
with starter, free_port as picked, handler, patch.object(tx.requests, "post") as p:
|
||||
p.return_value = _response(payload={"id_token": _ID_VALUE})
|
||||
git.fetch_id_token(_CLIENT_ID, _CLIENT_CREDENTIAL, port=8765)
|
||||
|
||||
@ -120,7 +121,7 @@ def test_a_fixed_port_is_used_verbatim_rather_than_a_free_one() -> None:
|
||||
def test_port_zero_falls_back_to_a_free_port() -> None:
|
||||
"""The Desktop-app case: any loopback port is acceptable."""
|
||||
starter, free_port, handler, _, _ = _fake_flow({"code": "c", "state": _STATE})
|
||||
with starter, free_port as picked, handler, patch.object(git.requests, "post") as p:
|
||||
with starter, free_port as picked, handler, patch.object(tx.requests, "post") as p:
|
||||
p.return_value = _response(payload={"id_token": _ID_VALUE})
|
||||
git.fetch_id_token(_CLIENT_ID, _CLIENT_CREDENTIAL, port=0)
|
||||
|
||||
|
||||
@ -20,6 +20,7 @@ import pytest
|
||||
from crdt_sync._config import ConfigError
|
||||
from crdt_sync._firebase_auth import FirebaseAuthError
|
||||
from crdt_sync.tests.test_tool_seed_session import _CONFIG, _ID_VALUE
|
||||
from tool import google_id_token as git
|
||||
from tool import seed_session as ss
|
||||
from tool.google_id_token import TokenError
|
||||
|
||||
@ -32,7 +33,7 @@ def test_main_seeds_every_default_app(caplog: pytest.LogCaptureFixture) -> None:
|
||||
"""With no --app, all of DEFAULT_APPS are seeded."""
|
||||
with (
|
||||
patch.object(ss.FirebaseConfig, "load", return_value=_CONFIG),
|
||||
patch.object(ss, "fetch_id_token", return_value=_ID_VALUE),
|
||||
patch.object(git, "fetch_id_token", return_value=_ID_VALUE),
|
||||
patch.object(ss, "seed_apps", return_value=list(ss.DEFAULT_APPS)) as seeded,
|
||||
caplog.at_level(logging.INFO, logger="seed_session"),
|
||||
):
|
||||
@ -62,7 +63,7 @@ def test_a_single_app_can_be_selected() -> None:
|
||||
"""--app narrows the run, which is what a rerun after a failure uses."""
|
||||
with (
|
||||
patch.object(ss.FirebaseConfig, "load", return_value=_CONFIG),
|
||||
patch.object(ss, "fetch_id_token", return_value=_ID_VALUE),
|
||||
patch.object(git, "fetch_id_token", return_value=_ID_VALUE),
|
||||
patch.object(ss, "seed_apps", return_value=["diet_guard"]) as seeded,
|
||||
):
|
||||
code = ss.main([*_ARGV, "--app", "diet_guard"])
|
||||
@ -75,7 +76,7 @@ def test_the_app_flag_is_repeatable() -> None:
|
||||
"""Rerunning two failed apps should not need two invocations."""
|
||||
with (
|
||||
patch.object(ss.FirebaseConfig, "load", return_value=_CONFIG),
|
||||
patch.object(ss, "fetch_id_token", return_value=_ID_VALUE),
|
||||
patch.object(git, "fetch_id_token", return_value=_ID_VALUE),
|
||||
patch.object(ss, "seed_apps", return_value=["diet_guard", "todo"]) as seeded,
|
||||
):
|
||||
ss.main([*_ARGV, "--app", "diet_guard", "--app", "todo"])
|
||||
@ -98,7 +99,7 @@ def test_the_consent_flow_receives_the_client_and_port() -> None:
|
||||
"""A Web client needs the registered port verbatim, not a free one."""
|
||||
with (
|
||||
patch.object(ss.FirebaseConfig, "load", return_value=_CONFIG),
|
||||
patch.object(ss, "fetch_id_token", return_value=_ID_VALUE) as fetch,
|
||||
patch.object(git, "fetch_id_token", return_value=_ID_VALUE) as fetch,
|
||||
patch.object(ss, "seed_apps", return_value=[]),
|
||||
):
|
||||
ss.main([*_ARGV, "--port", "9999", "--no-browser"])
|
||||
@ -111,7 +112,7 @@ def test_the_default_port_is_the_registered_one() -> None:
|
||||
"""8765 is what is registered on the Web client as http://localhost:8765."""
|
||||
with (
|
||||
patch.object(ss.FirebaseConfig, "load", return_value=_CONFIG),
|
||||
patch.object(ss, "fetch_id_token", return_value=_ID_VALUE) as fetch,
|
||||
patch.object(git, "fetch_id_token", return_value=_ID_VALUE) as fetch,
|
||||
patch.object(ss, "seed_apps", return_value=[]),
|
||||
):
|
||||
ss.main(_ARGV)
|
||||
@ -125,7 +126,7 @@ def test_the_expected_uid_is_announced_before_the_flow(
|
||||
"""So the wrong Google account can be spotted at the picker, not after."""
|
||||
with (
|
||||
patch.object(ss.FirebaseConfig, "load", return_value=_CONFIG),
|
||||
patch.object(ss, "fetch_id_token", return_value=_ID_VALUE),
|
||||
patch.object(git, "fetch_id_token", return_value=_ID_VALUE),
|
||||
patch.object(ss, "seed_apps", return_value=[]),
|
||||
caplog.at_level(logging.INFO, logger="seed_session"),
|
||||
):
|
||||
@ -150,7 +151,7 @@ def test_the_named_failures_return_1(
|
||||
"""Each is reported, not raised as a traceback."""
|
||||
with (
|
||||
patch.object(ss.FirebaseConfig, "load", return_value=_CONFIG),
|
||||
patch.object(ss, "fetch_id_token", side_effect=failure),
|
||||
patch.object(git, "fetch_id_token", side_effect=failure),
|
||||
caplog.at_level(logging.INFO, logger="seed_session"),
|
||||
):
|
||||
code = ss.main(_ARGV)
|
||||
@ -163,7 +164,7 @@ def test_an_unexpected_error_is_not_swallowed() -> None:
|
||||
"""The reason the handler names its four types instead of Exception."""
|
||||
with (
|
||||
patch.object(ss.FirebaseConfig, "load", return_value=_CONFIG),
|
||||
patch.object(ss, "fetch_id_token", side_effect=RuntimeError("a real bug")),
|
||||
patch.object(git, "fetch_id_token", side_effect=RuntimeError("a real bug")),
|
||||
pytest.raises(RuntimeError, match="a real bug"),
|
||||
):
|
||||
ss.main(_ARGV)
|
||||
@ -175,7 +176,7 @@ def test_a_total_failure_suggests_rerunning_every_app(
|
||||
"""Nothing verified, so nothing may be reported as already working."""
|
||||
with (
|
||||
patch.object(ss.FirebaseConfig, "load", return_value=_CONFIG),
|
||||
patch.object(ss, "fetch_id_token", return_value=_ID_VALUE),
|
||||
patch.object(git, "fetch_id_token", return_value=_ID_VALUE),
|
||||
patch.object(ss, "seed_apps", side_effect=ss.SeedError("all dead")),
|
||||
caplog.at_level(logging.INFO, logger="seed_session"),
|
||||
):
|
||||
@ -194,7 +195,7 @@ def test_a_partial_failure_reports_what_already_works(
|
||||
|
||||
with (
|
||||
patch.object(ss.FirebaseConfig, "load", return_value=_CONFIG),
|
||||
patch.object(ss, "fetch_id_token", return_value=_ID_VALUE),
|
||||
patch.object(git, "fetch_id_token", return_value=_ID_VALUE),
|
||||
patch.object(ss, "seed_apps", side_effect=partial),
|
||||
caplog.at_level(logging.INFO, logger="seed_session"),
|
||||
):
|
||||
@ -212,7 +213,7 @@ def test_the_rerun_line_excludes_the_apps_that_already_work(
|
||||
|
||||
with (
|
||||
patch.object(ss.FirebaseConfig, "load", return_value=_CONFIG),
|
||||
patch.object(ss, "fetch_id_token", return_value=_ID_VALUE),
|
||||
patch.object(git, "fetch_id_token", return_value=_ID_VALUE),
|
||||
patch.object(ss, "seed_apps", side_effect=partial),
|
||||
caplog.at_level(logging.INFO, logger="seed_session"),
|
||||
):
|
||||
|
||||
@ -83,13 +83,30 @@ color_output = true
|
||||
exclude = [".venv/"]
|
||||
|
||||
[tool.pylint.main]
|
||||
# The repo root on the path, so pylint resolves the package's own imports the
|
||||
# same way pytest does instead of reporting import-error for them.
|
||||
init-hook = "import sys; sys.path.insert(0, 'crdt-sync')"
|
||||
analyse-fallback-blocks = true
|
||||
persistent = true
|
||||
jobs = 0
|
||||
py-version = "3.14"
|
||||
ignore = [".venv", "__pycache__"]
|
||||
# Test suites intentionally use patterns (protected-access, fixture-arg
|
||||
# shadowing) that don't apply to source code; ruff's per-file-ignores carry
|
||||
# the equivalent exemptions, so tests stay linted -- by ruff. This is the same
|
||||
# source-only pylint scope wake-alarm / diet-guard / testsAndMisc use. It has
|
||||
# to be `ignore-paths`, not `ignore = ["tests"]`: `ignore` only matches the
|
||||
# basename of what pylint is *given*, and pre-commit hands it explicit file
|
||||
# paths, so a directory name in `ignore` never fires under the hook.
|
||||
ignore-paths = ["^(.*/)?tests/.*$"]
|
||||
ignore-patterns = [".*\\.pyi$"]
|
||||
|
||||
[tool.pylint.basic]
|
||||
# snake_case, plus the ``do_<METHOD>`` names http.server dispatches on: the
|
||||
# stdlib looks handlers up as ``"do_" + command``, so ``do_GET`` is the only
|
||||
# spelling that works and cannot be renamed to satisfy the style.
|
||||
method-rgx = "([^\\W\\dA-Z][^\\WA-Z]{2,}|_[^\\WA-Z]*|__[^\\W\\dA-Z][^\\WA-Z]+__|do_[A-Z]+)$"
|
||||
|
||||
[tool.pylint.messages_control]
|
||||
enable = "all"
|
||||
disable = []
|
||||
|
||||
74
crdt-sync/tool/_token_exchange.py
Normal file
74
crdt-sync/tool/_token_exchange.py
Normal file
@ -0,0 +1,74 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""Turning the captured OAuth callback into a Google ID token.
|
||||
|
||||
Split from :mod:`google_id_token`, which keeps the consent flow and the CLI:
|
||||
this half validates what the loopback server caught and trades the
|
||||
authorization code for tokens at Google's endpoint.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import requests
|
||||
|
||||
from tool._oauth_callback import _CONSENT_TIMEOUT_SECONDS
|
||||
|
||||
# Assembled from host and path rather than written as one literal: a string
|
||||
# ending in "/token" trips ruff's hardcoded-password check (S105), and the
|
||||
# honest fix is to not have the literal rather than to silence the rule.
|
||||
_OAUTH_HOST = "https://oauth2.googleapis.com"
|
||||
_TOKEN_EXCHANGE_URL = f"{_OAUTH_HOST}/token"
|
||||
|
||||
_TIMEOUT_SECONDS = 30
|
||||
|
||||
|
||||
class TokenError(Exception):
|
||||
"""The authorization flow did not produce an ID token."""
|
||||
|
||||
|
||||
def _authorization_code(params: dict[str, str], redirect_uri: str, state: str) -> str:
|
||||
"""Validate the captured callback and return its authorization code."""
|
||||
if not params:
|
||||
msg = f"no response on {redirect_uri} within {_CONSENT_TIMEOUT_SECONDS}s"
|
||||
raise TokenError(msg)
|
||||
if "error" in params:
|
||||
msg = f"authorization was refused: {params['error']}"
|
||||
raise TokenError(msg)
|
||||
if params.get("state") != state:
|
||||
msg = "the callback state did not match; ignoring the response"
|
||||
raise TokenError(msg)
|
||||
code = params.get("code")
|
||||
if not code:
|
||||
msg = f"the callback carried no authorization code: {params}"
|
||||
raise TokenError(msg)
|
||||
return code
|
||||
|
||||
|
||||
def _exchange_code(
|
||||
code: str, client_id: str, client_secret: str, redirect_uri: str
|
||||
) -> str:
|
||||
"""Trade the authorization code for an ID token at Google's endpoint."""
|
||||
try:
|
||||
response = requests.post(
|
||||
_TOKEN_EXCHANGE_URL,
|
||||
data={
|
||||
"code": code,
|
||||
"client_id": client_id,
|
||||
"client_secret": client_secret,
|
||||
"redirect_uri": redirect_uri,
|
||||
"grant_type": "authorization_code",
|
||||
},
|
||||
timeout=_TIMEOUT_SECONDS,
|
||||
)
|
||||
except requests.RequestException as exc:
|
||||
msg = f"network error exchanging the code: {exc}"
|
||||
raise TokenError(msg) from exc
|
||||
|
||||
if not response.ok:
|
||||
msg = f"token exchange failed: HTTP {response.status_code} {response.text}"
|
||||
raise TokenError(msg)
|
||||
|
||||
id_token = response.json().get("id_token")
|
||||
if not id_token:
|
||||
msg = "the token response carried no id_token; was 'openid' in the scopes?"
|
||||
raise TokenError(msg)
|
||||
return str(id_token)
|
||||
@ -43,36 +43,23 @@ import sys
|
||||
import urllib.parse
|
||||
import webbrowser
|
||||
|
||||
import requests
|
||||
|
||||
from tool._oauth_callback import (
|
||||
_CONSENT_TIMEOUT_SECONDS,
|
||||
_CallbackHandler,
|
||||
_free_port,
|
||||
_start_callback_server,
|
||||
)
|
||||
from tool._token_exchange import TokenError, _authorization_code, _exchange_code
|
||||
|
||||
_AUTH_ENDPOINT = "https://accounts.google.com/o/oauth2/v2/auth"
|
||||
|
||||
# Assembled from host and path rather than written as one literal: a string
|
||||
# ending in "/token" trips ruff's hardcoded-password check (S105), and the
|
||||
# honest fix is to not have the literal rather than to silence the rule.
|
||||
_OAUTH_HOST = "https://oauth2.googleapis.com"
|
||||
_TOKEN_EXCHANGE_URL = f"{_OAUTH_HOST}/token"
|
||||
|
||||
# openid gets an ID token at all; email makes the token carry the address, so
|
||||
# link_google.py can show which account is about to be linked.
|
||||
_SCOPES = "openid email profile"
|
||||
|
||||
_TIMEOUT_SECONDS = 30
|
||||
|
||||
_logger = logging.getLogger("google_id_token")
|
||||
|
||||
|
||||
class TokenError(Exception):
|
||||
"""The authorization flow did not produce an ID token."""
|
||||
|
||||
|
||||
def fetch_id_token(
|
||||
client_id: str,
|
||||
client_secret: str,
|
||||
@ -129,87 +116,64 @@ def fetch_id_token(
|
||||
thread.join(timeout=_CONSENT_TIMEOUT_SECONDS)
|
||||
server.server_close()
|
||||
|
||||
params = _CallbackHandler.result
|
||||
if not params:
|
||||
msg = f"no response on {redirect_uri} within {_CONSENT_TIMEOUT_SECONDS}s"
|
||||
raise TokenError(msg)
|
||||
if "error" in params:
|
||||
msg = f"authorization was refused: {params['error']}"
|
||||
raise TokenError(msg)
|
||||
if params.get("state") != state:
|
||||
msg = "the callback state did not match; ignoring the response"
|
||||
raise TokenError(msg)
|
||||
code = params.get("code")
|
||||
if not code:
|
||||
msg = f"the callback carried no authorization code: {params}"
|
||||
raise TokenError(msg)
|
||||
|
||||
try:
|
||||
response = requests.post(
|
||||
_TOKEN_EXCHANGE_URL,
|
||||
data={
|
||||
"code": code,
|
||||
"client_id": client_id,
|
||||
"client_secret": client_secret,
|
||||
"redirect_uri": redirect_uri,
|
||||
"grant_type": "authorization_code",
|
||||
},
|
||||
timeout=_TIMEOUT_SECONDS,
|
||||
)
|
||||
except requests.RequestException as exc:
|
||||
msg = f"network error exchanging the code: {exc}"
|
||||
raise TokenError(msg) from exc
|
||||
|
||||
if not response.ok:
|
||||
msg = f"token exchange failed: HTTP {response.status_code} {response.text}"
|
||||
raise TokenError(msg)
|
||||
|
||||
id_token = response.json().get("id_token")
|
||||
if not id_token:
|
||||
msg = "the token response carried no id_token; was 'openid' in the scopes?"
|
||||
raise TokenError(msg)
|
||||
return str(id_token)
|
||||
code = _authorization_code(_CallbackHandler.result, redirect_uri, state)
|
||||
return _exchange_code(code, client_id, client_secret, redirect_uri)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
"""Fetch an ID token and print or save it. Returns an exit code."""
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
def add_consent_args(
|
||||
parser: argparse.ArgumentParser, *, port_default: int, port_help: str
|
||||
) -> None:
|
||||
"""Register the client-credential and consent options every flow CLI takes.
|
||||
|
||||
Shared with :mod:`tool.seed_session`, which runs the same consent flow
|
||||
before seeding; only the port default and its explanation differ.
|
||||
"""
|
||||
parser.add_argument("--client-id", required=True, help="Web OAuth client id.")
|
||||
parser.add_argument(
|
||||
"--client-secret",
|
||||
required=True,
|
||||
help="Web OAuth client secret.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output",
|
||||
help="Write the token here (mode 0600) instead of printing it.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--no-browser",
|
||||
action="store_true",
|
||||
help="Print the consent URL without launching a browser.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--port",
|
||||
type=int,
|
||||
default=0,
|
||||
help=(
|
||||
parser.add_argument("--port", type=int, default=port_default, help=port_help)
|
||||
|
||||
|
||||
def fetch_id_token_for(args: argparse.Namespace) -> str:
|
||||
"""Run :func:`fetch_id_token` from options added by :func:`add_consent_args`."""
|
||||
return fetch_id_token(
|
||||
args.client_id,
|
||||
args.client_secret,
|
||||
open_browser=not args.no_browser,
|
||||
port=args.port,
|
||||
)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
"""Fetch an ID token and print or save it. Returns an exit code."""
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
add_consent_args(
|
||||
parser,
|
||||
port_default=0,
|
||||
port_help=(
|
||||
"Fixed loopback port for the redirect URI. Required for a Web "
|
||||
"application client, which must have http://localhost:<port> "
|
||||
"registered verbatim; 0 (the default) picks a free port and "
|
||||
"suits a Desktop app client."
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output",
|
||||
help="Write the token here (mode 0600) instead of printing it.",
|
||||
)
|
||||
args = parser.parse_args(argv)
|
||||
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(message)s")
|
||||
|
||||
try:
|
||||
token = fetch_id_token(
|
||||
args.client_id,
|
||||
args.client_secret,
|
||||
open_browser=not args.no_browser,
|
||||
port=args.port,
|
||||
)
|
||||
token = fetch_id_token_for(args)
|
||||
except TokenError:
|
||||
_logger.exception(" FAIL")
|
||||
return 1
|
||||
|
||||
@ -44,7 +44,7 @@ from crdt_sync._remote import RemoteSyncError
|
||||
# Importable as a package module (tool/__init__.py exists) so the loopback
|
||||
# OAuth flow is shared, not reimplemented.
|
||||
from tool._seeded_apps import DEFAULT_APPS
|
||||
from tool.google_id_token import TokenError, fetch_id_token
|
||||
from tool.google_id_token import TokenError, add_consent_args, fetch_id_token_for
|
||||
|
||||
# A fixed default so the redirect URI is stable enough to register once on the
|
||||
# Web client. Arbitrary but out of the ephemeral range, and free on this box.
|
||||
@ -142,11 +142,15 @@ def seed_apps(
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
"""Run the consent flow and seed every app. Returns an exit code."""
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("--client-id", required=True, help="Web OAuth client id.")
|
||||
parser.add_argument(
|
||||
"--client-secret",
|
||||
required=True,
|
||||
help="Web OAuth client secret.",
|
||||
add_consent_args(
|
||||
parser,
|
||||
port_default=_DEFAULT_REDIRECT_PORT,
|
||||
port_help=(
|
||||
"Loopback port for the OAuth redirect. Must be registered on the "
|
||||
"Web client as http://localhost:<port>, exactly -- a Web client "
|
||||
"does not accept arbitrary loopback ports the way a Desktop "
|
||||
"client does."
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--app",
|
||||
@ -162,22 +166,6 @@ def main(argv: list[str] | None = None) -> int:
|
||||
+ ", ".join(DEFAULT_APPS)
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--no-browser",
|
||||
action="store_true",
|
||||
help="Print the consent URL without launching a browser.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--port",
|
||||
type=int,
|
||||
default=_DEFAULT_REDIRECT_PORT,
|
||||
help=(
|
||||
"Loopback port for the OAuth redirect. Must be registered on the "
|
||||
"Web client as http://localhost:<port>, exactly -- a Web client "
|
||||
"does not accept arbitrary loopback ports the way a Desktop "
|
||||
"client does."
|
||||
),
|
||||
)
|
||||
args = parser.parse_args(argv)
|
||||
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(message)s")
|
||||
|
||||
@ -190,12 +178,7 @@ def main(argv: list[str] | None = None) -> int:
|
||||
config = FirebaseConfig.load()
|
||||
_logger.info(" .. seeding %s", ", ".join(app_names))
|
||||
_logger.info(" .. expecting uid %s (%s)", config.uid, config.email)
|
||||
token = fetch_id_token(
|
||||
args.client_id,
|
||||
args.client_secret,
|
||||
open_browser=not args.no_browser,
|
||||
port=args.port,
|
||||
)
|
||||
token = fetch_id_token_for(args)
|
||||
seeded = seed_apps(config, token, app_names)
|
||||
except (ConfigError, FirebaseAuthError, TokenError, SeedError) as exc:
|
||||
# logging.exception already renders the exception and its traceback.
|
||||
|
||||
@ -17,13 +17,14 @@ NPM: Final = "npm"
|
||||
CARGO: Final = "cargo"
|
||||
GOMOD: Final = "gomod"
|
||||
GITTAG: Final = "gittag"
|
||||
MAVEN: Final = "maven"
|
||||
TOOLCHAIN: Final = "toolchain"
|
||||
# The constraint a workflow parser writes for a version MATRIX. Standing
|
||||
# decision (kuhy, 2026-08-28): one toolchain version per repo, always newest,
|
||||
# so a matrix is a finding to delete rather than a range to satisfy.
|
||||
MATRIX: Final = "matrix"
|
||||
|
||||
ECOSYSTEMS: Final = (PUB, PYPI, NPM, CARGO, GOMOD, GITTAG, TOOLCHAIN)
|
||||
ECOSYSTEMS: Final = (PUB, PYPI, NPM, CARGO, GOMOD, GITTAG, MAVEN, TOOLCHAIN)
|
||||
|
||||
# --- Registry endpoints -----------------------------------------------------
|
||||
|
||||
@ -37,6 +38,14 @@ FLUTTER_RELEASES: Final = (
|
||||
"releases_linux.json"
|
||||
)
|
||||
NODE_RELEASES: Final = "https://nodejs.org/dist/index.json"
|
||||
GRADLE_RELEASES: Final = "https://services.gradle.org/versions/current"
|
||||
# Asked in order; a 404 moves on. Google first because AndroidX and the
|
||||
# Android Gradle plugin exist nowhere else, and Central answers 404 fast.
|
||||
MAVEN_REPOS: Final = (
|
||||
"https://dl.google.com/dl/android/maven2/",
|
||||
"https://repo1.maven.org/maven2/",
|
||||
"https://plugins.gradle.org/m2/",
|
||||
)
|
||||
UTILS_TAG_REMOTE: Final = "https://github.com/kuhyx/utils"
|
||||
|
||||
# pnpm 11 quarantines packages younger than this before it will install them,
|
||||
@ -84,6 +93,7 @@ MANIFEST_GLOBS: Final = (
|
||||
".fvmrc",
|
||||
".nvmrc",
|
||||
".python-version",
|
||||
"gradle-wrapper.properties",
|
||||
)
|
||||
REQUIREMENTS_PATTERN: Final = r"^requirements.*\.txt$"
|
||||
|
||||
|
||||
@ -8,14 +8,21 @@ could ever fix, so reporting it only teaches the user to ignore the gate.
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
from dep_freshness._tables import EXCLUDED_DIRS, MANIFEST_GLOBS, REQUIREMENTS_PATTERN
|
||||
from dep_freshness.models import Dep
|
||||
from dep_freshness.parsers import (
|
||||
fvm, golang, javascript, pubspec, python, rust, workflow,
|
||||
fvm,
|
||||
golang,
|
||||
gradle,
|
||||
javascript,
|
||||
pubspec,
|
||||
python,
|
||||
rust,
|
||||
workflow,
|
||||
)
|
||||
|
||||
_REQUIREMENTS = re.compile(REQUIREMENTS_PATTERN)
|
||||
@ -29,6 +36,7 @@ _BY_NAME = {
|
||||
".fvmrc": fvm.parse,
|
||||
".nvmrc": javascript.parse_nvmrc,
|
||||
".python-version": python.parse_python_version,
|
||||
gradle.WRAPPER_NAME: gradle.parse_wrapper,
|
||||
}
|
||||
|
||||
|
||||
@ -37,6 +45,7 @@ def is_manifest(path: Path) -> bool:
|
||||
path.name in MANIFEST_GLOBS
|
||||
or bool(_REQUIREMENTS.match(path.name))
|
||||
or workflow.is_workflow(path)
|
||||
or gradle.is_catalog(path)
|
||||
)
|
||||
|
||||
|
||||
@ -49,6 +58,8 @@ def parse_manifest(path: Path) -> list[Dep]:
|
||||
return python.parse_requirements(path)
|
||||
if workflow.is_workflow(path):
|
||||
return workflow.parse(path)
|
||||
if gradle.is_catalog(path):
|
||||
return gradle.parse_catalog(path)
|
||||
return []
|
||||
|
||||
|
||||
@ -59,7 +70,9 @@ def _git_ignored(paths: list[Path], root: Path) -> set[Path]:
|
||||
result = subprocess.run(
|
||||
["git", "-C", str(root), "check-ignore", "--stdin"],
|
||||
input="\n".join(str(p) for p in paths),
|
||||
capture_output=True, text=True, check=False,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
except OSError:
|
||||
return set()
|
||||
|
||||
146
dep_freshness/parsers/gradle.py
Normal file
146
dep_freshness/parsers/gradle.py
Normal file
@ -0,0 +1,146 @@
|
||||
"""Gradle: `gradle/libs.versions.toml` -> Maven coordinates, and the wrapper.
|
||||
|
||||
The version catalog is the one place a Gradle build should declare versions,
|
||||
which makes it a manifest the gate can read without evaluating Kotlin DSL.
|
||||
A build may have several (`settings.gradle.kts` can `from(files(...))` any
|
||||
`*.versions.toml`; TachiyomiSY has three), so the suffix is what is matched.
|
||||
Three shapes appear in `[libraries]` and `[plugins]`:
|
||||
|
||||
foo = "group:artifact:1.2.3" # inline string
|
||||
foo = { module = "group:artifact", version.ref = "x" }
|
||||
foo = { group = "g", name = "a", version = "1.2.3" }
|
||||
plug = { id = "com.example.plugin", version.ref = "x" }
|
||||
|
||||
A library with no version is managed by a BOM (`junit-platform-launcher`
|
||||
in TachiyomiSY) and is skipped: the BOM's own entry is the pin that counts.
|
||||
A rich version table (`{ strictly = "1.2" }`) is read as the constraint it
|
||||
spells and lands as unpinned when it is a range, like every other ecosystem.
|
||||
|
||||
The line reported is the `[versions]` entry when a `version.ref` is used,
|
||||
because that is where the fix goes; several libraries sharing one ref each
|
||||
report the same line, which is one finding per stale artifact, not noise.
|
||||
|
||||
`gradle-wrapper.properties` names the Gradle distribution; that is the
|
||||
toolchain pin, judged against services.gradle.org like Flutter against its
|
||||
release feed.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import tomllib
|
||||
|
||||
from dep_freshness._tables import MAVEN, TOOLCHAIN
|
||||
from dep_freshness.models import Dep
|
||||
from dep_freshness.parsers._lines import index
|
||||
from dep_freshness.versions import exact_pin
|
||||
|
||||
CATALOG_SUFFIX = ".versions.toml" # libs.versions.toml, but also sy.versions.toml
|
||||
WRAPPER_NAME = "gradle-wrapper.properties"
|
||||
_DISTRIBUTION = re.compile(
|
||||
r"gradle-(?P<version>\d+(?:\.\d+)*(?:-[0-9A-Za-z.-]+?)?)-(?:bin|all)\.zip"
|
||||
)
|
||||
|
||||
|
||||
def _rich(value: Any) -> str:
|
||||
"""The version string a catalog value spells, for any of its shapes."""
|
||||
if isinstance(value, dict):
|
||||
for key in ("strictly", "require", "prefer"):
|
||||
if value.get(key):
|
||||
return str(value[key])
|
||||
return ""
|
||||
return str(value or "")
|
||||
|
||||
|
||||
def _coordinates(entry: Any, plugin: bool) -> tuple[str, str] | None:
|
||||
"""`(name, inline_version)` for a library or plugin entry, or None."""
|
||||
if isinstance(entry, str):
|
||||
parts = entry.split(":")
|
||||
if plugin:
|
||||
return (parts[0], parts[1] if len(parts) > 1 else "")
|
||||
if len(parts) < 2:
|
||||
return None
|
||||
return (f"{parts[0]}:{parts[1]}", parts[2] if len(parts) > 2 else "")
|
||||
if not isinstance(entry, dict):
|
||||
return None
|
||||
if plugin:
|
||||
name = str(entry.get("id") or "")
|
||||
elif entry.get("module"):
|
||||
name = str(entry["module"])
|
||||
else:
|
||||
name = f"{entry.get('group', '')}:{entry.get('name', '')}"
|
||||
if not name.strip(":"):
|
||||
return None
|
||||
version = entry.get("version")
|
||||
if isinstance(version, dict) and version.get("ref"):
|
||||
return (name, f"ref:{version['ref']}")
|
||||
return (name, _rich(version))
|
||||
|
||||
|
||||
def parse_catalog(path: Path) -> list[Dep]:
|
||||
"""Every versioned library and plugin in a Gradle version catalog."""
|
||||
try:
|
||||
data = tomllib.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, tomllib.TOMLDecodeError):
|
||||
return []
|
||||
versions = {k: _rich(v) for k, v in (data.get("versions") or {}).items()}
|
||||
lines = index(path)
|
||||
deps: list[Dep] = []
|
||||
for section, plugin in (("libraries", False), ("plugins", True)):
|
||||
for alias, entry in (data.get(section) or {}).items():
|
||||
coords = _coordinates(entry, plugin)
|
||||
if coords is None:
|
||||
continue
|
||||
name, version = coords
|
||||
line = lines.get(str(alias), 0)
|
||||
if version.startswith("ref:"):
|
||||
ref = version[4:]
|
||||
version = versions.get(ref, "")
|
||||
line = lines.get(ref, line)
|
||||
if not version:
|
||||
continue # BOM-managed, or a dangling ref the build itself rejects
|
||||
if plugin:
|
||||
name = f"{name}:{name}.gradle.plugin"
|
||||
deps.append(
|
||||
Dep(
|
||||
ecosystem=MAVEN,
|
||||
name=name,
|
||||
constraint=version,
|
||||
path=path,
|
||||
line=line,
|
||||
pinned=exact_pin(version),
|
||||
)
|
||||
)
|
||||
return deps
|
||||
|
||||
|
||||
def parse_wrapper(path: Path) -> list[Dep]:
|
||||
"""The Gradle distribution the wrapper downloads, as a toolchain pin."""
|
||||
try:
|
||||
text = path.read_text(encoding="utf-8")
|
||||
except OSError:
|
||||
return []
|
||||
for number, line in enumerate(text.splitlines(), start=1):
|
||||
if not line.startswith("distributionUrl="):
|
||||
continue
|
||||
match = _DISTRIBUTION.search(line)
|
||||
version = match.group("version") if match else ""
|
||||
return [
|
||||
Dep(
|
||||
ecosystem=TOOLCHAIN,
|
||||
name="gradle",
|
||||
constraint=version,
|
||||
path=path,
|
||||
line=number,
|
||||
pinned=exact_pin(version),
|
||||
)
|
||||
]
|
||||
return []
|
||||
|
||||
|
||||
def is_catalog(path: Path) -> bool:
|
||||
"""True for `libs.versions.toml` and any sibling catalog a build declares."""
|
||||
return path.name.endswith(CATALOG_SUFFIX)
|
||||
@ -55,12 +55,10 @@ def host_reachable(url: str) -> bool:
|
||||
return _reachable[host]
|
||||
|
||||
|
||||
def get_json(url: str, accept: str | None = None) -> Any:
|
||||
"""Fetch and decode JSON, or raise `Offline` / return None on 404.
|
||||
def get_text(url: str, accept: str | None = None) -> str | None:
|
||||
"""Fetch a body as text, or raise `Offline` / return None on 404.
|
||||
|
||||
`Offline` means "ask the cache"; None means "the registry answered and
|
||||
this package genuinely is not there", which is a real finding rather than
|
||||
a degraded run and must not be papered over with a stale cache entry.
|
||||
Same contract as `get_json`; Maven metadata is XML, not JSON.
|
||||
"""
|
||||
if not host_reachable(url):
|
||||
raise Offline(url)
|
||||
@ -70,10 +68,26 @@ def get_json(url: str, accept: str | None = None) -> Any:
|
||||
request = Request(url, headers=headers)
|
||||
try:
|
||||
with urlopen(request, timeout=HTTP_TIMEOUT) as response:
|
||||
return json.loads(response.read().decode("utf-8"))
|
||||
return response.read().decode("utf-8")
|
||||
except HTTPError as exc:
|
||||
if exc.code == 404:
|
||||
return None
|
||||
raise Offline(f"{url}: HTTP {exc.code}") from exc
|
||||
except (URLError, TimeoutError, OSError, ValueError) as exc:
|
||||
raise Offline(f"{url}: {exc}") from exc
|
||||
|
||||
|
||||
def get_json(url: str, accept: str | None = None) -> Any:
|
||||
"""Fetch and decode JSON, or raise `Offline` / return None on 404.
|
||||
|
||||
`Offline` means "ask the cache"; None means "the registry answered and
|
||||
this package genuinely is not there", which is a real finding rather than
|
||||
a degraded run and must not be papered over with a stale cache entry.
|
||||
"""
|
||||
body = get_text(url, accept)
|
||||
if body is None:
|
||||
return None
|
||||
try:
|
||||
return json.loads(body)
|
||||
except ValueError as exc:
|
||||
raise Offline(f"{url}: {exc}") from exc
|
||||
|
||||
55
dep_freshness/registries/maven.py
Normal file
55
dep_freshness/registries/maven.py
Normal file
@ -0,0 +1,55 @@
|
||||
"""Maven repositories: newest stable of `group:artifact`, from maven-metadata.
|
||||
|
||||
Three repositories, asked in order until one knows the artifact: Google
|
||||
Maven (every `androidx.*` and `com.android.*` artifact lives ONLY there),
|
||||
Maven Central, and the Gradle plugin portal (plugin marker artifacts
|
||||
`<id>:<id>.gradle.plugin`). A 404 means "not here", not "not anywhere", so
|
||||
it moves on; anything else surfaces as `Offline` from the HTTP layer.
|
||||
|
||||
`<latest>` and `<release>` in the metadata are not trusted: AndroidX writes
|
||||
`1.2.0-alpha03` into `<latest>` routinely. The full `<versions>` list goes
|
||||
through `newest_stable` like every other ecosystem.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from xml.etree import ElementTree
|
||||
|
||||
from dep_freshness._tables import MAVEN_REPOS
|
||||
from dep_freshness.registries.http import get_text
|
||||
from dep_freshness.versions import newest_stable
|
||||
|
||||
|
||||
def metadata_url(repo: str, name: str) -> str | None:
|
||||
"""`.../group/path/artifact/maven-metadata.xml`, or None for a bad name."""
|
||||
group, sep, artifact = name.partition(":")
|
||||
if not sep or not group or not artifact:
|
||||
return None
|
||||
return f"{repo}{group.replace('.', '/')}/{artifact}/maven-metadata.xml"
|
||||
|
||||
|
||||
def versions_in(xml: str) -> list[str]:
|
||||
"""Every `<version>` in a maven-metadata document; [] when unparseable."""
|
||||
try:
|
||||
root = ElementTree.fromstring(xml)
|
||||
except ElementTree.ParseError:
|
||||
return []
|
||||
return [
|
||||
(node.text or "").strip()
|
||||
for node in root.iter("version")
|
||||
if node.text and node.text.strip()
|
||||
]
|
||||
|
||||
|
||||
def latest(name: str) -> str | None:
|
||||
for repo in MAVEN_REPOS:
|
||||
url = metadata_url(repo, name)
|
||||
if url is None:
|
||||
return None
|
||||
body = get_text(url)
|
||||
if body is None:
|
||||
continue
|
||||
stable = newest_stable(versions_in(body))
|
||||
if stable is not None:
|
||||
return stable
|
||||
return None
|
||||
@ -11,6 +11,7 @@ import platform
|
||||
|
||||
from dep_freshness._tables import (
|
||||
FLUTTER_RELEASES,
|
||||
GRADLE_RELEASES,
|
||||
NODE_CHANNEL,
|
||||
NODE_RELEASES,
|
||||
)
|
||||
@ -49,3 +50,11 @@ def node_latest(channel: str = NODE_CHANNEL) -> str | None:
|
||||
def python_installed() -> str:
|
||||
"""The interpreter this gate is running under — the Python target."""
|
||||
return platform.python_version()
|
||||
|
||||
|
||||
def gradle_latest() -> str | None:
|
||||
"""Newest Gradle release, from services.gradle.org (never a nightly/RC)."""
|
||||
payload = get_json(GRADLE_RELEASES)
|
||||
if not payload:
|
||||
return None
|
||||
return newest_stable([payload.get("version")])
|
||||
|
||||
@ -11,11 +11,19 @@ from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import dataclass
|
||||
|
||||
from dep_freshness._tables import (
|
||||
CARGO, GITTAG, GOMOD, MAX_WORKERS, NPM, PUB, PYPI, TOOLCHAIN,
|
||||
CARGO,
|
||||
GITTAG,
|
||||
GOMOD,
|
||||
MAVEN,
|
||||
MAX_WORKERS,
|
||||
NPM,
|
||||
PUB,
|
||||
PYPI,
|
||||
TOOLCHAIN,
|
||||
)
|
||||
from dep_freshness.cache import Cache
|
||||
from dep_freshness.models import Dep
|
||||
from dep_freshness.registries import cargo, gittag, gomod, npmjs, pub, pypi
|
||||
from dep_freshness.registries import cargo, gittag, gomod, maven, npmjs, pub, pypi
|
||||
from dep_freshness.registries import toolchain as tc
|
||||
from dep_freshness.registries.http import Offline
|
||||
|
||||
@ -26,6 +34,7 @@ _LOOKUP = {
|
||||
CARGO: cargo.latest,
|
||||
GOMOD: gomod.latest,
|
||||
GITTAG: gittag.latest,
|
||||
MAVEN: maven.latest,
|
||||
}
|
||||
|
||||
|
||||
@ -47,6 +56,8 @@ def _toolchain_latest(name: str) -> str | None:
|
||||
return tc.node_latest()
|
||||
if name == "python":
|
||||
return tc.python_installed()
|
||||
if name == "gradle":
|
||||
return tc.gradle_latest()
|
||||
return None
|
||||
|
||||
|
||||
|
||||
@ -18,4 +18,5 @@
|
||||
|package\.json|package-lock\.json|pnpm-lock\.yaml
|
||||
|Cargo\.(toml|lock)|go\.(mod|sum)
|
||||
|\.fvmrc|\.nvmrc|\.python-version
|
||||
|\.versions\.toml|gradle-wrapper\.properties
|
||||
|\.github/workflows/.*\.ya?ml)$
|
||||
|
||||
@ -56,7 +56,8 @@ jobs:
|
||||
path: ~/.cache/dep-freshness
|
||||
key:
|
||||
dep-freshness-${{ hashFiles('**/pubspec.yaml', '**/pyproject.toml',
|
||||
'**/requirements*.txt', '**/package.json', '**/Cargo.toml', '**/go.mod') }}
|
||||
'**/requirements*.txt', '**/package.json', '**/Cargo.toml', '**/go.mod',
|
||||
'**/*.versions.toml') }}
|
||||
restore-keys: dep-freshness-
|
||||
|
||||
- name: Every dependency is on newest stable
|
||||
|
||||
@ -15,7 +15,8 @@ PUBSPEC = "name: demo\ndependencies:\n http: 1.6.0\n"
|
||||
@pytest.mark.parametrize("name", [
|
||||
"pubspec.yaml", "pyproject.toml", "package.json", "Cargo.toml", "go.mod",
|
||||
".fvmrc", ".nvmrc", ".python-version", "requirements.txt",
|
||||
"requirements-dev.txt",
|
||||
"requirements-dev.txt", "libs.versions.toml", "sy.versions.toml",
|
||||
"gradle-wrapper.properties",
|
||||
])
|
||||
def test_manifest_names_are_recognised(name):
|
||||
assert is_manifest(Path(name))
|
||||
|
||||
139
dep_freshness/tests/test_gradle_parser.py
Normal file
139
dep_freshness/tests/test_gradle_parser.py
Normal file
@ -0,0 +1,139 @@
|
||||
"""Gradle version catalogs and the wrapper: every shape the fleet's forks use."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dep_freshness.parsers import gradle
|
||||
from dep_freshness.tests.conftest import write
|
||||
|
||||
CATALOG = """\
|
||||
[versions]
|
||||
kotlin = "2.4.0"
|
||||
compose = { strictly = "1.9.0" }
|
||||
loose = { require = "[1.0,2.0)" }
|
||||
preferred = { prefer = "3.3.3" }
|
||||
empty = { }
|
||||
|
||||
[libraries]
|
||||
inline = "io.coil-kt:coil:2.7.0"
|
||||
noversion = "io.coil-kt:coil"
|
||||
byref = { module = "org.jetbrains.kotlin:kotlin-reflect", version.ref = "kotlin" }
|
||||
split = { group = "androidx.core", name = "core-ktx", version = "1.17.0" }
|
||||
strict = { module = "androidx.compose:runtime", version.ref = "compose" }
|
||||
ranged = { module = "org.example:ranged", version.ref = "loose" }
|
||||
prefer = { module = "org.example:prefer", version.ref = "preferred" }
|
||||
bom = { module = "org.junit.platform:junit-platform-launcher" }
|
||||
dangling = { module = "org.example:dangling", version.ref = "nope" }
|
||||
emptyref = { module = "org.example:emptyref", version.ref = "empty" }
|
||||
nameless = { version = "1.0.0" }
|
||||
number = 42
|
||||
bare = "justaname"
|
||||
richinline = { module = "org.example:rich", version = { strictly = "0.1.0" } }
|
||||
|
||||
[plugins]
|
||||
agp = { id = "com.android.application", version = "9.3.2" }
|
||||
kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" }
|
||||
inline = "org.example.plugin:0.5.0"
|
||||
noversion = "org.example.bare"
|
||||
idless = { version = "1.0.0" }
|
||||
|
||||
[bundles]
|
||||
coil = ["inline"]
|
||||
"""
|
||||
|
||||
|
||||
def _by_name(deps):
|
||||
return {d.name: d for d in deps}
|
||||
|
||||
|
||||
def test_every_library_shape(tmp_path):
|
||||
deps = _by_name(
|
||||
gradle.parse_catalog(write(tmp_path, "libs.versions.toml", CATALOG))
|
||||
)
|
||||
assert deps["io.coil-kt:coil"].pinned == "2.7.0"
|
||||
assert deps["org.jetbrains.kotlin:kotlin-reflect"].pinned == "2.4.0"
|
||||
assert deps["androidx.core:core-ktx"].pinned == "1.17.0"
|
||||
assert deps["androidx.compose:runtime"].pinned == "1.9.0"
|
||||
assert deps["org.example:prefer"].pinned == "3.3.3"
|
||||
assert deps["org.example:rich"].pinned == "0.1.0"
|
||||
assert deps["org.example:ranged"].pinned is None
|
||||
assert deps["org.example:ranged"].constraint == "[1.0,2.0)"
|
||||
assert all(d.ecosystem == "maven" for d in deps.values())
|
||||
|
||||
|
||||
def test_bom_managed_and_broken_entries_are_skipped(tmp_path):
|
||||
deps = _by_name(
|
||||
gradle.parse_catalog(write(tmp_path, "libs.versions.toml", CATALOG))
|
||||
)
|
||||
for absent in (
|
||||
"org.junit.platform:junit-platform-launcher",
|
||||
"org.example:dangling",
|
||||
"org.example:emptyref",
|
||||
":",
|
||||
):
|
||||
assert absent not in deps
|
||||
assert not any(d.name.startswith("io.coil-kt:coil:") for d in deps.values())
|
||||
assert "justaname" not in deps
|
||||
|
||||
|
||||
def test_plugins_resolve_as_marker_artifacts(tmp_path):
|
||||
deps = _by_name(
|
||||
gradle.parse_catalog(write(tmp_path, "libs.versions.toml", CATALOG))
|
||||
)
|
||||
agp = deps["com.android.application:com.android.application.gradle.plugin"]
|
||||
assert agp.pinned == "9.3.2"
|
||||
kt = deps["org.jetbrains.kotlin.jvm:org.jetbrains.kotlin.jvm.gradle.plugin"]
|
||||
assert kt.pinned == "2.4.0"
|
||||
assert deps["org.example.plugin:org.example.plugin.gradle.plugin"].pinned == "0.5.0"
|
||||
assert not any("org.example.bare" in n for n in deps)
|
||||
assert not any(n.startswith(":") for n in deps)
|
||||
|
||||
|
||||
def test_a_version_ref_points_the_fix_at_the_versions_table(tmp_path):
|
||||
path = write(tmp_path, "libs.versions.toml", CATALOG)
|
||||
deps = _by_name(gradle.parse_catalog(path))
|
||||
lines = path.read_text().splitlines()
|
||||
assert lines[deps["org.jetbrains.kotlin:kotlin-reflect"].line - 1].startswith(
|
||||
"kotlin ="
|
||||
)
|
||||
assert lines[deps["io.coil-kt:coil"].line - 1].startswith("inline =")
|
||||
|
||||
|
||||
def test_unreadable_or_malformed_catalog_yields_nothing(tmp_path):
|
||||
assert gradle.parse_catalog(tmp_path / "missing.toml") == []
|
||||
assert gradle.parse_catalog(write(tmp_path, "bad.toml", "[versions\n")) == []
|
||||
|
||||
|
||||
def test_wrapper_distribution_is_the_gradle_toolchain_pin(tmp_path):
|
||||
body = (
|
||||
"distributionBase=GRADLE_USER_HOME\n"
|
||||
"distributionUrl=https\\://services.gradle.org/distributions/gradle-9.6.1-bin.zip\n"
|
||||
)
|
||||
(dep,) = gradle.parse_wrapper(write(tmp_path, "gradle-wrapper.properties", body))
|
||||
assert (dep.ecosystem, dep.name, dep.pinned, dep.line) == (
|
||||
"toolchain",
|
||||
"gradle",
|
||||
"9.6.1",
|
||||
2,
|
||||
)
|
||||
|
||||
|
||||
def test_wrapper_accepts_the_all_distribution_and_prereleases(tmp_path):
|
||||
body = "distributionUrl=https\\://x/gradle-9.7.0-rc-1-all.zip\n"
|
||||
(dep,) = gradle.parse_wrapper(write(tmp_path, "gradle-wrapper.properties", body))
|
||||
assert dep.constraint == "9.7.0-rc-1"
|
||||
|
||||
|
||||
def test_wrapper_without_a_recognisable_url_is_unpinned(tmp_path):
|
||||
body = "distributionUrl=https\\://example.com/custom.zip\n"
|
||||
(dep,) = gradle.parse_wrapper(write(tmp_path, "gradle-wrapper.properties", body))
|
||||
assert dep.constraint == "" and dep.pinned is None
|
||||
|
||||
|
||||
def test_wrapper_without_a_url_or_file_yields_nothing(tmp_path):
|
||||
assert (
|
||||
gradle.parse_wrapper(
|
||||
write(tmp_path, "gradle-wrapper.properties", "zipStoreBase=x\n")
|
||||
)
|
||||
== []
|
||||
)
|
||||
assert gradle.parse_wrapper(tmp_path / "missing.properties") == []
|
||||
109
dep_freshness/tests/test_gradle_registry.py
Normal file
109
dep_freshness/tests/test_gradle_registry.py
Normal file
@ -0,0 +1,109 @@
|
||||
"""Maven metadata across three repositories, and the Gradle release feed."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from dep_freshness import discover
|
||||
from dep_freshness.registries import maven
|
||||
from dep_freshness.registries import toolchain as tc
|
||||
from dep_freshness.registries.http import Offline
|
||||
from dep_freshness.resolve import _toolchain_latest
|
||||
from dep_freshness.tests.conftest import write
|
||||
|
||||
GOOGLE, CENTRAL, PORTAL = maven.MAVEN_REPOS
|
||||
|
||||
|
||||
def metadata(*versions: str, latest: str | None = None) -> str:
|
||||
body = "".join(f"<version>{v}</version>" for v in versions)
|
||||
head = f"<latest>{latest}</latest>" if latest else ""
|
||||
return f"<metadata><versioning>{head}<versions>{body}</versions></versioning></metadata>"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def repos(monkeypatch):
|
||||
"""Canned bodies per metadata URL; anything unlisted is a 404."""
|
||||
table: dict[str, str] = {}
|
||||
monkeypatch.setattr(maven, "get_text", lambda url, *a, **k: table.get(url))
|
||||
return table
|
||||
|
||||
|
||||
def test_metadata_url_shape():
|
||||
assert (
|
||||
maven.metadata_url(CENTRAL, "io.coil-kt:coil")
|
||||
== f"{CENTRAL}io/coil-kt/coil/maven-metadata.xml"
|
||||
)
|
||||
assert maven.metadata_url(CENTRAL, "nocolon") is None
|
||||
assert maven.metadata_url(CENTRAL, ":artifact") is None
|
||||
|
||||
|
||||
def test_versions_in_ignores_blank_nodes_and_bad_xml():
|
||||
assert maven.versions_in(metadata("1.0", " ", "2.0")) == ["1.0", "2.0"]
|
||||
assert maven.versions_in("<metadata><versions>") == []
|
||||
|
||||
|
||||
def test_google_is_asked_first_and_latest_tag_is_not_trusted(repos):
|
||||
repos[maven.metadata_url(GOOGLE, "androidx.core:core-ktx")] = metadata(
|
||||
"1.16.0", "1.17.0", "1.18.0-alpha03", latest="1.18.0-alpha03"
|
||||
)
|
||||
assert maven.latest("androidx.core:core-ktx") == "1.17.0"
|
||||
|
||||
|
||||
def test_central_answers_when_google_has_no_such_artifact(repos):
|
||||
repos[maven.metadata_url(CENTRAL, "io.coil-kt:coil")] = metadata("2.6.0", "2.7.0")
|
||||
assert maven.latest("io.coil-kt:coil") == "2.7.0"
|
||||
|
||||
|
||||
def test_plugin_markers_come_from_the_portal(repos):
|
||||
name = "org.example.plugin:org.example.plugin.gradle.plugin"
|
||||
repos[maven.metadata_url(PORTAL, name)] = metadata("0.5.0")
|
||||
assert maven.latest(name) == "0.5.0"
|
||||
|
||||
|
||||
def test_a_repo_with_only_prereleases_does_not_stop_the_search(repos):
|
||||
repos[maven.metadata_url(GOOGLE, "g:a")] = metadata("1.0.0-beta01")
|
||||
repos[maven.metadata_url(CENTRAL, "g:a")] = metadata("0.9.0")
|
||||
assert maven.latest("g:a") == "0.9.0"
|
||||
|
||||
|
||||
def test_unknown_everywhere_or_malformed_name_is_none(repos):
|
||||
assert maven.latest("g:nowhere") is None
|
||||
assert maven.latest("bare") is None
|
||||
|
||||
|
||||
def test_offline_propagates_from_the_transport(monkeypatch):
|
||||
def down(*_a, **_k):
|
||||
raise Offline("down")
|
||||
|
||||
monkeypatch.setattr(maven, "get_text", down)
|
||||
with pytest.raises(Offline):
|
||||
maven.latest("g:a")
|
||||
|
||||
|
||||
def test_gradle_latest_from_the_release_feed(monkeypatch):
|
||||
monkeypatch.setattr(tc, "get_json", lambda *_a, **_k: {"version": "9.7.1"})
|
||||
assert tc.gradle_latest() == "9.7.1"
|
||||
monkeypatch.setattr(tc, "get_json", lambda *_a, **_k: {"version": "10.0.0-rc-1"})
|
||||
assert tc.gradle_latest() is None
|
||||
monkeypatch.setattr(tc, "get_json", lambda *_a, **_k: None)
|
||||
assert tc.gradle_latest() is None
|
||||
|
||||
|
||||
def test_the_resolver_routes_gradle_to_the_toolchain_feed(monkeypatch):
|
||||
monkeypatch.setattr(tc, "gradle_latest", lambda: "9.7.1")
|
||||
assert _toolchain_latest("gradle") == "9.7.1"
|
||||
|
||||
|
||||
def test_discovery_routes_catalog_and_wrapper(tmp_path: Path):
|
||||
catalog = write(
|
||||
tmp_path, "gradle/libs.versions.toml", '[libraries]\nc = "g:a:1.0.0"\n'
|
||||
)
|
||||
wrapper = write(
|
||||
tmp_path,
|
||||
"gradle/wrapper/gradle-wrapper.properties",
|
||||
"distributionUrl=https\\://x/gradle-9.6.1-bin.zip\n",
|
||||
)
|
||||
assert [d.name for d in discover.parse_manifest(catalog)] == ["g:a"]
|
||||
assert [d.name for d in discover.parse_manifest(wrapper)] == ["gradle"]
|
||||
@ -120,3 +120,12 @@ class _Response:
|
||||
|
||||
def __exit__(self, *_exc):
|
||||
return False
|
||||
|
||||
|
||||
def test_get_text_returns_the_raw_body_and_none_on_404(monkeypatch):
|
||||
_reachable(monkeypatch)
|
||||
monkeypatch.setattr(http, "urlopen", lambda *a, **k: _Response(b"<x/>"))
|
||||
assert http.get_text("https://repo1.maven.org/x") == "<x/>"
|
||||
monkeypatch.setattr(http, "urlopen", _raiser(
|
||||
HTTPError("u", 404, "Not Found", {}, None)))
|
||||
assert http.get_text("https://repo1.maven.org/x") is None
|
||||
|
||||
@ -17,9 +17,10 @@ fails closed on it (exit 2) instead of honouring it silently.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from functools import cache
|
||||
from pathlib import Path, PurePosixPath
|
||||
from pathlib import Path
|
||||
|
||||
#: Basename of the per-repo exemption list, looked up in the gate's cwd.
|
||||
EXEMPT_FILE = ".file-length-exempt"
|
||||
@ -53,6 +54,35 @@ def parse(text: str) -> list[Exemption]:
|
||||
return entries
|
||||
|
||||
|
||||
def glob_to_regex(pattern: str) -> re.Pattern[str]:
|
||||
"""A repo-relative glob as an anchored regex.
|
||||
|
||||
`**` spans directories, `*` and `?` stop at a slash. Hand-rolled rather
|
||||
than `PurePath.full_match` because that needs Python 3.13 and the gate
|
||||
runs on whatever `python3` a CI runner ships (3.12 broke it in the
|
||||
TachiyomiSY fork's first CI run).
|
||||
"""
|
||||
out: list[str] = []
|
||||
i = 0
|
||||
while i < len(pattern):
|
||||
char = pattern[i]
|
||||
if pattern.startswith("**", i):
|
||||
out.append(".*")
|
||||
i += 2
|
||||
if pattern.startswith("/", i):
|
||||
out[-1] = "(?:.*/)?"
|
||||
i += 1
|
||||
continue
|
||||
if char == "*":
|
||||
out.append("[^/]*")
|
||||
elif char == "?":
|
||||
out.append("[^/]")
|
||||
else:
|
||||
out.append(re.escape(char))
|
||||
i += 1
|
||||
return re.compile("^" + "".join(out) + "$")
|
||||
|
||||
|
||||
@cache
|
||||
def load(root: Path) -> tuple[Exemption, ...]:
|
||||
"""The exemptions for the repo at `root`, empty when it has no file."""
|
||||
@ -72,10 +102,10 @@ def repo_exempt_reason(path: Path, root: Path) -> str | None:
|
||||
if not entries:
|
||||
return None
|
||||
try:
|
||||
relative = PurePosixPath(path.relative_to(root).as_posix())
|
||||
relative = path.relative_to(root).as_posix()
|
||||
except ValueError:
|
||||
return None
|
||||
for entry in entries:
|
||||
if relative.full_match(entry.pattern):
|
||||
if glob_to_regex(entry.pattern).match(relative):
|
||||
return f"repo exemption: {entry.reason}"
|
||||
return None
|
||||
|
||||
@ -10,6 +10,7 @@ from file_length.repo_exempt import (
|
||||
EXEMPT_FILE,
|
||||
ExemptFileError,
|
||||
Exemption,
|
||||
glob_to_regex,
|
||||
load,
|
||||
parse,
|
||||
repo_exempt_reason,
|
||||
@ -64,3 +65,21 @@ def test_reason_none_for_paths_outside_root(tmp_path: Path) -> None:
|
||||
write(tmp_path, EXEMPT_FILE, "**/*.kt # everything\n")
|
||||
outside = tmp_path.parent / "elsewhere.kt"
|
||||
assert repo_exempt_reason(outside, tmp_path) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("pattern", "hit", "miss"),
|
||||
[
|
||||
("a/*.kt", "a/x.kt", "a/b/x.kt"),
|
||||
("a/**/*.kt", "a/b/c/x.kt", "b/x.kt"),
|
||||
("a/**/*.kt", "a/x.kt", "a/x.kts"),
|
||||
("**/tags/*.kt", "tags/x.kt", "tags/sub/x.kt"),
|
||||
("a/?.kt", "a/x.kt", "a/xy.kt"),
|
||||
("a/**", "a/b/c.kt", "b/a"),
|
||||
("a.b", "a.b", "axb"),
|
||||
],
|
||||
)
|
||||
def test_glob_to_regex(pattern: str, hit: str, miss: str) -> None:
|
||||
regex = glob_to_regex(pattern)
|
||||
assert regex.match(hit), (pattern, hit)
|
||||
assert not regex.match(miss), (pattern, miss)
|
||||
|
||||
@ -105,12 +105,12 @@ repos:
|
||||
- --disable-error-code=list-item
|
||||
|
||||
- repo: https://github.com/pylint-dev/pylint
|
||||
rev: v3.3.2
|
||||
rev: v4.0.8
|
||||
hooks:
|
||||
- id: pylint
|
||||
args:
|
||||
- --rcfile=music_theory/pyproject.toml
|
||||
- --fail-under=8.0
|
||||
- --fail-under=10
|
||||
- --jobs=4
|
||||
additional_dependencies:
|
||||
- pytest
|
||||
|
||||
@ -81,11 +81,22 @@ color_output = true
|
||||
exclude = [".venv/"]
|
||||
|
||||
[tool.pylint.main]
|
||||
# The repo root on the path, so pylint resolves the package's own imports the
|
||||
# same way pytest does instead of reporting import-error for them.
|
||||
init-hook = "import sys; sys.path.insert(0, 'music_theory')"
|
||||
analyse-fallback-blocks = true
|
||||
persistent = true
|
||||
jobs = 0
|
||||
py-version = "3.14"
|
||||
ignore = [".venv", "__pycache__"]
|
||||
# Test suites intentionally use patterns (protected-access, fixture-arg
|
||||
# shadowing) that don't apply to source code; ruff's per-file-ignores carry
|
||||
# the equivalent exemptions, so tests stay linted -- by ruff. This is the same
|
||||
# source-only pylint scope wake-alarm / diet-guard / testsAndMisc use. It has
|
||||
# to be `ignore-paths`, not `ignore = ["tests"]`: `ignore` only matches the
|
||||
# basename of what pylint is *given*, and pre-commit hands it explicit file
|
||||
# paths, so a directory name in `ignore` never fires under the hook.
|
||||
ignore-paths = ["^(.*/)?tests/.*$"]
|
||||
ignore-patterns = [".*\\.pyi$"]
|
||||
|
||||
[tool.pylint.messages_control]
|
||||
|
||||
Loading…
Reference in New Issue
Block a user