@recoder.xyz/rithub 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -26,13 +26,37 @@ rit logout
26
26
  ```
27
27
 
28
28
  Rithub has no OAuth2 device-code flow to log in with (confirmed live:
29
- `https://rithub.dev/login/device/code` is a plain 404), so `rit login`
30
- is the fallback the task spec calls for: open
31
- `https://rithub.dev/user/settings/applications`, generate a personal
32
- access token, paste it (hidden input, never echoed) or pass
33
- `--token`/`RITHUB_TOKEN`. The token is validated against the real
34
- account (`GET /api/v1/user`) before anything is saved to
35
- `~/.config/rithub/config.json` (written `0600`).
29
+ `https://rithub.dev/login/device/code` is a plain 404 -- a real device
30
+ flow needs a server-side route that doesn't exist yet; see "Server change
31
+ this would need" below). `rit login` with no `--token` falls back to
32
+ opening `https://rithub.dev/user/settings/applications` in the real
33
+ browser (best-effort -- still prints the URL either way) and reading a
34
+ pasted personal access token back, hidden input, never echoed. The token
35
+ is validated against the real account (`GET /api/v1/user`) before
36
+ anything is saved to `~/.config/rithub/config.json` (written `0600`).
37
+
38
+ That prompt only happens at a real TTY. Run `rit login` with no
39
+ `--token`/`RITHUB_TOKEN` from a non-interactive session -- an agent, CI,
40
+ anything with stdin open but nobody there to answer it -- and it fails
41
+ immediately with a clear message instead of hanging forever (confirmed
42
+ live, 2026-11-30/12-01, that the previous version could hang
43
+ indefinitely on exactly that stdin shape):
44
+
45
+ ```
46
+ rit login: not an interactive terminal -- pass a token instead of pasting
47
+ one: `rit login --token <token>` or `RITHUB_TOKEN=<token> rit login`.
48
+ Get one at https://rithub.dev/user/settings/applications.
49
+ ```
50
+
51
+ `rit clone <owner/repo>` while signed out, on a repo that's either
52
+ private or doesn't exist, says so plainly instead of a bare "not found"
53
+ and exits non-zero:
54
+
55
+ ```
56
+ rit clone: not signed in, and caelum0x/afterbeat was not found while
57
+ signed out -- if it's private, run `rit login` first (or set
58
+ RITHUB_TOKEN), then retry
59
+ ```
36
60
 
37
61
  **Scopes:** cloning and pushing to a repo that already exists needs
38
62
  `read:user` + `write:repository`. Creating one — `rit repo create` and
@@ -96,6 +120,8 @@ REST API at `/api/v1` with a plain `fetch` — no SDK there either.
96
120
 
97
121
  ## Commands
98
122
 
123
+ The original surface (unchanged):
124
+
99
125
  ```
100
126
  rit init [--repo <name>] [--api-url <url>] [--json]
101
127
  rit claim --email <you@example.com> [--json]
@@ -103,13 +129,103 @@ rit login [--token <token>] [--api-url <url>] [--json]
103
129
  rit logout [--json]
104
130
  rit whoami [--json]
105
131
  rit clone <owner/repo|repo> [dir] [--json]
106
- rit repo create <name> [--private] [--description <text>] [--json]
107
132
  rit push [--private] [--name <name>] [--json]
108
133
  rit help, --help, -h
109
134
  rit --version, -v
110
135
  ```
111
136
 
137
+ The full `gh`-parity surface added on top of it, every command taking
138
+ `--repo <owner/name>` to override inferring the repo from the current
139
+ directory's git remote, and `--json` for machine-readable output:
140
+
141
+ | Command | Subcommands |
142
+ | --- | --- |
143
+ | `rit repo` | `create <name> [--private] [--description <t>]`, `list [owner]`, `view <owner/repo\|repo>`, `fork <owner/repo>`, `delete <owner/repo> --confirm`, `rename <owner/repo> <new-name>`, `edit <owner/repo> [--description <t>] [--private\|--public]`, `archive <owner/repo> [--unarchive]`, `sync <git-url> [--name <n>] [--private]`, `sync-now <owner/repo>`, `import <git-url> [--name <n>] [--private]` |
144
+ | `rit issue` | `list [--state open\|closed\|all] [--search <q>]`, `create --title <t> [--body <t>]`, `view <n>`, `close <n>`, `reopen <n>`, `edit <n> [--title <t>] [--body <t>]`, `comment <n> --body <t>` |
145
+ | `rit change` (alias `rit pr`) | `list [--state ...]`, `create --title <t> [--head <b>] [--base <b>] [--body <t>]`, `view <n>`, `checkout <n>`, `diff <n>`, `merge <n> [--squash\|--rebase] [--delete-branch]`, `close <n>`, `comment <n> --body <t>`, `review approve <n> [--body <t>]` |
146
+ | `rit release` | `list`, `create <tag> [--title <t>] [--notes <t>] [--draft] [--prerelease] [--asset <path>]...`, `view <tag>`, `delete <tag>` |
147
+ | `rit branch` | `list`, `delete <name>`, `protect <name> [--required-approvals <n>]` |
148
+ | `rit label` | `list`, `create <name> --color <hex> [--description <t>]` |
149
+ | `rit milestone` | `list`, `create <title> [--description <t>] [--due <date>]` |
150
+ | `rit key` | `list`, `add <title> <key-or-path> [--read-only]` (account SSH keys) |
151
+ | `rit secret` | `list`, `set <NAME> <value>` (repo Actions secrets -- values are write-only) |
152
+ | `rit webhook` | `list`, `create --url <url> [--events a,b] [--secret <t>]` |
153
+ | `rit org` | `list`, `view <org>` |
154
+ | `rit user` | `view <username>` |
155
+ | `rit search` | `repos <query>`, `issues <query> [--type issues\|pulls] [--owner <o>]`, `code` (no server endpoint -- fails loudly, see below) |
156
+ | `rit status` | your assigned issues, open changes, and changes awaiting your review -- the one command not scoped to a single repo |
157
+ | `rit browse` | `[issue\|change <n>] [--print-url]` -- opens the repo/issue/change in the real browser, or just prints the URL |
158
+ | `rit api` | `<path> [--method <m>] [--field k=v]... [--input -\|@file]` -- raw authenticated request against `/api/v1`, like `gh api` |
159
+
112
160
  `RITHUB_API_URL` overrides the default `https://rithub.dev` (useful for
113
161
  local development against this repo's own test fixtures). `RITHUB_TOKEN`
114
162
  overrides the saved login for one command. Zero runtime dependencies,
115
163
  plain `node:fetch`/`node:child_process`/`node:fs`, Node >= 18.
164
+
165
+ ### Scopes, found live (2026-12-01)
166
+
167
+ A token's scopes gate whole command groups, and the gate is stricter
168
+ than the names suggest -- confirmed against this server's own 403s while
169
+ building this, not assumed from the API docs:
170
+
171
+ - `read:repository` / `write:repository`: `repo`, `branch`, `secret`,
172
+ `webhook`, `release`, and (surprisingly) `change`/`pr` itself --
173
+ opening, viewing, diffing, checking out, and merging a change all
174
+ worked with a token that had **no** issue scope at all.
175
+ - `read:issue` / `write:issue`: `issue`, `label`, `milestone`, `status`,
176
+ and commenting on a `change` (Rithub's own PR comments reuse the issue
177
+ comment endpoint, so they need the issue scope even though opening the
178
+ PR itself didn't).
179
+ - `read:user` + `read:organization`: `org list`/`org view`.
180
+
181
+ The token this package was built and verified with
182
+ (`write:repository,write:user` only, confirmed via `rit whoami`'s own
183
+ account settings page) covers every `repo`/`branch`/`secret`/`webhook`/
184
+ `release`/`change` command end to end, but 403s on `issue`/`label`/
185
+ `milestone`/`status`/`change comment`/`org`. Generating a new token with
186
+ the broader scope list needs the real rithub.dev web session (password,
187
+ no API route creates a scoped token from an existing token) -- that part
188
+ is a standing owner-only step, not a CLI bug.
189
+
190
+ ### `rit search code`
191
+
192
+ There is no code-search REST endpoint on this server (checked its own
193
+ `swagger.v1.json`, 2026-12-01 -- only repo/issue/user/org/team search
194
+ exist). `rit search code` says so and exits non-zero rather than
195
+ pretending to search and silently returning nothing.
196
+
197
+ ## Server change this would need
198
+
199
+ A real browser/device sign-in (poll until approved, no pasted token) --
200
+ what `rit login` falls back from -- needs a device-authorization-grant
201
+ route added server-side (e.g. the standard `POST /login/oauth/device` +
202
+ `POST /login/oauth/token` pair with `device_code`/`user_code` polling).
203
+ That route doesn't exist on rithub.dev today; `rit login`'s browser +
204
+ paste flow is the closest equivalent until it does. Out of scope for
205
+ this package (server/API code is a different agent's lane).
206
+
207
+ ## Design notes
208
+
209
+ `src/http.mjs` is the shared request helper for every command added in
210
+ this round (`issue`/`change`/`release`/`branch`/`label`/`milestone`/
211
+ `key`/`secret`/`webhook`/`org`/`user`/`search`/`status`/`browse`/`api`).
212
+ The original `login`/`clone`/`repo create`/`push` surface
213
+ (`src/auth.mjs`/`src/repo.mjs`/`src/init.mjs`) keeps its own small,
214
+ already-tested copy of the same JSON-call pattern rather than being
215
+ refactored to import it -- minimizing the diff to code that already had
216
+ passing tests and a careful token-handling writeup, rather than risking
217
+ a regression there for the sake of removing a few duplicated lines.
218
+
219
+ ## Agent examples
220
+
221
+ ```
222
+ # open a change from the current branch, wait for review, merge once approved
223
+ rit change create --title "fix: retry on 429" --base main --json
224
+ rit change merge 42 --squash --delete-branch --json
225
+
226
+ # triage: what needs this agent's attention right now, machine-readable
227
+ rit status --json
228
+
229
+ # anything this CLI doesn't have a dedicated command for yet
230
+ rit api /repos/caelum0x/scribase/commits --json
231
+ ```
package/bin/rithub.mjs CHANGED
@@ -6,6 +6,7 @@ import { fileURLToPath } from "node:url";
6
6
  import { homedir } from "node:os";
7
7
 
8
8
  import { main } from "../src/cli.mjs";
9
+ import { openUrl } from "../src/open-browser.mjs";
9
10
 
10
11
  const pkg = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), "..", "package.json"), "utf8"));
11
12
 
@@ -63,6 +64,8 @@ const code = await main(process.argv.slice(2), {
63
64
  now: () => Date.now(),
64
65
  fetchImpl: fetch,
65
66
  promptHidden,
67
+ isTTY: process.stdin.isTTY === true,
68
+ openUrl,
66
69
  exists: (path) => existsSync(path),
67
70
  readFile: (path) => (existsSync(path) ? readFileSync(path, "utf8") : null),
68
71
  writeFile: (path, contents, opts) => {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@recoder.xyz/rithub",
3
- "version": "0.2.1",
4
- "description": "A gh-style CLI for Rithub: `rit login`, `rit clone`, `rit repo create`, `rit push`, plus `rit init`'s no-human agent signup. One command, zero deps.",
3
+ "version": "0.3.1",
4
+ "description": "A gh-style CLI for Rithub: full gh parity -- issue/change(pr)/release/branch/label/milestone/key/secret/webhook/org/user/search/status/browse/api, plus login/clone/repo/push and `rit init`'s no-human agent signup. One command, zero deps.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
7
7
  "engines": { "node": ">=18" },
package/src/api.mjs ADDED
@@ -0,0 +1,30 @@
1
+ // `rit api <path>` -- a raw authenticated request against Rithub's own
2
+ // `/api/v1`, for anything this CLI doesn't have a dedicated command for
3
+ // yet. Same spirit as `gh api`: the path is relative to `/api/v1` unless it
4
+ // already starts with `/api/`, the saved/env token rides along
5
+ // automatically, and the response prints exactly as the server sent it
6
+ // (pretty-printed if it parses as JSON, raw otherwise) rather than being
7
+ // reshaped into this CLI's own JSON envelope.
8
+ import { CliError } from "./init.mjs";
9
+ import { resolveSession } from "./config.mjs";
10
+ import { apiCallRaw } from "./http.mjs";
11
+
12
+ export async function runApi(options, io) {
13
+ const session = resolveSession(io, { apiUrl: options.apiUrl });
14
+ const apiUrl = session?.apiUrl ?? (options.apiUrl ?? io.env.RITHUB_API_URL ?? "https://rithub.dev").replace(/\/+$/, "");
15
+ if (!options.path) throw new CliError("`rit api` needs a path: `rit api <path>` (e.g. `rit api /user`)", { code: "invalid_argument" });
16
+ const path = options.path.startsWith("/api/") ? options.path : `/api/v1${options.path.startsWith("/") ? "" : "/"}${options.path}`;
17
+
18
+ let body;
19
+ if (options.fields.length > 0) {
20
+ body = JSON.stringify(Object.fromEntries(options.fields.map((f) => f.split(/=(.*)/s).slice(0, 2))));
21
+ } else if (options.input) {
22
+ body = options.input === "-" ? io.readFile("/dev/stdin") ?? "" : io.readFile(options.input);
23
+ if (body === null) throw new CliError(`could not read --input ${options.input}`, { code: "invalid_argument" });
24
+ }
25
+ const method = options.method ?? (body ? "POST" : "GET");
26
+
27
+ const { status, text } = await apiCallRaw(io, apiUrl, path, { method, body, headers: body ? { "content-type": "application/json" } : {}, accept: "application/json" }, session?.token);
28
+ if (status >= 400) throw new CliError(`${method} ${path} -> HTTP ${status}: ${text.slice(0, 500)}`, { code: "http_error" });
29
+ return { status, text };
30
+ }
package/src/auth.mjs CHANGED
@@ -1,11 +1,13 @@
1
- // `rit login` / `rit logout` / `rit whoami`. Rithub (Gitea underneath) has
2
- // no OAuth2 device-code flow -- confirmed live, 2026-11-30:
3
- // `https://rithub.dev/login/device/code` answers a plain 404 -- so this is
4
- // the token-paste flow the task spec calls for as the fallback: open the
5
- // applications settings page, paste a personal access token, we validate it
6
- // against the real account before saving anything.
1
+ // `rit login` / `rit logout` / `rit whoami`. 2026-12-01: Rithub now has a
2
+ // real device-authorization sign-in (apps/rithub-device-auth, see that
3
+ // app's README) -- a TTY with no `--token`/`RITHUB_TOKEN` runs the device
4
+ // flow (deviceLogin.mjs) instead of the old "paste a token" fallback.
5
+ // `--token`/`RITHUB_TOKEN` keep working unchanged (still the only path for
6
+ // a non-interactive caller -- an agent/CI session).
7
7
  import { CliError, DEFAULT_API_URL } from "./init.mjs";
8
8
  import { loadConfig, saveConfig, clearConfig, resolveSession } from "./config.mjs";
9
+ import { openUrl } from "./open-browser.mjs";
10
+ import { runDeviceLogin } from "./deviceLogin.mjs";
9
11
 
10
12
  async function fetchUser(io, apiUrl, token) {
11
13
  const res = await io.fetchImpl(`${apiUrl}/api/v1/user`, {
@@ -24,18 +26,42 @@ async function fetchUser(io, apiUrl, token) {
24
26
  /** `rit login [--token <token>] [--api-url <url>]`: validates a token against
25
27
  * the real account (GET /api/v1/user) before saving it, so a typo or a
26
28
  * token missing `read:user` scope fails loudly here instead of surfacing
27
- * later as a confusing 401/403 from `rit clone`. */
29
+ * later as a confusing 401/403 from `rit clone`.
30
+ *
31
+ * No `--token`/`RITHUB_TOKEN` given: Rithub has no OAuth2 device-code flow
32
+ * to poll (confirmed live, 2026-11-30: `/login/device/code` is a plain
33
+ * 404 -- a real device flow would need a server-side route that doesn't
34
+ * exist yet, see this package's README "Server change this would need"),
35
+ * so the closest thing to a browser sign-in is opening the token-settings
36
+ * page for the human and reading the token back. A TTY opens the browser
37
+ * and waits for the paste; a non-TTY caller (an agent, CI, anything piping
38
+ * this in a harness) gets a clear, immediate, non-zero-exit error instead
39
+ * of hanging on a prompt nobody is there to answer -- confirmed live,
40
+ * 2026-11-30, that the old code could hang indefinitely on stdin that is
41
+ * open but never sends data or EOF. */
28
42
  export async function runLogin(options, io) {
29
43
  const apiUrl = (options.apiUrl ?? io.env.RITHUB_API_URL ?? DEFAULT_API_URL).replace(/\/+$/, "");
30
44
  let token = options.token ?? io.env.RITHUB_TOKEN;
31
45
  if (!token) {
32
- // write:user is not a typo for write:repository: Gitea's own
33
- // POST /api/v1/user/repos (used by `rit repo create` and `rit push`'s
34
- // auto-create) is gated on write:user, not write:repository -- confirmed
35
- // live, 2026-11-30, from the server's own 403 scope error. A token
36
- // missing it still works for `rit clone`/`rit push` to an existing repo.
37
- io.out(`Open ${apiUrl}/user/settings/applications, generate a token (needs "read:user" and "write:repository" to clone/push; add "write:user" too if you want \`rit repo create\`/\`rit push\` to create repos), then paste it below.`);
38
- token = (await io.promptHidden("Token: ")).trim();
46
+ const settingsUrl = `${apiUrl}/user/settings/applications`;
47
+ if (!io.isTTY) {
48
+ throw new CliError(
49
+ `not an interactive terminal -- pass a token instead of signing in: \`rit login --token <token>\` or \`RITHUB_TOKEN=<token> rit login\`. Get one at ${settingsUrl}.`,
50
+ { code: "no_tty" }
51
+ );
52
+ }
53
+ if (options.pasteToken) {
54
+ // Explicit escape hatch (`rit login --paste-token`) back to the old
55
+ // paste-a-PAT flow, kept for a box with no outbound access to the
56
+ // device-flow endpoints or a locked-down headless display.
57
+ const howTo = `Open ${settingsUrl}, generate a token (needs "read:user" and "write:repository" to clone/push; add "write:user" too if you want \`rit repo create\`/\`rit push\` to create repos), then paste it below.`;
58
+ io.out(howTo);
59
+ io.openUrl?.(settingsUrl);
60
+ token = (await io.promptHidden("Token: ")).trim();
61
+ } else {
62
+ const device = await runDeviceLogin(io, apiUrl);
63
+ token = device.token;
64
+ }
39
65
  }
40
66
  token = token.trim();
41
67
  if (!token) throw new CliError("no token given", { code: "invalid_argument" });
package/src/branch.mjs ADDED
@@ -0,0 +1,42 @@
1
+ // `rit branch list/delete/protect`, against
2
+ // `/api/v1/repos/{owner}/{repo}/branches` and `.../branch_protections`.
3
+ import { CliError } from "./init.mjs";
4
+ import { resolveRepoArg, requireSession } from "./repo-arg.mjs";
5
+ import { apiCall, buildQuery } from "./http.mjs";
6
+
7
+ function repoPath(r, suffix) {
8
+ return `/api/v1/repos/${encodeURIComponent(r.owner)}/${encodeURIComponent(r.repo)}${suffix}`;
9
+ }
10
+
11
+ export async function runBranchList(options, io) {
12
+ const r = resolveRepoArg(io, options);
13
+ const { status, body } = await apiCall(io, r.apiUrl, repoPath(r, "/branches") + buildQuery({ page: options.page, limit: options.limit ?? 50 }), { method: "GET" }, r.session?.token);
14
+ if (status !== 200) throw new CliError(`could not list branches on ${r.owner}/${r.repo} (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "network_error" });
15
+ return { owner: r.owner, repo: r.repo, branches: (body ?? []).map((b) => ({ name: b.name, protected: !!b.protected })) };
16
+ }
17
+
18
+ export async function runBranchDelete(options, io) {
19
+ const r = resolveRepoArg(io, options);
20
+ requireSession(r);
21
+ const { status, body } = await apiCall(io, r.apiUrl, repoPath(r, `/branches/${encodeURIComponent(options.name)}`), { method: "DELETE" }, r.session.token);
22
+ if (status !== 204 && status !== 200) throw new CliError(`could not delete branch ${options.name} (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "delete_failed" });
23
+ return { owner: r.owner, repo: r.repo, branch: options.name, deleted: true };
24
+ }
25
+
26
+ /** `rit branch protect <name|pattern> [--required-approvals <n>] [--no-force-push] [--no-delete-protected]`:
27
+ * creates one branch protection rule (`POST .../branch_protections`).
28
+ * Rithub matches `rule_name` against branch names as a glob, so `main` and
29
+ * `release/*` both work as given. */
30
+ export async function runBranchProtect(options, io) {
31
+ const r = resolveRepoArg(io, options);
32
+ requireSession(r);
33
+ const payload = {
34
+ rule_name: options.name,
35
+ required_approvals: Number(options.requiredApprovals ?? 0),
36
+ enable_push: !!options.allowPush,
37
+ enable_force_push: !!options.allowForcePush,
38
+ };
39
+ const { status, body } = await apiCall(io, r.apiUrl, repoPath(r, "/branch_protections"), { method: "POST", body: JSON.stringify(payload) }, r.session.token);
40
+ if (status !== 201) throw new CliError(`could not protect ${options.name} (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "create_failed" });
41
+ return { owner: r.owner, repo: r.repo, rule: body.rule_name, required_approvals: body.required_approvals };
42
+ }
package/src/browse.mjs ADDED
@@ -0,0 +1,21 @@
1
+ // `rit browse [issue|change <number>] [--print-url]`: opens the repo, an
2
+ // issue, or a change in the default browser. `--print-url` (or no display
3
+ // at all, e.g. over SSH/in an agent sandbox) just prints the URL instead of
4
+ // trying to launch anything.
5
+ import { CliError } from "./init.mjs";
6
+ import { resolveRepoArg } from "./repo-arg.mjs";
7
+
8
+ export async function runBrowse(options, io) {
9
+ const r = resolveRepoArg(io, options);
10
+ const base = `${r.apiUrl}/${r.owner}/${r.repo}`;
11
+ let url = base;
12
+ if (options.kind === "issue") {
13
+ if (!options.number) throw new CliError("`rit browse issue` needs a number: `rit browse issue <number>`", { code: "invalid_argument" });
14
+ url = `${base}/issues/${options.number}`;
15
+ } else if (options.kind === "change" || options.kind === "pr") {
16
+ if (!options.number) throw new CliError("`rit browse change` needs a number: `rit browse change <number>`", { code: "invalid_argument" });
17
+ url = `${base}/pulls/${options.number}`;
18
+ }
19
+ if (!options.printUrl) io.openUrl?.(url);
20
+ return { url };
21
+ }
package/src/change.mjs ADDED
@@ -0,0 +1,134 @@
1
+ // `rit change` -- Rithub's name for what GitHub calls a pull request (`pr`
2
+ // stays as an alias everywhere in the CLI and its help text, never in
3
+ // output copy). create/list/view/checkout/merge/close/comment/diff/review
4
+ // approve, against `/api/v1/repos/{owner}/{repo}/pulls`. Issue comments and
5
+ // PR comments share one Rithub endpoint (`/issues/{index}/comments`), so
6
+ // `change comment` reuses `issue.mjs`'s path builder rather than duplicating it.
7
+ import { CliError, currentBranch } from "./init.mjs";
8
+ import { gitAuthedArgs } from "./repo.mjs";
9
+ import { resolveRepoArg, requireSession } from "./repo-arg.mjs";
10
+ import { apiCall, apiCallRaw, buildQuery } from "./http.mjs";
11
+
12
+ function pullsPath(r, suffix = "") {
13
+ return `/api/v1/repos/${encodeURIComponent(r.owner)}/${encodeURIComponent(r.repo)}/pulls${suffix}`;
14
+ }
15
+
16
+ export async function runChangeList(options, io) {
17
+ const r = resolveRepoArg(io, options);
18
+ const path = pullsPath(r) + buildQuery({ state: options.state ?? "open", page: options.page, limit: options.limit ?? 30 });
19
+ const { status, body } = await apiCall(io, r.apiUrl, path, { method: "GET" }, r.session?.token);
20
+ if (status !== 200) throw new CliError(`could not list changes on ${r.owner}/${r.repo} (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "network_error" });
21
+ return { owner: r.owner, repo: r.repo, changes: (body ?? []).map((p) => ({ number: p.number, title: p.title, state: p.state, head: p.head?.ref, base: p.base?.ref, html_url: p.html_url })) };
22
+ }
23
+
24
+ export async function runChangeView(options, io) {
25
+ const r = resolveRepoArg(io, options);
26
+ const { status, body } = await apiCall(io, r.apiUrl, pullsPath(r, `/${options.number}`), { method: "GET" }, r.session?.token);
27
+ if (status !== 200) throw new CliError(`change #${options.number} not found on ${r.owner}/${r.repo} (HTTP ${status})`, { code: "not_found" });
28
+ return { owner: r.owner, repo: r.repo, number: body.number, title: body.title, state: body.state, head: body.head?.ref, base: body.base?.ref, mergeable: body.mergeable, html_url: body.html_url };
29
+ }
30
+
31
+ export async function runChangeCreate(options, io) {
32
+ const r = resolveRepoArg(io, options);
33
+ requireSession(r);
34
+ if (!options.title) throw new CliError("`rit change create` needs --title <text>", { code: "invalid_argument" });
35
+ const head = options.head ?? currentBranch(io, options.cwd ?? io.cwd);
36
+ let base = options.base;
37
+ if (!base) {
38
+ const view = await apiCall(io, r.apiUrl, `/api/v1/repos/${encodeURIComponent(r.owner)}/${encodeURIComponent(r.repo)}`, { method: "GET" }, r.session.token);
39
+ base = view.body?.default_branch ?? "main";
40
+ }
41
+ const { status, body } = await apiCall(
42
+ io,
43
+ r.apiUrl,
44
+ pullsPath(r),
45
+ { method: "POST", body: JSON.stringify({ title: options.title, body: options.body ?? "", head, base }) },
46
+ r.session.token
47
+ );
48
+ if (status !== 201) throw new CliError(`could not open a change from ${head} into ${base} (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "create_failed" });
49
+ return { owner: r.owner, repo: r.repo, number: body.number, head, base, html_url: body.html_url };
50
+ }
51
+
52
+ export async function runChangeClose(options, io) {
53
+ const r = resolveRepoArg(io, options);
54
+ requireSession(r);
55
+ const { status, body } = await apiCall(io, r.apiUrl, pullsPath(r, `/${options.number}`), { method: "PATCH", body: JSON.stringify({ state: "closed" }) }, r.session.token);
56
+ if (status !== 200) throw new CliError(`could not close change #${options.number} (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "update_failed" });
57
+ return { owner: r.owner, repo: r.repo, number: options.number, state: body.state };
58
+ }
59
+
60
+ export async function runChangeMerge(options, io) {
61
+ const r = resolveRepoArg(io, options);
62
+ requireSession(r);
63
+ const style = options.squash ? "squash" : options.rebase ? "rebase" : "merge";
64
+ const { status, body } = await apiCall(
65
+ io,
66
+ r.apiUrl,
67
+ pullsPath(r, `/${options.number}/merge`),
68
+ { method: "POST", body: JSON.stringify({ Do: style, delete_branch_after_merge: !!options.deleteBranch }) },
69
+ r.session.token
70
+ );
71
+ if (status !== 200) throw new CliError(`could not merge change #${options.number} (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "merge_failed" });
72
+ return { owner: r.owner, repo: r.repo, number: options.number, merged: true, style };
73
+ }
74
+
75
+ export async function runChangeComment(options, io) {
76
+ const r = resolveRepoArg(io, options);
77
+ requireSession(r);
78
+ if (!options.body) throw new CliError("`rit change comment` needs --body <text>", { code: "invalid_argument" });
79
+ const { status, body } = await apiCall(
80
+ io,
81
+ r.apiUrl,
82
+ `/api/v1/repos/${encodeURIComponent(r.owner)}/${encodeURIComponent(r.repo)}/issues/${options.number}/comments`,
83
+ { method: "POST", body: JSON.stringify({ body: options.body }) },
84
+ r.session.token
85
+ );
86
+ if (status !== 201) throw new CliError(`could not comment on change #${options.number} (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "create_failed" });
87
+ return { owner: r.owner, repo: r.repo, number: options.number, id: body.id, html_url: body.html_url };
88
+ }
89
+
90
+ export async function runChangeDiff(options, io) {
91
+ const r = resolveRepoArg(io, options);
92
+ const { status, text } = await apiCallRaw(io, r.apiUrl, pullsPath(r, `/${options.number}.diff`), { method: "GET" }, r.session?.token);
93
+ if (status !== 200) throw new CliError(`could not get the diff for change #${options.number} (HTTP ${status})`, { code: "network_error" });
94
+ return { owner: r.owner, repo: r.repo, number: options.number, diff: text };
95
+ }
96
+
97
+ export async function runChangeReviewApprove(options, io) {
98
+ const r = resolveRepoArg(io, options);
99
+ requireSession(r);
100
+ const { status, body } = await apiCall(
101
+ io,
102
+ r.apiUrl,
103
+ pullsPath(r, `/${options.number}/reviews`),
104
+ { method: "POST", body: JSON.stringify({ event: "APPROVED", body: options.body ?? "" }) },
105
+ r.session.token
106
+ );
107
+ if (status !== 200) throw new CliError(`could not approve change #${options.number} (HTTP ${status}): ${body?.message ?? "unknown error"}`, { code: "create_failed" });
108
+ return { owner: r.owner, repo: r.repo, number: options.number, approved: true };
109
+ }
110
+
111
+ /** `rit change checkout <number>`: fetches the change's head via Rithub's
112
+ * GitHub-style `refs/pull/<number>/head` ref (Rithub mirrors that
113
+ * convention) into a local `rit-change-<number>` branch and switches to
114
+ * it -- no fork/clone juggling needed even for a change opened from a
115
+ * fork. */
116
+ export async function runChangeCheckout(options, io) {
117
+ const r = resolveRepoArg(io, options);
118
+ const cwd = options.cwd ?? io.cwd;
119
+ const view = await apiCall(io, r.apiUrl, pullsPath(r, `/${options.number}`), { method: "GET" }, r.session?.token);
120
+ if (view.status !== 200) throw new CliError(`change #${options.number} not found on ${r.owner}/${r.repo} (HTTP ${view.status})`, { code: "not_found" });
121
+
122
+ const cloneUrl = view.body.base?.repo?.clone_url ?? `${r.apiUrl}/${r.owner}/${r.repo}.git`;
123
+ const localBranch = `rit-change-${options.number}`;
124
+ const fetchArgs = gitAuthedArgs(r.session?.token, ["fetch", cloneUrl, `refs/pull/${options.number}/head:${localBranch}`]);
125
+ const fetchResult = io.run("git", fetchArgs, cwd);
126
+ if (!fetchResult.ok) {
127
+ // Force-update the local branch ref if it already exists from a previous checkout of the same change.
128
+ const retry = io.run("git", gitAuthedArgs(r.session?.token, ["fetch", cloneUrl, `+refs/pull/${options.number}/head:${localBranch}`]), cwd);
129
+ if (!retry.ok) throw new CliError(`git fetch failed: ${retry.output.slice(-500)}`, { code: "git_failed" });
130
+ }
131
+ const checkoutResult = io.run("git", ["checkout", localBranch], cwd);
132
+ if (!checkoutResult.ok) throw new CliError(`git checkout failed: ${checkoutResult.output.slice(-500)}`, { code: "git_failed" });
133
+ return { owner: r.owner, repo: r.repo, number: options.number, branch: localBranch };
134
+ }