OXYGENHUB
# 1cc0ff44e5ca oxygenhub-vscode / src / extension.ts
20.0 KiB · last changed Releases view and Draft Release from a tag with notes from history (0.6.0) 1 month ago source blame history raw
1
// Activation: sign in, find the Oxygen extension's API, register the
2
// remote provider, wire the views, the review controller and the commands.
3
4
import * as vscode from "vscode";
5
import { HubAuth } from "./auth";
6
import { ChecksBar } from "./checks";
7
import { ProposalContentProvider, SCHEME, openAllChanges, openFileDiff, refOf } from "./diff";
8
import { hubUrl } from "./hub";
9
import { InboxBar } from "./inbox";
10
import { draftRelease, ReleasesProvider } from "./releases";
11
import { ReferenceCompletions, ReferenceHovers, ReferenceIndex, SELECTOR } from "./references";
12
import { annotateTodo, issueBody, todoTitle } from "./refs";
13
import { IssueNode, IssuesProvider, showIssue } from "./issues";
14
import type { OxygenAPI } from "./oxygenapi";
15
import { HubRepo, ProposalFileNode, ProposalNode, ProposalsProvider, showDetail } from "./proposals";
16
import { makeProvider } from "./provider";
17
import { ReviewController } from "./review";
18
19
let auth: HubAuth;
20
let oxygen: OxygenAPI | undefined;
21
let proposals: ProposalsProvider;
22
let issues: IssuesProvider;
23
let review: ReviewController;
24
let bar: ChecksBar;
25
let content: ProposalContentProvider;
26
let inbox: InboxBar;
27
let references: ReferenceIndex;
28
let releases: ReleasesProvider;
29
30
export async function activate(context: vscode.ExtensionContext): Promise<void> {
31
  auth = new HubAuth(context.secrets);
32
  await auth.load();
33
  context.subscriptions.push(auth);
34
35
  const ext = vscode.extensions.getExtension<OxygenAPI>("oxygen.oxygen-vscode");
36
  oxygen = ext ? ((await ext.activate()) as OxygenAPI | undefined) : undefined;
37
  if (!oxygen) {
38
    void vscode.window.showWarningMessage("Oxygenhub: the Oxygen extension is not available; install oxygen.oxygen-vscode 0.7.0 or later.");
39
  } else {
40
    context.subscriptions.push(oxygen.registerRemoteProvider(makeProvider({ bases: () => auth.bases() })));
41
    context.subscriptions.push(oxygen.onDidChangeRepositories(() => refreshAll()));
42
  }
43
44
  proposals = new ProposalsProvider(() => oxygen, auth);
45
  issues = new IssuesProvider(() => proposals.repos(), auth);
46
  review = new ReviewController(auth);
47
  bar = new ChecksBar(auth, () => proposals.repos());
48
  inbox = new InboxBar(auth, async (t) => {
49
    const repo = (await proposals.repos()).find((r) => r.base === t.base && r.owner === t.owner && r.name === t.name);
50
    if (!repo) {
51
      return false;
52
    }
53
    const client = auth.clientFor(repo.base);
54
    if (t.kind === "proposal") {
55
      const [p, checks] = await Promise.all([client.proposal(repo.owner, repo.name, t.number), client.proposalChecks(repo.owner, repo.name, t.number).catch(() => [])]);
56
      showDetail(repo, p, checks);
57
    } else {
58
      await showIssue(auth, repo, await client.issue(repo.owner, repo.name, t.number));
59
    }
60
    return true;
61
  });
62
  context.subscriptions.push(inbox);
63
  releases = new ReleasesProvider(() => proposals.repos(), auth);
64
  context.subscriptions.push(vscode.window.registerTreeDataProvider("oxygenhub.releases", releases));
65
  references = new ReferenceIndex(auth, () => proposals.repos());
66
  context.subscriptions.push(
67
    vscode.languages.registerCompletionItemProvider(SELECTOR, new ReferenceCompletions(references), "#", "@"),
68
    vscode.languages.registerHoverProvider(SELECTOR, new ReferenceHovers(references)),
69
  );
70
  content = new ProposalContentProvider(auth);
71
  context.subscriptions.push(content, vscode.workspace.registerTextDocumentContentProvider(SCHEME, content));
72
  context.subscriptions.push(vscode.window.registerTreeDataProvider("oxygenhub.proposals", proposals), vscode.window.registerTreeDataProvider("oxygenhub.issues", issues), review, bar);
73
  context.subscriptions.push(auth.onDidChange(() => refreshAll()));
74
75
  context.subscriptions.push(
76
    vscode.commands.registerCommand("oxygenhub.signIn", async () => {
77
      const repos = oxygen ? await guessHubs() : [];
78
      await auth.signIn(repos[0]);
79
      refreshAll();
80
    }),
81
    vscode.commands.registerCommand("oxygenhub.signOut", async () => {
82
      const pick = await vscode.window.showQuickPick(auth.all().map((s) => s.base), { placeHolder: "Sign out of" });
83
      if (pick) {
84
        await auth.removeSession(pick);
85
        refreshAll();
86
      }
87
    }),
88
    vscode.commands.registerCommand("oxygenhub.refresh", () => refreshAll()),
89
    vscode.commands.registerCommand("oxygenhub.inbox", () => inbox.show()),
90
    vscode.commands.registerCommand("oxygenhub.draftRelease", async (node?: { repo?: HubRepo }) => {
91
      const repos = await proposals.repos();
92
      const repo = node?.repo ?? (repos.length === 1 ? repos[0] : (await vscode.window.showQuickPick(repos.map((r) => ({ label: `${r.owner}/${r.name}`, r })), { placeHolder: "Repository" }))?.r);
93
      if (!repo) {
94
        return;
95
      }
96
      try {
97
        const r = await draftRelease(auth, repo);
98
        if (r) {
99
          releases.refresh();
100
          const open = await vscode.window.showInformationMessage(`Oxygenhub: released ${r.tag}.`, "Open on Hub");
101
          if (open) {
102
            void vscode.env.openExternal(vscode.Uri.parse(r.url));
103
          }
104
        }
105
      } catch (e) {
106
        void vscode.window.showErrorMessage(`Oxygenhub: ${(e as Error).message}`);
107
      }
108
    }),
109
    vscode.commands.registerCommand("oxygenhub.openProposal", async (node?: ProposalNode) => {
110
      const n = node ?? (await pickProposal());
111
      if (!n) {
112
        return;
113
      }
114
      const checks = await auth.clientFor(n.repo.base).proposalChecks(n.repo.owner, n.repo.name, n.p.number).catch(() => []);
115
      showDetail(n.repo, n.p, checks);
116
    }),
117
    vscode.commands.registerCommand("oxygenhub.openOnHub", (node?: ProposalNode | IssueNode) => {
118
      if (!node) {
119
        return;
120
      }
121
      const target = node.kind === "proposal" ? { kind: "proposal", number: node.p.number } : { kind: "issue", number: node.i.number };
122
      void vscode.env.openExternal(vscode.Uri.parse(hubUrl(node.repo.base, node.repo.owner, node.repo.name, target)));
123
    }),
124
    vscode.commands.registerCommand("oxygenhub.openProposalFile", async (node: ProposalFileNode) => {
125
      await openFileDiff(node.repo, node.p.number, node.f);
126
      await review.loadDiff(node.repo, node.p.number).catch(() => undefined);
127
    }),
128
    vscode.commands.registerCommand("oxygenhub.openProposalChanges", (...args: unknown[]) =>
129
      withProposal(args, async (repo, number) => {
130
        try {
131
          const client = auth.clientFor(repo.base);
132
          const [p, files] = await Promise.all([client.proposal(repo.owner, repo.name, number), client.proposalFiles(repo.owner, repo.name, number)]);
133
          await openAllChanges(repo, p, files);
134
          await review.loadDiff(repo, number);
135
        } catch (e) {
136
          void vscode.window.showErrorMessage(`Oxygenhub: ${(e as Error).message}`);
137
        }
138
      }),
139
    ),
140
    vscode.commands.registerCommand("oxygenhub.checkoutProposal", (...args: unknown[]) => withProposal(args, checkout)),
141
    vscode.commands.registerCommand("oxygenhub.review", (...args: unknown[]) => withProposal(args, reviewProposal)),
142
    vscode.commands.registerCommand("oxygenhub.sealApproval", (...args: unknown[]) => withProposal(args, (repo, number) => runInTerminal(repo, `oxy seal --proposal ${hubUrl(repo.base, repo.owner, repo.name, { kind: "proposal", number })}`))),
143
    vscode.commands.registerCommand("oxygenhub.land", (...args: unknown[]) => withProposal(args, (repo, number) => runInTerminal(repo, `oxy proposal land ${hubUrl(repo.base, repo.owner, repo.name, { kind: "proposal", number })}`))),
144
    vscode.commands.registerCommand("oxygenhub.closeProposal", (...args: unknown[]) =>
145
      withProposal(args, async (repo, number) => {
146
        void vscode.env.openExternal(vscode.Uri.parse(hubUrl(repo.base, repo.owner, repo.name, { kind: "proposal", number })));
147
      }),
148
    ),
149
    vscode.commands.registerCommand("oxygenhub.createProposal", () => createProposal()),
150
    vscode.commands.registerCommand("oxygenhub.newIssue", () => newIssue()),
151
    vscode.commands.registerCommand("oxygenhub.issueFromSelection", () => issueFromSelection()),
152
    vscode.commands.registerCommand("oxygenhub.openIssue", async (node?: IssueNode) => node && showIssue(auth, node.repo, node.i)),
153
    vscode.commands.registerCommand("oxygenhub.commentIssue", (...args: unknown[]) =>
154
      withIssue(args, async (repo, number) => {
155
        const body = await vscode.window.showInputBox({ prompt: `Comment on #${number}` });
156
        if (body) {
157
          await auth.clientFor(repo.base).commentIssue(repo.owner, repo.name, number, body);
158
          issues.refresh();
159
        }
160
      }),
161
    ),
162
    vscode.commands.registerCommand("oxygenhub.closeIssue", (...args: unknown[]) => withIssue(args, async (repo, number) => (await auth.clientFor(repo.base).setIssueState(repo.owner, repo.name, number, "closed"), issues.refresh()))),
163
    vscode.commands.registerCommand("oxygenhub.reopenIssue", (...args: unknown[]) => withIssue(args, async (repo, number) => (await auth.clientFor(repo.base).setIssueState(repo.owner, repo.name, number, "open"), issues.refresh()))),
164
    vscode.commands.registerCommand("oxygenhub.assignMe", (...args: unknown[]) =>
165
      withIssue(args, async (repo, number) => {
166
        void vscode.window.showInformationMessage(`Oxygenhub: assigning is on the hub for now: ${hubUrl(repo.base, repo.owner, repo.name, { kind: "issue", number })}`);
167
      }),
168
    ),
169
    vscode.commands.registerCommand("oxygenhub.reply", (reply: vscode.CommentReply) => review.reply(reply)),
170
    vscode.commands.registerCommand("oxygenhub.newThread", (reply: vscode.CommentReply) => review.reply(reply)),
171
    vscode.commands.registerCommand("oxygenhub.resolveThread", (thread: vscode.CommentThread) => {
172
      thread.state = thread.state === vscode.CommentThreadState.Resolved ? vscode.CommentThreadState.Unresolved : vscode.CommentThreadState.Resolved;
173
    }),
174
  );
175
  bar.start();
176
  inbox.start();
177
}
178
179
function refreshAll(): void {
180
  proposals.refresh();
181
  references.clear();
182
  refreshOpenDiffs();
183
  issues.refresh();
184
  releases.refresh();
185
  void bar.refresh();
186
  void inbox.refresh();
187
}
188
189
/** Reload the sides of open proposal diffs, which may have gained changes. */
190
function refreshOpenDiffs(): void {
191
  const seen = new Set<string>();
192
  for (const doc of vscode.workspace.textDocuments) {
193
    const r = refOf(doc.uri);
194
    const key = r && `${r.base}/${r.owner}/${r.name}#${r.number}`;
195
    if (r && key && !seen.has(key)) {
196
      seen.add(key);
197
      content.refresh(r.base, r.owner, r.name, r.number);
198
    }
199
  }
200
}
201
202
async function guessHubs(): Promise<string[]> {
203
  const out: string[] = [];
204
  for (const r of oxygen?.repositories ?? []) {
205
    for (const remote of await r.remotes().catch(() => [])) {
206
      const m = /^(https?:\/\/[^/]+)\/[^/]+\/[^/]+\/?$/.exec(remote.url);
207
      if (m && !out.includes(m[1])) {
208
        out.push(m[1]);
209
      }
210
    }
211
  }
212
  return out;
213
}
214
215
async function pickProposal(): Promise<ProposalNode | undefined> {
216
  const items: { label: string; description: string; node: ProposalNode }[] = [];
217
  for (const repo of await proposals.repos()) {
218
    for (const p of await proposals.proposalsOf(repo).catch(() => [])) {
219
      items.push({ label: `#${p.number} ${p.title}`, description: `${repo.owner}/${repo.name} · ${p.author} → ${p.target}`, node: { kind: "proposal", repo, p } });
220
    }
221
  }
222
  return (await vscode.window.showQuickPick(items, { placeHolder: "Proposal" }))?.node;
223
}
224
225
/** Commands take a tree node, or the webview's `[base, owner, name, number]`. */
226
async function withProposal(args: unknown[], f: (repo: HubRepo, number: number) => Promise<void>): Promise<void> {
227
  const a = args[0];
228
  if (a && typeof a === "object" && (a as ProposalNode).kind === "proposal") {
229
    const n = a as ProposalNode;
230
    return f(n.repo, n.p.number);
231
  }
232
  if (Array.isArray(a) && a.length === 4) {
233
    const [base, owner, name, number] = a as [string, string, string, number];
234
    const repo = (await proposals.repos()).find((r) => r.base === base && r.owner === owner && r.name === name);
235
    if (repo) {
236
      return f(repo, number);
237
    }
238
  }
239
  const n = await pickProposal();
240
  if (n) {
241
    return f(n.repo, n.p.number);
242
  }
243
}
244
245
async function withIssue(args: unknown[], f: (repo: HubRepo, number: number) => Promise<void>): Promise<void> {
246
  const a = args[0];
247
  if (a && typeof a === "object" && (a as IssueNode).kind === "issue") {
248
    const n = a as IssueNode;
249
    return f(n.repo, n.i.number);
250
  }
251
  if (Array.isArray(a) && a.length === 4) {
252
    const [base, owner, name, number] = a as [string, string, string, number];
253
    const repo = (await proposals.repos()).find((r) => r.base === base && r.owner === owner && r.name === name);
254
    if (repo) {
255
      return f(repo, number);
256
    }
257
  }
258
}
259
260
function runInTerminal(repo: HubRepo, command: string): Promise<void> {
261
  const t = vscode.window.createTerminal({ name: "Oxygenhub", cwd: repo.handle.root });
262
  t.show();
263
  t.sendText(command);
264
  return Promise.resolve();
265
}
266
267
/** Fetch the proposal's changes and switch to a local bookmark at its projected heads (spec §5). */
268
async function checkout(repo: HubRepo, number: number): Promise<void> {
269
  const p = await auth.clientFor(repo.base).proposal(repo.owner, repo.name, number);
270
  const prefix = vscode.workspace.getConfiguration("oxygenhub").get<string>("proposalBookmarkPrefix") ?? "proposal/";
271
  const bookmark = `${prefix}${number}`;
272
  try {
273
    await repo.handle.json(["fetch", repo.remote, "--json"]);
274
    const existing = repo.handle.bookmarks.some((b) => b.name === bookmark);
275
    if (!existing) {
276
      await repo.handle.json(["bookmark", "create", bookmark, ...p.projected_heads, "--json"]).catch(() => repo.handle.json(["bookmark", "create", bookmark, "--json"]));
277
    }
278
    await repo.handle.json(["bookmark", "set", bookmark, ...p.projected_heads, "--json"]).catch(() => undefined);
279
    await repo.handle.json(["bookmark", "switch", bookmark, "--json"]);
280
    await repo.handle.refresh();
281
    await review.load(repo, number);
282
    void vscode.window.showInformationMessage(`Oxygenhub: checked out #${number} as ${bookmark}; review threads are in place.`);
283
  } catch (e) {
284
    void vscode.window.showErrorMessage(`Oxygenhub: could not check out #${number}: ${(e as Error).message}`);
285
  }
286
}
287
288
async function reviewProposal(repo: HubRepo, number: number): Promise<void> {
289
  const verdict = await vscode.window.showQuickPick(
290
    [
291
      { label: "Comment", value: "comment" as const },
292
      { label: "Approve", value: "approve" as const, description: "then seal it with oxy so it counts" },
293
      { label: "Request changes", value: "changes" as const },
294
    ],
295
    { placeHolder: `Review #${number}` },
296
  );
297
  if (!verdict) {
298
    return;
299
  }
300
  const body = (await vscode.window.showInputBox({ prompt: "Summary (optional)" })) ?? "";
301
  try {
302
    await auth.clientFor(repo.base).review(repo.owner, repo.name, number, verdict.value, body);
303
  } catch (e) {
304
    void vscode.window.showErrorMessage(`Oxygenhub: ${(e as Error).message}`);
305
    return;
306
  }
307
  proposals.refresh();
308
  if (verdict.value === "approve") {
309
    const pick = await vscode.window.showInformationMessage("Approval recorded. Seal it with your key so it counts?", "Seal now");
310
    if (pick === "Seal now") {
311
      await runInTerminal(repo, `oxy seal --proposal ${hubUrl(repo.base, repo.owner, repo.name, { kind: "proposal", number })}`);
312
    }
313
  }
314
}
315
316
async function createProposal(): Promise<void> {
317
  const repos = await proposals.repos();
318
  const repo = repos.length === 1 ? repos[0] : (await vscode.window.showQuickPick(repos.map((r) => ({ label: `${r.owner}/${r.name}`, r })), { placeHolder: "Repository" }))?.r;
319
  if (!repo) {
320
    return;
321
  }
322
  const source = repo.handle.currentBookmark;
323
  if (!source) {
324
    void vscode.window.showWarningMessage("Oxygenhub: no current bookmark.");
325
    return;
326
  }
327
  const remoteBookmarks = await auth.clientFor(repo.base).bookmarks(repo.owner, repo.name).catch(() => []);
328
  const target = await vscode.window.showQuickPick(remoteBookmarks.filter((b) => b.name !== source).map((b) => b.name), { placeHolder: `Propose ${source} into…` });
329
  if (!target) {
330
    return;
331
  }
332
  const title = await vscode.window.showInputBox({ prompt: "Title", value: source });
333
  if (!title) {
334
    return;
335
  }
336
  try {
337
    await repo.handle.json(["push", repo.remote, "--bookmark", source, "--json"]).catch(() => undefined);
338
    const p = await auth.clientFor(repo.base).createProposal(repo.owner, repo.name, { title, body: "", target, source, draft: false });
339
    proposals.refresh();
340
    void vscode.env.openExternal(vscode.Uri.parse(p.url));
341
  } catch (e) {
342
    void vscode.window.showErrorMessage(`Oxygenhub: ${(e as Error).message}`);
343
  }
344
}
345
346
async function newIssue(): Promise<void> {
347
  const repos = await proposals.repos();
348
  const repo = repos.length === 1 ? repos[0] : (await vscode.window.showQuickPick(repos.map((r) => ({ label: `${r.owner}/${r.name}`, r })), { placeHolder: "Repository" }))?.r;
349
  if (!repo) {
350
    return;
351
  }
352
  const title = await vscode.window.showInputBox({ prompt: "Issue title" });
353
  if (!title) {
354
    return;
355
  }
356
  const body = (await vscode.window.showInputBox({ prompt: "Description (optional)" })) ?? "";
357
  try {
358
    const i = await auth.clientFor(repo.base).createIssue(repo.owner, repo.name, title, body);
359
    issues.refresh();
360
    void vscode.window.showInformationMessage(`Oxygenhub: opened #${i.number}.`);
361
  } catch (e) {
362
    void vscode.window.showErrorMessage(`Oxygenhub: ${(e as Error).message}`);
363
  }
364
}
365
366
/**
367
 * An issue from the editor (spec §8.1): the selection, or the current line,
368
 * quoted under a permalink to it on the hub. A TODO line suggests the title
369
 * and afterwards records the issue's number.
370
 */
371
async function issueFromSelection(): Promise<void> {
372
  const editor = vscode.window.activeTextEditor;
373
  if (!editor || editor.document.uri.scheme !== "file") {
374
    void vscode.window.showWarningMessage("Oxygenhub: open a file of the repository first.");
375
    return;
376
  }
377
  const doc = editor.document;
378
  const file = doc.uri.fsPath;
379
  const repo = (await proposals.repos()).filter((r) => file.startsWith(r.handle.root + "/") || file.startsWith(r.handle.root + "\\")).sort((a, b) => b.handle.root.length - a.handle.root.length)[0];
380
  if (!repo) {
381
    void vscode.window.showWarningMessage("Oxygenhub: this file is not in a repository with a hub remote.");
382
    return;
383
  }
384
  const sel = editor.selection;
385
  const startLine = sel.start.line;
386
  const endLine = sel.isEmpty ? sel.start.line : sel.end.character === 0 && sel.end.line > sel.start.line ? sel.end.line - 1 : sel.end.line;
387
  const code = doc.getText(new vscode.Range(startLine, 0, endLine, doc.lineAt(endLine).text.length));
388
  const todoLine = [...Array(endLine - startLine + 1).keys()].map((i) => startLine + i).find((l) => todoTitle(doc.lineAt(l).text) !== undefined);
389
  const title = await vscode.window.showInputBox({ prompt: "Issue title", value: todoLine !== undefined ? todoTitle(doc.lineAt(todoLine).text) : "" });
390
  if (!title) {
391
    return;
392
  }
393
  // Pin the link to the head when the bookmark has one; otherwise follow the bookmark.
394
  const bookmark = repo.handle.bookmarks.find((b) => b.name === repo.handle.currentBookmark);
395
  const pinned = bookmark?.heads.length === 1 && !doc.isDirty;
396
  const reference = pinned ? bookmark!.heads[0] : (repo.handle.currentBookmark ?? "main");
397
  const path = file.slice(repo.handle.root.length + 1).split("\\").join("/");
398
  const permalink = hubUrl(repo.base, repo.owner, repo.name, { kind: "file", reference, path, line: startLine + 1, endLine: endLine + 1 });
399
  const body = issueBody({ permalink, path, startLine: startLine + 1, endLine: endLine + 1, language: doc.languageId === "plaintext" ? "" : doc.languageId, code, pinned });
400
  try {
401
    const client = auth.clientFor(repo.base);
402
    const issue = await client.createIssue(repo.owner, repo.name, title, body);
403
    issues.refresh();
404
    references.clear();
405
    if (todoLine !== undefined) {
406
      const line = doc.lineAt(todoLine);
407
      const annotated = annotateTodo(line.text, issue.number);
408
      if (annotated !== line.text) {
409
        const pick = await vscode.window.showInformationMessage(`Oxygenhub: opened #${issue.number}. Record it in the TODO?`, "Add (#" + issue.number + ")");
410
        if (pick) {
411
          await editor.edit((e) => e.replace(line.range, annotated));
412
        }
413
      }
414
    }
415
    await showIssue(auth, repo, issue);
416
  } catch (e) {
417
    void vscode.window.showErrorMessage(`Oxygenhub: ${(e as Error).message}`);
418
  }
419
}
420
421
export function deactivate(): void {}