Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(cli): repowise publish, put a local repo on repowise.dev in one command (#3004)
Swati Ahujabcb514e5ac6b
diff --git a/README.md b/README.mdindex a24232420..9bddf58b7 100644--- a/README.md+++ b/README.md@@ -836,6 +836,13 @@ on our own codebase in the open:[live snapshot](https://www.repowise.dev/s/5a6b93fa9a69) ·[explore public repos](https://www.repowise.dev/explore).+Already indexed locally? `repowise publish` puts the same repo on repowise.dev in one+command: it asks repowise.dev to index the repo's GitHub remote, so nothing is uploaded+from your machine and only what you have pushed is published. A hosted index usually+takes about 10 minutes. Public repos publish on a free account (up to 2 repos, no card);+private repos and more repos need Pro, free for 10 days with a card.+[What hosted adds →](https://repowise.dev/hosted?src=oss_readme)+---## Privacy@@ -883,6 +890,7 @@ repowise distill pytest # compact, errors-first, reversible command outputrepowise saved # tokens and dollars saved by distillationrepowise workspace add # multi-repo workspace managementrepowise doctor # check setup, API keys, index drift+repowise publish # put this repo on repowise.dev (indexed from GitHub; public repos free)repowise uninstall # remove what repowise wrote, and say what it left```diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex 464b519bb..37ac7bc8a 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -2210,6 +2210,32 @@ Show the Repowise account this machine is signed in to.repowise whoami```+### `repowise publish [PATH]`++Put this repo on repowise.dev. The command reads the GitHub `origin` remote and+asks repowise.dev to index it there: nothing is uploaded from your machine, so+only what you have pushed is published. Signed out, it runs the `repowise login`+browser sign-in first. A hosted index usually takes about 10 minutes.++On success it prints the indexing page (and opens it), the repo page for when it+is ready, and the MCP address to add in Claude.ai or ChatGPT. When repowise.dev+refuses, it says why and links the next step: a private repo on a free account+goes to the repo's page, which starts the Pro trial (10 days free, card+required) and the GitHub App install; a paid account without the GitHub App+gets the install link; the free plan's 2-repo limit links the trial checkout.+A repo without a GitHub remote is not published.++| Flag | Description |+|------|-------------|+| `--ref` | Branch or tag on GitHub to publish (default: the branch you are on if it is pushed, else the default branch) |+| `--no-open` | Don't open the indexing page in the browser |++```bash+repowise publish # publish the repo in this directory+repowise publish --ref release # publish another pushed branch+repowise publish --no-open+```+---### `repowise delete [REPO_ID]`diff --git a/packages/cli/src/repowise/cli/commands/login_cmd.py b/packages/cli/src/repowise/cli/commands/login_cmd.pyindex dbea6c623..33c50021e 100644--- a/packages/cli/src/repowise/cli/commands/login_cmd.py+++ b/packages/cli/src/repowise/cli/commands/login_cmd.py@@ -178,6 +178,17 @@ def login_command(with_token: bool, device_name: str | None) -> None:_greet(account)return+ browser_sign_in(device, src="cli_login")+++def browser_sign_in(device: str | None, *, src: str) -> dict:+ """Run the browser PKCE sign-in and return the account (``{}`` when the+ platform did not answer ``/auth/me``). ``src`` credits a signup that+ starts here to the command that sent the person. Raises+ ``click.ClickException`` when the sign-in does not complete.+ """+ from repowise.cli.platform import auth, credentials+# Browser PKCE flow.verifier, challenge = auth.make_pkce_pair()state = secrets.token_urlsafe(16)@@ -197,6 +208,7 @@ def login_command(with_token: bool, device_name: str | None) -> None:code_challenge=challenge,state=state,device_name=device,+ src=src,)console.print("Opening your browser to sign in to Repowise...")console.print(f"If it doesn't open, visit:\n [cyan]{url}[/cyan]\n")@@ -231,6 +243,7 @@ def login_command(with_token: bool, device_name: str | None) -> None:auth.store_account_snapshot(account)_link_anonymous_id()_greet(account or {})+ return account or {}@click.command(name="logout")diff --git a/packages/cli/src/repowise/cli/commands/publish_cmd.py b/packages/cli/src/repowise/cli/commands/publish_cmd.pynew file mode 100644index 000000000..0d6424dc7--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/publish_cmd.py@@ -0,0 +1,88 @@+"""``repowise publish``: put this repo on repowise.dev with one command.++repowise.dev indexes the repo's GitHub remote itself; nothing from this+machine is uploaded, so only pushed code is published. Signed out, the+command runs the normal browser sign-in first. The decision and every+message live in :mod:`repowise.cli.platform.publish`, which the local web+UI's publish button shares.+"""++from __future__ import annotations++import re+import webbrowser+from pathlib import Path++import click+from rich.markup import escape++from repowise.cli.helpers import console+from repowise.cli.output import emit_json, format_option++[email protected](name="publish")[email protected]("path", required=False, type=click.Path(exists=True, file_okay=False))+ "--ref",+ default=None,+ help="Branch or tag on GitHub to publish (default: the branch you are on, "+ "if it is pushed, else the repo's default branch).",+)[email protected]("--no-open", is_flag=True, help="Don't open the indexing page in the browser.")+ "--src",+ default=None,+ hidden=True,+ help="Surface that asked for the publish, for the links' attribution.",+)+@format_option(+ help="table prints for a person; json prints the result as one object and never "+ "starts a browser sign-in (signed out reads as outcome signed_out)."+)+def publish_command(+ path: str | None, ref: str | None, no_open: bool, src: str | None, fmt: str+) -> None:+ """Publish this repo on repowise.dev (indexed from GitHub, free for public repos)."""+ from repowise.cli.platform import publish as pub+ from repowise.cli.platform import telemetry++ repo_path = Path(path or ".").resolve()+ if src is not None and not re.fullmatch(r"[a-z0-9_]{1,64}", src):+ raise click.BadParameter("must be 1-64 of a-z, 0-9 and _", param_hint="--src")++ interactive = fmt != "json"+ if interactive and pub.read_remote(repo_path) is not None and not pub.is_signed_in():+ from repowise.cli.commands.login_cmd import _default_device_name, browser_sign_in++ console.print("Publishing needs a free repowise.dev account. Signing you in first.\n")+ browser_sign_in(_default_device_name(), src=pub.SRC)+ console.print()++ result = pub.publish(repo_path, ref=ref, src=src or pub.SRC)+ telemetry.add_command_outcome(outcome=result.outcome)++ ok = result.outcome in {"published", "curated"}+ if not interactive:+ emit_json(result.to_dict())+ if not ok:+ raise SystemExit(1)+ return++ mark = "[green]✓[/green] " if ok else ""+ console.print(f"{mark}{escape(result.message)}")+ if result.url:+ # Unhighlighted, so the URL stays one hyperlink instead of one per token.+ console.print(+ f" [cyan][link={result.url}]{escape(result.url)}[/link][/cyan]", highlight=False+ )+ for line in result.details:+ console.print(f" [dim]{escape(line)}[/dim]", highlight=False)+ if result.outcome != "not_github":+ # No highlighting: it would colour "<branch>" inside the dim line.+ console.print(f"\n[dim]{escape(pub.PUSHED_ONLY)}[/dim]", highlight=False)++ if result.open_url and not no_open:+ webbrowser.open(result.open_url)++ if not ok:+ raise SystemExit(1)diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.pyindex a1acee827..b0a520a1e 100644--- a/packages/cli/src/repowise/cli/main.py+++ b/packages/cli/src/repowise/cli/main.py@@ -98,6 +98,7 @@ _OSS_COMMANDS: tuple[tuple[str, str], ...] = (("wiki-styles", "restyle_cmd:wiki_styles_command"),("whats-new", "whats_new_cmd:whats_new_command"),("telemetry", "telemetry_cmd:telemetry_command"),+ ("publish", "publish_cmd:publish_command"),("login", "login_cmd:login_command"),("logout", "login_cmd:logout_command"),("whoami", "login_cmd:whoami_command"),diff --git a/packages/cli/src/repowise/cli/platform/auth.py b/packages/cli/src/repowise/cli/platform/auth.pyindex 7d53057c9..61526d1a4 100644--- a/packages/cli/src/repowise/cli/platform/auth.py+++ b/packages/cli/src/repowise/cli/platform/auth.py@@ -15,7 +15,6 @@ then simply proceeds anonymously.from __future__ import annotationsimport base64-import contextlibimport hashlibimport secretsimport time@@ -50,9 +49,12 @@ def build_authorize_url(code_challenge: str,state: str,device_name: str | None,+ src: str = "cli_login",) -> str:from urllib.parse import urlencode+ from repowise.cli.platform.links import attribution_params+params = {"client_id": CLIENT_ID,"redirect_uri": redirect_uri,@@ -65,14 +67,10 @@ def build_authorize_url(if device_name:params["device_name"] = device_name# Where the visit came from, so a signup that starts here is credited to- # the CLI. The install id rides along only with telemetry on; the site- # uses it to tie this install's usage to the new account.- params["src"] = "cli_login"- with contextlib.suppress(Exception):- from repowise.cli.platform import identity, settings-- if settings.is_enabled():- params["aid"] = identity.get_anonymous_id()+ # the CLI command that sent it. The install id rides along only with+ # telemetry on; the site uses it to tie this install's usage to the new+ # account.+ params.update(attribution_params(src))return f"{AUTHORIZE_URL}?{urlencode(params)}"diff --git a/packages/cli/src/repowise/cli/platform/client.py b/packages/cli/src/repowise/cli/platform/client.pyindex ac0d51226..6570216c9 100644--- a/packages/cli/src/repowise/cli/platform/client.py+++ b/packages/cli/src/repowise/cli/platform/client.py@@ -119,6 +119,38 @@ class PlatformClient:# Network, JSON — all advisory. The CLI works offline.return 0+ def post_json(+ self,+ path: str,+ payload: dict[str, Any],+ *,+ timeout: float | None = None,+ ) -> tuple[int, dict[str, Any]]:+ """POST ``payload`` as JSON and return ``(status_code, parsed_body)``.++ For account actions whose refusals the user has to read (a plan+ limit, a missing GitHub App install), so unlike :meth:`post` the+ status and body come back instead of a bool. A body that is not a+ JSON object reads as ``{}``; no answer at all is ``(0, {})``.+ """+ url = f"{self.base_url}/{path.lstrip('/')}"+ try:+ import httpx++ resp = httpx.post(+ url,+ json=payload,+ headers=self._headers(),+ timeout=timeout or self.timeout,+ )+ except Exception:+ return 0, {}+ try:+ body = resp.json()+ except Exception:+ body = {}+ return resp.status_code, body if isinstance(body, dict) else {}+def post_form(self,path: str,diff --git a/packages/cli/src/repowise/cli/platform/links.py b/packages/cli/src/repowise/cli/platform/links.pynew file mode 100644index 000000000..476472da4--- /dev/null+++ b/packages/cli/src/repowise/cli/platform/links.py@@ -0,0 +1,40 @@+"""Links from the CLI to repowise.dev, tagged with where they were shown.++Every link carries ``src`` (which CLI moment it came from), so a signup that+starts from it is credited to that moment. Only the sign-in URL also carries+the anonymous install id (``aid``, telemetry on only); a link someone merely+opens never does.+"""++from __future__ import annotations++import contextlib+from urllib.parse import urlencode++#: The hosted site. Production only, matching the PlatformClient design rule.+SITE_URL = "https://repowise.dev"+++def attribution_params(src: str) -> dict[str, str]:+ """``{"src": src}``, plus ``aid`` when telemetry is enabled. Sign-in only."""+ params = {"src": src}+ with contextlib.suppress(Exception):+ from repowise.cli.platform import identity, settings++ if settings.is_enabled():+ params["aid"] = identity.get_anonymous_id()+ return params+++def site_link(+ path: str,+ src: str,+ *,+ fragment: str | None = None,+ params: dict[str, str] | None = None,+) -> str:+ """``https://repowise.dev/<path>?<params>&src=…[#fragment]``."""+ query = dict(params or {})+ query["src"] = src+ url = f"{SITE_URL}/{path.lstrip('/')}?{urlencode(query)}"+ return f"{url}#{fragment}" if fragment else urldiff --git a/packages/cli/src/repowise/cli/platform/publish.py b/packages/cli/src/repowise/cli/platform/publish.pynew file mode 100644index 000000000..b82f885ac--- /dev/null+++ b/packages/cli/src/repowise/cli/platform/publish.py@@ -0,0 +1,334 @@+"""Publish a local repo on repowise.dev by asking it to index the GitHub remote.++Nothing local is uploaded: the hosted indexer clones the repo from GitHub, so+only what has been pushed is published. This module holds the whole decision+(which repo, which branch, what the platform answered, what to tell the user)+and returns it as a :class:`PublishResult`, so ``repowise publish`` and the+local web UI's publish button say exactly the same thing.+"""++from __future__ import annotations++import re+import subprocess+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any++from repowise.cli.platform.links import site_link++#: Every link this flow prints or opens is credited to it.+SRC = "cli_publish"++#: The GitHub App that gives repowise.dev read access to private repos.+GITHUB_APP_INSTALL_URL = "https://github.com/apps/repowise-app/installations/new"++#: The hosted MCP endpoint for one repo.+MCP_URL = "https://api.repowise.dev/mcp/{owner}/{name}"++PUSHED_ONLY = (+ "Only what's pushed to GitHub is published. Local uncommitted or unpushed "+ "changes are not. Use --ref <branch> to publish another branch."+)+HOW_LONG = "A hosted index usually takes about 10 minutes, longer for big repos."++#: Paid tiers. Anyone else hitting a private-repo refusal needs a plan first.+_PAID_TIERS = {"pro", "teams", "admin"}++# https://github.com/o/n(.git), [email protected]:o/n(.git), ssh://[email protected]/o/n+_GITHUB_REMOTE = re.compile(+ r"^(?:https?://(?:[^@/]+@)?github\.com/|git@github\.com:|ssh://git@github\.com(?::\d+)?/)"+ r"(?P<owner>[A-Za-z0-9-]+)/(?P<name>[A-Za-z0-9._-]+?)(?:\.git)?/?$"+)+++@dataclass+class PublishResult:+ """What happened, in words a person reads, plus the links to act on.++ ``outcome`` is one of ``published | curated | needs_app | needs_plan |+ cap | too_big | rate_limited | not_github | signed_out | offline |+ error``. A repo already indexed at this commit is ``published`` too: it+ is in the account now, and only the message differs.+ """++ outcome: str+ message: str+ #: The one link to act on next, if any.+ url: str | None = None+ #: Further plain lines, shown after the message.+ details: list[str] = field(default_factory=list)+ #: What the CLI opens in the browser (the indexing page on success).+ open_url: str | None = None+ #: ``owner/name`` once the remote was read.+ repo: str | None = None++ def to_dict(self) -> dict[str, Any]:+ return {+ "outcome": self.outcome,+ "message": self.message,+ "url": self.url,+ "details": list(self.details),+ "open_url": self.open_url,+ "repo": self.repo,+ }+++def parse_github_remote(url: str) -> tuple[str, str] | None:+ """``(owner, name)`` for a GitHub remote URL, ``None`` for anything else."""+ match = _GITHUB_REMOTE.match(url.strip())+ if not match:+ return None+ return match.group("owner"), match.group("name")+++def _git(repo_path: Path, *args: str) -> str | None:+ try:+ out = subprocess.run(+ ["git", "-C", str(repo_path), *args],+ capture_output=True,+ text=True,+ timeout=10,+ check=False,+ )+ except (OSError, subprocess.SubprocessError):+ return None+ return out.stdout.strip() if out.returncode == 0 else None+++def read_remote(repo_path: Path) -> tuple[str, str] | None:+ """The GitHub ``(owner, name)`` of ``origin``, or ``None``."""+ url = _git(repo_path, "remote", "get-url", "origin")+ return parse_github_remote(url) if url else None+++def pushed_branch(repo_path: Path) -> str | None:+ """The branch on ``origin`` the current branch tracks, or ``None``.++ ``None`` (detached HEAD, a branch never pushed, or one tracking another+ remote) means "publish the default branch": a ref GitHub does not have+ would only be refused.+ """+ upstream = _git(repo_path, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}")+ if not upstream or not upstream.startswith("origin/"):+ return None+ return upstream.removeprefix("origin/") or None+++def is_signed_in() -> bool:+ from repowise.cli.platform import auth++ try:+ return auth.get_valid_credentials() is not None+ except Exception:+ return False+++def _detail_text(body: dict[str, Any]) -> str:+ detail = body.get("detail")+ if isinstance(detail, dict):+ return str(detail.get("message") or "")+ return str(detail or "")+++def _detail_code(body: dict[str, Any]) -> str | None:+ detail = body.get("detail")+ return detail.get("code") if isinstance(detail, dict) else None+++def _account() -> dict[str, Any]:+ """``/auth/me`` for the refusals whose advice depends on the plan."""+ from repowise.cli.platform import auth++ try:+ return auth.fetch_account() or {}+ except Exception:+ return {}+++def _trial_days(account: dict[str, Any]) -> int:+ if not account.get("trial_eligible"):+ return 0+ days = account.get("trial_days")+ return days if isinstance(days, int) and days > 0 else 0+++def publish(repo_path: Path, *, ref: str | None = None, src: str = SRC) -> PublishResult:+ """Ask repowise.dev to index this repo's GitHub remote.++ The caller signs the user in first; signed out, this only says so.+ ``src`` tags every link in the result with the surface that published.+ Never raises.+ """+ remote = read_remote(repo_path)+ if remote is None:+ return PublishResult(+ outcome="not_github",+ message="Publish works with GitHub repos. Push this repo to GitHub first.",+ )+ owner, name = remote+ repo = f"{owner}/{name}"+ if not is_signed_in():+ return PublishResult(+ outcome="signed_out",+ message="Sign in to repowise.dev first: repowise login",+ repo=repo,+ )++ branch = ref or pushed_branch(repo_path)+ payload: dict[str, Any] = {"url": f"https://github.com/{repo}"}+ if branch:+ payload["ref"] = branch++ from repowise.cli.platform.client import default_client++ status, body = default_client.post_json("repos/index", payload, timeout=60.0)+ result = _interpret(status, body, owner=owner, name=name, src=src)+ result.repo = repo+ return result+++def _interpret(+ status: int, body: dict[str, Any], *, owner: str, name: str, src: str+) -> PublishResult:+ repo = f"{owner}/{name}"+ repo_page = site_link(f"repo/{owner}/{name}", src)+ code = _detail_code(body)+ text = _detail_text(body)++ if status == 200 and body.get("short_id"):+ mcp = MCP_URL.format(owner=owner, name=name)+ connect = (+ f"Use it from Claude.ai or ChatGPT: add {mcp} as a connector. "+ f"How: {site_link('hosted', src, fragment='mcp')}"+ )+ if body.get("status") == "failed":+ return PublishResult(+ outcome="error",+ message="repowise.dev could not start the index. Try again in a few minutes.",+ )+ if body.get("status") == "ready":+ return PublishResult(+ outcome="published",+ message=f"{repo} is already indexed on repowise.dev at this commit:",+ url=repo_page,+ details=[connect],+ )+ indexing = site_link(f"s/{body['short_id']}/indexing", src)+ return PublishResult(+ outcome="published",+ message="Your repo is being indexed:",+ url=indexing,+ open_url=indexing,+ details=[HOW_LONG, f"When it's ready: {repo_page}", connect],+ )++ if status == 0:+ return PublishResult(+ outcome="offline",+ message="Couldn't reach repowise.dev. Check your connection and try again.",+ )++ if status == 401:+ return PublishResult(+ outcome="signed_out",+ message="Your repowise.dev sign-in has expired. Run repowise login, then publish again.",+ )++ private = code in {+ "repo_not_found_or_private",+ "private_repo_needs_plan",+ "private_repo_needs_app",+ }+ if private:+ account = _account()+ if (account.get("tier") or "free") not in _PAID_TIERS:+ # The repo page runs the whole private-repo path on the site:+ # trial checkout, GitHub App install, then the index starts.+ days = _trial_days(account)+ offer = (+ f"Start a {days}-day free Pro trial (card required, cancel anytime). "+ "This page takes you through it, then GitHub access, then the index:"+ if days+ else "Upgrade to Pro on this page; it then takes you through GitHub access and the index:"+ )+ lead = (+ "GitHub can't see this repo without access, so it is private or the name is wrong."+ if code == "repo_not_found_or_private"+ else "This repo is private."+ )+ return PublishResult(+ outcome="needs_plan",+ message=f"{lead} Private repos need Pro. {offer}",+ url=repo_page,+ )+ lead = (+ "GitHub can't see this repo. If it is private, install"+ if code == "repo_not_found_or_private"+ else "This repo is private. Install"+ )+ return PublishResult(+ outcome="needs_app",+ message=f"{lead} the Repowise GitHub App on it, then publish again:",+ url=GITHUB_APP_INSTALL_URL,+ )++ if code == "repo_curated":+ return PublishResult(+ outcome="curated",+ message=f"{repo} is kept up to date on repowise.dev by the Repowise team:",+ url=repo_page,+ )++ if status == 402:+ # The repo-count limit. Its detail is plain text naming the limit.+ account = _account()+ days = _trial_days(account)+ if (account.get("tier") or "free") == "free":+ if days:+ return PublishResult(+ outcome="cap",+ message=(+ f"Free accounts index 2 repos. Start a {days}-day Pro trial for "+ "5 repos and private ones (card required, cancel anytime):"+ ),+ url=site_link(+ "pricing",+ src,+ params={"checkout": "pro", "interval": "monthly", "trial": "1"},+ ),+ )+ return PublishResult(+ outcome="cap",+ message="Free accounts index 2 repos. Pro indexes 5, private ones too:",+ url=site_link("pricing", src),+ )+ return PublishResult(+ outcome="cap",+ message=text or "Your plan's repo limit is reached.",+ url=site_link("pricing", src),+ )++ if status == 413:+ return PublishResult(+ outcome="too_big",+ message=text or "This repo is too big for your plan.",+ details=["Free indexes repos up to 250 MB; Pro up to 5 GB."],+ url=site_link("pricing", src),+ )++ if status == 429:+ if "in flight" in text:+ return PublishResult(+ outcome="rate_limited",+ message=f"{text} Then publish again.",+ )+ return PublishResult(+ outcome="rate_limited",+ message="You can start 10 hosted indexes a day. Try again tomorrow.",+ )++ return PublishResult(+ outcome="error",+ message=f"repowise.dev refused the publish (HTTP {status}): {text or 'no details'}",+ )diff --git a/tests/unit/cli/test_lazy_commands.py b/tests/unit/cli/test_lazy_commands.pyindex f6a0db6aa..a93152262 100644--- a/tests/unit/cli/test_lazy_commands.py+++ b/tests/unit/cli/test_lazy_commands.py@@ -37,7 +37,7 @@ _EXPECTED_NAMES = frozenset("dead-code", "decision", "delete", "distill", "doc-drift", "doctor","expand","export", "generate", "generate-claude-md", "health", "hook",- "impacted-tests", "init", "login", "logout", "mcp", "next", "overlap", "reindex",+ "impacted-tests", "init", "login", "logout", "mcp", "next", "overlap", "publish", "reindex","restyle","risk", "saved", "savings", "search", "security", "serve", "status", "symbol","telemetry", "uninstall", "update", "watch", "whats-new", "whoami", "why",diff --git a/tests/unit/cli/test_publish.py b/tests/unit/cli/test_publish.pynew file mode 100644index 000000000..050b21047--- /dev/null+++ b/tests/unit/cli/test_publish.py@@ -0,0 +1,468 @@+"""``repowise publish``: one command from a local repo to repowise.dev.++What protects the user here: only GitHub remotes are published, a signed-out+user is signed in with the publish source, every refusal the platform can+give reads as a next step with its link, and every link carries the source+(never the install id; only sign-in carries that).+"""++from __future__ import annotations++import subprocess+import time+from pathlib import Path+from urllib.parse import parse_qs, urlparse++import pytest+from click.testing import CliRunner++from repowise.cli.platform import auth, credentials, links, store+from repowise.cli.platform import publish as pub+from repowise.cli.platform.client import PlatformClient++[email protected](autouse=True)+def isolated_platform(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setattr(credentials, "_path", lambda: tmp_path / "credentials.json")+ monkeypatch.setattr(store, "_path", lambda: tmp_path / "platform.json")+ monkeypatch.delenv("DO_NOT_TRACK", raising=False)+ monkeypatch.delenv("REPOWISE_TELEMETRY_DISABLED", raising=False)+ store.update(anon_id="abc123def456")+ yield+++def _sign_in() -> None:+ credentials.save(+ {+ "token_kind": "oauth",+ "client_id": "repowise-cli",+ "access_token": "at-1",+ "access_expires_at": int(time.time()) + 3600,+ "refresh_token": "rt-1",+ }+ )+++def _git(repo: Path, *args: str) -> None:+ subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True)+++def repo(tmp_path: Path) -> Path:+ path = tmp_path / "widget"+ path.mkdir()+ _git(path, "init", "-q", "-b", "main")+ _git(+ path,+ "-c",+ "[email protected]",+ "-c",+ "user.name=t",+ "commit",+ "-q",+ "--allow-empty",+ "-m",+ "x",+ )+ _git(path, "remote", "add", "origin", "[email protected]:acme/widget.git")+ return path+++def _answer(monkeypatch, status: int, body: dict, *, account: dict | None = None) -> list:+ sent: list = []++ def fake_post_json(self, path, payload, *, timeout=None):+ sent.append((path, payload))+ return status, body++ monkeypatch.setattr(PlatformClient, "post_json", fake_post_json)+ monkeypatch.setattr(auth, "fetch_account", lambda: account)+ return sent+++def _query(url: str) -> dict[str, list[str]]:+ return parse_qs(urlparse(url).query)+++class TestRemote:+ @pytest.mark.parametrize(+ "url",+ [+ "https://github.com/acme/widget",+ "https://github.com/acme/widget.git",+ "https://[email protected]/acme/widget.git",+ "[email protected]:acme/widget.git",+ "ssh://[email protected]/acme/widget.git",+ "https://github.com/acme/widget/",+ ],+ )+ def test_reads_github_remotes(self, url):+ assert pub.parse_github_remote(url) == ("acme", "widget")++ @pytest.mark.parametrize(+ "url",+ [+ "https://gitlab.com/acme/widget.git",+ "[email protected]:acme/widget.git",+ "/srv/widget.git",+ "",+ ],+ )+ def test_refuses_everything_else(self, url):+ assert pub.parse_github_remote(url) is None++ def test_no_remote_says_push_to_github_first(self, repo, monkeypatch):+ _git(repo, "remote", "remove", "origin")+ sent = _answer(monkeypatch, 200, {})+ result = pub.publish(repo)+ assert result.outcome == "not_github"+ assert "Push this repo to GitHub first" in result.message+ assert sent == []++ def test_non_github_remote_is_not_published(self, repo, monkeypatch):+ _git(repo, "remote", "set-url", "origin", "https://gitlab.com/acme/widget.git")+ _sign_in()+ sent = _answer(monkeypatch, 200, {})+ assert pub.publish(repo).outcome == "not_github"+ assert sent == []+++class TestPublish:+ def test_signed_out_does_not_call_the_platform(self, repo, monkeypatch):+ sent = _answer(monkeypatch, 200, {})+ result = pub.publish(repo)+ assert result.outcome == "signed_out"+ assert sent == []++ def test_unpushed_branch_publishes_the_default_branch(self, repo, monkeypatch):+ _sign_in()+ sent = _answer(monkeypatch, 200, {"short_id": "s1", "status": "queued"})+ pub.publish(repo)+ assert sent == [("repos/index", {"url": "https://github.com/acme/widget"})]++ def test_pushed_branch_is_the_ref(self, repo, monkeypatch):+ _git(repo, "update-ref", "refs/remotes/origin/feature", "HEAD")+ _git(repo, "config", "branch.main.remote", "origin")+ _git(repo, "config", "branch.main.merge", "refs/heads/feature")+ _sign_in()+ sent = _answer(monkeypatch, 200, {"short_id": "s1", "status": "queued"})+ pub.publish(repo)+ assert sent[0][1]["ref"] == "feature"++ def test_ref_option_wins(self, repo, monkeypatch):+ _sign_in()+ sent = _answer(monkeypatch, 200, {"short_id": "s1", "status": "queued"})+ pub.publish(repo, ref="release")+ assert sent[0][1]["ref"] == "release"++ def test_success_links_the_indexing_page_repo_page_and_mcp(self, repo, monkeypatch):+ _sign_in()+ _answer(monkeypatch, 200, {"short_id": "s1", "status": "queued"})+ result = pub.publish(repo)+ assert result.outcome == "published"+ assert result.url == result.open_url+ assert result.url.startswith("https://repowise.dev/s/s1/indexing?")+ assert _query(result.url) == {"src": ["cli_publish"]}+ text = "\n".join(result.details)+ assert "https://repowise.dev/repo/acme/widget?src=cli_publish" in text+ assert "https://api.repowise.dev/mcp/acme/widget" in text+ assert "10 minutes" in text++ def test_links_carry_no_install_id_with_telemetry_off(self, repo, monkeypatch):+ monkeypatch.setenv("DO_NOT_TRACK", "1")+ _sign_in()+ _answer(monkeypatch, 200, {"short_id": "s1", "status": "queued"})+ result = pub.publish(repo)+ assert _query(result.url) == {"src": ["cli_publish"]}++ def test_already_indexed_links_the_repo_page(self, repo, monkeypatch):+ _sign_in()+ _answer(monkeypatch, 200, {"short_id": "s1", "status": "ready", "cached": True})+ result = pub.publish(repo)+ assert result.outcome == "published"+ assert "already indexed" in result.message+ assert result.url.startswith("https://repowise.dev/repo/acme/widget?")+ assert result.open_url is None++ def test_dispatch_failure_is_an_error(self, repo, monkeypatch):+ _sign_in()+ _answer(monkeypatch, 200, {"short_id": "s1", "status": "failed"})+ assert pub.publish(repo).outcome == "error"+++def _refusal(code: str, message: str = "nope") -> dict:+ return {"detail": {"code": code, "message": message}}+++class TestRefusals:+ @pytest.mark.parametrize(+ ("status", "code"),+ [+ (400, "repo_not_found_or_private"),+ (403, "private_repo_needs_plan"),+ (403, "private_repo_needs_app"),+ ],+ )+ def test_free_private_repo_goes_to_the_trial_flow_on_its_page(+ self, repo, monkeypatch, status, code+ ):+ _sign_in()+ _answer(+ monkeypatch,+ status,+ _refusal(code),+ account={"tier": "free", "trial_eligible": True, "trial_days": 10},+ )+ result = pub.publish(repo)+ assert result.outcome == "needs_plan"+ assert "10-day free Pro trial (card required" in result.message+ assert result.url.startswith("https://repowise.dev/repo/acme/widget?")+ assert _query(result.url) == {"src": ["cli_publish"]}++ def test_private_repo_without_a_trial_offers_the_upgrade(self, repo, monkeypatch):+ _sign_in()+ _answer(+ monkeypatch,+ 403,+ _refusal("private_repo_needs_plan"),+ account={"tier": "free", "trial_eligible": False, "trial_days": 10},+ )+ result = pub.publish(repo)+ assert result.outcome == "needs_plan"+ assert "trial" not in result.message+ assert "Upgrade to Pro" in result.message++ @pytest.mark.parametrize("code", ["repo_not_found_or_private", "private_repo_needs_app"])+ def test_paid_private_repo_needs_the_github_app(self, repo, monkeypatch, code):+ _sign_in()+ _answer(monkeypatch, 403, _refusal(code), account={"tier": "pro"})+ result = pub.publish(repo)+ assert result.outcome == "needs_app"+ assert result.url == pub.GITHUB_APP_INSTALL_URL++ def test_free_cap_offers_the_trial_checkout(self, repo, monkeypatch):+ _sign_in()+ _answer(+ monkeypatch,+ 402,+ {"detail": "You've reached your plan's limit of 2 indexed repositories."},+ account={"tier": "free", "trial_eligible": True, "trial_days": 10},+ )+ result = pub.publish(repo)+ assert result.outcome == "cap"+ assert result.message.startswith(+ "Free accounts index 2 repos. Start a 10-day Pro trial for 5 repos and private ones"+ )+ assert "card required" in result.message+ assert urlparse(result.url).path == "/pricing"+ assert _query(result.url) == {+ "checkout": ["pro"],+ "interval": ["monthly"],+ "trial": ["1"],+ "src": ["cli_publish"],+ }++ def test_free_cap_without_a_trial_links_pricing(self, repo, monkeypatch):+ _sign_in()+ _answer(+ monkeypatch, 402, {"detail": "limit"}, account={"tier": "free", "trial_eligible": False}+ )+ result = pub.publish(repo)+ assert result.outcome == "cap"+ assert "trial" not in result.message+ assert "trial" not in _query(result.url)++ def test_pro_cap_shows_the_platform_message(self, repo, monkeypatch):+ _sign_in()+ _answer(+ monkeypatch, 402, {"detail": "Upgrade to Teams for 25 repos."}, account={"tier": "pro"}+ )+ result = pub.publish(repo)+ assert result.outcome == "cap"+ assert result.message == "Upgrade to Teams for 25 repos."++ def test_too_big_names_both_limits(self, repo, monkeypatch):+ _sign_in()+ _answer(monkeypatch, 413, {"detail": "Repo is 900 MB; Free indexes up to 250 MB."})+ result = pub.publish(repo)+ assert result.outcome == "too_big"+ assert "900 MB" in result.message+ assert "5 GB" in result.details[0]++ def test_daily_limit_says_when(self, repo, monkeypatch):+ _sign_in()+ _answer(monkeypatch, 429, {"detail": "Rate limit exceeded: 10 per 1 day"})+ result = pub.publish(repo)+ assert result.outcome == "rate_limited"+ assert "tomorrow" in result.message++ def test_jobs_in_flight_says_wait(self, repo, monkeypatch):+ _sign_in()+ _answer(monkeypatch, 429, {"detail": "You have 1 index/reindex job(s) in flight already."})+ result = pub.publish(repo)+ assert result.outcome == "rate_limited"+ assert "in flight" in result.message++ def test_offline(self, repo, monkeypatch):+ _sign_in()+ _answer(monkeypatch, 0, {})+ assert pub.publish(repo).outcome == "offline"++ def test_expired_sign_in(self, repo, monkeypatch):+ _sign_in()+ _answer(monkeypatch, 401, {"detail": "Invalid token"})+ result = pub.publish(repo)+ assert result.outcome == "signed_out"+ assert "repowise login" in result.message++ def test_curated_repo_is_already_there(self, repo, monkeypatch):+ _sign_in()+ _answer(monkeypatch, 403, _refusal("repo_curated"))+ assert pub.publish(repo).outcome == "curated"++ def test_anything_else_shows_the_platform_message(self, repo, monkeypatch):+ _sign_in()+ _answer(monkeypatch, 400, {"detail": "Branch 'x' not found"})+ result = pub.publish(repo)+ assert result.outcome == "error"+ assert "Branch 'x' not found" in result.message+++class TestPostJson:+ def test_returns_status_and_body_on_a_refusal(self, monkeypatch):+ import httpx++ def fake_post(url, **kwargs):+ return httpx.Response(402, json={"detail": "limit"}, request=httpx.Request("POST", url))++ monkeypatch.setattr(httpx, "post", fake_post)+ assert PlatformClient().post_json("repos/index", {}) == (402, {"detail": "limit"})++ def test_no_answer_is_zero(self, monkeypatch):+ import httpx++ def boom(url, **kwargs):+ raise httpx.ConnectError("offline")++ monkeypatch.setattr(httpx, "post", boom)+ assert PlatformClient().post_json("repos/index", {}) == (0, {})+++class TestLinks:+ def test_site_link_with_params_and_fragment(self):+ url = links.site_link("hosted", "cli_x", fragment="mcp", params={"a": "1"})+ assert url == "https://repowise.dev/hosted?a=1&src=cli_x#mcp"++ def test_authorize_url_takes_the_source(self):+ url = auth.build_authorize_url(+ redirect_uri="http://127.0.0.1:1/callback",+ code_challenge="c",+ state="s",+ device_name=None,+ src="cli_publish",+ )+ assert _query(url)["src"] == ["cli_publish"]+ # Sign-in is the one URL that ties this install to the new account.+ assert _query(url)["aid"] == ["abc123def456"]+++class TestCommand:+ def _run(self, repo: Path, *args: str):+ from repowise.cli.main import cli++ return CliRunner().invoke(cli, ["publish", str(repo), *args])++ def test_signed_out_signs_in_with_the_publish_source_then_publishes(self, repo, monkeypatch):+ from repowise.cli.commands import login_cmd++ seen = {}++ def fake_sign_in(device, *, src):+ seen["src"] = src+ _sign_in()+ return {}++ monkeypatch.setattr(login_cmd, "browser_sign_in", fake_sign_in)+ opened: list[str] = []+ monkeypatch.setattr("webbrowser.open", opened.append)+ sent = _answer(monkeypatch, 200, {"short_id": "s1", "status": "queued"})++ result = self._run(repo)++ assert result.exit_code == 0, result.output+ assert seen == {"src": "cli_publish"}+ assert len(sent) == 1+ assert opened and opened[0].startswith("https://repowise.dev/s/s1/indexing?")+ assert "Your repo is being indexed" in result.output+ assert "Only what's pushed to GitHub is published" in result.output++ def test_no_open_keeps_the_browser_closed(self, repo, monkeypatch):+ _sign_in()+ opened: list[str] = []+ monkeypatch.setattr("webbrowser.open", opened.append)+ _answer(monkeypatch, 200, {"short_id": "s1", "status": "queued"})+ result = self._run(repo, "--no-open")+ assert result.exit_code == 0, result.output+ assert opened == []++ def test_refusal_exits_non_zero_and_records_the_outcome(self, repo, monkeypatch):+ from repowise.cli.platform import telemetry++ _sign_in()+ recorded: dict = {}+ monkeypatch.setattr(telemetry, "add_command_outcome", lambda **f: recorded.update(f))+ _answer(+ monkeypatch,+ 402,+ {"detail": "limit"},+ account={"tier": "free", "trial_eligible": True, "trial_days": 10},+ )+ result = self._run(repo)+ assert result.exit_code == 1+ assert recorded["outcome"] == "cap"+ assert "Start a 10-day Pro trial" in result.output++ def test_no_remote_never_signs_in(self, repo, monkeypatch):+ from repowise.cli.commands import login_cmd++ _git(repo, "remote", "remove", "origin")+ monkeypatch.setattr(login_cmd, "browser_sign_in", lambda *a, **k: pytest.fail("signed in"))+ result = self._run(repo)+ assert result.exit_code == 1+ assert "Push this repo to GitHub first" in result.output+++class TestJsonMode:+ def _run(self, repo: Path, *args: str):+ from repowise.cli.main import cli++ return CliRunner().invoke(cli, ["publish", str(repo), "--format", "json", *args])++ def test_signed_out_never_starts_a_browser_sign_in(self, repo, monkeypatch):+ import json++ from repowise.cli.commands import login_cmd++ monkeypatch.setattr(login_cmd, "browser_sign_in", lambda *a, **k: pytest.fail("signed in"))+ result = self._run(repo)+ assert result.exit_code == 1+ assert json.loads(result.stdout)["outcome"] == "signed_out"++ def test_prints_the_result_and_opens_nothing(self, repo, monkeypatch):+ import json++ _sign_in()+ opened: list[str] = []+ monkeypatch.setattr("webbrowser.open", opened.append)+ _answer(monkeypatch, 200, {"short_id": "s1", "status": "queued"})+ result = self._run(repo, "--src", "local_web_publish")+ assert result.exit_code == 0, result.output+ payload = json.loads(result.stdout)+ assert payload["outcome"] == "published"+ assert payload["repo"] == "acme/widget"+ assert _query(payload["url"])["src"] == ["local_web_publish"]+ assert opened == []++ def test_src_is_checked(self, repo):+ result = self._run(repo, "--src", "Bad Src!")+ assert result.exit_code == 2