:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(hogli): add upload-image command for PR screenshots (#69335)
Raúl Negrón-Otero72bd5418fe7e
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.mdindex fc82b7a7432e..2a3973199f44 100644--- a/.github/pull_request_template.md+++ b/.github/pull_request_template.md@@ -8,6 +8,8 @@## Changes<!-- If there are frontend changes, please include screenshots. -->+<!-- PostHog employees: `hogli pr:upload-image <file>` uploads to the public PostHog/pr-assets repo and prints markdown to paste here. Never upload customer data, secrets, or internal info. -->+<!-- If a reference design was involved, include a link to the relevant Figma frame! -->## How did you test this code?diff --git a/AGENTS.md b/AGENTS.mdindex 70d5b781e1ce..c00e66b2b211 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -67,6 +67,8 @@ Do not invent a different format.Always fill the `## 🤖 Agent context` section when creating PRs.NEVER share sensitive information in a PR description. Users may share sensitive data in an agent session, but those should never surface to a PR description, or comments.+**Screenshots:** Upload frontend/visual changes with `hogli pr:upload-image <file>` (PostHog employees only; public + permanent `PostHog/pr-assets`) and embed the printed markdown. The first run only warns and uploads nothing; re-run with `--yes` to confirm, and only if the image has no customer data, secrets, or internal info.+### Rules- Scope is optional but encouraged when the change is specific to a feature areadiff --git a/hogli.yaml b/hogli.yamlindex 8f82c2b55d8c..17bbce02f937 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -1020,6 +1020,9 @@ utilities:worktrees:clean:click: hogli_commands.worktrees:worktrees_cleandescription: Clear out unused Claude Code / Codex / PostHog Code worktrees by age+ pr:upload-image:+ click: hogli_commands.upload_image:upload_image+ description: Upload screenshot(s) to the public PostHog/pr-assets repo and print embeddable PR markdownutilities:posthog-worktree:bin_script: posthog-worktreedescription: Manage isolated git worktrees for PostHog developmentdiff --git a/tools/hogli-commands/hogli_commands/db_schema.py b/tools/hogli-commands/hogli_commands/db_schema.pyindex 673b0d082891..3a27702d9dd9 100644--- a/tools/hogli-commands/hogli_commands/db_schema.py+++ b/tools/hogli-commands/hogli_commands/db_schema.py@@ -18,6 +18,8 @@ from typing import Literal, TypeVar, castimport clickimport requests+from hogli_commands.github_auth import github_headers, github_token+ArtifactMode = Literal["off", "auto", "on"]GITHUB_REPOSITORY = "PostHog/posthog"@@ -207,44 +209,6 @@ def restore_schema_dump(click.echo(f"Restored {target_db} from {schema_path}")-def _github_token() -> str | None:- for env_var in ("GH_TOKEN", "GITHUB_TOKEN"):- token = os.environ.get(env_var)- if token:- return token-- gh_path = shutil.which("gh")- if gh_path is None:- return None-- try:- result = subprocess.run(- [gh_path, "auth", "token"],- cwd=REPO_ROOT,- capture_output=True,- text=True,- timeout=10,- check=False,- )- except (OSError, subprocess.TimeoutExpired):- return None-- token = result.stdout.strip()- if result.returncode == 0 and token:- return token- return None---def _github_headers(token: str | None) -> dict[str, str]:- headers = {- "Accept": "application/vnd.github+json",- "X-GitHub-Api-Version": "2022-11-28",- }- if token:- headers["Authorization"] = f"Bearer {token}"- return headers--def _artifact_from_api(raw: Mapping[str, object]) -> SchemaArtifact | None:workflow_run = raw.get("workflow_run")if not isinstance(workflow_run, Mapping):@@ -307,7 +271,7 @@ def fetch_schema_artifacts(*, token: str | None, session: requests.Session | Nonresponse = http.get(f"https://api.github.com/repos/{GITHUB_REPOSITORY}/actions/artifacts",params={"name": SCHEMA_ARTIFACT_NAME, "per_page": 100, "page": page},- headers=_github_headers(token),+ headers=github_headers(token),timeout=30,)response.raise_for_status()@@ -345,7 +309,7 @@ def download_schema_artifact(http = session or requests.Session()response = http.get(artifact.archive_download_url,- headers=_github_headers(token),+ headers=github_headers(token),stream=True,timeout=60,)@@ -406,7 +370,7 @@ def download_latest_compatible_schema(base_branch: str = DEFAULT_BASE_BRANCH,session: requests.Session | None = None,) -> SchemaArtifact:- token = _github_token()+ token = github_token()artifacts = fetch_schema_artifacts(token=token, session=session)artifact = select_newest_compatible_artifact(artifacts, base_branch=base_branch)if artifact is None:diff --git a/tools/hogli-commands/hogli_commands/github_auth.py b/tools/hogli-commands/hogli_commands/github_auth.pynew file mode 100644index 000000000000..d325c8135fc7--- /dev/null+++ b/tools/hogli-commands/hogli_commands/github_auth.py@@ -0,0 +1,48 @@+"""Shared GitHub auth for hogli commands: a token from the env or gh CLI, plus API headers.++Centralizes the one decision (how to source a github.com token and what REST headers to+send) so callers like db:restore-test-db and pr:upload-image don't each reimplement it.+"""++from __future__ import annotations++import os+import shutil+import subprocess+++def github_token() -> str | None:+ """A github.com token from GH_TOKEN/GITHUB_TOKEN, else `gh auth token`, else None.++ Env vars win so CI and explicit overrides work without gh; otherwise fall back to the+ caller's gh login. Pinned to github.com so the result is independent of the cwd's repo.+ """+ for env_var in ("GH_TOKEN", "GITHUB_TOKEN"):+ if token := os.environ.get(env_var):+ return token+ gh = shutil.which("gh")+ if gh is None:+ return None+ try:+ result = subprocess.run(+ [gh, "auth", "token", "--hostname", "github.com"],+ capture_output=True,+ text=True,+ timeout=10,+ check=False,+ )+ except (OSError, subprocess.TimeoutExpired):+ return None+ token = result.stdout.strip()+ return token if result.returncode == 0 and token else None+++def github_headers(token: str | None) -> dict[str, str]:+ """Standard GitHub REST API headers, with Bearer auth when a token is available."""+ headers = {+ "Accept": "application/vnd.github+json",+ "X-GitHub-Api-Version": "2022-11-28",+ }+ if token:+ headers["Authorization"] = f"Bearer {token}"+ return headersdiff --git a/tools/hogli-commands/hogli_commands/tests/test_db_schema.py b/tools/hogli-commands/hogli_commands/tests/test_db_schema.pyindex d79ba8525b7b..86a2e730b39f 100644--- a/tools/hogli-commands/hogli_commands/tests/test_db_schema.py+++ b/tools/hogli-commands/hogli_commands/tests/test_db_schema.py@@ -104,7 +104,7 @@ def test_download_diagnostics_on_no_compatible_artifact(monkeypatch: pytest.Monk_artifact(10, "pr-sha", "2026-01-01T00:00:00Z", head_branch="some-pr"),_artifact(11, "master-sha", "2026-01-02T00:00:00Z", head_branch="some-other-pr"),]- monkeypatch.setattr(db_schema, "_github_token", lambda: "token")+ monkeypatch.setattr(db_schema, "github_token", lambda: "token")monkeypatch.setattr(db_schema, "fetch_schema_artifacts", lambda **kwargs: artifacts)split_runner = CliRunner(mix_stderr=False)diff --git a/tools/hogli-commands/hogli_commands/tests/test_github_auth.py b/tools/hogli-commands/hogli_commands/tests/test_github_auth.pynew file mode 100644index 000000000000..f37ccb2cb834--- /dev/null+++ b/tools/hogli-commands/hogli_commands/tests/test_github_auth.py@@ -0,0 +1,37 @@+from __future__ import annotations++from types import SimpleNamespace++import pytest+from unittest.mock import patch++from hogli_commands import github_auth+++def test_env_token_wins_over_gh(monkeypatch: pytest.MonkeyPatch) -> None:+ # Env vars must take precedence so CI and explicit overrides work without gh.+ monkeypatch.setenv("GH_TOKEN", "env-tok")+ with patch.object(github_auth.subprocess, "run") as run:+ assert github_auth.github_token() == "env-tok"+ run.assert_not_called()+++def test_falls_back_to_gh_cli(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("GH_TOKEN", raising=False)+ monkeypatch.delenv("GITHUB_TOKEN", raising=False)+ monkeypatch.setattr(github_auth.shutil, "which", lambda _: "/usr/bin/gh")+ with patch.object(github_auth.subprocess, "run", return_value=SimpleNamespace(returncode=0, stdout="gh-tok\n")):+ assert github_auth.github_token() == "gh-tok"+++def test_none_when_no_env_and_no_gh(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("GH_TOKEN", raising=False)+ monkeypatch.delenv("GITHUB_TOKEN", raising=False)+ monkeypatch.setattr(github_auth.shutil, "which", lambda _: None)+ assert github_auth.github_token() is None+++def test_headers_carry_bearer_only_with_a_token() -> None:+ # db_schema relies on the None case omitting Authorization (anonymous reads).+ assert github_auth.github_headers("tok")["Authorization"] == "Bearer tok"+ assert "Authorization" not in github_auth.github_headers(None)diff --git a/tools/hogli-commands/hogli_commands/tests/test_upload_image.py b/tools/hogli-commands/hogli_commands/tests/test_upload_image.pynew file mode 100644index 000000000000..80392566efc4--- /dev/null+++ b/tools/hogli-commands/hogli_commands/tests/test_upload_image.py@@ -0,0 +1,211 @@+"""Tests for hogli pr:upload-image.++The framework's parametrized ``--help`` test covers command wellformedness; these guard+the upload contract the README pins down: the exact key shape, the base64 content body,+the SHA-pinned markdown that lands on stdout and nothing else, the single retry on a+concurrent-commit 409, and the --yes confirmation gate. Token sourcing lives in+``test_github_auth`` since it moved to the shared helper.+"""++from __future__ import annotations++import re+import base64+from pathlib import Path+from types import SimpleNamespace++import pytest+from unittest.mock import Mock, patch++from click.testing import CliRunner+from hogli_commands import github_auth, upload_image++_KEY_RE = r"\d{4}/\d{2}/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"+++def png(tmp_path: Path) -> Path:+ path = tmp_path / "diagram.png"+ path.write_bytes(b"\x89PNG\r\n\x1a\n fake bytes")+ return path+++def _resp(status: int, sha: str | None = None) -> SimpleNamespace:+ return SimpleNamespace(+ status_code=status,+ ok=status < 400,+ json=lambda: {"commit": {"sha": sha}} if sha is not None else {},+ )+++def _session(*responses: SimpleNamespace) -> Mock:+ session = Mock()+ session.put.side_effect = responses+ return session+++def test_make_key_shape() -> None:+ # YYYY/MM/<uuid4>.<ext>: the README-pinned layout keeps the tree browsable and prunable.+ assert re.fullmatch(_KEY_RE + r"\.png", upload_image._make_key("png"))+++def test_upload_puts_base64_body_and_returns_sha(png: Path) -> None:+ session = _session(_resp(201, "deadbeef"))+ sha = upload_image._upload(png, "2026/07/abc.png", "tok", session)++ assert sha == "deadbeef"+ url = session.put.call_args.args[0]+ assert url == "https://api.github.com/repos/PostHog/pr-assets/contents/2026/07/abc.png"+ body = session.put.call_args.kwargs["json"]+ assert body["message"] == "add screenshot"+ assert body["content"] == base64.b64encode(png.read_bytes()).decode()+ assert "\n" not in body["content"] # the contents API rejects line-wrapped base64+ assert session.put.call_args.kwargs["headers"]["Authorization"] == "Bearer tok"+++def test_upload_retries_once_on_409_with_same_key(png: Path) -> None:+ session = _session(_resp(409), _resp(201, "sha2"))+ sha = upload_image._upload(png, "2026/07/abc.png", "tok", session)++ assert sha == "sha2"+ assert session.put.call_count == 2+ # both attempts target the identical key; a fresh key on retry would orphan the first+ urls = {call.args[0] for call in session.put.call_args_list}+ assert urls == {"https://api.github.com/repos/PostHog/pr-assets/contents/2026/07/abc.png"}+++def test_upload_gives_up_after_second_409(png: Path) -> None:+ session = _session(_resp(409), _resp(409))+ with pytest.raises(upload_image.click.ClickException):+ upload_image._upload(png, "2026/07/x.png", "tok", session)+ assert session.put.call_count == 2 # one retry, then surface the failure++[email protected]("status", [403, 404], ids=["forbidden", "not_found"])+def test_permission_denied_points_at_org_access(png: Path, status: int) -> None:+ # A denied PUT must explain the write-access fix, not surface a raw error; this is the+ # "only PostHog org members can write" boundary.+ session = _session(_resp(status))+ with pytest.raises(upload_image.click.ClickException, match="PostHog org"):+ upload_image._upload(png, "2026/07/x.png", "tok", session)+++def test_upload_wraps_unexpected_response(png: Path) -> None:+ # A 2xx whose body isn't the contents-API shape must surface as a ClickException, not a+ # raw KeyError traceback.+ session = _session(_resp(201)) # json() -> {} with no commit.sha+ with pytest.raises(upload_image.click.ClickException, match="unexpected response"):+ upload_image._upload(png, "2026/07/x.png", "tok", session)+++def test_command_prints_only_sha_pinned_markdown_to_stdout(png: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("GH_TOKEN", "tok") # token via the real env path+ with patch.object(upload_image.requests, "Session", return_value=_session(_resp(201, "abc123"))):+ result = CliRunner(mix_stderr=False).invoke(upload_image.upload_image, ["--yes", str(png)])++ assert result.exit_code == 0+ line = result.stdout.strip()+ assert re.fullmatch(+ rf"!\[diagram\]\(https://raw\.githubusercontent\.com/PostHog/pr-assets/abc123/{_KEY_RE}\.png\)", line+ )+ # the public-repo warning must reach stderr, never stdout (stdout is piped into PRs verbatim)+ assert "PUBLIC" in result.stderr+ assert "PUBLIC" not in result.stdout+++ ("alt", "expected_prefix"),+ [("before / after", ", ("", "!["), ("chart]v2", "![chart\\]v2](")],+ ids=["override", "empty_honored", "bracket_escaped"],+)+def test_command_caption_rendering(png: Path, monkeypatch: pytest.MonkeyPatch, alt: str, expected_prefix: str) -> None:+ # --alt is used verbatim (empty stays empty, not replaced by the stem) and its markdown+ # metacharacters are escaped so a `]` can't truncate the embed.+ monkeypatch.setenv("GH_TOKEN", "tok")+ with patch.object(upload_image.requests, "Session", return_value=_session(_resp(201, "abc123"))):+ result = CliRunner(mix_stderr=False).invoke(upload_image.upload_image, ["--yes", "--alt", alt, str(png)])++ assert result.stdout.strip().startswith(expected_prefix)+++def test_requires_yes_before_uploading(png: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ # The gate: a first run without --yes must warn and abort without uploading, so the+ # caller has to read the warning and re-run to confirm the public upload.+ monkeypatch.setenv("GH_TOKEN", "tok")+ session = _session(_resp(201, "x"))+ with patch.object(upload_image.requests, "Session", return_value=session):+ result = CliRunner(mix_stderr=False).invoke(upload_image.upload_image, [str(png)])++ assert result.exit_code != 0+ assert "--yes" in result.stderr+ assert not result.stdout # no markdown emitted+ session.put.assert_not_called()+++def test_command_errors_without_a_token(png: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("GH_TOKEN", raising=False)+ monkeypatch.delenv("GITHUB_TOKEN", raising=False)+ monkeypatch.setattr(github_auth.shutil, "which", lambda _: None) # no env, no gh -> no token+ result = CliRunner(mix_stderr=False).invoke(upload_image.upload_image, ["--yes", str(png)])++ assert result.exit_code != 0+ assert "token" in result.stderr.lower()+++def test_rejects_alt_with_multiple_files(tmp_path: Path) -> None:+ # A single --alt can't caption N files distinctly; reject it rather than silently+ # captioning every image identically.+ a, b = tmp_path / "a.png", tmp_path / "b.png"+ a.write_bytes(b"x")+ b.write_bytes(b"y")+ result = CliRunner(mix_stderr=False).invoke(upload_image.upload_image, ["--yes", "--alt", "shared", str(a), str(b)])++ assert result.exit_code != 0+ assert "--alt" in result.stderr+++ ("name", "expected"),+ [("notes.txt", "unsupported"), ("clip.mp4", "unsupported"), ("diagram.svg", "unsupported")],+ ids=["txt", "mp4", "svg"],+)+def test_rejects_unsupported_extensions(tmp_path: Path, name: str, expected: str) -> None:+ path = tmp_path / name+ path.write_bytes(b"data")+ with pytest.raises(upload_image.click.ClickException, match=expected):+ upload_image._validate(path)+++def test_validate_rejects_symlink_before_reading_target(tmp_path: Path) -> None:+ # A `screenshot.png` symlink pointing at a sensitive file must be refused before its+ # target is stat'd or read; the .png name would otherwise pass the ext gate and upload .env.+ target = tmp_path / "secret.env"+ target.write_bytes(b"SECRET=1")+ link = tmp_path / "screenshot.png"+ link.symlink_to(target)+ with pytest.raises(upload_image.click.ClickException, match="symlink"):+ upload_image._validate(link)+++def test_symlink_is_rejected_on_stderr_without_any_upload(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ target = tmp_path / "secret.env"+ target.write_bytes(b"SECRET=1")+ link = tmp_path / "screenshot.png"+ link.symlink_to(target)+ monkeypatch.setenv("GH_TOKEN", "tok")+ session = _session(_resp(201, "x"))+ with patch.object(upload_image.requests, "Session", return_value=session):+ result = CliRunner(mix_stderr=False).invoke(upload_image.upload_image, ["--yes", str(link)])++ assert result.exit_code != 0+ assert "symlink" in result.stderr.lower()+ assert not result.stdout # nothing uploaded, no markdown+ session.put.assert_not_called() # the target was never fetched or PUT+++def test_rejects_oversized_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ path = tmp_path / "huge.png"+ path.write_bytes(b"x")+ monkeypatch.setattr(upload_image, "_MAX_BYTES", 0)+ with pytest.raises(upload_image.click.ClickException, match="exceeds the"):+ upload_image._validate(path)diff --git a/tools/hogli-commands/hogli_commands/upload_image.py b/tools/hogli-commands/hogli_commands/upload_image.pynew file mode 100644index 000000000000..b6d7b6b5aa37--- /dev/null+++ b/tools/hogli-commands/hogli_commands/upload_image.py@@ -0,0 +1,175 @@+"""hogli pr:upload-image: upload screenshots to the public PostHog/pr-assets repo.++Wraps the GitHub contents API upload documented in the pr-assets README so engineers+and agents can turn a local screenshot into an embeddable, SHA-pinned markdown image+line for a PR description with one command. Running through hogli means the usage is+tracked by hogli's built-in command telemetry.++Auth reuses a GitHub token from GH_TOKEN/GITHUB_TOKEN or the gh CLI (`gh auth token`),+so it works with or without gh installed as long as a token with write access to a+PostHog org repo is available. The target repo is public by design: GitHub renders PR+images through its anonymous camo proxy, which requires anonymous read. The command+warns about this on every run.+"""++from __future__ import annotations++import base64+from datetime import UTC, datetime+from pathlib import Path+from typing import Final+from uuid import uuid4++import click+import requests++from hogli_commands.github_auth import github_headers, github_token++_REPO: Final = "PostHog/pr-assets"+# svg is excluded: raw.githubusercontent.com serves it as text/plain, so GitHub won't inline it+_ALLOWED_EXTS: Final = frozenset({"png", "jpg", "jpeg", "gif", "webp"})+_MAX_MB: Final = 10 # GitHub caps image/gif attachments at 10 MB; larger is a video or wrong file+_MAX_BYTES: Final = _MAX_MB * 1024 * 1024+_COMMIT_MESSAGE: Final = "add screenshot"+_PUBLIC_WARNING: Final = (+ "⚠ PUBLIC + PERMANENT upload to PostHog/pr-assets.\n"+ " SHA-pinned URLs keep serving even after the file is deleted, so an upload cannot be taken back.\n"+ " Never upload customer data, secrets, tokens, or internal-only information."+)+++def _make_key(ext: str) -> str:+ """Object key for an upload: ``YYYY/MM/<uuid4>.<ext>`` in UTC.++ Random names avoid collisions; the date dirs keep the tree browsable and prunable.+ """+ now = datetime.now(UTC)+ return f"{now:%Y/%m}/{uuid4()}.{ext}"+++def _encode_base64(path: Path) -> str:+ """Base64-encode the file as a single newline-free line.++ The contents API wants raw base64 with no line breaks; ``b64encode`` (unlike+ ``encodebytes``) never inserts them.+ """+ return base64.b64encode(path.read_bytes()).decode("ascii")+++def _put(session: requests.Session, url: str, token: str, body: dict[str, str]) -> requests.Response:+ """PUT to the contents API, turning a network error into a friendly ClickException."""+ try:+ return session.put(url, headers=github_headers(token), json=body, timeout=120)+ except requests.RequestException as exc:+ raise click.ClickException(f"GitHub request failed: {exc}")+++def _upload(path: Path, key: str, token: str, session: requests.Session) -> str:+ """PUT the file to the contents API, returning the created commit sha.++ Retries once on HTTP 409 with the same key, since concurrent commits to the repo's+ default branch can race.+ """+ url = f"https://api.github.com/repos/{_REPO}/contents/{key}"+ body = {"message": _COMMIT_MESSAGE, "content": _encode_base64(path)}++ resp = _put(session, url, token, body)+ if resp.status_code == 409:+ # a concurrent commit to the default branch raced us; retry once with the same key+ resp = _put(session, url, token, body)++ if resp.status_code in (403, 404):+ raise click.ClickException(_denied_message(path))+ if not resp.ok:+ raise click.ClickException(f"upload of {path.name} failed (HTTP {resp.status_code})")+ try:+ return resp.json()["commit"]["sha"]+ except (ValueError, KeyError, TypeError) as exc:+ raise click.ClickException(f"GitHub returned an unexpected response uploading {path.name}: {exc}")+++def _denied_message(path: Path) -> str:+ """Explain a 403/404: the token can't write to pr-assets (not an org member, or missing scope)."""+ return (+ f"upload of {path.name} was denied. Writing to {_REPO} needs write access to a public PostHog repo: "+ "confirm your token is a PostHog org account with the `repo` scope "+ "(gh users: `gh auth refresh -s repo`; or set GH_TOKEN to a PAT with the repo scope)."+ )+++def _validate(path: Path) -> str:+ """Return the lowercased extension, or raise on a symlink / unsupported type / oversized file."""+ # Reject symlinks before any stat/read: a `screenshot.png` link pointing at `.env` would+ # otherwise be followed and its target uploaded to the public repo.+ if path.is_symlink():+ raise click.ClickException(f"{path.name}: refusing to upload a symlink (it could point at a sensitive file)")+ ext = path.suffix.lower().lstrip(".")+ if ext not in _ALLOWED_EXTS:+ allowed = ", ".join(sorted(_ALLOWED_EXTS))+ raise click.ClickException(f"{path.name}: unsupported extension '.{ext}' (allowed: {allowed})")+ size = path.stat().st_size+ if size > _MAX_BYTES:+ raise click.ClickException(f"{path.name}: {size / 1024 / 1024:.1f} MB exceeds the {_MAX_MB} MB limit")+ return ext+++def _escape_alt(text: str) -> str:+ """Escape the one markdown metacharacter that would truncate image alt text."""+ return text.replace("]", "\\]")++[email protected](name="pr:upload-image")[email protected]("files", nargs=-1, required=True, type=click.Path(exists=True, dir_okay=False, path_type=Path))[email protected]("--alt", help="Alt text for the markdown (defaults to each file's stem).")+# Hidden on purpose: the first run without it prints the warning and stops, so the caller+# has to read the warning and re-run with --yes. Undocumented is the whole point of the gate.[email protected]("-y", "--yes", is_flag=True, hidden=True)+def upload_image(files: tuple[Path, ...], alt: str | None, yes: bool) -> None:+ """Upload screenshot(s) to the public PostHog/pr-assets repo and print embeddable markdown.++ Prints one `` line per file to stdout (everything else goes to stderr),+ so you can pipe or copy the markdown straight into a PR description. URLs are pinned+ to the commit sha, so they keep rendering even if the file is later moved or deleted.++ \b+ hogli pr:upload-image screenshot.png+ hogli pr:upload-image --alt "dashboard after fix" result.png+ hogli pr:upload-image before.png after.png++ Uploads land in a PUBLIC repo (GitHub image embeds require anonymous read) and are+ permanent: SHA-pinned URLs keep serving even after the file is deleted. Never upload+ customer data, secrets, or internal-only information.+ """+ click.secho(_PUBLIC_WARNING, fg="yellow", bold=True, err=True)++ if alt is not None and len(files) > 1:+ raise click.ClickException("--alt captions a single image; drop it to caption each file with its stem")++ validated = [(path, _validate(path)) for path in files]++ # Deliberate speed bump: make the caller read the warning above and re-run to confirm.+ if not yes:+ click.secho(+ "\nNothing uploaded. If the image is safe to publish (no customer data, secrets, or internal "+ "info), re-run the same command with --yes to confirm.",+ fg="yellow",+ err=True,+ )+ raise SystemExit(1)++ token = github_token()+ if token is None:+ raise click.ClickException(+ "no GitHub token found. Set GH_TOKEN or GITHUB_TOKEN, or install gh "+ "(https://cli.github.com/) and run `gh auth login`."+ )+ session = requests.Session()++ for path, ext in validated:+ key = _make_key(ext)+ click.secho(f"Uploading {path.name} → {_REPO}/{key} …", fg="cyan", err=True)+ sha = _upload(path, key, token, session)+ caption = alt if alt is not None else path.stem+ markdown = f""+ click.echo(markdown) # stdout carries only the markdown, so callers can pipe it+ click.secho(f"✓ uploaded {path.name}", fg="green", err=True)