OXYGENHUB
# 0c26846a9a81 oxygen-vscode / src / extension.ts
65.8 KiB · last changed Stop the Source Control refresh loop; remotes carry their CA (0.13.0) 1 month ago source blame history raw
1
// Activation: find oxy, find repositories, wire the source control view,
2
// decorations, the content provider, and the commands (spec §3).
3
4
import * as vscode from "vscode";
5
import { OxygenAPI, RemoteProvider, RemoteTarget, RepositoryHandle, linkedLines, pickProvider, repositoryFor as rootFor, stateSpec } from "./api";
6
import { basename, join } from "node:path";
7
import { Oxy, OxyError, ShowInfo, findBinary } from "./oxy";
8
import { Repository, OxyResourceState, SubrepoState } from "./repository";
9
import { BisectProvider, TrustProvider } from "./panels";
10
import { OxyContentProvider, SCHEME, baseUri, oxyUri } from "./contentProvider";
11
import { OxyDecorationProvider } from "./decorations";
12
import { OperationItem, OperationsProvider, timeAgo } from "./operations";
13
import { BlameController } from "./blame";
14
import { HistoryPanel } from "./history";
15
import { MessageHistory, conflictMarkerLines, placeholder, signingLabel } from "./commitbox";
16
import { readFile, stat } from "node:fs/promises";
17
import { ConflictCodeLensProvider, acceptSides, keepCandidate, markResolved } from "./conflicts";
18
import { parsePlanQuery, parseResolveQuery, sameRemote } from "./handoff";
19
20
const MIN_VERSION = { format: 2, protocol: 1 };
21
22
let output: vscode.OutputChannel;
23
let oxy: Oxy;
24
let contentProvider: OxyContentProvider;
25
let decorations: OxyDecorationProvider;
26
let operations: OperationsProvider;
27
let blame: BlameController;
28
let conflictLenses: ConflictCodeLensProvider;
29
let bisectView: BisectProvider;
30
let trustView: TrustProvider;
31
const repositories = new Map<string, Repository>();
32
33
export async function activate(context: vscode.ExtensionContext): Promise<OxygenAPI | undefined> {
34
  extensionContext = context;
35
  output = vscode.window.createOutputChannel("Oxygen");
36
  context.subscriptions.push(output);
37
  output.appendLine(`Oxygen extension ${context.extension.packageJSON.version} activating; folders: ${(vscode.workspace.workspaceFolders ?? []).map((f) => f.uri.fsPath).join(", ") || "(none)"}`);
38
  oxy = new Oxy(findBinary(vscode.workspace.getConfiguration("oxygen").get<string>("path")), (line) => output.appendLine(line));
39
40
  try {
41
    const v = await oxy.version();
42
    output.appendLine(`oxy ${v.version} (format ${v.format}, protocol ${v.protocol}) at ${oxy.binary}`);
43
    if (v.format < MIN_VERSION.format || v.protocol < MIN_VERSION.protocol) {
44
      void vscode.window.showWarningMessage(`Oxygen: oxy ${v.version} is older than this extension supports.`);
45
    }
46
  } catch (e) {
47
    const pick = await vscode.window.showErrorMessage(`Oxygen: could not run oxy (${(e as Error).message}). Set "oxygen.path" or put oxy on your PATH.`, "Open Settings");
48
    if (pick === "Open Settings") {
49
      void vscode.commands.executeCommand("workbench.action.openSettings", "oxygen.path");
50
    }
51
    return;
52
  }
53
54
  contentProvider = new OxyContentProvider(oxy);
55
  context.subscriptions.push(vscode.workspace.registerTextDocumentContentProvider(SCHEME, contentProvider));
56
  decorations = new OxyDecorationProvider(() => [...repositories.values()]);
57
  context.subscriptions.push(decorations);
58
  operations = new OperationsProvider(() => [...repositories.values()]);
59
  context.subscriptions.push(vscode.window.registerTreeDataProvider("oxygen.operations", operations));
60
  blame = new BlameController(() => [...repositories.values()]);
61
  context.subscriptions.push(blame);
62
  conflictLenses = new ConflictCodeLensProvider(() => [...repositories.values()]);
63
  context.subscriptions.push(vscode.languages.registerCodeLensProvider({ scheme: "file" }, conflictLenses));
64
  bisectView = new BisectProvider(() => [...repositories.values()]);
65
  trustView = new TrustProvider(() => [...repositories.values()]);
66
  context.subscriptions.push(vscode.window.registerTreeDataProvider("oxygen.bisect", bisectView), vscode.window.registerTreeDataProvider("oxygen.trust", trustView));
67
68
  context.subscriptions.push(
69
    vscode.commands.registerCommand("oxygen.refresh", async () => {
70
      await Promise.all([...repositories.values()].map((r) => r.refresh()));
71
    }),
72
    vscode.commands.registerCommand("oxygen.showOutput", () => output.show()),
73
    vscode.commands.registerCommand("oxygen.openOnRemote", (arg?: Repository | vscode.SourceControl | LinkArg) =>
74
      openOnRemote(undefined, arg instanceof Repository ? arg : undefined, "open", arg instanceof Repository || isSourceControl(arg) ? undefined : (arg as LinkArg)),
75
    ),
76
    vscode.commands.registerCommand("oxygen.copyRemoteLink", (arg?: LinkArg) => openOnRemote(undefined, undefined, "copy", arg)),
77
    vscode.commands.registerCommand("oxygen.copyPermalink", (arg?: LinkArg) => openOnRemote(undefined, undefined, "permalink", arg)),
78
    vscode.commands.registerCommand("oxygen.openChangeOnRemote", (root: string, hash: string) => openOnRemote({ kind: "change", hash }, repositories.get(root))),
79
    vscode.commands.registerCommand("oxygen.openFile", (state?: OxyResourceState) => state && vscode.commands.executeCommand("vscode.open", state.resourceUri)),
80
    vscode.commands.registerCommand("oxygen.openChanges", (state?: OxyResourceState) => state && openChanges(state)),
81
    vscode.commands.registerCommand("oxygen.openBaseVersion", (state?: OxyResourceState) => state && vscode.commands.executeCommand("vscode.open", baseUri(state.repository.root, state.path))),
82
    vscode.commands.registerCommand("oxygen.commit", (arg?: Repository | vscode.SourceControl) => commit(arg)),
83
    vscode.commands.registerCommand("oxygen.showLog", () => showLog()),
84
    vscode.commands.registerCommand("oxygen.init", () => initRepository()),
85
    vscode.commands.registerCommand("oxygen.discard", (state?: OxyResourceState, states?: OxyResourceState[]) => discard(states?.length ? states : state ? [state] : [])),
86
    vscode.commands.registerCommand("oxygen.commitSelected", (state?: OxyResourceState, states?: OxyResourceState[]) => commitSelected(states?.length ? states : state ? [state] : [])),
87
    vscode.commands.registerCommand("oxygen.commitHunks", (arg?: Repository | vscode.SourceControl) => commitHunks(arg)),
88
    vscode.commands.registerCommand("oxygen.amend", (arg?: Repository | vscode.SourceControl) => amend(arg)),
89
    vscode.commands.registerCommand("oxygen.history.split", (ctx?: { root?: string; hash?: string }) => historyContext(ctx, "split")),
90
    vscode.commands.registerCommand("oxygen.history.squash", (ctx?: { root?: string; hash?: string }) => historyContext(ctx, "squash")),
91
    vscode.commands.registerCommand("oxygen.history.rebase", (ctx?: { root?: string; hash?: string }) => historyContext(ctx, "rebase")),
92
    vscode.commands.registerCommand("oxygen.amendMode", (arg?: Repository | vscode.SourceControl) => toggleAmend(arg, true)),
93
    vscode.commands.registerCommand("oxygen.leaveAmendMode", (arg?: Repository | vscode.SourceControl) => toggleAmend(arg, false)),
94
    vscode.commands.registerCommand("oxygen.messageHistory", (arg?: Repository | vscode.SourceControl) => messageHistory(arg)),
95
    vscode.commands.registerCommand("oxygen.undo", (arg?: Repository | vscode.SourceControl) => undo(arg, 1)),
96
    vscode.commands.registerCommand("oxygen.undoTo", (item?: OperationItem) => item && undo(item.repository, item.stepsBack)),
97
    vscode.commands.registerCommand("oxygen.refreshOperations", () => operations.refresh()),
98
    vscode.commands.registerCommand("oxygen.switchBookmark", (arg?: Repository | vscode.SourceControl) => switchBookmark(arg)),
99
    vscode.commands.registerCommand("oxygen.createBookmark", (arg?: Repository | vscode.SourceControl) => createBookmark(arg)),
100
    vscode.commands.registerCommand("oxygen.mergeBookmark", (arg?: Repository | vscode.SourceControl) => mergeBookmark(arg)),
101
    vscode.commands.registerCommand("oxygen.deleteBookmark", (arg?: Repository | vscode.SourceControl) => deleteBookmark(arg)),
102
    vscode.commands.registerCommand("oxygen.fetch", (arg?: Repository | vscode.SourceControl) => fetch(arg)),
103
    vscode.commands.registerCommand("oxygen.pull", (arg?: Repository | vscode.SourceControl) => pull(arg)),
104
    vscode.commands.registerCommand("oxygen.push", (arg?: Repository | vscode.SourceControl) => push(arg, false)),
105
    vscode.commands.registerCommand("oxygen.pushBookmark", (arg?: Repository | vscode.SourceControl) => push(arg, true)),
106
    vscode.commands.registerCommand("oxygen.sync", (arg?: Repository | vscode.SourceControl) => sync(arg)),
107
    vscode.commands.registerCommand("oxygen.showHistory", (arg?: Repository | vscode.SourceControl) => {
108
      const repo = repositoryFor(arg);
109
      if (repo) {
110
        HistoryPanel.show(repo, (hash) => void showChange(repo.root, hash));
111
      }
112
    }),
113
    vscode.commands.registerCommand("oxygen.fileHistory", (uri?: vscode.Uri) => fileHistory(uri ?? vscode.window.activeTextEditor?.document.uri)),
114
    vscode.commands.registerCommand("oxygen.toggleBlame", () => blame.toggle()),
115
    vscode.commands.registerCommand("oxygen.showChange", (root?: string, hash?: string) => root && hash && showChange(root, hash)),
116
    vscode.commands.registerCommand("oxygen.acceptSides", (uri: vscode.Uri, index: number, keep: number[]) => acceptSides(uri, index, keep).catch(showError)),
117
    vscode.commands.registerCommand("oxygen.keepCandidate", (state?: OxyResourceState) => state && keepCandidate(state.repository, state.path).catch(showError)),
118
    vscode.commands.registerCommand("oxygen.markResolved", (arg?: Repository | vscode.SourceControl) => {
119
      const repo = repositoryFor(arg);
120
      return repo && markResolved(repo).catch(showError);
121
    }),
122
    vscode.commands.registerCommand("oxygen.openConflict", (state?: OxyResourceState) => state && vscode.commands.executeCommand("vscode.open", state.resourceUri)),
123
    vscode.commands.registerCommand("oxygen.openSubrepo", (state?: SubrepoState) => state && openSubrepo(state)),
124
    vscode.commands.registerCommand("oxygen.updateSubrepo", (state?: SubrepoState) => state && updateSubrepos(state.repository, true, [state.info.path])),
125
    vscode.commands.registerCommand("oxygen.updateSubrepos", (arg?: Repository | vscode.SourceControl) => {
126
      const repo = repositoryFor(arg);
127
      return repo && updateSubrepos(repo, true, []);
128
    }),
129
    vscode.commands.registerCommand("oxygen.bisectStart", (arg?: Repository) => bisect(arg, (r) => r.oxy.bisectStart(r.root).then(() => "Started; mark a good and a bad change"))),
130
    vscode.commands.registerCommand("oxygen.bisectGood", (arg?: Repository, changes?: string[]) => bisectMark(arg, "good", changes)),
131
    vscode.commands.registerCommand("oxygen.bisectBad", (arg?: Repository, changes?: string[]) => bisectMark(arg, "bad", changes)),
132
    vscode.commands.registerCommand("oxygen.bisectSkip", (arg?: Repository) => bisect(arg, (r) => r.oxy.bisectMark(r.root, "skip"))),
133
    vscode.commands.registerCommand("oxygen.bisectRun", (arg?: Repository) => bisectRun(arg)),
134
    vscode.commands.registerCommand("oxygen.bisectReset", (arg?: Repository) => bisect(arg, (r) => r.oxy.bisectReset(r.root).then(() => "Bisect reset; working copy restored"))),
135
    vscode.commands.registerCommand("oxygen.refreshBisect", () => bisectView.refresh()),
136
    vscode.commands.registerCommand("oxygen.refreshTrust", () => trustView.refresh()),
137
    vscode.commands.registerCommand("oxygen.verify", (arg?: Repository | vscode.SourceControl) => verify(arg)),
138
    vscode.commands.registerCommand("oxygen.tags", (arg?: Repository | vscode.SourceControl) => tags(arg)),
139
    vscode.commands.registerCommand("oxygen.createTag", (arg?: Repository | vscode.SourceControl) => createTag(arg)),
140
    vscode.commands.registerCommand("oxygen.addWorkspace", (arg?: Repository | vscode.SourceControl) => addWorkspace(arg)),
141
    vscode.commands.registerCommand("oxygen.clone", () => cloneRepository()),
142
    vscode.window.registerUriHandler({ handleUri: (uri) => handleUri(uri) }),
143
    vscode.workspace.onDidChangeWorkspaceFolders(() => void discover()),
144
    vscode.workspace.onDidChangeConfiguration((e) => {
145
      if (e.affectsConfiguration("oxygen.path")) {
146
        void vscode.window.showInformationMessage("Oxygen: reload the window to use the new oxy path.");
147
      }
148
      if (e.affectsConfiguration("oxygen")) {
149
        decorations.refresh();
150
        for (const r of repositories.values()) {
151
          r.scheduleRefresh();
152
        }
153
      }
154
    }),
155
  );
156
  context.subscriptions.push({ dispose: () => repositories.forEach((r) => r.dispose()) });
157
158
  await discover();
159
  return buildApi();
160
}
161
162
163
// ---------------------------------------------------------------- exported API
164
165
const remoteProviders: RemoteProvider[] = [];
166
const onDidChangeRepositoriesEmitter = new vscode.EventEmitter<void>();
167
const onDidChangeStatusEmitter = new vscode.EventEmitter<RepositoryHandle>();
168
169
function handleOf(repo: Repository): RepositoryHandle {
170
  return {
171
    root: repo.root,
172
    get status() {
173
      return repo.status;
174
    },
175
    get bookmarks() {
176
      return repo.bookmarks.map((b) => ({ name: b.name, heads: b.heads, current: b.current }));
177
    },
178
    get currentBookmark() {
179
      return repo.currentBookmark?.name;
180
    },
181
    remotes: async () => (await repo.oxy.remotes(repo.root)).map((r) => ({ name: r.name, url: r.url, ca: r.ca ?? undefined })),
182
    json: <T>(args: string[]) => repo.oxy.json<T>(repo.root, args),
183
    refresh: () => repo.refresh(),
184
  };
185
}
186
187
function buildApi(): OxygenAPI {
188
  return {
189
    version: 1,
190
    get repositories() {
191
      return [...repositories.values()].map(handleOf);
192
    },
193
    onDidChangeStatus: (listener) => onDidChangeStatusEmitter.event(listener),
194
    onDidChangeRepositories: (listener) => onDidChangeRepositoriesEmitter.event(listener),
195
    getRepository: (fsPath) => {
196
      const root = rootFor([...repositories.keys()], fsPath);
197
      const repo = root ? repositories.get(root) : undefined;
198
      return repo ? handleOf(repo) : undefined;
199
    },
200
    registerRemoteProvider: (provider) => {
201
      remoteProviders.push(provider);
202
      void vscode.commands.executeCommand("setContext", "oxygen.hasRemoteProvider", true);
203
      return {
204
        dispose: () => {
205
          const i = remoteProviders.indexOf(provider);
206
          if (i >= 0) {
207
            remoteProviders.splice(i, 1);
208
          }
209
          void vscode.commands.executeCommand("setContext", "oxygen.hasRemoteProvider", remoteProviders.length > 0);
210
        },
211
      };
212
    },
213
    remoteProviders: () => [...remoteProviders],
214
  };
215
}
216
217
/** What a remote-link command does with the URL. */
218
type LinkMode = "open" | "copy" | "permalink";
219
220
/** The editor gutter passes `{ lineNumber, uri }`; an editor title menu passes the file's Uri. */
221
type LinkArg = { lineNumber?: number; uri?: vscode.Uri } | vscode.Uri | undefined;
222
223
/**
224
 * Open or copy a link to the current repository, file or change on
225
 * whichever provider knows its remote. For a file, the lines are the
226
 * gutter's clicked line or the selection; `permalink` pins the link to the
227
 * bookmark's current state (its heads), so it keeps pointing at these lines.
228
 */
229
async function openOnRemote(target?: RemoteTarget, repoArg?: Repository, mode: LinkMode = "open", arg?: LinkArg): Promise<void> {
230
  const argUri = arg instanceof vscode.Uri ? arg : arg?.uri;
231
  const clicked = arg && !(arg instanceof vscode.Uri) ? arg.lineNumber : undefined;
232
  const editor = vscode.window.activeTextEditor;
233
  const docUri = argUri ?? editor?.document.uri;
234
  const repo = repoArg ?? (docUri ? repositoryFor2(docUri) : undefined) ?? [...repositories.values()][0];
235
  if (!repo) {
236
    void vscode.window.showInformationMessage("Oxygen: no repository is open.");
237
    return;
238
  }
239
  const remotes = (await repo.oxy.remotes(repo.root)).map((r) => ({ name: r.name, url: r.url }));
240
  const pick = pickProvider(remoteProviders, remotes);
241
  if (!pick) {
242
    void vscode.window.showInformationMessage("Oxygen: no extension knows this repository's remotes. Install a forge extension such as OxygenHub.");
243
    return;
244
  }
245
  let t: RemoteTarget = target ?? { kind: "repository" };
246
  let note = "";
247
  if (!target && docUri) {
248
    const rel = repo.relativePath(docUri);
249
    if (rel) {
250
      const bookmark = repo.currentBookmark;
251
      let reference = bookmark?.name ?? "main";
252
      if (mode === "permalink") {
253
        const spec = stateSpec(bookmark?.heads ?? []);
254
        if (!spec) {
255
          void vscode.window.showInformationMessage("Oxygen: this bookmark has no committed state to link to yet.");
256
          return;
257
        }
258
        reference = spec;
259
      }
260
      const sameDoc = editor && editor.document.uri.toString() === docUri.toString();
261
      const sel = sameDoc
262
        ? { start: editor.selection.start.line + 1, end: editor.selection.end.line + 1, endColumn: editor.selection.end.character, empty: editor.selection.isEmpty }
263
        : { start: clicked ?? 1, end: clicked ?? 1, endColumn: 0, empty: true };
264
      const lines = clicked !== undefined || sameDoc ? linkedLines(clicked, sel) : {};
265
      t = { kind: "file", reference, path: rel, ...lines };
266
      // Lines are counted in the editor; say so when they may not match the remote.
267
      const edited = repo.status?.paths.some((p) => p.path === rel);
268
      if (edited || (sameDoc && editor.document.isDirty)) {
269
        note = " The file has uncommitted edits, so the lines may differ from the remote's.";
270
      } else if (mode !== "permalink" && bookmark && bookmark.ahead !== null && bookmark.ahead > 0) {
271
        note = ` ${bookmark.name} has unpushed changes; the remote may not show them yet.`;
272
      }
273
    }
274
  }
275
  const url = pick.provider.urlFor(pick.remote.url, t);
276
  if (!url) {
277
    return;
278
  }
279
  if (mode === "open") {
280
    await vscode.env.openExternal(vscode.Uri.parse(url));
281
    if (note) {
282
      void vscode.window.showInformationMessage(`Oxygen:${note}`);
283
    }
284
    return;
285
  }
286
  await vscode.env.clipboard.writeText(url);
287
  const what = mode === "permalink" ? "Permalink" : "Link";
288
  if (note) {
289
    void vscode.window.showWarningMessage(`Oxygen: ${what} copied.${note}`);
290
  } else {
291
    vscode.window.setStatusBarMessage(`$(link) ${what} copied`, 4000);
292
  }
293
}
294
295
function isSourceControl(arg: unknown): arg is vscode.SourceControl {
296
  return typeof arg === "object" && arg !== null && "inputBox" in arg && "rootUri" in arg;
297
}
298
299
function repositoryFor2(uri: vscode.Uri): Repository | undefined {
300
  const root = rootFor([...repositories.keys()], uri.fsPath);
301
  return root ? repositories.get(root) : undefined;
302
}
303
304
export function deactivate(): void {
305
  for (const r of repositories.values()) {
306
    r.dispose();
307
  }
308
  repositories.clear();
309
}
310
311
/** One Repository per distinct oxy root among the workspace folders. */
312
async function discover(): Promise<void> {
313
  const wanted = new Map<string, vscode.WorkspaceFolder>();
314
  for (const folder of vscode.workspace.workspaceFolders ?? []) {
315
    const info = await oxy.root(folder.uri.fsPath);
316
    if (info) {
317
      wanted.set(info.root, folder);
318
    }
319
  }
320
  for (const [root, repo] of repositories) {
321
    if (!wanted.has(root)) {
322
      repo.dispose();
323
      repositories.delete(root);
324
      onDidChangeRepositoriesEmitter.fire();
325
    }
326
  }
327
  if (wanted.size === 0 && (vscode.workspace.workspaceFolders ?? []).length > 0) {
328
    output.appendLine("no Oxygen repository in the open folders (oxy root found none)");
329
  }
330
  for (const [root, folder] of wanted) {
331
    if (!repositories.has(root)) {
332
      const repo = new Repository(oxy, root, folder);
333
      repo.onDidChangeStatus((status) => {
334
        decorations.refresh();
335
        contentProvider.invalidate(root);
336
        operations.refresh();
337
        blame.invalidate(root);
338
        HistoryPanel.refresh(root);
339
        conflictLenses.refresh();
340
        bisectView.refresh();
341
        trustView.refresh();
342
        // The commit action reads as a resolution while conflicts are resolved but uncommitted.
343
        box(repo).resolution = status.conflicted && status.conflicts.length > 0 && status.conflicts.every((c) => c.resolved === true);
344
        void refreshSigning(repo);
345
        updateBox(repo);
346
      });
347
      repositories.set(root, repo);
348
      repo.onDidChangeStatus(() => onDidChangeStatusEmitter.fire(handleOf(repo)));
349
      onDidChangeRepositoriesEmitter.fire();
350
      output.appendLine(`repository ${root}`);
351
      await repo.refresh();
352
    }
353
  }
354
  void vscode.commands.executeCommand("setContext", "oxygen.hasRepository", repositories.size > 0);
355
}
356
357
function repositoryFor(arg: Repository | vscode.SourceControl | undefined): Repository | undefined {
358
  if (arg instanceof Repository) {
359
    return arg;
360
  }
361
  if (arg && "rootUri" in arg && arg.rootUri) {
362
    return repositories.get(arg.rootUri.fsPath);
363
  }
364
  const active = vscode.window.activeTextEditor?.document.uri;
365
  for (const repo of repositories.values()) {
366
    if (active && repo.relativePath(active) !== undefined) {
367
      return repo;
368
    }
369
  }
370
  return repositories.size === 1 ? [...repositories.values()][0] : undefined;
371
}
372
373
async function openChanges(state: OxyResourceState): Promise<void> {
374
  const repo = state.repository;
375
  const title = `${basename(state.path)} (base ↔ working copy)`;
376
  if (state.status === "Added") {
377
    await vscode.commands.executeCommand("vscode.open", state.resourceUri);
378
    return;
379
  }
380
  if (state.status === "Removed") {
381
    await vscode.commands.executeCommand("vscode.open", baseUri(repo.root, state.path));
382
    return;
383
  }
384
  await vscode.commands.executeCommand("vscode.diff", baseUri(repo.root, state.path), state.resourceUri, title);
385
}
386
387
async function commit(arg: Repository | vscode.SourceControl | undefined): Promise<void> {
388
  const repo = repositoryFor(arg);
389
  if (!repo) {
390
    void vscode.window.showErrorMessage("Oxygen: no repository for the active file.");
391
    return;
392
  }
393
  if (box(repo).amend) {
394
    await amend(repo);
395
    return;
396
  }
397
  let message = repo.sourceControl.inputBox.value.trim();
398
  if (!message) {
399
    message = (await vscode.window.showInputBox({ prompt: "Commit message", placeHolder: "What did you change?" }))?.trim() ?? "";
400
  }
401
  if (!message) {
402
    return;
403
  }
404
  if (!(await markersOk(repo))) {
405
    return;
406
  }
407
  try {
408
    await vscode.window.withProgress({ location: vscode.ProgressLocation.SourceControl, title: "Committing" }, () => repo.oxy.commit(repo.root, message));
409
    remember(repo, message);
410
    repo.sourceControl.inputBox.value = "";
411
    await repo.refresh();
412
  } catch (e) {
413
    showError(e);
414
  }
415
}
416
417
async function initRepository(): Promise<void> {
418
  const folders = vscode.workspace.workspaceFolders ?? [];
419
  if (folders.length === 0) {
420
    void vscode.window.showErrorMessage("Oxygen: open a folder first.");
421
    return;
422
  }
423
  const folder = folders.length === 1 ? folders[0] : await vscode.window.showWorkspaceFolderPick({ placeHolder: "Folder to initialize as an Oxygen repository" });
424
  if (!folder) {
425
    return;
426
  }
427
  try {
428
    await oxy.check(folder.uri.fsPath, ["init"]);
429
    await discover();
430
    void vscode.window.showInformationMessage(`Oxygen: initialized ${folder.name}.`);
431
  } catch (e) {
432
    showError(e);
433
  }
434
}
435
436
async function discard(states: OxyResourceState[]): Promise<void> {
437
  if (states.length === 0) {
438
    return;
439
  }
440
  const repo = states[0].repository;
441
  const names = states.length === 1 ? basename(states[0].path) : `${states.length} files`;
442
  const pick = await vscode.window.showWarningMessage(`Discard changes in ${names}? This cannot be undone with oxy undo.`, { modal: true }, "Discard");
443
  if (pick !== "Discard") {
444
    return;
445
  }
446
  try {
447
    await repo.oxy.discard(repo.root, states.map((s) => s.path));
448
    await repo.refresh();
449
  } catch (e) {
450
    showError(e);
451
  }
452
}
453
454
async function commitSelected(states: OxyResourceState[]): Promise<void> {
455
  if (states.length === 0) {
456
    return;
457
  }
458
  const repo = states[0].repository;
459
  const message = await askMessage(repo, `Commit ${states.length === 1 ? basename(states[0].path) : `${states.length} files`}`);
460
  if (!message) {
461
    return;
462
  }
463
  if (!(await markersOk(repo, states.map((s) => s.path)))) {
464
    return;
465
  }
466
  try {
467
    await vscode.window.withProgress({ location: vscode.ProgressLocation.SourceControl, title: "Committing" }, () => repo.oxy.commit(repo.root, message, states.map((s) => s.path)));
468
    remember(repo, message);
469
    repo.sourceControl.inputBox.value = "";
470
    await repo.refresh();
471
  } catch (e) {
472
    showError(e);
473
  }
474
}
475
476
async function commitHunks(arg: Repository | vscode.SourceControl | undefined): Promise<void> {
477
  const repo = repositoryFor(arg);
478
  if (!repo) {
479
    return;
480
  }
481
  let hunks;
482
  try {
483
    hunks = await repo.oxy.hunks(repo.root);
484
  } catch (e) {
485
    showError(e);
486
    return;
487
  }
488
  if (hunks.length === 0) {
489
    void vscode.window.showInformationMessage("Oxygen: nothing to commit.");
490
    return;
491
  }
492
  const picks = await vscode.window.showQuickPick(
493
    hunks.map((h) => ({
494
      label: `$(diff) ${h.path}`,
495
      description: `#${h.index}`,
496
      detail: h.text.split("\n").filter((l) => l.startsWith("+") || l.startsWith("-") || l.startsWith("A ") || l.startsWith("D ") || l.startsWith("R ")).slice(0, 3).join("  ").slice(0, 160),
497
      hunk: h,
498
      picked: false,
499
    })),
500
    { canPickMany: true, placeHolder: "Choose the hunks to commit; anything a chosen hunk needs comes along" },
501
  );
502
  if (!picks || picks.length === 0) {
503
    return;
504
  }
505
  const message = await askMessage(repo, `Commit ${picks.length} hunk${picks.length === 1 ? "" : "s"}`);
506
  if (!message) {
507
    return;
508
  }
509
  try {
510
    await repo.oxy.commitHunks(repo.root, message, picks.map((p) => p.hunk.index));
511
    remember(repo, message);
512
    repo.sourceControl.inputBox.value = "";
513
    await repo.refresh();
514
  } catch (e) {
515
    showError(e);
516
  }
517
}
518
519
async function amend(arg: Repository | vscode.SourceControl | undefined): Promise<void> {
520
  const repo = repositoryFor(arg);
521
  if (!repo) {
522
    return;
523
  }
524
  const message = repo.sourceControl.inputBox.value.trim();
525
  if (!(await markersOk(repo))) {
526
    return;
527
  }
528
  try {
529
    await vscode.window.withProgress({ location: vscode.ProgressLocation.SourceControl, title: "Amending" }, () => repo.oxy.amend(repo.root, message || undefined));
530
    remember(repo, message);
531
    repo.sourceControl.inputBox.value = "";
532
    setAmend(repo, false);
533
    await repo.refresh();
534
  } catch (e) {
535
    showError(e);
536
  }
537
}
538
539
async function undo(arg: Repository | vscode.SourceControl | undefined, steps: number): Promise<void> {
540
  const repo = repositoryFor(arg);
541
  if (!repo || steps <= 0) {
542
    return;
543
  }
544
  if (steps > 1) {
545
    const pick = await vscode.window.showWarningMessage(`Undo the last ${steps} operations?`, { modal: true }, "Undo");
546
    if (pick !== "Undo") {
547
      return;
548
    }
549
  }
550
  try {
551
    let last = "";
552
    for (let i = 0; i < steps; i++) {
553
      last = await repo.oxy.undo(repo.root);
554
    }
555
    await repo.refresh();
556
    vscode.window.setStatusBarMessage(`$(discard) ${last || "Undone"}`, 4000);
557
  } catch (e) {
558
    showError(e);
559
  }
560
}
561
562
// ---------------------------------------------------------------- subrepos, bisect, trust, tags, workspaces, clone
563
564
async function openSubrepo(state: SubrepoState): Promise<void> {
565
  if (!state.info.actual) {
566
    const pick = await vscode.window.showInformationMessage(`${state.info.path} is not checked out yet.`, "Update --init");
567
    if (pick) {
568
      await updateSubrepos(state.repository, true, [state.info.path]);
569
    }
570
    return;
571
  }
572
  const pick = await vscode.window.showQuickPick(
573
    [
574
      { label: "$(folder-opened) Open in new window", action: "window" },
575
      { label: "$(cloud-download) Update to the pin", action: "update", description: state.info.at_pin ? "already at pin" : "moves the nested repository" },
576
    ],
577
    { placeHolder: `${state.info.path} · ${state.decorations.tooltip}` },
578
  );
579
  if (pick?.action === "window") {
580
    await vscode.commands.executeCommand("vscode.openFolder", state.resourceUri, { forceNewWindow: true });
581
  } else if (pick?.action === "update") {
582
    await updateSubrepos(state.repository, true, [state.info.path]);
583
  }
584
}
585
586
async function updateSubrepos(repo: Repository, init: boolean, paths: string[]): Promise<void> {
587
  try {
588
    const out = await vscode.window.withProgress({ location: vscode.ProgressLocation.SourceControl, title: "Updating subrepos" }, () => repo.oxy.submoduleUpdate(repo.root, init, paths));
589
    await repo.refresh();
590
    const lines = out.trim().split("\n").filter(Boolean);
591
    if (lines.some((l) => /missing|uncommitted|✖|x /.test(l))) {
592
      void vscode.window.showWarningMessage(`Oxygen: ${lines.join("; ")}`);
593
    } else {
594
      vscode.window.setStatusBarMessage(`$(check) ${lines.join("; ") || "Subrepos up to date"}`, 5000);
595
    }
596
  } catch (e) {
597
    showError(e);
598
  }
599
}
600
601
async function bisect(arg: Repository | undefined, run: (repo: Repository) => Promise<string>): Promise<void> {
602
  const repo = arg instanceof Repository ? arg : repositoryFor(undefined);
603
  if (!repo) {
604
    return;
605
  }
606
  try {
607
    const out = await run(repo);
608
    await repo.refresh();
609
    vscode.window.setStatusBarMessage(`$(search) ${out.split("\n")[0]}`, 5000);
610
  } catch (e) {
611
    showError(e);
612
  }
613
}
614
615
async function bisectMark(arg: Repository | undefined, verdict: "good" | "bad", changes?: string[]): Promise<void> {
616
  const repo = arg instanceof Repository ? arg : repositoryFor(undefined);
617
  if (!repo) {
618
    return;
619
  }
620
  let picked = changes;
621
  if (picked === undefined) {
622
    const status = await repo.oxy.bisectStatus(repo.root).catch(() => null);
623
    if (!status || status.state === "need-marks") {
624
      const value = await vscode.window.showInputBox({ prompt: `A change, bookmark or tag known to be ${verdict}`, placeHolder: verdict === "good" ? "v1.2 or a ChangeId prefix" : "main" });
625
      if (!value?.trim()) {
626
        return;
627
      }
628
      picked = value.trim().split(/\s+/);
629
    } else {
630
      picked = [];
631
    }
632
  }
633
  await bisect(repo, (r) => r.oxy.bisectMark(r.root, verdict, picked));
634
}
635
636
async function bisectRun(arg: Repository | undefined): Promise<void> {
637
  const repo = arg instanceof Repository ? arg : repositoryFor(undefined);
638
  if (!repo) {
639
    return;
640
  }
641
  const value = await vscode.window.showInputBox({ prompt: "Command to run for each step (exit 0 good, 125 skip, anything else bad)", placeHolder: "make test" });
642
  if (!value?.trim()) {
643
    return;
644
  }
645
  await bisect(repo, (r) => Promise.resolve(vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: "Oxygen: bisecting", cancellable: false }, () => r.oxy.bisectRun(r.root, ["sh", "-c", value.trim()]))));
646
}
647
648
async function verify(arg: Repository | vscode.SourceControl | undefined): Promise<void> {
649
  const repo = repositoryFor(arg);
650
  if (!repo) {
651
    return;
652
  }
653
  try {
654
    const results = await repo.oxy.verify(repo.root);
655
    const icon = (s: string, revoked: boolean) => (s === "invalid" ? "$(error)" : s === "unsigned" ? "$(circle-outline)" : revoked ? "$(warning)" : "$(verified)");
656
    const pick = await vscode.window.showQuickPick(
657
      results.map((r) => ({
658
        label: `${icon(r.status, r.revoked)} ${r.change_id.slice(0, 8)} ${r.status}${r.revoked ? " (key revoked)" : ""}`,
659
        description: r.name ?? "",
660
        detail: r.reason ?? undefined,
661
        hash: r.hash,
662
      })),
663
      { placeHolder: `${results.length} changes; ${results.filter((r) => r.status === "invalid").length} invalid`, matchOnDescription: true },
664
    );
665
    if (pick) {
666
      await showChange(repo.root, pick.hash);
667
    }
668
  } catch (e) {
669
    showError(e);
670
  }
671
}
672
673
async function tags(arg: Repository | vscode.SourceControl | undefined): Promise<void> {
674
  const repo = repositoryFor(arg);
675
  if (!repo) {
676
    return;
677
  }
678
  try {
679
    const list = await repo.oxy.tags(repo.root);
680
    if (list.length === 0) {
681
      const pick = await vscode.window.showInformationMessage("Oxygen: no tags yet.", "Create tag");
682
      if (pick) {
683
        await createTag(repo);
684
      }
685
      return;
686
    }
687
    const pick = await vscode.window.showQuickPick(
688
      list.map((t) => ({ label: `$(tag) ${t.name}`, description: `${t.heads.length} head${t.heads.length === 1 ? "" : "s"}${t.signer ? ` · signed by ${t.signer}` : ""}`, detail: t.message || undefined, tag: t })),
689
      { placeHolder: "Check out a tag's state" },
690
    );
691
    if (!pick) {
692
      return;
693
    }
694
    await repo.oxy.checkout(repo.root, [pick.tag.name]);
695
    await repo.refresh();
696
  } catch (e) {
697
    if (e instanceof OxyError && e.message.includes("has changes")) {
698
      void vscode.window.showWarningMessage("Oxygen: commit or discard your changes before checking out a tag.");
699
      return;
700
    }
701
    showError(e);
702
  }
703
}
704
705
async function createTag(arg: Repository | vscode.SourceControl | undefined): Promise<void> {
706
  const repo = repositoryFor(arg);
707
  if (!repo) {
708
    return;
709
  }
710
  const name = await vscode.window.showInputBox({ prompt: "Tag name (tags the current bookmark's heads)" });
711
  if (!name?.trim()) {
712
    return;
713
  }
714
  const message = (await vscode.window.showInputBox({ prompt: "Tag message (optional)" })) ?? "";
715
  try {
716
    await repo.oxy.tagCreate(repo.root, name.trim(), [], message);
717
    await repo.refresh();
718
    vscode.window.setStatusBarMessage(`$(tag) Tagged ${name.trim()}`, 4000);
719
  } catch (e) {
720
    showError(e);
721
  }
722
}
723
724
async function addWorkspace(arg: Repository | vscode.SourceControl | undefined): Promise<void> {
725
  const repo = repositoryFor(arg);
726
  if (!repo) {
727
    return;
728
  }
729
  const folders = await vscode.window.showOpenDialog({ canSelectFiles: false, canSelectFolders: true, canSelectMany: false, openLabel: "Create workspace here", title: "Folder for the new workspace (must be empty or absent)" });
730
  if (!folders?.[0]) {
731
    return;
732
  }
733
  try {
734
    await repo.oxy.workspaceAdd(repo.root, folders[0].fsPath);
735
    const pick = await vscode.window.showInformationMessage(`Oxygen: workspace created at ${folders[0].fsPath}.`, "Open in new window");
736
    if (pick) {
737
      await vscode.commands.executeCommand("vscode.openFolder", folders[0], { forceNewWindow: true });
738
    }
739
  } catch (e) {
740
    showError(e);
741
  }
742
}
743
744
/**
745
 * vscode://oxygen.oxygen-vscode/resolve?url=…&bookmark=…&path=… from
746
 * OxygenHub's conflict resolver: find the open repository with that remote
747
 * (or offer to clone it), switch to the bookmark if asked to, pull it, and
748
 * open the file, where the conflict lenses take over.
749
 */
750
async function handleUri(uri: vscode.Uri): Promise<void> {
751
  if (uri.path === "/plan") {
752
    return applyPlan(uri);
753
  }
754
  if (uri.path !== "/resolve") {
755
    return;
756
  }
757
  const req = parseResolveQuery(uri.query);
758
  if (typeof req === "string") {
759
    vscode.window.showErrorMessage(`Oxygen: cannot open this conflict: ${req}.`);
760
    return;
761
  }
762
  let found: { repo: Repository; remote: string } | undefined;
763
  for (const repo of repositories.values()) {
764
    const remotes = await repo.oxy.remotes(repo.root).catch(() => []);
765
    const r = remotes.find((x) => sameRemote(x.url, req.url));
766
    if (r) {
767
      found = { repo, remote: r.name };
768
      break;
769
    }
770
  }
771
  if (!found) {
772
    const pick = await vscode.window.showInformationMessage(
773
      `Oxygen: no open folder is a checkout of ${req.url}. Clone it, open it, then follow the link again.`,
774
      "Clone…",
775
    );
776
    if (pick) {
777
      await cloneRepository(req.url);
778
    }
779
    return;
780
  }
781
  const { repo, remote } = found;
782
  try {
783
    if (repo.currentBookmark?.name !== req.bookmark) {
784
      const ok = await vscode.window.showInformationMessage(
785
        `Oxygen: the conflict is on ${req.bookmark}; this checkout is on ${repo.currentBookmark?.name ?? "another bookmark"}. Switch?`,
786
        { modal: true },
787
        "Switch",
788
      );
789
      if (!ok) {
790
        return;
791
      }
792
      await vscode.window.withProgress({ location: vscode.ProgressLocation.SourceControl, title: `Switching to ${req.bookmark}` }, () =>
793
        repo.oxy.bookmarkSwitch(repo.root, req.bookmark),
794
      );
795
    }
796
    await vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: `Oxygen: pulling ${req.bookmark}` }, () =>
797
      repo.oxy.pull(repo.root, remote),
798
    );
799
    await repo.refresh();
800
    await vscode.commands.executeCommand("vscode.open", vscode.Uri.joinPath(vscode.Uri.file(repo.root), req.path));
801
  } catch (e) {
802
    showError(e);
803
  }
804
}
805
806
/** The open checkout whose remote is `url`, with that remote's name. */
807
async function checkoutOf(url: string): Promise<{ repo: Repository; remote: string } | undefined> {
808
  for (const repo of repositories.values()) {
809
    const remotes = await repo.oxy.remotes(repo.root).catch(() => []);
810
    const r = remotes.find((x) => sameRemote(x.url, url));
811
    if (r) {
812
      return { repo, remote: r.name };
813
    }
814
  }
815
  return undefined;
816
}
817
818
/**
819
 * vscode://oxygen.oxygen-vscode/plan?… from OxygenHub's swimlanes: squash
820
 * or rebase a change of a proposal's bookmark here, where it is signed as
821
 * you, then push the rewritten bookmark.
822
 */
823
async function applyPlan(uri: vscode.Uri): Promise<void> {
824
  const plan = parsePlanQuery(uri.query);
825
  if (typeof plan === "string") {
826
    vscode.window.showErrorMessage(`Oxygen: cannot apply this plan: ${plan}.`);
827
    return;
828
  }
829
  const found = await checkoutOf(plan.url);
830
  if (!found) {
831
    const pick = await vscode.window.showInformationMessage(`Oxygen: no open folder is a checkout of ${plan.url}. Clone it, open it, then follow the link again.`, "Clone…");
832
    if (pick) {
833
      await cloneRepository(plan.url);
834
    }
835
    return;
836
  }
837
  const { repo, remote } = found;
838
  const [c, t] = [plan.change.slice(0, 12), plan.target.slice(0, 12)];
839
  const what = plan.kind === "squash" ? `Squash #${c} into #${t}` : `Rebase #${c} onto #${t}`;
840
  const ok = await vscode.window.showInformationMessage(`Oxygen: ${what} on ${plan.bookmark}? The rewritten changes are signed as you.`, { modal: true }, "Apply");
841
  if (!ok) {
842
    return;
843
  }
844
  try {
845
    if (repo.currentBookmark?.name !== plan.bookmark) {
846
      await repo.oxy.bookmarkSwitch(repo.root, plan.bookmark);
847
    }
848
    await repo.oxy.pull(repo.root, remote);
849
    await vscode.window.withProgress({ location: vscode.ProgressLocation.SourceControl, title: what }, () =>
850
      plan.kind === "squash"
851
        ? repo.oxy.squash(repo.root, `#${plan.change}`, `#${plan.target}`)
852
        : repo.oxy.rebase(repo.root, `#${plan.change}`, [`#${plan.target}`]),
853
    );
854
    await repo.refresh();
855
    const push = await vscode.window.showInformationMessage(`Oxygen: ${what} done. Push ${plan.bookmark}? Its history changed, so this replaces it on ${remote}.`, "Push");
856
    if (push) {
857
      await vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: `Oxygen: pushing ${plan.bookmark}` }, () =>
858
        repo.oxy.push(repo.root, remote, plan.bookmark, true),
859
      );
860
    }
861
  } catch (e) {
862
    showError(e);
863
  }
864
}
865
866
async function cloneRepository(prefill?: string): Promise<void> {
867
  const url = await vscode.window.showInputBox({ prompt: "Repository to clone (path or https URL)", placeHolder: "https://host:8890/project", value: prefill });
868
  if (!url?.trim()) {
869
    return;
870
  }
871
  const parent = await vscode.window.showOpenDialog({ canSelectFiles: false, canSelectFolders: true, canSelectMany: false, openLabel: "Clone into this folder" });
872
  if (!parent?.[0]) {
873
    return;
874
  }
875
  const name = url.trim().replace(/\/+$/, "").split("/").pop()?.replace(/\.oxy$/, "") || "repository";
876
  const dest = vscode.Uri.joinPath(parent[0], name);
877
  try {
878
    await vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: `Oxygen: cloning ${name}` }, () => oxy.clone(parent[0].fsPath, url.trim(), dest.fsPath));
879
    const pick = await vscode.window.showInformationMessage(`Oxygen: cloned into ${dest.fsPath}.`, "Open", "Open in new window");
880
    if (pick) {
881
      await vscode.commands.executeCommand("vscode.openFolder", dest, { forceNewWindow: pick === "Open in new window" });
882
    }
883
  } catch (e) {
884
    showError(e);
885
  }
886
}
887
888
// ---------------------------------------------------------------- history
889
890
async function showChange(root: string, hash: string): Promise<void> {
891
  const repo = repositories.get(root);
892
  if (!repo) {
893
    return;
894
  }
895
  let info;
896
  try {
897
    info = await repo.oxy.show(repo.root, `#${hash.slice(0, 12)}`);
898
  } catch (e) {
899
    showError(e);
900
    return;
901
  }
902
  const subject = info.message.split("\n")[0];
903
  type Item = vscode.QuickPickItem & { action: string; path?: string };
904
  const items: Item[] = [
905
    { label: "$(diff) Show diff", description: `${info.files.length} file${info.files.length === 1 ? "" : "s"}`, action: "diff" },
906
    { label: "$(arrow-right) Check out this state", description: "the change and its dependencies", action: "checkout" },
907
    { label: "$(edit) Describe…", description: "change the message", action: "describe" },
908
    { label: "$(tag) Tag…", action: "tag" },
909
    { label: "$(trash) Abandon", description: "drop the change; its content stays on disk if the working copy sat on it", action: "abandon" },
910
    ...historyItems(info),
911
    { label: "$(copy) Copy ChangeId", action: "copy" },
912
    ...info.files.map((f) => ({ label: `$(file) ${f.path}`, description: `${f.kind}${f.from ? ` from ${f.from}` : ""}`, action: "file", path: f.path })),
913
  ];
914
  const pick = await vscode.window.showQuickPick(items, {
915
    title: `${info.change_id.slice(0, 8)}  ${subject}`,
916
    placeHolder: `${info.author} · ${timeAgo(info.when_ms)} · ${info.signature?.status ?? "unsigned"}${info.signature?.revoked ? " (key revoked)" : ""} · ${info.deps.length} dependenc${info.deps.length === 1 ? "y" : "ies"}`,
917
    matchOnDescription: true,
918
  });
919
  if (!pick) {
920
    return;
921
  }
922
  try {
923
    switch (pick.action) {
924
      case "diff":
925
      case "file": {
926
        const text = await repo.oxy.diffText(repo.root, `#${hash.slice(0, 12)}`);
927
        const body = `# ${info.change_id.slice(0, 8)} ${subject}\n# ${info.author} · ${new Date(info.when_ms).toLocaleString()}\n\n${text}`;
928
        const doc = await vscode.workspace.openTextDocument({ content: body, language: "diff" });
929
        await vscode.window.showTextDocument(doc, { preview: true });
930
        return;
931
      }
932
      case "checkout":
933
        await repo.oxy.checkout(repo.root, [`#${hash.slice(0, 12)}`]);
934
        break;
935
      case "describe": {
936
        const message = await vscode.window.showInputBox({ prompt: "New message", value: info.message });
937
        if (!message?.trim()) {
938
          return;
939
        }
940
        await repo.oxy.describe(repo.root, `#${hash.slice(0, 12)}`, message.trim());
941
        break;
942
      }
943
      case "tag": {
944
        const name = await vscode.window.showInputBox({ prompt: "Tag name" });
945
        if (!name?.trim()) {
946
          return;
947
        }
948
        await repo.oxy.tagCreate(repo.root, name.trim(), [`#${hash.slice(0, 12)}`]);
949
        break;
950
      }
951
      case "abandon": {
952
        const confirm = await vscode.window.showWarningMessage(`Abandon "${subject}"?`, { modal: true }, "Abandon");
953
        if (confirm !== "Abandon") {
954
          return;
955
        }
956
        const out = await repo.oxy.abandon(repo.root, `#${hash.slice(0, 12)}`);
957
        vscode.window.setStatusBarMessage(`$(trash) ${out.split("\n")[0]}`, 5000);
958
        break;
959
      }
960
      case "copy":
961
        await vscode.env.clipboard.writeText(info.change_id);
962
        return;
963
      case "split":
964
      case "squash":
965
      case "rebase":
966
        await historyAction(repo, info, pick.action);
967
        return;
968
    }
969
    await repo.refresh();
970
  } catch (e) {
971
    if (e instanceof OxyError && e.message.includes("has changes")) {
972
      const confirm = await vscode.window.showWarningMessage("The working copy has uncommitted changes. Discard them and check out?", { modal: true }, "Discard and check out");
973
      if (confirm) {
974
        try {
975
          await repo.oxy.checkout(repo.root, [`#${hash.slice(0, 12)}`], true);
976
          await repo.refresh();
977
        } catch (e2) {
978
          showError(e2);
979
        }
980
      }
981
      return;
982
    }
983
    showError(e);
984
  }
985
}
986
987
// ------------------------------------------------ history rewriting (V6)
988
989
type HistoryAction = "split" | "squash" | "rebase";
990
991
/** The rewriting actions a change offers: split for a head with several files, squash when it has dependencies, rebase always. */
992
function historyItems(info: ShowInfo): (vscode.QuickPickItem & { action: string })[] {
993
  const items: (vscode.QuickPickItem & { action: string })[] = [];
994
  if (info.head && info.files.length > 1) {
995
    items.push({ label: "$(split-horizontal) Split…", description: "chosen files become a separate first change", action: "split" });
996
  }
997
  if (info.deps.length > 0) {
998
    items.push({ label: "$(fold) Squash into a dependency…", description: "fold this change into one it depends on", action: "squash" });
999
  }
1000
  items.push({ label: "$(git-pull-request-go-to-changes) Rebase onto…", description: "re-express against another state", action: "rebase" });
1001
  return items;
1002
}
1003
1004
/** Run `action` on a change: choose, confirm, run, then offer Undo (oxy undo reverses every rewrite). */
1005
async function historyAction(repo: Repository, info: ShowInfo, action: HistoryAction): Promise<void> {
1006
  const change = `#${info.hash.slice(0, 12)}`;
1007
  const subject = info.message.split("\n")[0] || "(no description)";
1008
  let run: () => Promise<string>;
1009
  let question: string;
1010
  if (action === "split") {
1011
    if (!info.head) {
1012
      void vscode.window.showInformationMessage("Oxygen: only a head can be split; nothing may depend on it yet.");
1013
      return;
1014
    }
1015
    const picked = await vscode.window.showQuickPick(
1016
      info.files.map((f) => ({ label: f.path, description: f.kind, picked: false })),
1017
      { title: `Split ${info.change_id.slice(0, 8)}: the files you choose become the first change`, canPickMany: true },
1018
    );
1019
    if (!picked || picked.length === 0) {
1020
      return;
1021
    }
1022
    if (picked.length === info.files.length) {
1023
      void vscode.window.showInformationMessage("Oxygen: leave at least one file for the second change.");
1024
      return;
1025
    }
1026
    const paths = picked.map((p) => p.label);
1027
    question = `Split "${subject}"? ${paths.length} file${paths.length === 1 ? "" : "s"} (${paths.join(", ")}) become a separate change; the rest stay.`;
1028
    run = () => repo.oxy.split(repo.root, change, paths);
1029
  } else if (action === "squash") {
1030
    if (info.deps.length === 0) {
1031
      void vscode.window.showInformationMessage("Oxygen: this change has no dependency to fold into.");
1032
      return;
1033
    }
1034
    const log = await repo.oxy.log(repo.root, 500);
1035
    const byHash = new Map(log.changes.map((c) => [c.hash, c]));
1036
    const choices = info.deps.map((d) => {
1037
      const c = byHash.get(d);
1038
      return { label: c ? c.message.split("\n")[0] || "(no description)" : d.slice(0, 12), description: c ? c.change_id.slice(0, 8) : "", hash: d };
1039
    });
1040
    const into = choices.length === 1 ? choices[0] : await vscode.window.showQuickPick(choices, { title: `Squash ${info.change_id.slice(0, 8)} into…` });
1041
    if (!into) {
1042
      return;
1043
    }
1044
    question = `Squash "${subject}" into "${into.label}"? The dependency keeps its ChangeId and absorbs these edits.`;
1045
    run = () => repo.oxy.squash(repo.root, change, `#${into.hash.slice(0, 12)}`);
1046
  } else {
1047
    const bookmarks = await repo.oxy.bookmarks(repo.root);
1048
    type Onto = vscode.QuickPickItem & { onto?: string };
1049
    const choices: Onto[] = [
1050
      ...bookmarks.map((b) => ({ label: `$(bookmark) ${b.name}`, description: b.current ? "current bookmark" : "", onto: b.name })),
1051
      { label: "$(edit) Another change, bookmark or tag…" },
1052
    ];
1053
    const pick = await vscode.window.showQuickPick(choices, { title: `Rebase ${info.change_id.slice(0, 8)} onto…` });
1054
    if (!pick) {
1055
      return;
1056
    }
1057
    let onto = pick.onto;
1058
    if (!onto) {
1059
      onto = (await vscode.window.showInputBox({ prompt: "ChangeId prefix, #hash prefix, bookmark or tag" }))?.trim();
1060
      if (!onto) {
1061
        return;
1062
      }
1063
    }
1064
    const target = onto;
1065
    question = `Rebase "${subject}" onto ${target}? The change is re-expressed against that state; its ChangeId stays.`;
1066
    run = () => repo.oxy.rebase(repo.root, change, [target]);
1067
  }
1068
  const verb = action[0].toUpperCase() + action.slice(1);
1069
  if ((await vscode.window.showWarningMessage(question, { modal: true, detail: "Undo reverses it (Oxygen: Undo, or oxy undo)." }, verb)) !== verb) {
1070
    return;
1071
  }
1072
  try {
1073
    const out = await run();
1074
    await repo.refresh();
1075
    HistoryPanel.refresh(repo.root);
1076
    const undo = await vscode.window.showInformationMessage(`Oxygen: ${out.split("\n")[0].replace(/^\* /, "")}`, "Undo");
1077
    if (undo === "Undo") {
1078
      await repo.oxy.undo(repo.root);
1079
      await repo.refresh();
1080
      HistoryPanel.refresh(repo.root);
1081
    }
1082
  } catch (e) {
1083
    showError(e);
1084
  }
1085
}
1086
1087
/** A history-graph context menu command: the webview passes `{ root, hash }`. */
1088
async function historyContext(ctx: { root?: string; hash?: string } | undefined, action: HistoryAction): Promise<void> {
1089
  const repo = ctx?.root ? repositories.get(ctx.root) : undefined;
1090
  if (!repo || !ctx?.hash) {
1091
    return;
1092
  }
1093
  try {
1094
    const info = await repo.oxy.show(repo.root, `#${ctx.hash.slice(0, 12)}`);
1095
    await historyAction(repo, info, action);
1096
  } catch (e) {
1097
    showError(e);
1098
  }
1099
}
1100
1101
// ------------------------------------------------------ commit box (V7)
1102
1103
interface BoxState {
1104
  amend: boolean;
1105
  resolution: boolean;
1106
  signing: string;
1107
  checkedMs: number;
1108
}
1109
1110
const boxes = new Map<string, BoxState>();
1111
let extensionContext: vscode.ExtensionContext | undefined;
1112
1113
function box(repo: Repository): BoxState {
1114
  let b = boxes.get(repo.root);
1115
  if (!b) {
1116
    b = { amend: false, resolution: false, signing: "", checkedMs: 0 };
1117
    boxes.set(repo.root, b);
1118
  }
1119
  return b;
1120
}
1121
1122
/** Placeholder and the Ctrl+Enter action follow amend mode, resolution and signing. */
1123
function updateBox(repo: Repository): void {
1124
  const b = box(repo);
1125
  repo.sourceControl.acceptInputCommand = { command: "oxygen.commit", title: b.amend ? "Amend" : b.resolution ? "Commit resolution" : "Commit", arguments: [repo] };
1126
  repo.sourceControl.inputBox.placeholder = placeholder(b);
1127
}
1128
1129
/** Re-read how commits will be signed, at most every 30 seconds. */
1130
async function refreshSigning(repo: Repository, force = false): Promise<void> {
1131
  const b = box(repo);
1132
  if (!force && Date.now() - b.checkedMs < 30_000) {
1133
    return;
1134
  }
1135
  b.checkedMs = Date.now();
1136
  try {
1137
    b.signing = signingLabel(await repo.oxy.identity(repo.root));
1138
  } catch {
1139
    b.signing = "";
1140
  }
1141
  updateBox(repo);
1142
}
1143
1144
function setAmend(repo: Repository, on: boolean): void {
1145
  box(repo).amend = on;
1146
  void vscode.commands.executeCommand("setContext", "oxygen.amending", [...boxes.values()].some((b) => b.amend));
1147
  updateBox(repo);
1148
}
1149
1150
async function toggleAmend(arg: Repository | vscode.SourceControl | undefined, on: boolean): Promise<void> {
1151
  const repo = repositoryFor(arg);
1152
  if (!repo) {
1153
    return;
1154
  }
1155
  setAmend(repo, on);
1156
  if (on && !repo.sourceControl.inputBox.value.trim()) {
1157
    // Start from the message being amended.
1158
    try {
1159
      const last = (await repo.oxy.log(repo.root, 2)).changes.find((c) => !c.working_copy);
1160
      if (last) {
1161
        repo.sourceControl.inputBox.value = last.message;
1162
      }
1163
    } catch {
1164
      // An empty box keeps the message anyway.
1165
    }
1166
  }
1167
}
1168
1169
function historyOf(repo: Repository): MessageHistory {
1170
  return new MessageHistory(extensionContext?.workspaceState.get<string[]>(`oxygen.messages:${repo.root}`) ?? []);
1171
}
1172
1173
function remember(repo: Repository, message: string): void {
1174
  const h = historyOf(repo);
1175
  h.add(message);
1176
  void extensionContext?.workspaceState.update(`oxygen.messages:${repo.root}`, h.entries);
1177
}
1178
1179
async function messageHistory(arg: Repository | vscode.SourceControl | undefined): Promise<void> {
1180
  const repo = repositoryFor(arg);
1181
  if (!repo) {
1182
    return;
1183
  }
1184
  const entries = historyOf(repo).entries;
1185
  if (entries.length === 0) {
1186
    void vscode.window.showInformationMessage("Oxygen: no messages yet; they are remembered as you commit.");
1187
    return;
1188
  }
1189
  const pick = await vscode.window.showQuickPick(
1190
    entries.map((m) => ({ label: m.split("\n")[0], detail: m.includes("\n") ? m.split("\n").slice(1).join(" ").trim().slice(0, 160) : undefined, message: m })),
1191
    { title: "Previous commit messages", placeHolder: "Put one back in the commit box", matchOnDetail: true },
1192
  );
1193
  if (pick) {
1194
    repo.sourceControl.inputBox.value = pick.message;
1195
  }
1196
}
1197
1198
/**
1199
 * Warn before committing files that still hold conflict markers: those oxy
1200
 * reports (markers left in a conflicted file) and any text file whose lines
1201
 * open or close a conflict. `paths` limits the check to what is committed.
1202
 */
1203
async function markersOk(repo: Repository, paths?: string[]): Promise<boolean> {
1204
  const status = repo.status;
1205
  if (!status) {
1206
    return true;
1207
  }
1208
  const found: { path: string; line?: number }[] = [];
1209
  for (const p of status.paths) {
1210
    if (p.status === "Removed" || (paths && !paths.includes(p.path))) {
1211
      continue;
1212
    }
1213
    if (p.status === "ConflictEdited") {
1214
      found.push({ path: p.path });
1215
      continue;
1216
    }
1217
    try {
1218
      const file = join(repo.root, p.path);
1219
      if ((await stat(file)).size > 4 * 1024 * 1024) {
1220
        continue;
1221
      }
1222
      const text = (await readFile(file)).toString("utf8");
1223
      const lines = conflictMarkerLines(text);
1224
      if (lines.length > 0) {
1225
        found.push({ path: p.path, line: lines[0] });
1226
      }
1227
    } catch {
1228
      // Unreadable or gone: nothing to check.
1229
    }
1230
  }
1231
  if (found.length === 0) {
1232
    return true;
1233
  }
1234
  const list = found.slice(0, 5).map((f) => (f.line ? `${f.path} (line ${f.line})` : f.path)).join(", ") + (found.length > 5 ? ` and ${found.length - 5} more` : "");
1235
  const pick = await vscode.window.showWarningMessage(
1236
    `Conflict markers remain in ${list}. Commit anyway?`,
1237
    { modal: true, detail: "Committing records the marker lines as ordinary text." },
1238
    "Commit anyway",
1239
    `Open ${basename(found[0].path)}`,
1240
  );
1241
  if (pick?.startsWith("Open ")) {
1242
    const doc = await vscode.workspace.openTextDocument(vscode.Uri.file(join(repo.root, found[0].path)));
1243
    const line = Math.max(0, (found[0].line ?? 1) - 1);
1244
    await vscode.window.showTextDocument(doc, { selection: new vscode.Range(line, 0, line, 0) });
1245
    return false;
1246
  }
1247
  return pick === "Commit anyway";
1248
}
1249
1250
async function fileHistory(uri: vscode.Uri | undefined): Promise<void> {
1251
  if (!uri) {
1252
    return;
1253
  }
1254
  const repo = [...repositories.values()].find((r) => r.relativePath(uri) !== undefined);
1255
  const rel = repo?.relativePath(uri);
1256
  if (!repo || !rel) {
1257
    void vscode.window.showInformationMessage("Oxygen: this file is not in an Oxygen repository.");
1258
    return;
1259
  }
1260
  try {
1261
    const log = await repo.oxy.log(repo.root, 200, rel);
1262
    const changes = log.changes.filter((c) => !c.working_copy);
1263
    if (changes.length === 0) {
1264
      void vscode.window.showInformationMessage(`Oxygen: no committed change touches ${rel}.`);
1265
      return;
1266
    }
1267
    const pick = await vscode.window.showQuickPick(
1268
      changes.map((c, i) => ({
1269
        label: `${c.head ? "$(circle-filled)" : "$(circle-outline)"} ${c.message.split("\n")[0]}`,
1270
        description: `${c.change_id.slice(0, 8)} · ${c.author} · ${timeAgo(c.when_ms)}`,
1271
        change: c,
1272
        previous: changes[i + 1],
1273
      })),
1274
      { placeHolder: `${changes.length} change${changes.length === 1 ? "" : "s"} touched ${rel}; pick one to compare with the version before it`, matchOnDescription: true },
1275
    );
1276
    if (!pick) {
1277
      return;
1278
    }
1279
    const after = oxyUriFor(repo.root, rel, pick.change.hash);
1280
    if (pick.previous) {
1281
      const before = oxyUriFor(repo.root, rel, pick.previous.hash);
1282
      await vscode.commands.executeCommand("vscode.diff", before, after, `${basename(rel)} (${pick.previous.change_id.slice(0, 8)} ↔ ${pick.change.change_id.slice(0, 8)})`);
1283
    } else {
1284
      await vscode.commands.executeCommand("vscode.open", after);
1285
    }
1286
  } catch (e) {
1287
    showError(e);
1288
  }
1289
}
1290
1291
function oxyUriFor(root: string, rel: string, hash: string): vscode.Uri {
1292
  return oxyUri(root, rel, `#${hash.slice(0, 12)}`);
1293
}
1294
1295
// ---------------------------------------------------------------- bookmarks
1296
1297
async function switchBookmark(arg: Repository | vscode.SourceControl | undefined): Promise<void> {
1298
  const repo = repositoryFor(arg);
1299
  if (!repo) {
1300
    return;
1301
  }
1302
  let bookmarks;
1303
  try {
1304
    bookmarks = await repo.oxy.bookmarks(repo.root);
1305
  } catch (e) {
1306
    showError(e);
1307
    return;
1308
  }
1309
  type Item = vscode.QuickPickItem & { action: "switch" | "create" | "merge" | "delete"; name?: string };
1310
  const items: Item[] = bookmarks.map((b) => ({
1311
    label: `${b.current ? "$(circle-filled)" : "$(bookmark)"} ${b.name}`,
1312
    description: `${b.heads.length} head${b.heads.length === 1 ? "" : "s"}${b.ahead ? ` $(arrow-up)${b.ahead}` : ""}${b.behind ? ` $(arrow-down)${b.behind}` : ""}`,
1313
    detail: b.current ? "current bookmark" : undefined,
1314
    action: "switch",
1315
    name: b.name,
1316
  }));
1317
  items.push(
1318
    { label: "$(add) Create bookmark…", action: "create", alwaysShow: true },
1319
    { label: "$(git-merge) Merge a bookmark into the current one…", action: "merge", alwaysShow: true },
1320
    { label: "$(trash) Delete a bookmark…", action: "delete", alwaysShow: true },
1321
  );
1322
  const pick = await vscode.window.showQuickPick(items, { placeHolder: "Switch to a bookmark" });
1323
  if (!pick) {
1324
    return;
1325
  }
1326
  switch (pick.action) {
1327
    case "create":
1328
      return createBookmark(repo);
1329
    case "merge":
1330
      return mergeBookmark(repo);
1331
    case "delete":
1332
      return deleteBookmark(repo);
1333
    case "switch":
1334
      if (pick.name && !bookmarks.find((b) => b.name === pick.name)?.current) {
1335
        await doSwitch(repo, pick.name);
1336
      }
1337
  }
1338
}
1339
1340
async function doSwitch(repo: Repository, name: string): Promise<void> {
1341
  try {
1342
    await vscode.window.withProgress({ location: vscode.ProgressLocation.SourceControl, title: `Switching to ${name}` }, () => repo.oxy.bookmarkSwitch(repo.root, name));
1343
  } catch (e) {
1344
    if (e instanceof OxyError && e.message.includes("has changes")) {
1345
      const pick = await vscode.window.showWarningMessage(`The working copy has uncommitted changes. Switching to ${name} would discard them.`, { modal: true }, "Discard and switch");
1346
      if (pick === "Discard and switch") {
1347
        try {
1348
          await repo.oxy.bookmarkSwitch(repo.root, name, true);
1349
        } catch (e2) {
1350
          showError(e2);
1351
        }
1352
      }
1353
    } else {
1354
      showError(e);
1355
    }
1356
  }
1357
  await repo.refresh();
1358
}
1359
1360
async function createBookmark(arg: Repository | vscode.SourceControl | undefined): Promise<void> {
1361
  const repo = repositoryFor(arg);
1362
  if (!repo) {
1363
    return;
1364
  }
1365
  const name = await vscode.window.showInputBox({
1366
    prompt: "New bookmark name (created at the working copy's base)",
1367
    validateInput: (v) => (!v.trim() || v.startsWith("-") || v.includes("..") || v.includes("//") || /[\s@{]/.test(v) ? "Not a valid bookmark name" : undefined),
1368
  });
1369
  if (!name) {
1370
    return;
1371
  }
1372
  try {
1373
    await repo.oxy.bookmarkCreate(repo.root, name.trim());
1374
    const pick = await vscode.window.showInformationMessage(`Oxygen: created bookmark ${name}.`, "Switch to it");
1375
    if (pick) {
1376
      await doSwitch(repo, name.trim());
1377
    }
1378
    await repo.refresh();
1379
  } catch (e) {
1380
    showError(e);
1381
  }
1382
}
1383
1384
async function pickBookmark(repo: Repository, placeHolder: string, excludeCurrent: boolean): Promise<string | undefined> {
1385
  const bookmarks = await repo.oxy.bookmarks(repo.root);
1386
  const items = bookmarks.filter((b) => !excludeCurrent || !b.current).map((b) => ({ label: b.name, description: `${b.heads.length} head${b.heads.length === 1 ? "" : "s"}` }));
1387
  if (items.length === 0) {
1388
    void vscode.window.showInformationMessage("Oxygen: no other bookmarks.");
1389
    return undefined;
1390
  }
1391
  return (await vscode.window.showQuickPick(items, { placeHolder }))?.label;
1392
}
1393
1394
async function mergeBookmark(arg: Repository | vscode.SourceControl | undefined): Promise<void> {
1395
  const repo = repositoryFor(arg);
1396
  if (!repo) {
1397
    return;
1398
  }
1399
  try {
1400
    const name = await pickBookmark(repo, `Merge into ${repo.currentBookmark?.name ?? "the current bookmark"}`, true);
1401
    if (!name) {
1402
      return;
1403
    }
1404
    const out = await vscode.window.withProgress({ location: vscode.ProgressLocation.SourceControl, title: `Merging ${name}` }, () => repo.oxy.merge(repo.root, name));
1405
    await repo.refresh();
1406
    if (repo.status?.conflicted) {
1407
      void vscode.window.showWarningMessage(`Oxygen: merged ${name}; the result has conflicts to resolve.`);
1408
    } else {
1409
      vscode.window.setStatusBarMessage(`$(git-merge) ${out.split("\n")[0]}`, 5000);
1410
    }
1411
  } catch (e) {
1412
    showError(e);
1413
  }
1414
}
1415
1416
async function deleteBookmark(arg: Repository | vscode.SourceControl | undefined): Promise<void> {
1417
  const repo = repositoryFor(arg);
1418
  if (!repo) {
1419
    return;
1420
  }
1421
  try {
1422
    const name = await pickBookmark(repo, "Delete which bookmark? Its changes stay.", true);
1423
    if (!name) {
1424
      return;
1425
    }
1426
    const pick = await vscode.window.showWarningMessage(`Delete bookmark ${name}?`, { modal: true }, "Delete");
1427
    if (pick !== "Delete") {
1428
      return;
1429
    }
1430
    await repo.oxy.bookmarkDelete(repo.root, name);
1431
    await repo.refresh();
1432
  } catch (e) {
1433
    showError(e);
1434
  }
1435
}
1436
1437
// ---------------------------------------------------------------- sync
1438
1439
async function pickRemote(repo: Repository): Promise<string | undefined> {
1440
  const remotes = await repo.oxy.remotes(repo.root);
1441
  if (remotes.length === 0) {
1442
    void vscode.window.showErrorMessage("Oxygen: this repository has no remotes. Add one with oxy remote add <name> <url>.");
1443
    return undefined;
1444
  }
1445
  if (remotes.length === 1) {
1446
    return remotes[0].name;
1447
  }
1448
  return (await vscode.window.showQuickPick(remotes.map((r) => ({ label: r.name, description: r.url })), { placeHolder: "Remote" }))?.label;
1449
}
1450
1451
async function fetch(arg: Repository | vscode.SourceControl | undefined): Promise<void> {
1452
  const repo = repositoryFor(arg);
1453
  if (!repo) {
1454
    return;
1455
  }
1456
  try {
1457
    const remote = await pickRemote(repo);
1458
    if (!remote) {
1459
      return;
1460
    }
1461
    const info = await vscode.window.withProgress({ location: vscode.ProgressLocation.SourceControl, title: `Fetching from ${remote}` }, () => repo.oxy.fetch(repo.root, remote));
1462
    await repo.refresh();
1463
    const fresh = info.refs.filter((r) => r.new > 0);
1464
    const summary = fresh.length ? fresh.map((r) => `${r.name}: ${r.new} new`).join(", ") : "nothing new";
1465
    vscode.window.setStatusBarMessage(`$(cloud-download) ${remote}: ${summary}`, 5000);
1466
    if (info.unverified) {
1467
      void vscode.window.showWarningMessage(`Oxygen: ${remote} has no trust policy; nothing fetched from it was verified.`);
1468
    }
1469
  } catch (e) {
1470
    showError(e);
1471
  }
1472
}
1473
1474
async function pull(arg: Repository | vscode.SourceControl | undefined): Promise<void> {
1475
  const repo = repositoryFor(arg);
1476
  if (!repo) {
1477
    return;
1478
  }
1479
  try {
1480
    const remote = await pickRemote(repo);
1481
    if (!remote) {
1482
      return;
1483
    }
1484
    const info = await vscode.window.withProgress({ location: vscode.ProgressLocation.SourceControl, title: `Pulling from ${remote}` }, () => repo.oxy.pull(repo.root, remote));
1485
    await repo.refresh();
1486
    if (!info.changed) {
1487
      vscode.window.setStatusBarMessage("$(check) Already up to date", 4000);
1488
    } else if (info.conflicted) {
1489
      void vscode.window.showWarningMessage("Oxygen: pulled; the result has conflicts to resolve.");
1490
    } else if (!info.checked_out) {
1491
      void vscode.window.showInformationMessage("Oxygen: pulled; the working copy was not updated because it has changes. Check out when ready.");
1492
    } else {
1493
      vscode.window.setStatusBarMessage(`$(cloud-download) Pulled from ${remote}`, 4000);
1494
    }
1495
  } catch (e) {
1496
    showError(e);
1497
  }
1498
}
1499
1500
async function push(arg: Repository | vscode.SourceControl | undefined, chooseBookmark: boolean): Promise<void> {
1501
  const repo = repositoryFor(arg);
1502
  if (!repo) {
1503
    return;
1504
  }
1505
  try {
1506
    const remote = await pickRemote(repo);
1507
    if (!remote) {
1508
      return;
1509
    }
1510
    let bookmark: string | undefined;
1511
    if (chooseBookmark) {
1512
      bookmark = await pickBookmark(repo, "Push which bookmark?", false);
1513
      if (!bookmark) {
1514
        return;
1515
      }
1516
    }
1517
    if (vscode.workspace.getConfiguration("oxygen").get<boolean>("confirmSync", true)) {
1518
      const pick = await vscode.window.showInformationMessage(`Push ${bookmark ?? repo.currentBookmark?.name ?? "the current bookmark"} to ${remote}?`, { modal: false }, "Push", "Always push without asking");
1519
      if (!pick) {
1520
        return;
1521
      }
1522
      if (pick === "Always push without asking") {
1523
        await vscode.workspace.getConfiguration("oxygen").update("confirmSync", false, vscode.ConfigurationTarget.Global);
1524
      }
1525
    }
1526
    const results = await vscode.window.withProgress({ location: vscode.ProgressLocation.SourceControl, title: `Pushing to ${remote}` }, () => repo.oxy.push(repo.root, remote, bookmark));
1527
    await repo.refresh();
1528
    const rejected = results.filter((r) => !r.ok);
1529
    if (rejected.length === 0) {
1530
      vscode.window.setStatusBarMessage(`$(cloud-upload) Pushed to ${remote}`, 4000);
1531
      return;
1532
    }
1533
    const reason = rejected.map((r) => `${r.name}: ${r.reason}`).join("; ");
1534
    const pick = await vscode.window.showErrorMessage(`Oxygen: push rejected. ${reason}`, "Pull", "Show Output");
1535
    if (pick === "Pull") {
1536
      await pull(repo);
1537
    } else if (pick === "Show Output") {
1538
      output.show();
1539
    }
1540
  } catch (e) {
1541
    if (e instanceof OxyError && e.message.includes("pull first")) {
1542
      const pick = await vscode.window.showWarningMessage(`Oxygen: ${e.message}`, "Pull");
1543
      if (pick === "Pull") {
1544
        await pull(repo);
1545
      }
1546
      return;
1547
    }
1548
    showError(e);
1549
  }
1550
}
1551
1552
async function sync(arg: Repository | vscode.SourceControl | undefined): Promise<void> {
1553
  const repo = repositoryFor(arg);
1554
  if (!repo) {
1555
    return;
1556
  }
1557
  await pull(repo);
1558
  if (repo.status?.conflicted) {
1559
    return;
1560
  }
1561
  if ((repo.currentBookmark?.ahead ?? 0) > 0) {
1562
    await push(repo, false);
1563
  }
1564
}
1565
1566
/** The commit message from the input box, else a prompt. */
1567
async function askMessage(repo: Repository, prompt: string): Promise<string | undefined> {
1568
  const fromBox = repo.sourceControl.inputBox.value.trim();
1569
  if (fromBox) {
1570
    return fromBox;
1571
  }
1572
  return (await vscode.window.showInputBox({ prompt, placeHolder: "Commit message" }))?.trim() || undefined;
1573
}
1574
1575
async function showLog(): Promise<void> {
1576
  const repo = repositoryFor(undefined);
1577
  if (!repo) {
1578
    return;
1579
  }
1580
  try {
1581
    const log = await repo.oxy.log(repo.root, 50);
1582
    const items = log.changes
1583
      .filter((c) => !c.working_copy)
1584
      .map((c) => ({
1585
        label: `${c.head ? "$(circle-filled)" : "$(circle-outline)"} ${c.message.split("\n")[0]}`,
1586
        description: `${c.change_id.slice(0, 8)} · ${c.author}`,
1587
        detail: `${new Date(c.when_ms).toLocaleString()} · ${c.signature?.status ?? "unsigned"}${c.signature?.revoked ? " (key revoked)" : ""}`,
1588
        change: c,
1589
      }));
1590
    const pick = await vscode.window.showQuickPick(items, { placeHolder: `${log.bookmark}: ${log.total - 1} changes`, matchOnDescription: true, matchOnDetail: true });
1591
    if (pick) {
1592
      const doc = await vscode.workspace.openTextDocument({ content: pick.change.message, language: "markdown" });
1593
      await vscode.window.showTextDocument(doc, { preview: true });
1594
    }
1595
  } catch (e) {
1596
    showError(e);
1597
  }
1598
}
1599
1600
function showError(e: unknown): void {
1601
  const message = e instanceof OxyError ? e.message : String(e);
1602
  void vscode.window.showErrorMessage(`Oxygen: ${message}`, "Show Output").then((pick) => pick && output.show());
1603
}