From 08e8806c913ea771361d4cc6f10aa4b02daa557d Mon Sep 17 00:00:00 2001 From: Seth Troisi Date: Mon, 23 Nov 2026 12:35:03 -0800 Subject: [PATCH] feat(update): add standalone version-gated notices via movable GitHub tag docs,tools: add standalone notices guide and tools/notices.py CLI fix(tools): isolate git env vars and use UTF-8 LF bytes in notices tool doc: fiddling --- docs/04_automation_and_utility.md | 64 ++-- docs/07_update_notices.md | 169 ++++++++++ integration/README.md | 1 + integration/repro_update_notices/test.sh | 120 +++++++ src/colab_cli/auto_update.py | 196 ++++++++--- src/colab_cli/state.py | 15 +- tests/test_notices_tool.py | 331 +++++++++++++++++++ tests/test_state.py | 19 +- tests/test_update.py | 293 ++++++++++++++++- tools/NOTICE.md | 7 + tools/notices.py | 400 +++++++++++++++++++++++ 11 files changed, 1539 insertions(+), 76 deletions(-) create mode 100644 docs/07_update_notices.md create mode 100755 integration/repro_update_notices/test.sh create mode 100644 tests/test_notices_tool.py create mode 100644 tools/NOTICE.md create mode 100755 tools/notices.py diff --git a/docs/04_automation_and_utility.md b/docs/04_automation_and_utility.md index 8a9637a5..2c33ddd4 100644 --- a/docs/04_automation_and_utility.md +++ b/docs/04_automation_and_utility.md @@ -1,5 +1,6 @@ --- log: +2026-11-23: Added standalone version-gated update notices fetched from a movable GitHub tag (`notices_url`, defaulting to `https://raw.githubusercontent.com/googlecolab/google-colab-cli/refs/tags/notices/notices.json`) and cached as `update_notices` in `Settings`. Matching PEP 440 `affects` rules display via `announce_notices` independently of whether PyPI reports a newer version, HTTP 404 silently clears retracted notices without warning, transient errors preserve cached notices, and ANSI/control sequences are stripped. 2026-11-13: `_get_adc_credentials` in `auth.py` now catches `DefaultCredentialsError` from `google.auth.default()` so missing local ADC prints the 4-scope `gcloud auth application-default login` command and exits 1 instead of surfacing `google-auth`'s stock unscoped setup message. Updated scope documentation to clarify that both `colaboratory` and `userinfo.email` are required by `colab.research.google.com`. 2026-11-07: Optimized `_get_adc_credentials` in `auth.py` to stub `google.auth._cloud_sdk.get_project_id` around `google.auth.default()`. When ADC user credentials lack a `quota_project_id`, `google-auth` otherwise spawns `gcloud config get-value project` on every CLI invocation to resolve a `project_id` that `_get_adc_credentials` immediately discards (`_`). 2026-11-04: `colab drivemount` now opens the Drive consent URL in the system browser (`utils.open_url_in_browser`, also used by `colab pay`/`colab url --open`) instead of only printing it. The URL is still printed first, and a missing browser opener (SSH, containers, CI) is treated as normal: the flow keeps waiting for the user exactly as before. The prompt moved into `commands/automation.py::show_drive_auth_url` so it can be unit-tested. @@ -194,44 +195,67 @@ How each provider supplies the scopes: Git commit hash using `git rev-parse --short HEAD`. - Dynamic versioning is supported in the build system via `hatch-vcs`. -### 8. Auto-Update (`colab update`) +### 8. Auto-Update & Standalone Notices (`colab update`) -- **Action**: Check if a new version of the Colab CLI is available. -- **Auto-check**: The CLI automatically checks for updates once every 24 hours - during the execution of any command. Independently, the cached - `latest_version` (see below) is consulted on **every** invocation so the - upgrade banner remains visible between fetches without requiring a network +- **Action**: Check if a new version of the Colab CLI or any standalone + version-gated advisory notice is available. +- **Auto-check**: The CLI automatically fetches PyPI and the standalone + notices feed once every 24 hours during the execution of any non-suppressed + command. Independently, the cached `latest_version` and `update_notices` + are consulted on **every** invocation so upgrade and standalone notice + banners remain visible between fetches without requiring a network round-trip. - **Suppressed subcommands**: To keep machine-parseable output clean, the - daily fetch and the cached banner are suppressed for `update` (which - runs its own check), `version`, `log`, `pay`, `url`, `help`, and - `whoami`. The list lives as `_AUTO_UPDATE_SUPPRESSED` in the global - Typer callback in `cli.py`. -- **Manual-check**: `colab update` forces a check and prints the status. + daily fetch and the cached banners are suppressed for subcommands listed in + `_AUTO_UPDATE_SUPPRESSED` (and non-TTY `ssh`) in the global Typer callback + in `cli.py`. +- **Manual-check**: `colab update` forces a check and prints the status plus + any matching standalone notices. - **Implementation**: - - Fetches a PyPI-style JSON document from a configurable `update_url` + - Fetches a PyPI-style JSON document from `update_url` (default: `https://pypi.org/pypi/google-colab-cli/json`) and reads `info.version`. - Compares the fetched version with the current CLI version using PEP 440 / semantic versioning, falling back to string equality when a version is unparseable. + - Independently fetches standalone notices from `notices_url` (default: + `https://raw.githubusercontent.com/googlecolab/google-colab-cli/refs/tags/notices/notices.json`; + managed via `tools/notices.py`, see [07_update_notices.md](07_update_notices.md)). + - Notice payload schema: a JSON array `[{"affects": "<1.0.0", "message": "..."}]` + (or `{"notices": [...]}`). Each entry's `affects` is evaluated against + the installed version with `packaging.specifiers.SpecifierSet(..., prereleases=True)`. + ANSI escape codes and control characters are stripped, messages are + truncated to 500 characters, and at most 3 deduplicated notices are + printed. - Persists the following fields in `~/.config/colab-cli/settings.json`: - - `update_url`: source configuration. + - `update_url`: PyPI JSON source configuration. + - `notices_url`: standalone notices JSON source configuration. - `last_check`: timestamp of the last fetch (drives the daily throttle). - `enable_update_check`: master switch for both the daily fetch and - the cached banner. + cached upgrade/notice banners. - `latest_version`: highest version observed during the most recent successful check. Updated whenever a strictly-newer version is observed (never downgraded), and preserved verbatim across failed checks so transient network issues do not erase the cache. -- **Notification**: If a new version is found, a non-intrusive message is - printed to the console with a `Run 'pip install --upgrade google-colab-cli' to - update.` hint. On Linux and macOS platforms where `--install` self-update is supported, - an additional hint `You can run 'colab update --install' to upgrade in place.` - is displayed above the pip/uv install command. The cached banner shown between - fetches uses the generic `Run 'colab update' to update.` hint. + - `update_notices`: list of `{affects, message}` entries from the + most recent successful notices fetch. Overwritten on HTTP 200 or + cleared to `[]` on HTTP 404 (absent/deleted `notices` tag, with no + warning printed), and preserved across transient network failures. + `affects` is re-evaluated on every invocation so cached notices + stop appearing immediately once the user upgrades past the range. +- **Notification**: + - If a new version is found, a non-intrusive banner is printed with a + `Run 'pip install --upgrade google-colab-cli' to update.` (or `uv tool + install -U`) hint, plus `You can run 'colab update --install' to upgrade + in place.` on Linux and macOS. Cached banners between fetches use the + generic `Run 'colab update' to update.` hint. + - Any matching standalone notices are printed via `announce_notices` as + `[colab] Notice: `, **even when the CLI is already on the + latest PyPI version**. When both an upgrade banner and notices are + shown unsolicited, the `"enable_update_check": false` silence hint is + printed only once at the bottom. - **Self-install (`--install`)**: An opt-in `--install` flag (default `False`) makes `colab update` upgrade the CLI in place (**Linux and macOS**). It detects how the CLI was installed: diff --git a/docs/07_update_notices.md b/docs/07_update_notices.md new file mode 100644 index 00000000..f9c0e1ef --- /dev/null +++ b/docs/07_update_notices.md @@ -0,0 +1,169 @@ +--- +log: +2026-11-23: Initial design and maintainer workflow documentation for standalone version-gated update notices (`refs/tags/notices` on GitHub CDN) and the `tools/notices.py` management script. +--- + +# Design & Operations: Standalone Update Notices (`refs/tags/notices`) + +## Motivation + +`colab update` and the daily background update check notify users when a newer +version is published on PyPI, but PyPI release metadata is immutable once +published. Maintainers need a lightweight way to surface targeted messages to +existing installations **in the future without cutting a new PyPI release** — +for example: + +- Breaking CLI migrations (e.g., "`colab console` was removed; use `colab ssh` + instead"). +- Retroactive security advisories affecting older versions (e.g., `<0.8.0`). +- Upcoming Colab backend or authentication changes that affect **all** current + releases (`<=X.Y.Z`), even when no newer PyPI version exists yet. + +## Architecture + +1. **Movable Git Tag (`refs/tags/notices`)**: + - Active notices live in a single root file `notices.json` under the tag `refs/tags/notices`. + - Avoids triggering a release build from `cloudbuild.yaml` which triggers on `refs/tags/v*` +2. **CDN Delivery (`raw.githubusercontent.com`)**: + - Clients fetch `settings.notices_url`, which defaults to: + `https://raw.githubusercontent.com/googlecolab/google-colab-cli/refs/tags/notices/notices.json` + - Served by GitHub's Fastly CDN (`Cache-Control: max-age=300`, ~5-minute propagation window) + with no authentication required +3. **Standalone Evaluation**: + - Notices are evaluated and displayed via `announce_notices` **independently** + of whether PyPI reports a newer version (`latest > current`). A user + already on the latest PyPI version still sees any notice whose `affects` + specifier matches their installed version. + +## Payload Schema + +`notices.json` at the root of `refs/tags/notices` is a UTF-8 JSON array (or an +object `{"notices": [...]}`) of rule objects: + +```json +[ + { + "affects": "<0.8.0", + "message": "Versions <0.8.0 logged credentials to ~/.config/colab-cli/colab.log; upgrade and delete old logs." + }, + { + "affects": "<0.9.0", + "message": "colab console was removed; use colab ssh instead." + } +] +``` + +| Field | Type | Rules | +|---|---|---| +| `affects` | `str` | Non-empty PEP 440 version specifier parsed with `packaging.specifiers.SpecifierSet(..., prereleases=True)`. Examples: `<0.9.0`, `<=0.8.0`, `>=0.7.0,<0.8.0`, `==0.8.2`, `>=0.0.0`. | +| `message` | `str` | Plain-text notice (`<= 500` characters). Clients strip ANSI escape sequences and control characters, deduplicate identical messages, and display at most `3` matching notices. | + +Unknown JSON fields are ignored so future schema additions remain backward +compatible with older CLI installations. + +## Maintainer Workflow (`tools/notices.py`) + +`tools/notices.py` manages `refs/tags/notices` using low-level Git plumbing +(`git hash-object`, `git mktree`, `git commit-tree`, `git tag -fa`). It **never** +checks out branches or modifies your `HEAD`, staging area, or working directory, +and it chains each update onto the previous `refs/tags/notices` commit so +`git log notices` preserves a linear audit history. + +By default, commands update only your local `refs/tags/notices` tag so you can +inspect and preview first; pass `--push` to publish immediately to `origin`. + +### 1. List Active Notices & Preview Client Output + +```bash +# Fetch refs/tags/notices from origin and display active JSON rules: +./tools/notices.py list + +# Preview the exact banner a user on version 0.8.0 will see: +./tools/notices.py list --version 0.8.0 +``` + +### 2. Add a Notice + +```bash +# Stage locally first, then preview: +./tools/notices.py add \ + --affects "<0.9.0" \ + --message "colab console was removed; use colab ssh instead." +./tools/notices.py list --no-fetch --version 0.8.5 + +# Or validate, commit to refs/tags/notices, and push in one step: +./tools/notices.py add \ + --affects "<0.9.0" \ + --message "colab console was removed; use colab ssh instead." \ + --push +``` + +`tools/notices.py` rejects empty/invalid PEP 440 specifiers, messages containing +ANSI/control characters, and messages over 500 characters before creating the +tag. + +### 3. Replace the Full Notice List from a File + +When editing or reordering multiple notices at once: + +```bash +./tools/notices.py set path/to/notices.json --push +``` + +(Pass `-` instead of a file path to read JSON from `stdin`.) + +### 4. Clear / Retract Notices + +There are two equivalent ways to retract all notices: + +```bash +# Option 1 (recommended): publish an empty [] list, keeping git log history on refs/tags/notices +./tools/notices.py clear --push + +# Option 2: delete refs/tags/notices from origin (HTTP 404 also clears client caches) +./tools/notices.py clear --delete-tag --push +``` + +## Client Behavior & Caching + +- **Schedule**: Fetched once every 24 hours alongside PyPI during non-suppressed + commands (`run_background_check`) and unconditionally on `colab update`. +- **Persistence**: Cached as `update_notices` in `~/.config/colab-cli/settings.json`. + - **HTTP 200**: Replaces `update_notices` with the newly fetched list. + - **HTTP 404**: Silently sets `update_notices = []` with **no** warning even on + explicit `colab update` (both before the `notices` tag is ever created and + after tag deletion). + - **Network / 5xx Error**: Preserves the previously cached `update_notices`. +- **Post-Upgrade Suppression**: `maybe_show_cached_banner` re-evaluates + `affects` against `get_app_version()` on every run, so once a user upgrades + past the affected range, cached notices stop displaying immediately without + waiting for the next 24-hour fetch. +- **Banner Formatting**: + ```text + [colab] Notice: colab console was removed; use colab ssh instead. + [colab] To silence this check, set "enable_update_check": false in ~/.config/colab-cli/settings.json + ``` + - Explicit `colab update` omits the `"To silence this check..."` line. + - When both an upgrade banner and standalone notices match on an unsolicited + check, the silence hint appears only once at the bottom. + - Setting `"enable_update_check": false` in `~/.config/colab-cli/settings.json` + disables both the PyPI check and standalone notices. + - Pipeable and machine-parsed subcommands in `_AUTO_UPDATE_SUPPRESSED` (and + non-TTY `ssh`) in `cli.py` never print notices. + +## Testing Strategy + +- **Runtime Unit Tests (`tests/test_update.py`, `tests/test_state.py`)**: + Standalone notice display when up to date (explicit, background, and cached), + combined upgrade + notice rendering without duplicate silence hints, PEP 440 + range filtering across skipped versions, immediate cache suppression after + upgrade, silent HTTP 404 clearing, transient error cache preservation, ANSI + and length sanitization, and `enable_update_check=False` suppression. +- **Tool Unit Tests (`tests/test_notices_tool.py`)**: + Verifies `list`, `list --version`, `add`, `set`, `clear`, and + `clear --delete-tag` against temporary bare `origin` + multi-clone Git + repositories, ensuring `HEAD` and dirty working-tree files remain untouched + and force-moved tag history chains cleanly across clones. +- **End-to-End Integration Test (`integration/repro_update_notices/test.sh`)**: + Verifies live PyPI + live GitHub CDN 404 handling, local HTTP notice serving, + offline throttled cache playback, suppressed subcommands, and 404 retraction. diff --git a/integration/README.md b/integration/README.md index 199429c7..a91540b9 100644 --- a/integration/README.md +++ b/integration/README.md @@ -16,6 +16,7 @@ End-to-end tests that run against a **live Colab backend** (unlike the mocked un | `repro_variable_persistence/` | Variables persist across `colab exec` calls in the same session. | | `repro_bundled_oauth/` | Fast smoke test (~5s): verifies that the fallback OAuth configuration is loaded and starts the OAuth flow with the default client ID when local config is missing. | | `repro_legacy_token_migration/` | Fast smoke test (~5s, no VM): a pre-keyring `~/.config/colab-cli/token.json` is migrated into the keyring and deleted, deleted when the keyring already has a token, and kept (with a stderr warning) when the keyring is inaccessible. Uses a throwaway HOME and file-backed test keyring. | +| `repro_update_notices/` | Fast smoke test (~5s, no VM): verifies live PyPI + default GitHub `notices` tag 404 handling, standalone notice display when already up to date, throttled cache playback, suppression on pipeable commands, and 404 notice retraction in an isolated HOME. | | `repro_ssh/` | Fast smoke test (~5s): `--help` advertises the flags and an unknown session exits. Slow soak test (~95s): Live e2e allocates a CPU VM, runs a real remote command over `colab ssh --proxy-mode` | | `repro_windows_ssh/` | Native Windows live CPU test: Windows OpenSSH launches the generated ProxyCommand, executes a remote marker command, and releases the recorded runtime. Requires OAuth2 credentials cached in the OS keyring; exits 77 if prerequisites are missing. | diff --git a/integration/repro_update_notices/test.sh b/integration/repro_update_notices/test.sh new file mode 100755 index 00000000..091f4ee0 --- /dev/null +++ b/integration/repro_update_notices/test.sh @@ -0,0 +1,120 @@ +#!/bin/bash +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +set -euo pipefail + +export UV_CACHE_DIR="${UV_CACHE_DIR:-$HOME/.cache/uv}" + +TMP_DIR=$(mktemp -d) +SERVER_PID="" +cleanup() { + if [ -n "$SERVER_PID" ]; then + kill "$SERVER_PID" 2>/dev/null || true + fi + rm -rf "$TMP_DIR" +} +trap cleanup EXIT + +TEST_HOME="$TMP_DIR/home" +SERVE_DIR="$TMP_DIR/www" +SETTINGS="$TEST_HOME/.config/colab-cli/settings.json" +OUT="$TMP_DIR/out.log" +mkdir -p "$TEST_HOME/.config/colab-cli" "$SERVE_DIR" + +FAILURES=0 +check() { + if eval "$2"; then + echo " [PASS] $1" + else + echo " [FAIL] $1" + FAILURES=$((FAILURES + 1)) + echo " ---- CLI output ----" + sed 's/^/ | /' "$OUT" + fi +} + +echo "[*] Scenario 1: live PyPI + live GitHub default notices_url (404 when tag absent)" +HOME="$TEST_HOME" PYTHON_KEYRING_BACKEND=keyring.backends.null.Keyring \ + uv run colab update > "$OUT" 2>&1 +check "no warning on missing notices tag" '! grep -q "Warning:" "$OUT"' +check "settings.json persisted empty update_notices" \ + 'python3 -c "import json, sys; assert json.load(open(sys.argv[1]))[\"update_notices\"] == []" "$SETTINGS"' + +PORT=$(python3 -c "import socket; s=socket.socket(); s.bind(('127.0.0.1', 0)); print(s.getsockname()[1]); s.close()") +python3 -m http.server "$PORT" --bind 127.0.0.1 --directory "$SERVE_DIR" >/dev/null 2>&1 & +SERVER_PID=$! + +INSTALLED_VER=$(HOME="$TEST_HOME" uv run colab version | awk '{print $2}') +cat > "$SERVE_DIR/pypi.json" < "$SERVE_DIR/notices.json" <<'EOF' +[ + {"affects": ">=0.0.0", "message": "Standalone advisory from movable notices tag"}, + {"affects": "<0.0.1", "message": "Unmatched older notice"} +] +EOF +cat > "$SETTINGS" < "$OUT" 2>&1 +check "reports up to date" 'grep -q "Colab CLI is up to date" "$OUT"' +check "prints matching standalone notice" \ + 'grep -q "\[colab\] Notice: Standalone advisory from movable notices tag" "$OUT"' +check "omits unmatched notice" '! grep -q "Unmatched older notice" "$OUT"' +check "explicit update omits silence hint" '! grep -q "To silence this check" "$OUT"' + +kill "$SERVER_PID" 2>/dev/null || true +wait "$SERVER_PID" 2>/dev/null || true +SERVER_PID="" + +HOME="$TEST_HOME" PYTHON_KEYRING_BACKEND=keyring.backends.null.Keyring \ + uv run colab stop < /dev/null > "$OUT" 2>&1 || true +check "throttled command prints cached standalone notice with server offline" \ + 'grep -q "\[colab\] Notice: Standalone advisory from movable notices tag" "$OUT"' +check "throttled unsolicited notice includes silence hint" \ + 'grep -q "To silence this check" "$OUT"' + +HOME="$TEST_HOME" PYTHON_KEYRING_BACKEND=keyring.backends.null.Keyring \ + uv run colab version < /dev/null > "$OUT" 2>&1 +check "suppressed subcommand omits standalone notice" \ + '! grep -q "Standalone advisory" "$OUT"' + +echo "[*] Scenario 3: deleting notices.json (HTTP 404) retracts cached notices" +rm -f "$SERVE_DIR/notices.json" +python3 -m http.server "$PORT" --bind 127.0.0.1 --directory "$SERVE_DIR" >/dev/null 2>&1 & +SERVER_PID=$! + +HOME="$TEST_HOME" PYTHON_KEYRING_BACKEND=keyring.backends.null.Keyring \ + uv run colab update < /dev/null > "$OUT" 2>&1 +check "404 retraction emits no warning" '! grep -q "Warning:" "$OUT"' +check "retracted notice no longer printed" '! grep -q "Standalone advisory" "$OUT"' + +HOME="$TEST_HOME" PYTHON_KEYRING_BACKEND=keyring.backends.null.Keyring \ + uv run colab stop < /dev/null > "$OUT" 2>&1 || true +check "cached notice cleared for subsequent commands" \ + '! grep -q "Standalone advisory" "$OUT"' + +if [ "$FAILURES" -ne 0 ]; then + echo "[FAILURE] $FAILURES check(s) failed." + exit 1 +fi +echo "[SUCCESS] Standalone update notices integration test passed." diff --git a/src/colab_cli/auto_update.py b/src/colab_cli/auto_update.py index 8fec1582..3ad02c56 100644 --- a/src/colab_cli/auto_update.py +++ b/src/colab_cli/auto_update.py @@ -12,35 +12,44 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Auto-update subsystem. - -Owns version detection, the PyPI-style update probe, the on-disk -``latest_version`` cache, and the upgrade-banner UX. The CLI's global -callback (``cli.py``) calls ``check_for_updates`` once per day and -``maybe_show_cached_banner`` on every other invocation; the -``colab update`` Typer command (``commands/utility.py``) delegates to -``check_for_updates``. +"""Auto-update and standalone notices subsystem. + +Owns version detection, the PyPI-style update probe, standalone version-gated +notices fetched from a movable GitHub tag (`notices_url`), the on-disk +`Settings` cache, and the upgrade / notice banners. The CLI's global callback +(`cli.py`) calls `check_for_updates` once per day and +`maybe_show_cached_banner` on every other invocation; the `colab update` Typer +command (`commands/utility.py`) delegates to `check_for_updates`. """ import json import platform +import re import subprocess +import urllib.error import urllib.request from datetime import datetime, timezone from importlib.metadata import PackageNotFoundError, version as installed_version +from packaging.specifiers import InvalidSpecifier, SpecifierSet from packaging.version import InvalidVersion, Version from typing import Optional import typer from colab_cli.common import state -from colab_cli.state import Settings +from colab_cli.state import Settings, UpdateNotice -# PyPI distribution name (different from the importable package name `colab`). PYPI_PACKAGE_NAME = "google-colab-cli" - - -# ---------- Version detection ------------------------------------------- +MAX_NOTICES = 3 +MAX_NOTICE_LENGTH = 500 +_DISABLE_HINT = ( + '[colab] To silence this check, set "enable_update_check": false in ' + "~/.config/colab-cli/settings.json" +) +_ANSI_ESCAPE_RE = re.compile( + r"\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\))" +) +_CONTROL_CHARS_RE = re.compile(r"[\x00-\x1f\x7f-\x9f]+") def is_self_install_supported() -> bool: @@ -65,9 +74,6 @@ def get_app_version() -> str: return "unknown" -# ---------- Source fetchers --------------------------------------------- - - def _parse_version(payload: Optional[dict]) -> Optional[str]: """Returns ``info.version`` from a PyPI-style payload, or None.""" return (payload or {}).get("info", {}).get("version") @@ -84,7 +90,53 @@ def _fetch_pypi(url: str, quiet: bool) -> Optional[dict]: return None -# ---------- Version comparison ------------------------------------------ +def _parse_notices(payload: object) -> Optional[list[UpdateNotice]]: + """Parse a JSON array (or ``{"notices": [...]}`` object) into valid notices.""" + if isinstance(payload, dict): + raw_items = payload.get("notices") + elif isinstance(payload, list): + raw_items = payload + else: + return None + if not isinstance(raw_items, list): + return None + + notices: list[UpdateNotice] = [] + for item in raw_items: + if not isinstance(item, dict): + continue + try: + notice = UpdateNotice.model_validate(item) + except Exception: + continue + if notice.affects.strip() and notice.message.strip(): + notices.append(notice) + return notices + + +def _fetch_notices(url: str, quiet: bool) -> Optional[list[UpdateNotice]]: + """Fetch remote standalone notices from ``url``. + + HTTP 404 returns ``[]`` without warning so an absent or deleted ``notices`` + tag cleanly clears stale cached notices; transient errors return ``None`` + so the caller preserves its cached notices. + """ + if not url: + return [] + try: + with urllib.request.urlopen(url, timeout=5) as response: + payload = json.loads(response.read().decode("utf-8")) + return _parse_notices(payload) + except urllib.error.HTTPError as e: + if e.code == 404: + return [] + if not quiet: + typer.echo(f"[colab] Warning: Failed to fetch update notices: {e}") + return None + except Exception as e: + if not quiet: + typer.echo(f"[colab] Warning: Failed to fetch update notices: {e}") + return None def _is_newer(candidate: Optional[str], current: str) -> bool: @@ -97,7 +149,36 @@ def _is_newer(candidate: Optional[str], current: str) -> bool: return candidate != current -# ---------- UX ---------------------------------------------------------- +def _sanitize_notice(text: str) -> str: + cleaned = _ANSI_ESCAPE_RE.sub("", text) + cleaned = _CONTROL_CHARS_RE.sub(" ", cleaned).strip() + return cleaned[:MAX_NOTICE_LENGTH] + + +def matching_notices(notices: list[UpdateNotice], current: str) -> list[str]: + """Return sanitized messages from ``notices`` whose PEP 440 specifier matches ``current``.""" + try: + current_ver = Version(current) + except InvalidVersion: + return [] + + matched: list[str] = [] + for notice in notices: + spec_text = notice.affects.strip() + if not spec_text: + continue + try: + spec = SpecifierSet(spec_text) + except InvalidSpecifier: + continue + if not spec.contains(current_ver, prereleases=True): + continue + msg = _sanitize_notice(notice.message) + if msg and msg not in matched: + matched.append(msg) + if len(matched) >= MAX_NOTICES: + break + return matched def announce_upgrade( @@ -122,15 +203,24 @@ def announce_upgrade( typer.echo("[colab] You can run 'colab update --install' to upgrade in place.") typer.echo(f"[colab] Run '{install_cmd}' to update.") if show_disable_hint: - typer.echo( - "[colab] To silence this check, set " - '"enable_update_check": false in ' - "~/.config/colab-cli/settings.json" - ) + typer.echo(_DISABLE_HINT) typer.echo("") -# ---------- Orchestration ----------------------------------------------- +def announce_notices( + messages: list[str], + *, + show_disable_hint: bool = False, +) -> None: + """Print standalone notices matching the installed CLI version.""" + if not messages: + return + typer.echo(f"\n[colab] Notice: {messages[0]}") + for msg in messages[1:]: + typer.echo(f"[colab] Notice: {msg}") + if show_disable_hint: + typer.echo(_DISABLE_HINT) + typer.echo("") def _get_install_command() -> str: @@ -143,11 +233,11 @@ def _get_install_command() -> str: def check_for_updates(quiet: bool = False) -> None: - """Check PyPI for updates and print a message if a new version is available. + """Check PyPI and standalone notices, printing applicable banners and caching state. - The disable-hint is appended to the banner only when ``quiet`` is True - (the daily background fetch); explicit ``colab update`` invocations - (``quiet=False``) omit it because the user asked for the check. + The disable-hint is appended only when ``quiet`` is True (the daily + background fetch); explicit ``colab update`` invocations (``quiet=False``) + omit it because the user asked for the check. """ settings = state.settings_store.load() current = get_app_version() @@ -155,19 +245,27 @@ def check_for_updates(quiet: bool = False) -> None: try: pypi = _fetch_pypi(settings.update_url, quiet) pypi_v = _parse_version(pypi) + fetched_notices = _fetch_notices(settings.notices_url, quiet) + if fetched_notices is not None: + settings.update_notices = fetched_notices - if _is_newer(pypi_v, current): + has_upgrade = _is_newer(pypi_v, current) + matched = matching_notices(settings.update_notices, current) + + if has_upgrade: announce_upgrade( pypi_v, current, _get_install_command(), - show_disable_hint=quiet, + show_disable_hint=quiet and not matched, ) elif not quiet: suffix = f", latest: {pypi_v}" if pypi_v else "" typer.echo(f"[colab] Colab CLI is up to date (version: {current}{suffix}).") - # Cache the highest observed version; never downgrade. + if matched: + announce_notices(matched, show_disable_hint=quiet) + cached = settings.latest_version or "0" if _is_newer(pypi_v, cached): settings.latest_version = pypi_v @@ -180,9 +278,6 @@ def check_for_updates(quiet: bool = False) -> None: typer.echo(f"[colab] Failed to check for updates: {e}") -# ---------- Background hooks (called from cli.py) ----------------------- - - def _is_throttled(settings: Settings, *, now: Optional[datetime] = None) -> bool: """True if the once-per-day fetch should be skipped.""" if settings.last_check is None: @@ -192,24 +287,26 @@ def _is_throttled(settings: Settings, *, now: Optional[datetime] = None) -> bool def maybe_show_cached_banner(settings: Settings) -> None: - """Print the cached upgrade banner if the cache reports a newer version. + """Print cached upgrade and/or standalone notice banners when throttled. Called from the global CLI callback when the daily fetch is throttled. - The banner uses a generic ``colab update`` install hint because the - cache does not record which source supplied the version; the disable - hint is shown because this is unsolicited output. + Both banners are evaluated independently so standalone notices still appear + when the user is already on the latest PyPI version. """ - if not settings.latest_version: - return current = get_app_version() - if not _is_newer(settings.latest_version, current): - return - announce_upgrade( - settings.latest_version, - current, - "colab update", - show_disable_hint=True, + has_upgrade = bool( + settings.latest_version and _is_newer(settings.latest_version, current) ) + matched = matching_notices(settings.update_notices, current) + if has_upgrade: + announce_upgrade( + settings.latest_version, + current, + "colab update", + show_disable_hint=not matched, + ) + if matched: + announce_notices(matched, show_disable_hint=True) def run_background_check() -> None: @@ -228,15 +325,10 @@ def run_background_check() -> None: check_for_updates(quiet=True) -# ---------- Self-install ------------------------------------------------ - - def self_install() -> None: """Upgrade the CLI in place, detecting uv vs pip.""" import sys - # If the executable path contains "/uv/", we assume it was installed via - # `uv tool install` and use `uv` to upgrade it. if "/uv/tools/" in sys.executable: cmd = ["uv", "tool", "install", "-U", PYPI_PACKAGE_NAME] else: diff --git a/src/colab_cli/state.py b/src/colab_cli/state.py index 6d08b7b3..6659370e 100644 --- a/src/colab_cli/state.py +++ b/src/colab_cli/state.py @@ -19,7 +19,7 @@ from typing import Dict, Optional, Tuple, Iterator, IO import filelock -from pydantic import BaseModel +from pydantic import BaseModel, ConfigDict, Field class SessionState(BaseModel): @@ -37,12 +37,23 @@ class SessionState(BaseModel): running: Optional[str] = None +class UpdateNotice(BaseModel): + model_config = ConfigDict(extra="ignore") + + affects: str + message: str + + class Settings(BaseModel): update_url: str = "https://pypi.org/pypi/google-colab-cli/json" + notices_url: str = ( + "https://raw.githubusercontent.com/googlecolab/google-colab-cli/" + "refs/tags/notices/notices.json" + ) last_check: Optional[datetime] = None enable_update_check: bool = True - # Highest version seen on the update source; cached for the banner. latest_version: Optional[str] = None + update_notices: list[UpdateNotice] = Field(default_factory=list) use_public_api: bool = False public_api_supported: Optional[bool] = None tunnel_api_supported: Optional[bool] = None diff --git a/tests/test_notices_tool.py b/tests/test_notices_tool.py new file mode 100644 index 00000000..b9a34845 --- /dev/null +++ b/tests/test_notices_tool.py @@ -0,0 +1,331 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import importlib.util +import json +import os +import subprocess +import sys +from pathlib import Path + +import pytest +from typer.testing import CliRunner + +_TOOL_PATH = Path(__file__).resolve().parents[1] / "tools" / "notices.py" +_SPEC = importlib.util.spec_from_file_location("notices_tool", _TOOL_PATH) +_MOD = importlib.util.module_from_spec(_SPEC) +assert _SPEC and _SPEC.loader +sys.modules[_SPEC.name] = _MOD +_SPEC.loader.exec_module(_MOD) +TAG_NAME = _MOD.TAG_NAME +app = _MOD.app + +runner = CliRunner() + + +def _git(cwd: Path, *args: str) -> str: + cmd = ["git", f"--git-dir={cwd}", *args] if cwd.suffix == ".git" else ["git", *args] + env = {k: v for k, v in os.environ.items() if k not in _MOD._GIT_REPO_ENV_VARS} + return subprocess.check_output( + cmd, + cwd=cwd, + env=env, + encoding="utf-8", + stderr=subprocess.PIPE, + ).strip() + + +@pytest.fixture +def git_repos(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + """Create a bare ``origin`` repo and two working clones isolated from host gitconfig.""" + empty_gitconfig = tmp_path / "gitconfig" + empty_gitconfig.write_text("", encoding="utf-8") + monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(empty_gitconfig)) + monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1") + + origin = tmp_path / "origin.git" + clone_a = tmp_path / "clone_a" + clone_b = tmp_path / "clone_b" + + _git(tmp_path, "init", "--bare", str(origin)) + _git(tmp_path, "clone", str(origin), str(clone_a)) + for repo in (clone_a,): + _git(repo, "config", "user.name", "Test User") + _git(repo, "config", "user.email", "test@example.com") + (clone_a / "README.md").write_text("hello\n", encoding="utf-8") + _git(clone_a, "add", "README.md") + _git(clone_a, "commit", "-m", "initial") + _git(clone_a, "push", "-u", "origin", "HEAD") + + _git(tmp_path, "clone", str(origin), str(clone_b)) + _git(clone_b, "config", "user.name", "Other User") + _git(clone_b, "config", "user.email", "other@example.com") + + return origin, clone_a, clone_b + + +def test_list_when_tag_absent(git_repos): + _, clone_a, _ = git_repos + res = runner.invoke(app, ["--repo", str(clone_a), "list"]) + assert res.exit_code == 0, res.output + assert "No active notices" in res.output + + +def test_add_preserves_working_tree_and_branch_and_pushes(git_repos): + origin, clone_a, _ = git_repos + head_before = _git(clone_a, "rev-parse", "HEAD") + dirty_file = clone_a / "uncommitted.txt" + dirty_file.write_text("work in progress\n", encoding="utf-8") + + res = runner.invoke( + app, + [ + "--repo", + str(clone_a), + "add", + "--affects", + "<0.9.0", + "--message", + "colab console was removed; use colab ssh instead.", + "--push", + ], + ) + assert res.exit_code == 0, res.output + assert _git(clone_a, "rev-parse", "HEAD") == head_before + assert dirty_file.read_text(encoding="utf-8") == "work in progress\n" + assert not (clone_a / "notices.json").exists() + + remote_json = json.loads(_git(origin, "show", f"refs/tags/{TAG_NAME}:notices.json")) + assert remote_json == [ + { + "affects": "<0.9.0", + "message": "colab console was removed; use colab ssh instead.", + } + ] + assert _git(origin, "cat-file", "-t", f"refs/tags/{TAG_NAME}") == "tag" + + +def test_add_without_push_stays_local_and_prints_push_hint(git_repos): + origin, clone_a, _ = git_repos + res = runner.invoke( + app, + [ + "--repo", + str(clone_a), + "add", + "--affects", + "<1.0.0", + "--message", + "Local draft notice.", + ], + ) + assert res.exit_code == 0, res.output + assert f"git push -f origin refs/tags/{TAG_NAME}" in res.output + + local_json = json.loads(_git(clone_a, "show", f"refs/tags/{TAG_NAME}:notices.json")) + assert len(local_json) == 1 + with pytest.raises(subprocess.CalledProcessError): + _git(origin, "rev-parse", "--verify", f"refs/tags/{TAG_NAME}") + + +def test_second_clone_fetches_force_moved_tag_and_chains_history(git_repos): + origin, clone_a, clone_b = git_repos + + runner.invoke( + app, + [ + "--repo", + str(clone_a), + "add", + "--affects", + "<0.8.0", + "--message", + "First notice.", + "--push", + ], + ) + runner.invoke(app, ["--repo", str(clone_b), "list"]) + + runner.invoke( + app, + [ + "--repo", + str(clone_a), + "add", + "--affects", + "<0.9.0", + "--message", + "Second notice.", + "--push", + ], + ) + + res_b = runner.invoke( + app, + [ + "--repo", + str(clone_b), + "add", + "--affects", + "<1.0.0", + "--message", + "Third notice.", + "--push", + ], + ) + assert res_b.exit_code == 0, res_b.output + + remote_json = json.loads(_git(origin, "show", f"refs/tags/{TAG_NAME}:notices.json")) + assert [n["affects"] for n in remote_json] == ["<0.8.0", "<0.9.0", "<1.0.0"] + + commits = _git(origin, "log", "--oneline", f"refs/tags/{TAG_NAME}").splitlines() + assert len(commits) == 3 + + +def test_list_preview_with_version(git_repos): + _, clone_a, _ = git_repos + runner.invoke( + app, + [ + "--repo", + str(clone_a), + "add", + "--affects", + "<0.8.0", + "--message", + "Old security notice.", + "--no-fetch", + ], + ) + runner.invoke( + app, + [ + "--repo", + str(clone_a), + "add", + "--affects", + "<1.0.0", + "--message", + "1.0 migration notice.", + "--no-fetch", + ], + ) + + res_080 = runner.invoke( + app, ["--repo", str(clone_a), "list", "--no-fetch", "--version", "0.8.0"] + ) + assert res_080.exit_code == 0, res_080.output + assert "[colab] Notice: 1.0 migration notice." in res_080.output + assert "[colab] Notice: Old security notice." not in res_080.output + + +@pytest.mark.parametrize( + "affects,message", + [ + ("", "Valid message"), + ("not-a-pep440-spec", "Valid message"), + ("<1.0.0", ""), + ("<1.0.0", "x" * 501), + ("<1.0.0", "bad \x1b[31mansi"), + ], +) +def test_add_rejects_invalid_inputs(git_repos, affects, message): + _, clone_a, _ = git_repos + res = runner.invoke( + app, + [ + "--repo", + str(clone_a), + "add", + "--affects", + affects, + "--message", + message, + "--no-fetch", + ], + ) + assert res.exit_code != 0 + + +def test_set_from_file_and_clear_and_delete_tag(git_repos, tmp_path): + origin, clone_a, _ = git_repos + payload_file = tmp_path / "input_notices.json" + payload_file.write_text( + json.dumps([{"affects": "<=0.8.0", "message": "From file."}]), + encoding="utf-8", + ) + + res_set = runner.invoke( + app, ["--repo", str(clone_a), "set", str(payload_file), "--push"] + ) + assert res_set.exit_code == 0, res_set.output + assert json.loads(_git(origin, "show", f"refs/tags/{TAG_NAME}:notices.json")) == [ + {"affects": "<=0.8.0", "message": "From file."} + ] + + res_clear = runner.invoke(app, ["--repo", str(clone_a), "clear", "--push"]) + assert res_clear.exit_code == 0, res_clear.output + assert json.loads(_git(origin, "show", f"refs/tags/{TAG_NAME}:notices.json")) == [] + + res_del = runner.invoke( + app, ["--repo", str(clone_a), "clear", "--delete-tag", "--push"] + ) + assert res_del.exit_code == 0, res_del.output + with pytest.raises(subprocess.CalledProcessError): + _git(origin, "rev-parse", "--verify", f"refs/tags/{TAG_NAME}") + + +def test_run_git_sends_utf8_lf_bytes_for_windows_mktree_compat(mocker, tmp_path): + """On Windows, text=True translates '\\n' to '\\r\\n' on stdin, causing + ``git mktree`` to create an entry named ``"notices.json\\r"`` instead of + ``notices.json``. ``_run_git`` must pass raw UTF-8 bytes without text mode. + """ + captured = {} + + def _fake_run(cmd, **kwargs): + captured["kwargs"] = kwargs + return subprocess.CompletedProcess(cmd, 0, stdout=b"deadbeef\n", stderr=b"") + + mocker.patch.object(_MOD.subprocess, "run", side_effect=_fake_run) + res = _MOD._run_git( + tmp_path, "mktree", stdin_text="100644 blob abc\tnotices.json\n" + ) + assert res.stdout == "deadbeef\n" + assert not captured["kwargs"].get("text") + assert captured["kwargs"]["input"] == b"100644 blob abc\tnotices.json\n" + + +def test_add_ignores_inherited_git_dir_and_index_env(git_repos, monkeypatch, tmp_path): + origin, clone_a, _ = git_repos + monkeypatch.setenv("GIT_DIR", str(tmp_path / "bogus.git")) + monkeypatch.setenv("GIT_INDEX_FILE", str(tmp_path / "bogus.index")) + + res = runner.invoke( + app, + [ + "--repo", + str(clone_a), + "add", + "--affects", + "<1.0.0", + "--message", + "Isolated from outer GIT_DIR — UTF-8 check.", + "--push", + ], + ) + assert res.exit_code == 0, res.output + monkeypatch.delenv("GIT_DIR") + monkeypatch.delenv("GIT_INDEX_FILE") + remote_json = json.loads(_git(origin, "show", f"refs/tags/{TAG_NAME}:notices.json")) + assert remote_json[0]["message"] == "Isolated from outer GIT_DIR — UTF-8 check." diff --git a/tests/test_state.py b/tests/test_state.py index 94285a3e..bba81839 100644 --- a/tests/test_state.py +++ b/tests/test_state.py @@ -21,7 +21,13 @@ import filelock -from colab_cli.state import StateStore, SessionState, SettingsStore, Settings +from colab_cli.state import ( + SessionState, + Settings, + SettingsStore, + StateStore, + UpdateNotice, +) @pytest.fixture @@ -134,6 +140,11 @@ def test_settings_store_defaults(temp_config): settings = store.load() assert settings.enable_update_check is True assert settings.last_check is None + assert ( + settings.notices_url + == "https://raw.githubusercontent.com/googlecolab/google-colab-cli/refs/tags/notices/notices.json" + ) + assert settings.update_notices == [] assert settings.use_public_api is False assert settings.public_api_supported is None assert settings.tunnel_api_supported is None @@ -144,6 +155,8 @@ def test_settings_store_save_load(temp_config): settings = Settings( enable_update_check=False, last_check=datetime(2026, 1, 1), + notices_url="https://example.com/notices.json", + update_notices=[UpdateNotice(affects="<1.0.0", message="Upgrade soon")], use_public_api=True, public_api_supported=True, tunnel_api_supported=False, @@ -153,6 +166,10 @@ def test_settings_store_save_load(temp_config): loaded = SettingsStore(temp_config).load() assert loaded.enable_update_check is False assert loaded.last_check == datetime(2026, 1, 1) + assert loaded.notices_url == "https://example.com/notices.json" + assert loaded.update_notices == [ + UpdateNotice(affects="<1.0.0", message="Upgrade soon") + ] assert loaded.use_public_api is True assert loaded.public_api_supported is True assert loaded.tunnel_api_supported is False diff --git a/tests/test_update.py b/tests/test_update.py index 5b522291..196f7dc5 100644 --- a/tests/test_update.py +++ b/tests/test_update.py @@ -12,14 +12,16 @@ # See the License for the specific language governing permissions and # limitations under the License. +import io import json +import urllib.error from datetime import datetime, timedelta, timezone import pytest from typer.testing import CliRunner from colab_cli.cli import app -from colab_cli.state import Settings +from colab_cli.state import Settings, UpdateNotice runner = CliRunner() @@ -42,6 +44,7 @@ def fake_settings(mocker): def _build(**overrides): kwargs = { "update_url": "http://test.url", + "notices_url": "http://notices.url", "last_check": None, **overrides, } @@ -581,3 +584,291 @@ def test_install_flag_propagates_pip_failure( result = runner.invoke(app, ["update", "--install"]) assert result.exit_code == 2 + + +@pytest.fixture +def mock_update_sources(mocker): + """Stub ``urllib.request.urlopen`` separately for PyPI and notices URLs.""" + + def _http_404(url): + return urllib.error.HTTPError(url, 404, "Not Found", {}, io.BytesIO(b"")) + + def _mock(*, pypi=None, notices="404"): + def _urlopen(req, timeout=5): + url = req.full_url if hasattr(req, "full_url") else req + target = notices if "notices" in url else pypi + if target == "404": + raise _http_404(url) + if isinstance(target, BaseException): + raise target + cm = mocker.MagicMock() + cm.__enter__.return_value.read.return_value = json.dumps(target).encode( + "utf-8" + ) + return cm + + return mocker.patch("urllib.request.urlopen", side_effect=_urlopen) + + return _mock + + +def test_standalone_notice_shown_when_up_to_date_on_explicit_update( + app_version, fake_settings, mock_update_sources +): + app_version("1.0.0") + mock_update_sources( + pypi={"info": {"version": "1.0.0"}}, + notices=[ + { + "affects": "<=1.0.0", + "message": "Tunnel backend retires soon; enable --public-api.", + } + ], + ) + fake_settings() + + result = runner.invoke(app, ["update"]) + assert result.exit_code == 0 + assert "up to date (version: 1.0.0, latest: 1.0.0)" in result.output + assert ( + "[colab] Notice: Tunnel backend retires soon; enable --public-api." + in result.output + ) + assert "To silence this check" not in result.output + + +def test_standalone_notice_shown_when_up_to_date_in_background_check( + app_version, fake_settings, mock_update_sources +): + app_version("1.0.0") + mock_update_sources( + pypi={"info": {"version": "1.0.0"}}, + notices=[{"affects": "<1.1.0", "message": "Advisory for 1.0 users."}], + ) + fake_settings(last_check=datetime.now(timezone.utc) - timedelta(days=2)) + + result = runner.invoke(app, ["sessions"]) + assert result.exit_code == 0 + assert "A new version" not in result.output + assert "[colab] Notice: Advisory for 1.0 users." in result.output + assert result.output.count("To silence this check") == 1 + + +def test_standalone_notice_shown_from_cache_when_throttled_and_up_to_date( + mocker, app_version, fake_settings +): + app_version("1.0.0") + fake_settings( + last_check=datetime.now(timezone.utc) - timedelta(hours=1), + latest_version="1.0.0", + update_notices=[ + UpdateNotice(affects="<=1.0.0", message="Cached standalone advisory.") + ], + ) + mock_check = mocker.patch("colab_cli.auto_update.check_for_updates") + + result = runner.invoke(app, ["sessions"]) + assert result.exit_code == 0 + assert mock_check.call_count == 0 + assert "A new version" not in result.output + assert "[colab] Notice: Cached standalone advisory." in result.output + assert result.output.count("To silence this check") == 1 + + +def test_upgrade_and_notice_shown_together_without_duplicate_disable_hint( + app_version, fake_settings, mock_update_sources +): + app_version("0.8.0") + mock_update_sources( + pypi={"info": {"version": "1.0.0"}}, + notices=[ + { + "affects": "<1.0.0", + "message": "colab console was removed; use colab ssh instead.", + } + ], + ) + fake_settings(last_check=datetime.now(timezone.utc) - timedelta(days=2)) + + result = runner.invoke(app, ["sessions"]) + assert result.exit_code == 0 + assert "available: 1.0.0 (current: 0.8.0)" in result.output + assert ( + "[colab] Notice: colab console was removed; use colab ssh instead." + in result.output + ) + assert result.output.count("To silence this check") == 1 + + +@pytest.mark.parametrize( + "installed,expected_present,expected_absent", + [ + ("0.7.5", ["Security fix in 0.8.0", "Breaking in 1.0.0"], ["Only 2.x"]), + ("0.8.0", ["Breaking in 1.0.0"], ["Security fix in 0.8.0", "Only 2.x"]), + ( + "1.0.0", + [], + ["Security fix in 0.8.0", "Breaking in 1.0.0", "Only 2.x"], + ), + ], +) +def test_notice_specifier_filtering_across_skipped_versions( + app_version, + fake_settings, + mock_update_sources, + installed, + expected_present, + expected_absent, +): + app_version(installed) + mock_update_sources( + pypi={"info": {"version": "1.0.0"}}, + notices={ + "notices": [ + { + "affects": "<0.8.0", + "message": "Security fix in 0.8.0", + "extra_field": "ignored", + }, + {"affects": "<1.0.0", "message": "Breaking in 1.0.0"}, + {"affects": ">=2.0.0", "message": "Only 2.x"}, + {"affects": "", "message": "Empty specifier ignored"}, + {"affects": "not-a-specifier", "message": "Invalid specifier ignored"}, + ] + }, + ) + fake_settings() + + result = runner.invoke(app, ["update"]) + assert result.exit_code == 0 + for msg in expected_present: + assert f"[colab] Notice: {msg}" in result.output + for msg in expected_absent: + assert msg not in result.output + assert "Empty specifier ignored" not in result.output + assert "Invalid specifier ignored" not in result.output + + +def test_cached_notice_stops_showing_immediately_after_upgrade( + mocker, app_version, fake_settings +): + app_version("1.0.0") + fake_settings( + last_check=datetime.now(timezone.utc) - timedelta(hours=1), + latest_version="1.0.0", + update_notices=[UpdateNotice(affects="<1.0.0", message="Old notice")], + ) + mocker.patch("colab_cli.auto_update.check_for_updates") + + result = runner.invoke(app, ["sessions"]) + assert result.exit_code == 0 + assert "Old notice" not in result.output + + +def test_notices_404_is_silent_and_clears_cached_notices( + app_version, fake_settings, mock_update_sources +): + app_version("1.0.0") + mock_update_sources(pypi={"info": {"version": "1.0.0"}}, notices="404") + settings = fake_settings( + update_notices=[UpdateNotice(affects="<=1.0.0", message="Retracted notice")] + ) + + result = runner.invoke(app, ["update"]) + assert result.exit_code == 0 + assert "Warning" not in result.output + assert "Retracted notice" not in result.output + assert settings.update_notices == [] + + +def test_notices_fetch_failure_preserves_cached_notices( + app_version, fake_settings, mock_update_sources +): + app_version("1.0.0") + mock_update_sources( + pypi={"info": {"version": "1.0.0"}}, + notices=OSError("github cdn unreachable"), + ) + settings = fake_settings( + update_notices=[UpdateNotice(affects="<=1.0.0", message="Cached notice")] + ) + + result = runner.invoke(app, ["update"]) + assert result.exit_code == 0 + assert len(settings.update_notices) == 1 + assert "[colab] Notice: Cached notice" in result.output + + +def test_notice_still_works_when_pypi_fails( + app_version, fake_settings, mock_update_sources +): + app_version("1.0.0") + mock_update_sources( + pypi=OSError("pypi unreachable"), + notices=[{"affects": "<=1.0.0", "message": "Standalone GitHub notice"}], + ) + fake_settings() + + result = runner.invoke(app, ["update"]) + assert result.exit_code == 0 + assert "[colab] Notice: Standalone GitHub notice" in result.output + + +def test_notice_sanitizes_ansi_and_caps_count_and_length( + app_version, fake_settings, mock_update_sources +): + app_version("1.0.0") + long_msg = "x" * 700 + mock_update_sources( + pypi={"info": {"version": "1.0.0"}}, + notices=[ + { + "affects": "<=1.0.0", + "message": "\x1b[31mRed\x1b[0m\rOverwrite\x07\nLine2", + }, + {"affects": "<=1.0.0", "message": long_msg}, + {"affects": "<=1.0.0", "message": "Third notice"}, + {"affects": "<=1.0.0", "message": "Fourth notice dropped"}, + ], + ) + fake_settings() + + result = runner.invoke(app, ["update"]) + assert result.exit_code == 0 + assert "\x1b" not in result.output + assert "\x07" not in result.output + assert "[colab] Notice: Red Overwrite Line2" in result.output + assert "[colab] Notice: " + ("x" * 500) in result.output + assert "x" * 501 not in result.output + assert "[colab] Notice: Third notice" in result.output + assert "Fourth notice dropped" not in result.output + + +def test_standalone_notice_suppressed_for_dev_git_sha_version( + app_version, fake_settings, mock_update_sources +): + app_version("0abf82d") + mock_update_sources( + pypi={"info": {"version": "1.0.0"}}, + notices=[{"affects": "<2.0.0", "message": "Should not crash dev version"}], + ) + fake_settings() + + result = runner.invoke(app, ["update"]) + assert result.exit_code == 0 + assert "Should not crash dev version" not in result.output + + +def test_standalone_notice_suppressed_when_update_check_disabled( + mocker, app_version, fake_settings +): + app_version("1.0.0") + fake_settings( + enable_update_check=False, + update_notices=[UpdateNotice(affects="<=1.0.0", message="Silenced notice")], + ) + mocker.patch("colab_cli.auto_update.check_for_updates") + + result = runner.invoke(app, ["sessions"]) + assert result.exit_code == 0 + assert "Silenced notice" not in result.output diff --git a/tools/NOTICE.md b/tools/NOTICE.md new file mode 100644 index 00000000..acf4b62d --- /dev/null +++ b/tools/NOTICE.md @@ -0,0 +1,7 @@ +# Standalone Update Notices Workflow + +To broadcast a message to existing CLI installations without cutting a new PyPI release, `auto_update.py` fetches `https://raw.githubusercontent.com/googlecolab/google-colab-cli/refs/tags/notices/notices.json` once per day (and on `colab update`). See [docs/07_update_notices.md](../docs/07_update_notices.md) for full details. Follow this workflow ONLY when explicitly publishing, updating, or retracting a CLI notice: + +1. **Inspect / preview**: Run `./tools/notices.py list [--version X.Y.Z]` to fetch `refs/tags/notices` and preview matching banners. +2. **Publish / update (decoupled from `main` and PyPI)**: Run `./tools/notices.py add --affects "" --message "" --push` (or `./tools/notices.py set --push`). The script validates inputs and writes `notices.json` directly onto `refs/tags/notices` via Git plumbing without touching `HEAD` or the working tree. Because `cloudbuild.yaml` triggers only on `refs/tags/v*`, pushing `refs/tags/notices` never triggers a PyPI release. +3. **Retract**: Run `./tools/notices.py clear --push` (writes `[]`) or `./tools/notices.py clear --delete-tag --push` (deletes `refs/tags/notices`; HTTP 404 silently clears cached `update_notices` on clients' next check). diff --git a/tools/notices.py b/tools/notices.py new file mode 100755 index 00000000..39ed7487 --- /dev/null +++ b/tools/notices.py @@ -0,0 +1,400 @@ +#!/usr/bin/env -S uv run python +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Maintainer CLI for managing standalone CLI notices on ``refs/tags/notices``. + +Builds commits and moves the annotated ``notices`` git tag via git plumbing +(``hash-object``, ``mktree``, ``commit-tree``, ``tag -fa``) so publishing or +retracting notices never touches the current branch, index, or working tree, +and never triggers the ``refs/tags/v*`` PyPI Cloud Build pipeline. +""" + +from dataclasses import dataclass +import json +import os +from pathlib import Path +import subprocess +import sys +from typing import Optional + +from packaging.specifiers import InvalidSpecifier, SpecifierSet +from packaging.version import InvalidVersion, Version +import typer +from typing_extensions import Annotated + +from colab_cli.auto_update import ( + MAX_NOTICE_LENGTH, + MAX_NOTICES, + _ANSI_ESCAPE_RE, + _CONTROL_CHARS_RE, + announce_notices, + matching_notices, +) +from colab_cli.state import UpdateNotice + +TAG_NAME = "notices" +TAG_REF = f"refs/tags/{TAG_NAME}" +NOTICES_FILENAME = "notices.json" +_GIT_REPO_ENV_VARS = frozenset( + { + "GIT_ALTERNATE_OBJECT_DIRECTORIES", + "GIT_COMMON_DIR", + "GIT_DIR", + "GIT_INDEX_FILE", + "GIT_NAMESPACE", + "GIT_OBJECT_DIRECTORY", + "GIT_PREFIX", + "GIT_SUPER_PREFIX", + "GIT_WORK_TREE", + } +) + +app = typer.Typer( + help="Manage standalone Colab CLI update notices on the movable 'notices' git tag.", + no_args_is_help=True, + context_settings={"help_option_names": ["-h", "--help"]}, +) + + +@dataclass +class RepoConfig: + repo: Path + remote: str + + +def _run_git( + repo: Path, + *args: str, + stdin_text: Optional[str] = None, + check: bool = True, +) -> subprocess.CompletedProcess[str]: + """Run ``git`` in ``repo`` using UTF-8 bytes so Windows never rewrites LF to CRLF.""" + env = {k: v for k, v in os.environ.items() if k not in _GIT_REPO_ENV_VARS} + raw = subprocess.run( + ["git", *args], + cwd=repo, + env=env, + input=stdin_text.encode("utf-8") if stdin_text is not None else None, + capture_output=True, + check=check, + ) + return subprocess.CompletedProcess( + raw.args, + raw.returncode, + stdout=raw.stdout.decode("utf-8", errors="replace"), + stderr=raw.stderr.decode("utf-8", errors="replace"), + ) + + +def _validate_notice(affects: str, message: str) -> UpdateNotice: + spec_text = affects.strip() + if not spec_text: + typer.echo("[notices] Error: 'affects' specifier must not be empty.", err=True) + raise typer.Exit(code=1) + try: + SpecifierSet(spec_text) + except InvalidSpecifier as e: + typer.echo( + f"[notices] Error: invalid PEP 440 specifier {affects!r}: {e}", err=True + ) + raise typer.Exit(code=1) + + if _ANSI_ESCAPE_RE.search(message) or _CONTROL_CHARS_RE.search(message): + typer.echo( + "[notices] Error: 'message' must not contain ANSI escapes or control characters.", + err=True, + ) + raise typer.Exit(code=1) + + msg_text = message.strip() + if not msg_text: + typer.echo("[notices] Error: 'message' must not be empty.", err=True) + raise typer.Exit(code=1) + if len(msg_text) > MAX_NOTICE_LENGTH: + typer.echo( + f"[notices] Error: 'message' length ({len(msg_text)}) exceeds {MAX_NOTICE_LENGTH} characters.", + err=True, + ) + raise typer.Exit(code=1) + + return UpdateNotice(affects=spec_text, message=msg_text) + + +def _fetch_tag(cfg: RepoConfig) -> None: + _run_git( + cfg.repo, + "fetch", + "--quiet", + cfg.remote, + f"+{TAG_REF}:{TAG_REF}", + check=False, + ) + + +def _current_tag_commit(repo: Path) -> Optional[str]: + res = _run_git( + repo, "rev-parse", "--verify", "-q", f"{TAG_REF}^{{commit}}", check=False + ) + if res.returncode != 0: + return None + return res.stdout.strip() + + +def _read_existing_notices(repo: Path) -> list[UpdateNotice]: + res = _run_git(repo, "show", f"{TAG_REF}:{NOTICES_FILENAME}", check=False) + if res.returncode != 0 or not res.stdout.strip(): + return [] + payload = json.loads(res.stdout) + items = payload.get("notices") if isinstance(payload, dict) else payload + if not isinstance(items, list): + return [] + return [UpdateNotice.model_validate(item) for item in items] + + +def _write_notices_tag( + cfg: RepoConfig, + notices: list[UpdateNotice], + commit_message: str, + *, + push: bool, +) -> str: + serialized = ( + json.dumps([n.model_dump() for n in notices], indent=2, ensure_ascii=False) + + "\n" + ) + blob_sha = _run_git( + cfg.repo, "hash-object", "-w", "--stdin", stdin_text=serialized + ).stdout.strip() + tree_entry = f"100644 blob {blob_sha}\t{NOTICES_FILENAME}\n" + tree_sha = _run_git(cfg.repo, "mktree", stdin_text=tree_entry).stdout.strip() + + commit_args = ["commit-tree", tree_sha] + parent_sha = _current_tag_commit(cfg.repo) + if parent_sha: + commit_args.extend(["-p", parent_sha]) + commit_args.extend(["-m", commit_message]) + commit_sha = _run_git(cfg.repo, *commit_args).stdout.strip() + + _run_git(cfg.repo, "tag", "-fa", TAG_NAME, "-m", commit_message, commit_sha) + typer.echo(serialized.rstrip("\n")) + + if len(notices) > MAX_NOTICES: + typer.echo( + f"[notices] Note: {len(notices)} rules stored; clients display at most {MAX_NOTICES} matching notices at once." + ) + + if push: + _run_git(cfg.repo, "push", "-f", cfg.remote, TAG_REF) + typer.echo(f"[notices] Pushed {TAG_REF} ({commit_sha[:7]}) to {cfg.remote}.") + else: + typer.echo( + f"[notices] Updated local {TAG_REF} ({commit_sha[:7]}). " + f"Run 'git push -f {cfg.remote} {TAG_REF}' (or pass --push) to publish." + ) + return commit_sha + + +@app.callback() +def main_callback( + ctx: typer.Context, + repo: Annotated[ + Path, + typer.Option("--repo", help="Path to git repository root."), + ] = Path("."), + remote: Annotated[ + str, + typer.Option("--remote", help="Git remote hosting refs/tags/notices."), + ] = "origin", +) -> None: + ctx.obj = RepoConfig(repo=repo.resolve(), remote=remote) + + +@app.command(name="list") +def list_notices( + ctx: typer.Context, + no_fetch: Annotated[ + bool, + typer.Option("--no-fetch", help="Inspect local tag without fetching remote."), + ] = False, + version: Annotated[ + Optional[str], + typer.Option( + "--version", + "-v", + help="Preview how a client on this PEP 440 version renders the notices.", + ), + ] = None, +) -> None: + """Show active notices on refs/tags/notices (and optionally preview for a version).""" + cfg: RepoConfig = ctx.obj + if not no_fetch: + _fetch_tag(cfg) + + notices = _read_existing_notices(cfg.repo) + if not notices: + typer.echo(f"[notices] No active notices on {TAG_REF}.") + return + + typer.echo(json.dumps([n.model_dump() for n in notices], indent=2)) + if version is not None: + try: + Version(version) + except InvalidVersion as e: + typer.echo( + f"[notices] Error: invalid PEP 440 version {version!r}: {e}", err=True + ) + raise typer.Exit(code=1) + matched = matching_notices(notices, version) + if matched: + typer.echo(f"\n[notices] Preview for version {version}:") + announce_notices(matched, show_disable_hint=False) + else: + typer.echo(f"\n[notices] No notices match version {version}.") + + +@app.command(name="add") +def add_notice( + ctx: typer.Context, + affects: Annotated[ + str, + typer.Option( + "--affects", + "-a", + help="PEP 440 version specifier (e.g. '<0.9.0' or '>=0.7.0,<0.8.0').", + ), + ], + message: Annotated[ + str, + typer.Option( + "--message", "-m", help="Plain-text notice message (<=500 chars)." + ), + ], + no_fetch: Annotated[ + bool, + typer.Option("--no-fetch", help="Do not fetch remote tag before appending."), + ] = False, + push: Annotated[ + bool, + typer.Option("--push", help="Force-push refs/tags/notices to the remote."), + ] = False, +) -> None: + """Validate and append a notice to refs/tags/notices without touching HEAD.""" + cfg: RepoConfig = ctx.obj + new_notice = _validate_notice(affects, message) + if not no_fetch: + _fetch_tag(cfg) + + notices = _read_existing_notices(cfg.repo) + if new_notice not in notices: + notices.append(new_notice) + _write_notices_tag( + cfg, + notices, + f"notices: add rule for {new_notice.affects}", + push=push, + ) + + +@app.command(name="set") +def set_notices( + ctx: typer.Context, + source: Annotated[ + str, + typer.Argument(help="Path to a JSON notices file, or '-' to read stdin."), + ], + no_fetch: Annotated[ + bool, + typer.Option("--no-fetch", help="Do not fetch remote tag before replacing."), + ] = False, + push: Annotated[ + bool, + typer.Option("--push", help="Force-push refs/tags/notices to the remote."), + ] = False, +) -> None: + """Replace notices.json on refs/tags/notices from a JSON file or stdin.""" + cfg: RepoConfig = ctx.obj + raw_text = ( + sys.stdin.read() if source == "-" else Path(source).read_text(encoding="utf-8") + ) + try: + payload = json.loads(raw_text) + except json.JSONDecodeError as e: + typer.echo(f"[notices] Error: invalid JSON: {e}", err=True) + raise typer.Exit(code=1) + + items = payload.get("notices") if isinstance(payload, dict) else payload + if not isinstance(items, list): + typer.echo( + "[notices] Error: JSON root must be a list or {'notices': [...]}.", + err=True, + ) + raise typer.Exit(code=1) + + validated: list[UpdateNotice] = [] + for item in items: + if not isinstance(item, dict) or "affects" not in item or "message" not in item: + typer.echo( + "[notices] Error: each item must be an object with 'affects' and 'message'.", + err=True, + ) + raise typer.Exit(code=1) + validated.append(_validate_notice(str(item["affects"]), str(item["message"]))) + + if not no_fetch: + _fetch_tag(cfg) + _write_notices_tag(cfg, validated, "notices: replace notices.json", push=push) + + +@app.command(name="clear") +def clear_notices( + ctx: typer.Context, + delete_tag: Annotated[ + bool, + typer.Option( + "--delete-tag", + help="Delete refs/tags/notices instead of writing an empty [] list.", + ), + ] = False, + no_fetch: Annotated[ + bool, + typer.Option("--no-fetch", help="Do not fetch remote tag before clearing."), + ] = False, + push: Annotated[ + bool, + typer.Option("--push", help="Push the cleared or deleted tag to the remote."), + ] = False, +) -> None: + """Retract all active notices (writes [] or deletes refs/tags/notices).""" + cfg: RepoConfig = ctx.obj + if not no_fetch: + _fetch_tag(cfg) + + if not delete_tag: + _write_notices_tag(cfg, [], "notices: clear all notices", push=push) + return + + _run_git(cfg.repo, "tag", "-d", TAG_NAME, check=False) + if push: + _run_git(cfg.repo, "push", cfg.remote, f":{TAG_REF}") + typer.echo(f"[notices] Deleted {TAG_REF} from {cfg.remote}.") + else: + typer.echo( + f"[notices] Deleted local {TAG_REF}. " + f"Run 'git push {cfg.remote} :{TAG_REF}' (or pass --push) to delete on {cfg.remote}." + ) + + +if __name__ == "__main__": + app()