@recoder.xyz/rithub 0.2.1 → 0.3.0

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.
@@ -0,0 +1,460 @@
1
+ // The gh-parity command surface added on top of the original
2
+ // init/claim/login/logout/whoami/clone/repo-create/push set (that part
3
+ // stays in src/cli.mjs, unchanged). Every command here is repo-scoped
4
+ // unless noted, takes `--repo <owner/name>` to override inferring the repo
5
+ // from the current directory's git remote, and `--json` for machine output.
6
+ import { CliError } from "./init.mjs";
7
+ import { toKey, parseFlags } from "./cli.mjs";
8
+ import { runIssueList, runIssueView, runIssueCreate, runIssueClose, runIssueReopen, runIssueEdit, runIssueComment } from "./issue.mjs";
9
+ import { runChangeList, runChangeView, runChangeCreate, runChangeClose, runChangeMerge, runChangeComment, runChangeDiff, runChangeReviewApprove, runChangeCheckout } from "./change.mjs";
10
+ import { runReleaseList, runReleaseView, runReleaseCreate, runReleaseDelete } from "./release.mjs";
11
+ import { runBranchList, runBranchDelete, runBranchProtect } from "./branch.mjs";
12
+ import { runLabelList, runLabelCreate } from "./label.mjs";
13
+ import { runMilestoneList, runMilestoneCreate } from "./milestone.mjs";
14
+ import { runKeyList, runKeyAdd } from "./ssh-key.mjs";
15
+ import { runSecretList, runSecretSet } from "./secret.mjs";
16
+ import { runWebhookList, runWebhookCreate } from "./webhook.mjs";
17
+ import { runOrgList, runOrgView, runUserView } from "./org.mjs";
18
+ import { runSearchRepos, runSearchIssues, runSearchCode } from "./search.mjs";
19
+ import { runStatus } from "./status.mjs";
20
+ import { runBrowse } from "./browse.mjs";
21
+ import { runApi } from "./api.mjs";
22
+ import {
23
+ runRepoList,
24
+ runRepoView,
25
+ runRepoFork,
26
+ runRepoDelete,
27
+ runRepoRename,
28
+ runRepoEdit,
29
+ runRepoArchive,
30
+ runRepoSync,
31
+ runRepoSyncNow,
32
+ runRepoImport,
33
+ } from "./repo-manage.mjs";
34
+
35
+ const REPO_FLAGS = { valueFlags: ["--repo", "--api-url"], boolFlags: ["--json"] };
36
+
37
+ function withRepoFlags(extra) {
38
+ return {
39
+ valueFlags: [...REPO_FLAGS.valueFlags, ...(extra?.valueFlags ?? [])],
40
+ boolFlags: [...REPO_FLAGS.boolFlags, ...(extra?.boolFlags ?? [])],
41
+ repeatableFlags: extra?.repeatableFlags ?? [],
42
+ };
43
+ }
44
+
45
+ function printResult(io, args, result, humanLine) {
46
+ io.out(args.json ? JSON.stringify(result) : humanLine(result));
47
+ }
48
+
49
+ const ISSUE_HELP = `rit issue <command>
50
+
51
+ list list issues (--state open|closed|all)
52
+ create --title <t> [--body <t>]
53
+ view <number>
54
+ close <number>
55
+ reopen <number>
56
+ edit <number> [--title <t>] [--body <t>]
57
+ comment <number> --body <text>`;
58
+
59
+ const CHANGE_HELP = `rit change <command> (alias: rit pr)
60
+
61
+ list list changes (--state open|closed|all)
62
+ create --title <t> [--head <branch>] [--base <branch>] [--body <t>]
63
+ view <number>
64
+ checkout <number>
65
+ diff <number>
66
+ merge <number> [--squash|--rebase] [--delete-branch]
67
+ close <number>
68
+ comment <number> --body <text>
69
+ review approve <number> [--body <text>]`;
70
+
71
+ async function runIssueCommand(rest, io) {
72
+ const [sub, ...args] = rest;
73
+ if (sub === "list") {
74
+ const a = parseFlags(args, withRepoFlags({ valueFlags: ["--state", "--search"] }));
75
+ return printResult(io, a, await runIssueList({ ...a, cwd: io.cwd }, io), (r) => (r.issues.length === 0 ? `No issues on ${r.owner}/${r.repo}.` : r.issues.map((i) => `#${i.number} [${i.state}] ${i.title}`).join("\n")));
76
+ }
77
+ if (sub === "create") {
78
+ const a = parseFlags(args, withRepoFlags({ valueFlags: ["--title", "--body"] }));
79
+ return printResult(io, a, await runIssueCreate({ ...a, cwd: io.cwd }, io), (r) => `Opened ${r.owner}/${r.repo}#${r.number} -> ${r.html_url}`);
80
+ }
81
+ if (sub === "view" || sub === "close" || sub === "reopen") {
82
+ const a = parseFlags(args, withRepoFlags());
83
+ const number = a._[0];
84
+ if (!number) throw new CliError(`\`rit issue ${sub}\` needs a number: \`rit issue ${sub} <number>\``, { code: "invalid_argument" });
85
+ const runner = sub === "view" ? runIssueView : sub === "close" ? runIssueClose : runIssueReopen;
86
+ const result = await runner({ ...a, number, cwd: io.cwd }, io);
87
+ return printResult(io, a, result, (r) => (sub === "view" ? `#${r.number} [${r.state}] ${r.title}\n${r.body ?? ""}\n${r.html_url}` : `#${r.number} is now ${r.state}.`));
88
+ }
89
+ if (sub === "edit") {
90
+ const a = parseFlags(args, withRepoFlags({ valueFlags: ["--title", "--body"] }));
91
+ const number = a._[0];
92
+ if (!number) throw new CliError("`rit issue edit` needs a number: `rit issue edit <number> [--title <t>] [--body <t>]`", { code: "invalid_argument" });
93
+ return printResult(io, a, await runIssueEdit({ ...a, number, cwd: io.cwd }, io), (r) => `Updated #${r.number}: ${r.title}`);
94
+ }
95
+ if (sub === "comment") {
96
+ const a = parseFlags(args, withRepoFlags({ valueFlags: ["--body"] }));
97
+ const number = a._[0];
98
+ if (!number) throw new CliError("`rit issue comment` needs a number: `rit issue comment <number> --body <text>`", { code: "invalid_argument" });
99
+ return printResult(io, a, await runIssueComment({ ...a, number, cwd: io.cwd }, io), (r) => `Commented on #${r.number} -> ${r.html_url}`);
100
+ }
101
+ io.out(ISSUE_HELP);
102
+ return sub ? 1 : 0;
103
+ }
104
+
105
+ async function runChangeCommand(rest, io) {
106
+ const [sub, ...args] = rest;
107
+ if (sub === "list") {
108
+ const a = parseFlags(args, withRepoFlags({ valueFlags: ["--state"] }));
109
+ return printResult(io, a, await runChangeList({ ...a, cwd: io.cwd }, io), (r) => (r.changes.length === 0 ? `No changes on ${r.owner}/${r.repo}.` : r.changes.map((c) => `#${c.number} [${c.state}] ${c.title} (${c.head} -> ${c.base})`).join("\n")));
110
+ }
111
+ if (sub === "create") {
112
+ const a = parseFlags(args, withRepoFlags({ valueFlags: ["--title", "--body", "--head", "--base"] }));
113
+ return printResult(io, a, await runChangeCreate({ ...a, cwd: io.cwd }, io), (r) => `Opened ${r.owner}/${r.repo}#${r.number} (${r.head} -> ${r.base}) -> ${r.html_url}`);
114
+ }
115
+ if (sub === "view" || sub === "close") {
116
+ const a = parseFlags(args, withRepoFlags());
117
+ const number = a._[0];
118
+ if (!number) throw new CliError(`\`rit change ${sub}\` needs a number: \`rit change ${sub} <number>\``, { code: "invalid_argument" });
119
+ const result = await (sub === "view" ? runChangeView : runChangeClose)({ ...a, number, cwd: io.cwd }, io);
120
+ return printResult(io, a, result, (r) => (sub === "view" ? `#${r.number} [${r.state}] ${r.title} (${r.head} -> ${r.base})\n${r.html_url}` : `#${r.number} is now ${r.state}.`));
121
+ }
122
+ if (sub === "checkout") {
123
+ const a = parseFlags(args, withRepoFlags());
124
+ const number = a._[0];
125
+ if (!number) throw new CliError("`rit change checkout` needs a number: `rit change checkout <number>`", { code: "invalid_argument" });
126
+ return printResult(io, a, await runChangeCheckout({ ...a, number, cwd: io.cwd }, io), (r) => `Checked out #${r.number} as ${r.branch}.`);
127
+ }
128
+ if (sub === "diff") {
129
+ const a = parseFlags(args, withRepoFlags());
130
+ const number = a._[0];
131
+ if (!number) throw new CliError("`rit change diff` needs a number: `rit change diff <number>`", { code: "invalid_argument" });
132
+ const result = await runChangeDiff({ ...a, number, cwd: io.cwd }, io);
133
+ io.out(a.json ? JSON.stringify(result) : result.diff);
134
+ return 0;
135
+ }
136
+ if (sub === "merge") {
137
+ const a = parseFlags(args, withRepoFlags({ boolFlags: ["--squash", "--rebase", "--delete-branch"] }));
138
+ const number = a._[0];
139
+ if (!number) throw new CliError("`rit change merge` needs a number: `rit change merge <number>`", { code: "invalid_argument" });
140
+ return printResult(io, a, await runChangeMerge({ ...a, number, cwd: io.cwd }, io), (r) => `Merged #${r.number} (${r.style}).`);
141
+ }
142
+ if (sub === "comment") {
143
+ const a = parseFlags(args, withRepoFlags({ valueFlags: ["--body"] }));
144
+ const number = a._[0];
145
+ if (!number) throw new CliError("`rit change comment` needs a number: `rit change comment <number> --body <text>`", { code: "invalid_argument" });
146
+ return printResult(io, a, await runChangeComment({ ...a, number, cwd: io.cwd }, io), (r) => `Commented on #${r.number} -> ${r.html_url}`);
147
+ }
148
+ if (sub === "review") {
149
+ const [action, ...reviewArgs] = args;
150
+ if (action !== "approve") throw new CliError(`unknown \`rit change review\` action "${action ?? ""}" (only "approve" exists)`, { code: "invalid_argument" });
151
+ const a = parseFlags(reviewArgs, withRepoFlags({ valueFlags: ["--body"] }));
152
+ const number = a._[0];
153
+ if (!number) throw new CliError("`rit change review approve` needs a number: `rit change review approve <number>`", { code: "invalid_argument" });
154
+ return printResult(io, a, await runChangeReviewApprove({ ...a, number, cwd: io.cwd }, io), (r) => `Approved #${r.number}.`);
155
+ }
156
+ io.out(CHANGE_HELP);
157
+ return sub ? 1 : 0;
158
+ }
159
+
160
+ async function runReleaseCommand(rest, io) {
161
+ const [sub, ...args] = rest;
162
+ if (sub === "list") {
163
+ const a = parseFlags(args, withRepoFlags());
164
+ return printResult(io, a, await runReleaseList({ ...a, cwd: io.cwd }, io), (r) => (r.releases.length === 0 ? `No releases on ${r.owner}/${r.repo}.` : r.releases.map((rel) => `${rel.tag}${rel.draft ? " (draft)" : ""}${rel.prerelease ? " (prerelease)" : ""} -- ${rel.name}`).join("\n")));
165
+ }
166
+ if (sub === "view") {
167
+ const a = parseFlags(args, withRepoFlags());
168
+ const tag = a._[0];
169
+ if (!tag) throw new CliError("`rit release view` needs a tag: `rit release view <tag>`", { code: "invalid_argument" });
170
+ return printResult(io, a, await runReleaseView({ ...a, tag, cwd: io.cwd }, io), (r) => `${r.tag} -- ${r.name}\n${r.body ?? ""}\nAssets: ${r.assets.join(", ") || "none"}\n${r.html_url}`);
171
+ }
172
+ if (sub === "delete") {
173
+ const a = parseFlags(args, withRepoFlags());
174
+ const tag = a._[0];
175
+ if (!tag) throw new CliError("`rit release delete` needs a tag: `rit release delete <tag>`", { code: "invalid_argument" });
176
+ return printResult(io, a, await runReleaseDelete({ ...a, tag, cwd: io.cwd }, io), (r) => `Deleted release ${r.tag}.`);
177
+ }
178
+ if (sub === "create") {
179
+ const a = parseFlags(args, withRepoFlags({ valueFlags: ["--title", "--notes"], boolFlags: ["--draft", "--prerelease"], repeatableFlags: ["--asset"] }));
180
+ const tag = a._[0];
181
+ const result = await runReleaseCreate({ ...a, tag, assets: a.asset, cwd: io.cwd }, io);
182
+ return printResult(io, a, result, (r) => `Released ${r.tag} -> ${r.html_url}${r.assets.length ? `\nUploaded: ${r.assets.join(", ")}` : ""}`);
183
+ }
184
+ io.out("rit release list|create|view|delete");
185
+ return sub ? 1 : 0;
186
+ }
187
+
188
+ async function runBranchCommand(rest, io) {
189
+ const [sub, ...args] = rest;
190
+ if (sub === "list") {
191
+ const a = parseFlags(args, withRepoFlags());
192
+ return printResult(io, a, await runBranchList({ ...a, cwd: io.cwd }, io), (r) => r.branches.map((b) => `${b.name}${b.protected ? " (protected)" : ""}`).join("\n"));
193
+ }
194
+ if (sub === "delete") {
195
+ const a = parseFlags(args, withRepoFlags());
196
+ const name = a._[0];
197
+ if (!name) throw new CliError("`rit branch delete` needs a name: `rit branch delete <name>`", { code: "invalid_argument" });
198
+ return printResult(io, a, await runBranchDelete({ ...a, name, cwd: io.cwd }, io), (r) => `Deleted branch ${r.branch}.`);
199
+ }
200
+ if (sub === "protect") {
201
+ const a = parseFlags(args, withRepoFlags({ valueFlags: ["--required-approvals"], boolFlags: ["--allow-push", "--allow-force-push"] }));
202
+ const name = a._[0];
203
+ if (!name) throw new CliError("`rit branch protect` needs a name/pattern: `rit branch protect <name>`", { code: "invalid_argument" });
204
+ return printResult(io, a, await runBranchProtect({ ...a, name, cwd: io.cwd }, io), (r) => `Protected ${r.rule} (required approvals: ${r.required_approvals}).`);
205
+ }
206
+ io.out("rit branch list|delete|protect");
207
+ return sub ? 1 : 0;
208
+ }
209
+
210
+ async function runLabelCommand(rest, io) {
211
+ const [sub, ...args] = rest;
212
+ if (sub === "list") {
213
+ const a = parseFlags(args, withRepoFlags());
214
+ return printResult(io, a, await runLabelList({ ...a, cwd: io.cwd }, io), (r) => r.labels.map((l) => `${l.name} (#${l.color})${l.description ? ` -- ${l.description}` : ""}`).join("\n"));
215
+ }
216
+ if (sub === "create") {
217
+ const a = parseFlags(args, withRepoFlags({ valueFlags: ["--color", "--description"] }));
218
+ const name = a._[0];
219
+ return printResult(io, a, await runLabelCreate({ ...a, name, cwd: io.cwd }, io), (r) => `Created label ${r.name}.`);
220
+ }
221
+ io.out("rit label list|create");
222
+ return sub ? 1 : 0;
223
+ }
224
+
225
+ async function runMilestoneCommand(rest, io) {
226
+ const [sub, ...args] = rest;
227
+ if (sub === "list") {
228
+ const a = parseFlags(args, withRepoFlags());
229
+ return printResult(io, a, await runMilestoneList({ ...a, cwd: io.cwd }, io), (r) => r.milestones.map((m) => `${m.title} [${m.state}]${m.due_on ? ` due ${m.due_on}` : ""}`).join("\n"));
230
+ }
231
+ if (sub === "create") {
232
+ const a = parseFlags(args, withRepoFlags({ valueFlags: ["--description", "--due"] }));
233
+ const title = a._[0];
234
+ return printResult(io, a, await runMilestoneCreate({ ...a, title, cwd: io.cwd }, io), (r) => `Created milestone ${r.title}.`);
235
+ }
236
+ io.out("rit milestone list|create");
237
+ return sub ? 1 : 0;
238
+ }
239
+
240
+ async function runKeyCommand(rest, io) {
241
+ const [sub, ...args] = rest;
242
+ if (sub === "list") {
243
+ const a = parseFlags(args, { boolFlags: ["--json"], valueFlags: ["--api-url"] });
244
+ return printResult(io, a, await runKeyList(a, io), (r) => (r.keys.length === 0 ? "No keys." : r.keys.map((k) => `${k.title} ${k.fingerprint}${k.read_only ? " (read-only)" : ""}`).join("\n")));
245
+ }
246
+ if (sub === "add") {
247
+ const a = parseFlags(args, { boolFlags: ["--json", "--read-only"], valueFlags: ["--api-url"] });
248
+ const [title, key] = a._;
249
+ return printResult(io, a, await runKeyAdd({ ...a, title, key }, io), (r) => `Added key ${r.title} (${r.fingerprint}).`);
250
+ }
251
+ io.out("rit key list|add <title> <key-or-path> [--read-only]");
252
+ return sub ? 1 : 0;
253
+ }
254
+
255
+ async function runSecretCommand(rest, io) {
256
+ const [sub, ...args] = rest;
257
+ if (sub === "list") {
258
+ const a = parseFlags(args, withRepoFlags());
259
+ return printResult(io, a, await runSecretList({ ...a, cwd: io.cwd }, io), (r) => (r.secrets.length === 0 ? `No secrets on ${r.owner}/${r.repo}.` : r.secrets.join("\n")));
260
+ }
261
+ if (sub === "set") {
262
+ const a = parseFlags(args, withRepoFlags());
263
+ const [name, value] = a._;
264
+ return printResult(io, a, await runSecretSet({ ...a, name, value, cwd: io.cwd }, io), (r) => `Set secret ${r.name} on ${r.owner}/${r.repo}.`);
265
+ }
266
+ io.out("rit secret list|set <NAME> <value>");
267
+ return sub ? 1 : 0;
268
+ }
269
+
270
+ async function runWebhookCommand(rest, io) {
271
+ const [sub, ...args] = rest;
272
+ if (sub === "list") {
273
+ const a = parseFlags(args, withRepoFlags());
274
+ return printResult(io, a, await runWebhookList({ ...a, cwd: io.cwd }, io), (r) => (r.webhooks.length === 0 ? `No webhooks on ${r.owner}/${r.repo}.` : r.webhooks.map((h) => `#${h.id} ${h.url} [${(h.events ?? []).join(",")}]${h.active ? "" : " (inactive)"}`).join("\n")));
275
+ }
276
+ if (sub === "create") {
277
+ const a = parseFlags(args, withRepoFlags({ valueFlags: ["--url", "--events", "--secret"] }));
278
+ return printResult(io, a, await runWebhookCreate({ ...a, cwd: io.cwd }, io), (r) => `Created webhook #${r.id} on ${r.owner}/${r.repo} for [${r.events.join(",")}].`);
279
+ }
280
+ io.out("rit webhook list|create --url <url> [--events a,b] [--secret <text>]");
281
+ return sub ? 1 : 0;
282
+ }
283
+
284
+ async function runOrgCommand(rest, io) {
285
+ const [sub, ...args] = rest;
286
+ if (sub === "list") {
287
+ const a = parseFlags(args, { boolFlags: ["--json"] });
288
+ return printResult(io, a, await runOrgList(a, io), (r) => (r.orgs.length === 0 ? "No organizations." : r.orgs.map((o) => o.name).join("\n")));
289
+ }
290
+ if (sub === "view") {
291
+ const a = parseFlags(args, { boolFlags: ["--json"], valueFlags: ["--api-url"] });
292
+ const name = a._[0];
293
+ return printResult(io, a, await runOrgView({ ...a, name }, io), (r) => `${r.name}${r.description ? ` -- ${r.description}` : ""}\n${r.html_url}`);
294
+ }
295
+ io.out("rit org list|view <org>");
296
+ return sub ? 1 : 0;
297
+ }
298
+
299
+ async function runUserCommand(rest, io) {
300
+ const [sub, ...args] = rest;
301
+ if (sub === "view") {
302
+ const a = parseFlags(args, { boolFlags: ["--json"], valueFlags: ["--api-url"] });
303
+ const name = a._[0];
304
+ return printResult(io, a, await runUserView({ ...a, name }, io), (r) => `${r.login}${r.full_name ? ` (${r.full_name})` : ""}\n${r.html_url}`);
305
+ }
306
+ io.out("rit user view <username>");
307
+ return sub ? 1 : 0;
308
+ }
309
+
310
+ async function runSearchCommand(rest, io) {
311
+ const [sub, ...args] = rest;
312
+ if (sub === "repos") {
313
+ const a = parseFlags(args, { boolFlags: ["--json"], valueFlags: ["--api-url", "--limit"] });
314
+ const query = a._[0];
315
+ return printResult(io, a, await runSearchRepos({ ...a, query }, io), (r) => (r.repos.length === 0 ? "No repos found." : r.repos.map((x) => `${x.full_name} (${x.stars} stars) -- ${x.html_url}`).join("\n")));
316
+ }
317
+ if (sub === "issues") {
318
+ const a = parseFlags(args, { boolFlags: ["--json"], valueFlags: ["--api-url", "--limit", "--type", "--owner"] });
319
+ const query = a._[0];
320
+ return printResult(io, a, await runSearchIssues({ ...a, query }, io), (r) => (r.issues.length === 0 ? "No issues found." : r.issues.map((x) => `${x.repository}#${x.number} ${x.title}`).join("\n")));
321
+ }
322
+ if (sub === "code") {
323
+ runSearchCode();
324
+ }
325
+ io.out("rit search repos|issues <query> (code: not supported by this server's API)");
326
+ return sub ? 1 : 0;
327
+ }
328
+
329
+ async function runBrowseCommand(rest, io) {
330
+ const [first, second] = rest;
331
+ const isSubKind = first === "issue" || first === "change" || first === "pr";
332
+ const args = isSubKind ? rest.slice(2) : rest.slice(1);
333
+ const a = parseFlags(args, withRepoFlags({ boolFlags: ["--print-url"] }));
334
+ const result = await runBrowse({ ...a, kind: isSubKind ? first : undefined, number: isSubKind ? second : undefined, cwd: io.cwd }, io);
335
+ io.out(a.json ? JSON.stringify(result) : result.url);
336
+ return 0;
337
+ }
338
+
339
+ async function runStatusCommand(rest, io) {
340
+ const a = parseFlags(rest, { boolFlags: ["--json"], valueFlags: ["--api-url"] });
341
+ const result = await runStatus(a, io);
342
+ if (a.json) {
343
+ io.out(JSON.stringify(result));
344
+ return 0;
345
+ }
346
+ const section = (title, items, line) => [`${title}:`, ...(items.length === 0 ? [" (none)"] : items.map((i) => ` ${line(i)}`))].join("\n");
347
+ io.out(
348
+ [
349
+ section("Assigned issues", result.assignedIssues, (i) => `${i.repository}#${i.number} ${i.title}`),
350
+ section("Your open changes", result.createdChanges, (i) => `${i.repository}#${i.number} ${i.title}`),
351
+ section("Review requested", result.reviewRequested, (i) => `${i.repository}#${i.number} ${i.title}`),
352
+ ].join("\n")
353
+ );
354
+ return 0;
355
+ }
356
+
357
+ async function runApiCommand(rest, io) {
358
+ const a = parseFlags(rest, { valueFlags: ["--method", "--input", "--api-url"], repeatableFlags: ["--field"] });
359
+ const path = a._[0];
360
+ const result = await runApi({ ...a, path, fields: a.field ?? [] }, io);
361
+ try {
362
+ io.out(JSON.stringify(JSON.parse(result.text), null, 2));
363
+ } catch {
364
+ io.out(result.text);
365
+ }
366
+ return 0;
367
+ }
368
+
369
+ const REPO_COMMAND_HELP = `rit repo <command>
370
+
371
+ list [owner]
372
+ view <owner/repo|repo>
373
+ fork <owner/repo>
374
+ delete <owner/repo> --confirm
375
+ rename <owner/repo> <new-name>
376
+ edit <owner/repo> [--description <t>] [--private|--public]
377
+ archive <owner/repo> [--unarchive]
378
+ sync <git-url> [--name <name>] [--private] create a pull mirror
379
+ sync-now <owner/repo> pull a mirror now
380
+ import <git-url> [--name <name>] [--private] one-time copy`;
381
+
382
+ /** Everything under `rit repo` besides `create` (handled in src/cli.mjs
383
+ * alongside the original `clone`/`push`/`create`). Returns `null` if
384
+ * `subcommand` isn't one of these, so the caller can fall through. */
385
+ export async function runRepoWorkCommand(subcommand, rest, io) {
386
+ if (subcommand === "list") {
387
+ const a = parseFlags(rest, { boolFlags: ["--json"], valueFlags: ["--api-url"] });
388
+ return printResult(io, a, await runRepoList({ ...a, owner: a._[0] }, io), (r) => (r.repos.length === 0 ? "No repos." : r.repos.map((x) => x.full_name).join("\n")));
389
+ }
390
+ if (subcommand === "view") {
391
+ const a = parseFlags(rest, { boolFlags: ["--json"], valueFlags: ["--api-url"] });
392
+ return printResult(io, a, await runRepoView({ ...a, name: a._[0] }, io), (r) => `${r.owner}/${r.repo}${r.private ? " (private)" : ""}\n${r.description ?? ""}\n${r.html_url}`);
393
+ }
394
+ if (subcommand === "fork") {
395
+ const a = parseFlags(rest, { boolFlags: ["--json"], valueFlags: ["--api-url"] });
396
+ return printResult(io, a, await runRepoFork({ ...a, name: a._[0] }, io), (r) => `Forked ${r.owner}/${r.repo} -> ${r.html_url}`);
397
+ }
398
+ if (subcommand === "delete") {
399
+ const a = parseFlags(rest, { boolFlags: ["--json", "--confirm"], valueFlags: ["--api-url"] });
400
+ return printResult(io, a, await runRepoDelete({ ...a, name: a._[0] }, io), (r) => `Deleted ${r.owner}/${r.repo}.`);
401
+ }
402
+ if (subcommand === "rename") {
403
+ const a = parseFlags(rest, { boolFlags: ["--json"], valueFlags: ["--api-url"] });
404
+ return printResult(io, a, await runRepoRename({ ...a, name: a._[0], newName: a._[1] }, io), (r) => `Renamed to ${r.owner}/${r.repo}.`);
405
+ }
406
+ if (subcommand === "edit") {
407
+ const a = parseFlags(rest, { boolFlags: ["--json", "--private", "--public"], valueFlags: ["--api-url", "--description"] });
408
+ return printResult(io, a, await runRepoEdit({ ...a, name: a._[0] }, io), (r) => `Updated ${r.owner}/${r.repo}.`);
409
+ }
410
+ if (subcommand === "archive") {
411
+ const a = parseFlags(rest, { boolFlags: ["--json", "--unarchive"], valueFlags: ["--api-url"] });
412
+ return printResult(io, a, await runRepoArchive({ ...a, name: a._[0] }, io), (r) => `${r.archived ? "Archived" : "Unarchived"} ${r.owner}/${r.repo}.`);
413
+ }
414
+ if (subcommand === "sync") {
415
+ const a = parseFlags(rest, { boolFlags: ["--json", "--private"], valueFlags: ["--api-url", "--name"] });
416
+ return printResult(io, a, await runRepoSync({ ...a, url: a._[0] }, io), (r) => `Mirroring ${r.source} -> ${r.owner}/${r.repo}.`);
417
+ }
418
+ if (subcommand === "sync-now") {
419
+ const a = parseFlags(rest, { boolFlags: ["--json"], valueFlags: ["--api-url"] });
420
+ return printResult(io, a, await runRepoSyncNow({ ...a, name: a._[0] }, io), (r) => `Synced ${r.owner}/${r.repo}.`);
421
+ }
422
+ if (subcommand === "import") {
423
+ const a = parseFlags(rest, { boolFlags: ["--json", "--private"], valueFlags: ["--api-url", "--name"] });
424
+ return printResult(io, a, await runRepoImport({ ...a, url: a._[0] }, io), (r) => `Imported ${r.source} -> ${r.owner}/${r.repo}.`);
425
+ }
426
+ if (subcommand === undefined || subcommand === "help") {
427
+ io.out(REPO_COMMAND_HELP);
428
+ return 0;
429
+ }
430
+ return null;
431
+ }
432
+
433
+ const WORK_COMMANDS = {
434
+ issue: runIssueCommand,
435
+ change: runChangeCommand,
436
+ pr: runChangeCommand,
437
+ release: runReleaseCommand,
438
+ branch: runBranchCommand,
439
+ label: runLabelCommand,
440
+ milestone: runMilestoneCommand,
441
+ key: runKeyCommand,
442
+ secret: runSecretCommand,
443
+ webhook: runWebhookCommand,
444
+ org: runOrgCommand,
445
+ user: runUserCommand,
446
+ search: runSearchCommand,
447
+ browse: runBrowseCommand,
448
+ status: runStatusCommand,
449
+ api: runApiCommand,
450
+ };
451
+
452
+ /** Dispatches every gh-parity command that isn't part of the original
453
+ * init/login/clone/push surface. Returns `null` (not a number) when
454
+ * `command` doesn't match anything here, so `src/cli.mjs`'s `main()` can
455
+ * fall through to printing USAGE. */
456
+ export async function runWorkCommand(command, rest, io) {
457
+ const handler = WORK_COMMANDS[command];
458
+ if (!handler) return null;
459
+ return handler(rest, io);
460
+ }
package/src/cli.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  import { runInit, runClaim, CliError, DEFAULT_API_URL } from "./init.mjs";
2
2
  import { runLogin, runLogout, runWhoami } from "./auth.mjs";
3
3
  import { runClone, runRepoCreate, runPush } from "./repo.mjs";
4
+ import { runWorkCommand, runRepoWorkCommand } from "./cli-work.mjs";
4
5
 
5
6
  const USAGE = `rit <command> [options] (alias: rithub)
6
7
 
@@ -9,36 +10,62 @@ const USAGE = `rit <command> [options] (alias: rithub)
9
10
  this directory's git remote at it
10
11
  claim --email <you@example.com> hands a human ownership of the account
11
12
  \`init\` created in this directory
12
- login [--token <token>] sign in: paste a token from
13
- ${DEFAULT_API_URL}/user/settings/applications
14
- (or pass --token / set RITHUB_TOKEN)
13
+ login [--token <token>] sign in: opens a browser to paste a
14
+ token from ${DEFAULT_API_URL}/user/settings/applications
15
+ (or pass --token / set RITHUB_TOKEN --
16
+ required on a non-interactive session)
15
17
  logout forget the saved token
16
18
  whoami print the account the saved/env token belongs to
17
19
  clone <owner/repo|repo> [dir] clone a repo (bare name = your own account)
18
- repo create <name> [--private] create a repo on Rithub (needs a token
19
- [--description <text>] with the "write:user" scope)
20
20
  push [--private] [--name <name>] create the repo if missing (needs
21
21
  "write:user" for that), add a \`rithub\`
22
22
  remote, push the current branch
23
- help, --help, -h show this
23
+
24
+ repo <cmd> create|list|view|fork|delete|rename|edit|archive|sync|sync-now|import
25
+ issue <cmd> list|create|view|close|reopen|edit|comment
26
+ change <cmd> list|create|view|checkout|diff|merge|close|comment|review approve
27
+ (alias: pr -- same subcommands)
28
+ release <cmd> list|create|view|delete
29
+ branch <cmd> list|delete|protect
30
+ label <cmd> list|create
31
+ milestone <cmd> list|create
32
+ key <cmd> list|add
33
+ secret <cmd> list|set
34
+ webhook <cmd> list|create
35
+ org <cmd> list|view
36
+ user <cmd> view
37
+ search <cmd> repos|issues (code: unsupported -- no server endpoint)
38
+ status your assigned issues, open changes, and review requests
39
+ browse [issue|change <number>] [--print-url]
40
+ api <path> [--method <m>] [--field k=v]... [--input -|@file]
41
+
42
+ help, --help, -h show this (each command above also
43
+ takes its own \`help\`/no-args for its
44
+ full flag list)
24
45
  --version, -v print the CLI version
25
46
 
26
- Flags on any command: --json (machine-readable output), --api-url <url>
27
- (or RITHUB_API_URL env, default ${DEFAULT_API_URL}).`;
47
+ Flags on any command: --json (machine-readable output), --repo <owner/name>
48
+ (repo-scoped commands -- overrides inferring it from the current directory's
49
+ git remote), --api-url <url> (or RITHUB_API_URL env, default ${DEFAULT_API_URL}).`;
28
50
 
29
- function toKey(flag) {
51
+ export function toKey(flag) {
30
52
  return flag.replace(/^--/, "").replace(/-([a-z])/g, (_, c) => c.toUpperCase());
31
53
  }
32
54
 
33
55
  /** One small generic parser for every command: declare which flags take a
34
56
  * value and which are booleans, everything else positional goes in `_`.
35
- * Keeps each command's own code free of argv-walking boilerplate. */
36
- function parseFlags(argv, { valueFlags = [], boolFlags = [] } = {}) {
57
+ * Keeps each command's own code free of argv-walking boilerplate.
58
+ * `repeatableFlags` (e.g. `--asset`, `-f`) collect every occurrence into an
59
+ * array instead of only keeping the last one. */
60
+ export function parseFlags(argv, { valueFlags = [], boolFlags = [], repeatableFlags = [] } = {}) {
37
61
  const out = { _: [] };
62
+ for (const flag of repeatableFlags) out[toKey(flag)] = [];
38
63
  for (let i = 0; i < argv.length; i++) {
39
64
  const arg = argv[i];
40
65
  if (boolFlags.includes(arg)) {
41
66
  out[toKey(arg)] = true;
67
+ } else if (repeatableFlags.includes(arg)) {
68
+ out[toKey(arg)].push(argv[++i]);
42
69
  } else if (valueFlags.includes(arg)) {
43
70
  out[toKey(arg)] = argv[++i];
44
71
  } else if (arg.startsWith("--")) {
@@ -116,15 +143,19 @@ export async function main(argv, io) {
116
143
 
117
144
  if (command === "repo") {
118
145
  const [subcommand, ...repoRest] = rest;
119
- if (subcommand !== "create") {
120
- throw new CliError(subcommand ? `unknown \`rit repo\` subcommand "${subcommand}" (only "create" exists)` : "`rit repo create <name>` needs a subcommand", { code: "invalid_argument" });
146
+ if (subcommand === "create") {
147
+ const args = parseFlags(repoRest, { valueFlags: ["--description", "--api-url"], boolFlags: ["--private", "--json"] });
148
+ const [name] = args._;
149
+ if (!name) throw new CliError("`rit repo create` needs a name: `rit repo create <name>`", { code: "invalid_argument" });
150
+ const result = await runRepoCreate({ name, private: args.private, description: args.description, apiUrl: args.apiUrl }, io);
151
+ io.out(args.json ? JSON.stringify(result) : `Created ${result.owner}/${result.repo} -> ${result.html_url}\nClone: ${result.clone_url}`);
152
+ return 0;
121
153
  }
122
- const args = parseFlags(repoRest, { valueFlags: ["--description", "--api-url"], boolFlags: ["--private", "--json"] });
123
- const [name] = args._;
124
- if (!name) throw new CliError("`rit repo create` needs a name: `rit repo create <name>`", { code: "invalid_argument" });
125
- const result = await runRepoCreate({ name, private: args.private, description: args.description, apiUrl: args.apiUrl }, io);
126
- io.out(args.json ? JSON.stringify(result) : `Created ${result.owner}/${result.repo} -> ${result.html_url}\nClone: ${result.clone_url}`);
127
- return 0;
154
+ // Everything else under `rit repo` (list/view/fork/delete/rename/edit/
155
+ // archive/sync/sync-now/import) lives in src/cli-work.mjs.
156
+ const code = await runRepoWorkCommand(subcommand, repoRest, io);
157
+ if (code !== null) return code;
158
+ throw new CliError(`unknown \`rit repo\` subcommand "${subcommand}"`, { code: "invalid_argument" });
128
159
  }
129
160
 
130
161
  if (command === "push") {
@@ -139,6 +170,9 @@ export async function main(argv, io) {
139
170
  return 0;
140
171
  }
141
172
 
173
+ const workCode = await runWorkCommand(command, rest, io);
174
+ if (workCode !== null) return workCode;
175
+
142
176
  io.err(USAGE);
143
177
  return command ? 1 : 0;
144
178
  } catch (err) {
package/src/http.mjs ADDED
@@ -0,0 +1,75 @@
1
+ // Shared HTTP helpers for every gh-parity command added on top of the
2
+ // original login/clone/repo-create/push surface (src/repo.mjs, src/init.mjs
3
+ // and src/auth.mjs each keep their own small, already-tested copy of this
4
+ // rather than being refactored to import it, to avoid touching working code
5
+ // for this change -- see the CLI's README "Design notes" section).
6
+ //
7
+ // All of it talks to Rithub's own REST API at `/api/v1` with a plain
8
+ // `fetch` -- no SDK, same choice the rest of this package already made.
9
+
10
+ /** One JSON request/response round trip. Always resolves (never throws on a
11
+ * non-2xx status) so callers can turn a specific status into a clear
12
+ * CliError message instead of an unhandled rejection. */
13
+ export async function apiCall(io, apiUrl, path, init, token) {
14
+ const headers = {
15
+ accept: "application/json",
16
+ "user-agent": "rithub-cli",
17
+ ...(init?.body ? { "content-type": "application/json" } : {}),
18
+ ...(token ? { authorization: `token ${token}` } : {}),
19
+ ...(init?.headers ?? {}),
20
+ };
21
+ const res = await io.fetchImpl(`${apiUrl}${path}`, { ...init, headers });
22
+ const text = await res.text();
23
+ let body = null;
24
+ try {
25
+ body = text ? JSON.parse(text) : null;
26
+ } catch {
27
+ body = { message: text.slice(0, 300) };
28
+ }
29
+ return { status: res.status, body, raw: text };
30
+ }
31
+
32
+ /** Same request, but returns the raw response body as text with no JSON
33
+ * parsing attempt -- for endpoints that answer with a diff/patch, not JSON
34
+ * (`rit change diff`). */
35
+ export async function apiCallRaw(io, apiUrl, path, init, token) {
36
+ const headers = {
37
+ accept: init?.accept ?? "*/*",
38
+ "user-agent": "rithub-cli",
39
+ ...(token ? { authorization: `token ${token}` } : {}),
40
+ };
41
+ const res = await io.fetchImpl(`${apiUrl}${path}`, { ...init, headers });
42
+ const text = await res.text();
43
+ return { status: res.status, text };
44
+ }
45
+
46
+ /** Uploads a local file as a release asset (`POST
47
+ * /repos/{owner}/{repo}/releases/{id}/assets`, multipart/form-data) --
48
+ * the one command here that isn't plain JSON in, JSON out. */
49
+ export async function uploadAsset(io, apiUrl, path, token, fileBuffer, fileName) {
50
+ const form = new FormData();
51
+ form.append("attachment", new Blob([fileBuffer]), fileName);
52
+ const res = await io.fetchImpl(`${apiUrl}${path}${buildQuery({ name: fileName })}`, {
53
+ method: "POST",
54
+ headers: { accept: "application/json", "user-agent": "rithub-cli", ...(token ? { authorization: `token ${token}` } : {}) },
55
+ body: form,
56
+ });
57
+ const text = await res.text();
58
+ let body = null;
59
+ try {
60
+ body = text ? JSON.parse(text) : null;
61
+ } catch {
62
+ body = { message: text.slice(0, 300) };
63
+ }
64
+ return { status: res.status, body };
65
+ }
66
+
67
+ /** `?a=b&c=d`, skipping any key whose value is `undefined`/`null`/`""` so
68
+ * optional filters don't show up as the literal string "undefined". */
69
+ export function buildQuery(params) {
70
+ const entries = Object.entries(params ?? {}).filter(([, v]) => v !== undefined && v !== null && v !== "");
71
+ if (entries.length === 0) return "";
72
+ const qs = new URLSearchParams();
73
+ for (const [k, v] of entries) qs.set(k, String(v));
74
+ return `?${qs.toString()}`;
75
+ }