OXYGENHUB
# dac6876e4d08 oxygen-vscode / src / oxy.ts
20.2 KiB · last changed Withdraw tags, verify the transparency log, shallow clones, keep a side or both sides of a conflict, commit and amend by paths, merge remote bookmarks (closes #11) 6 days ago source blame history raw
1
// The oxy process wrapper: one function per command the extension uses,
2
// all through `oxy --plain --json` (spec §4). This module never imports
3
// the vscode API so it can be tested with plain Node.
4
5
import { execFile } from "node:child_process";
6
import { SigningInfo, parseIdentityShow } from "./commitbox";
7
import { existsSync } from "node:fs";
8
import { homedir } from "node:os";
9
import { join } from "node:path";
10
11
export interface RunResult {
12
  code: number;
13
  stdout: Buffer;
14
  stderr: string;
15
}
16
17
export class OxyError extends Error {
18
  constructor(
19
    public readonly args: string[],
20
    public readonly code: number,
21
    public readonly stderr: string,
22
  ) {
23
    super(stderr.trim() || `oxy ${args.join(" ")} exited with status ${code}`);
24
    this.name = "OxyError";
25
  }
26
}
27
28
/** Where to find `oxy`: the configured path, else `oxy` on PATH, else ~/.local/bin/oxy. */
29
export function findBinary(configured: string | undefined): string {
30
  if (configured && configured.trim()) {
31
    return configured.trim();
32
  }
33
  const local = join(homedir(), ".local", "bin", "oxy");
34
  return existsSync(local) ? local : "oxy";
35
}
36
37
export type Logger = (line: string) => void;
38
39
export class Oxy {
40
  constructor(
41
    public readonly binary: string,
42
    private readonly logger: Logger = () => {},
43
  ) {}
44
45
  /** Run oxy in `cwd`; resolves with the exit status, never rejects on a non-zero status. */
46
  run(cwd: string, args: string[]): Promise<RunResult> {
47
    const started = Date.now();
48
    const full = ["--plain", ...args];
49
    return new Promise((resolve, reject) => {
50
      execFile(
51
        this.binary,
52
        full,
53
        { cwd, maxBuffer: 256 * 1024 * 1024, encoding: "buffer", env: { ...process.env, NO_COLOR: "1" } },
54
        (error, stdout, stderr) => {
55
          const err = stderr.toString("utf8");
56
          const code = error && typeof (error as NodeJS.ErrnoException).code === "number" ? ((error as NodeJS.ErrnoException).code as unknown as number) : error ? -1 : 0;
57
          this.logger(`oxy ${args.join(" ")} (${cwd}) → ${code} in ${Date.now() - started} ms${err.trim() ? `: ${err.trim()}` : ""}`);
58
          if (error && (error as NodeJS.ErrnoException).code === "ENOENT") {
59
            reject(new OxyError(full, -1, `oxy not found at ${this.binary}`));
60
            return;
61
          }
62
          resolve({ code, stdout: stdout as Buffer, stderr: err });
63
        },
64
      );
65
    });
66
  }
67
68
  /** Run and require success (exit 0, or one of `okCodes`). */
69
  async check(cwd: string, args: string[], okCodes: number[] = [0]): Promise<RunResult> {
70
    const r = await this.run(cwd, args);
71
    if (!okCodes.includes(r.code)) {
72
      throw new OxyError(args, r.code, r.stderr);
73
    }
74
    return r;
75
  }
76
77
  async json<T>(cwd: string, args: string[], okCodes: number[] = [0]): Promise<T> {
78
    const r = await this.check(cwd, [...args, "--json"], okCodes);
79
    const text = r.stdout.toString("utf8").trim();
80
    try {
81
      return JSON.parse(text) as T;
82
    } catch (e) {
83
      throw new OxyError(args, r.code, `oxy ${args.join(" ")} did not print JSON: ${text.slice(0, 200)}`);
84
    }
85
  }
86
87
  // ---------------------------------------------------------------- commands
88
89
  async version(): Promise<VersionInfo> {
90
    return this.json<VersionInfo>(process.cwd(), ["version"]);
91
  }
92
93
  /** The repository containing `cwd`, or null when there is none. */
94
  async root(cwd: string): Promise<RootInfo | null> {
95
    const r = await this.run(cwd, ["root", "--json"]);
96
    if (r.code !== 0) {
97
      return null;
98
    }
99
    const v = JSON.parse(r.stdout.toString("utf8"));
100
    return v === null ? null : (v as RootInfo);
101
  }
102
103
  status(root: string): Promise<StatusInfo> {
104
    return this.json<StatusInfo>(root, ["status"], [0, 2]);
105
  }
106
107
  async prompt(root: string, format?: string): Promise<string> {
108
    const args = ["prompt", "--glyphs"];
109
    if (format) {
110
      args.push("--format", format);
111
    }
112
    const r = await this.run(root, args);
113
    return r.code === 0 ? r.stdout.toString("utf8").trim() : "";
114
  }
115
116
  /** File content at a state; `change` may be a hash prefix, id prefix, bookmark, or tag. */
117
  async cat(root: string, path: string, change?: string): Promise<Buffer> {
118
    const args = ["cat", path];
119
    if (change) {
120
      args.push("-r", change);
121
    }
122
    return (await this.check(root, args)).stdout;
123
  }
124
125
  log(root: string, limit?: number, path?: string): Promise<LogInfo> {
126
    const args = ["log"];
127
    if (limit !== undefined) {
128
      args.push("-n", String(limit));
129
    }
130
    if (path) {
131
      args.push("--path", path);
132
    }
133
    return this.json<LogInfo>(root, args);
134
  }
135
136
  commit(root: string, message: string, paths: string[] = []): Promise<void> {
137
    return this.check(root, ["commit", "-m", message, ...paths]).then(() => undefined);
138
  }
139
140
  /** The local bookmarks; with `all`, remotes' bookmarks with no local one too, named `REMOTE/NAME`. */
141
  bookmarks(root: string, all = false): Promise<BookmarkInfo[]> {
142
    return this.json<BookmarkInfo[]>(root, ["bookmark", "list", ...(all ? ["--all"] : [])]);
143
  }
144
145
  /** Restore paths to the working copy's base. */
146
  discard(root: string, paths: string[]): Promise<void> {
147
    return this.check(root, ["discard", ...paths]).then(() => undefined);
148
  }
149
150
  discardHunks(root: string, hunks: number[]): Promise<void> {
151
    return this.check(root, ["discard", "--hunks", hunks.join(",")]).then(() => undefined);
152
  }
153
154
  hunks(root: string): Promise<HunkInfo[]> {
155
    return this.json<HunkInfo[]>(root, ["hunks"]);
156
  }
157
158
  commitHunks(root: string, message: string, hunks: number[]): Promise<void> {
159
    return this.check(root, ["commit", "-m", message, "--hunks", hunks.join(",")]).then(() => undefined);
160
  }
161
162
  /** Fold the working copy into the head it sits on; with `paths`, only those (the rest stays uncommitted). */
163
  amend(root: string, message?: string, paths: string[] = []): Promise<void> {
164
    const args = ["amend"];
165
    if (message) {
166
      args.push("-m", message);
167
    }
168
    return this.check(root, [...args, ...paths]).then(() => undefined);
169
  }
170
171
  undo(root: string): Promise<string> {
172
    return this.check(root, ["undo"]).then((r) => r.stdout.toString("utf8").trim());
173
  }
174
175
  opLog(root: string): Promise<OperationInfo[]> {
176
    return this.json<OperationInfo[]>(root, ["op", "log"]);
177
  }
178
179
  // ---------------------------------------------------------------- bookmarks
180
181
  bookmarkCreate(root: string, name: string, changes: string[] = []): Promise<void> {
182
    return this.check(root, ["bookmark", "create", name, ...changes]).then(() => undefined);
183
  }
184
185
  bookmarkSwitch(root: string, name: string, discard = false): Promise<void> {
186
    const args = ["bookmark", "switch", name];
187
    if (discard) {
188
      args.push("--discard");
189
    }
190
    return this.check(root, args).then(() => undefined);
191
  }
192
193
  bookmarkDelete(root: string, name: string): Promise<void> {
194
    return this.check(root, ["bookmark", "delete", name]).then(() => undefined);
195
  }
196
197
  /** Union a bookmark's heads into the current one: a local bookmark, or a remote's (`origin/develop`) as last fetched. */
198
  merge(root: string, name: string): Promise<string> {
199
    return this.check(root, ["merge", name]).then((r) => r.stdout.toString("utf8").trim());
200
  }
201
202
  // ---------------------------------------------------------------- remotes and sync
203
204
  remotes(root: string): Promise<RemoteInfo[]> {
205
    return this.json<RemoteInfo[]>(root, ["remote", "list"]);
206
  }
207
208
  fetch(root: string, remote?: string): Promise<FetchInfo> {
209
    return this.json<FetchInfo>(root, ["fetch", ...(remote ? [remote] : [])]);
210
  }
211
212
  pull(root: string, remote?: string): Promise<PullInfo> {
213
    return this.json<PullInfo>(root, ["pull", ...(remote ? [remote] : [])]);
214
  }
215
216
  push(root: string, remote?: string, bookmark?: string, force = false): Promise<PushResult[]> {
217
    const args = ["push", ...(remote ? [remote] : [])];
218
    if (bookmark) {
219
      args.push("-b", bookmark);
220
    }
221
    if (force) {
222
      args.push("--force");
223
    }
224
    return this.json<PushResult[]>(root, args, [0, 1]);
225
  }
226
227
  /** Clone `url` into `dest`; `depth` makes it shallow (0: the latest state only, from the remote's checkpoint). */
228
  clone(cwd: string, url: string, dest: string, depth?: number): Promise<void> {
229
    return this.check(cwd, ["clone", ...(depth !== undefined ? ["--depth", String(depth)] : []), url, dest]).then(() => undefined);
230
  }
231
232
  // ---------------------------------------------------------------- history and blame
233
234
  blame(root: string, path: string): Promise<BlameLine[]> {
235
    return this.json<BlameLine[]>(root, ["blame", path]);
236
  }
237
238
  show(root: string, change: string): Promise<ShowInfo> {
239
    return this.json<ShowInfo>(root, ["show", change]);
240
  }
241
242
  /** The rendered diff of a change (or the working copy), as `oxy diff` prints it. */
243
  diffText(root: string, change?: string): Promise<string> {
244
    return this.check(root, ["diff", ...(change ? [change] : [])]).then((r) => r.stdout.toString("utf8"));
245
  }
246
247
  describe(root: string, change: string, message: string): Promise<void> {
248
    return this.check(root, ["describe", change, "-m", message]).then(() => undefined);
249
  }
250
251
  abandon(root: string, change: string): Promise<string> {
252
    return this.check(root, ["abandon", change]).then((r) => r.stdout.toString("utf8").trim());
253
  }
254
255
  /** The configured identity and how commits are signed; `null` without one. */
256
  identity(root: string): Promise<SigningInfo | null> {
257
    return this.check(root, ["identity", "show"]).then((r) => parseIdentityShow(r.stdout.toString("utf8")));
258
  }
259
260
  /** Split a head: the edits to `paths` become a separate first change. Returns oxy's summary line. */
261
  split(root: string, change: string, paths: string[]): Promise<string> {
262
    return this.check(root, ["split", change, ...paths]).then((r) => r.stdout.toString("utf8").trim());
263
  }
264
265
  /** Fold `change` into its dependency `into`, which keeps its ChangeId. */
266
  squash(root: string, change: string, into: string): Promise<string> {
267
    return this.check(root, ["squash", change, "--into", into]).then((r) => r.stdout.toString("utf8").trim());
268
  }
269
270
  /** Re-express `change` against the state of `onto` (changes, a bookmark or a tag). */
271
  rebase(root: string, change: string, onto: string[]): Promise<string> {
272
    return this.check(root, ["rebase", change, "--onto", ...onto]).then((r) => r.stdout.toString("utf8").trim());
273
  }
274
275
  checkout(root: string, changes: string[], discard = false): Promise<void> {
276
    return this.check(root, ["checkout", ...changes, ...(discard ? ["--discard"] : [])]).then(() => undefined);
277
  }
278
279
  tagCreate(root: string, name: string, changes: string[] = [], message = ""): Promise<void> {
280
    return this.check(root, ["tag", "create", name, ...changes, "-m", message]).then(() => undefined);
281
  }
282
283
  /**
284
   * Withdraw a tag (`oxy tag delete`): a signed withdrawal kept beside the
285
   * tag's creation, which push sends on; the name is never used again.
286
   * Returns oxy's summary line.
287
   */
288
  tagWithdraw(root: string, name: string, reason: string): Promise<string> {
289
    return this.check(root, ["tag", "delete", name, "-r", reason]).then((r) => r.stdout.toString("utf8").trim().split("\n")[0].replace(/^\* /, ""));
290
  }
291
292
  // ---------------------------------------------------------------- settling conflicts
293
294
  /**
295
   * Settle the replace conflicts (binary files, subrepo pins) at `paths`
296
   * with what the working copy holds there (oxygen#140); the next commit
297
   * records the resolution. Returns the status after it.
298
   */
299
  resolvePaths(root: string, paths: string[]): Promise<StatusInfo> {
300
    return this.json<StatusInfo>(root, ["resolve", ...paths], [0, 2]);
301
  }
302
303
  /**
304
   * Settle adjacent insertions (two changes adding lines at the same place)
305
   * by keeping every side, earliest change first, or latest with `reverse`
306
   * (oxygen#121). No paths: every conflicted text file. What was kept and
307
   * what keeps its markers, and why.
308
   */
309
  resolveBoth(root: string, paths: string[] = [], reverse = false): Promise<KeptBoth> {
310
    return this.check(root, ["resolve", "--both", ...(reverse ? ["--reverse"] : []), ...paths], [0, 2]).then((r) => parseKeptBoth(r.stdout.toString("utf8")));
311
  }
312
313
  // ---------------------------------------------------------------- transparency log
314
315
  /**
316
   * Audit a hub's whole transparency log (`oxy tlog verify`): its checkpoint
317
   * against the log key and the last one seen, and every entry against the
318
   * root; then this repository's entries. `hub` defaults to the remote.
319
   */
320
  tlogVerify(root: string, hub?: string): Promise<TlogInfo> {
321
    return this.json<TlogInfo>(root, ["tlog", "verify", ...(hub ? [hub] : [])]);
322
  }
323
324
  // ---------------------------------------------------------------- subrepos, bisect, trust, tags, workspaces
325
326
  submodules(root: string): Promise<SubrepoInfo[]> {
327
    return this.json<SubrepoInfo[]>(root, ["submodule", "status"]);
328
  }
329
330
  submoduleUpdate(root: string, init: boolean, paths: string[] = []): Promise<string> {
331
    return this.check(root, ["submodule", "update", ...(init ? ["--init"] : []), ...paths], [0, 1]).then((r) => r.stdout.toString("utf8"));
332
  }
333
334
  bisectStatus(root: string): Promise<BisectStatus | null> {
335
    return this.json<BisectStatus | null>(root, ["bisect", "status"]);
336
  }
337
338
  bisectStart(root: string): Promise<void> {
339
    return this.check(root, ["bisect", "start"]).then(() => undefined);
340
  }
341
342
  bisectMark(root: string, verdict: "good" | "bad" | "skip", changes: string[] = []): Promise<string> {
343
    return this.check(root, ["bisect", verdict, ...changes]).then((r) => r.stdout.toString("utf8").trim());
344
  }
345
346
  bisectRun(root: string, command: string[]): Promise<string> {
347
    return this.check(root, ["bisect", "run", ...command], [0, 1]).then((r) => r.stdout.toString("utf8").trim());
348
  }
349
350
  bisectReset(root: string): Promise<void> {
351
    return this.check(root, ["bisect", "reset"]).then(() => undefined);
352
  }
353
354
  policyShow(root: string): Promise<PolicyInfo | null> {
355
    return this.json<PolicyInfo | null>(root, ["policy", "show"]);
356
  }
357
358
  verify(root: string, change?: string): Promise<VerifyInfo[]> {
359
    return this.json<VerifyInfo[]>(root, ["verify", ...(change ? [change] : [])], [0, 1]);
360
  }
361
362
  tags(root: string): Promise<TagInfo[]> {
363
    return this.json<TagInfo[]>(root, ["tag", "list"]);
364
  }
365
366
  workspaces(root: string): Promise<WorkspaceInfo[]> {
367
    return this.json<WorkspaceInfo[]>(root, ["workspace", "list"]);
368
  }
369
370
  workspaceAdd(root: string, path: string, changes: string[] = []): Promise<void> {
371
    return this.check(root, ["workspace", "add", path, ...changes]).then(() => undefined);
372
  }
373
}
374
375
export interface SubrepoInfo {
376
  path: string;
377
  pin: PinInfo;
378
  actual: PinInfo | null;
379
  at_pin: boolean;
380
  dirty: boolean;
381
  url: string | null;
382
}
383
384
export type PinInfo = { kind: "oxy"; repo: string; heads: string[]; bookmark: string } | { kind: "git"; sha: string; branch: string };
385
386
export type BisectStatus =
387
  | { state: "need-marks"; good: number; bad: number }
388
  | { state: "testing"; heads: string[]; remaining: number; steps_left: number }
389
  | { state: "found"; culprit: string }
390
  | { state: "inconclusive"; candidates: string[] };
391
392
export interface PolicyInfo {
393
  hash: string;
394
  serial: number;
395
  expires_ms: number;
396
  expired: boolean;
397
  root_threshold: number;
398
  roots: { key: string; name: string; email: string }[];
399
  rules: { pattern: string; keys: { key: string; name: string; email: string }[]; threshold: number; require: string; allow_conflicts: boolean }[];
400
  revoked: { key: string; name: string; email: string }[];
401
}
402
403
export interface VerifyInfo {
404
  hash: string;
405
  change_id: string;
406
  status: string;
407
  key: string | null;
408
  name: string | null;
409
  revoked: boolean;
410
  reason: string | null;
411
}
412
413
/** What `oxy resolve --both` did: the conflicts kept on every side, and those left with markers. */
414
export interface KeptBoth {
415
  kept: { path: string; conflicts: number[] }[];
416
  left: { path: string; conflict: number; why: string }[];
417
}
418
419
/** Read `oxy resolve --both`'s report lines (`kept both  PATH: conflict 1, 2`, `markers    PATH: conflict 3: why`). */
420
export function parseKeptBoth(text: string): KeptBoth {
421
  const out: KeptBoth = { kept: [], left: [] };
422
  for (const line of text.split(/\r?\n/)) {
423
    const kept = /^kept both\s+(.+): conflicts? ([\d, ]+)$/.exec(line);
424
    if (kept) {
425
      out.kept.push({ path: kept[1], conflicts: kept[2].split(",").map((n) => Number(n.trim())).filter((n) => n > 0) });
426
      continue;
427
    }
428
    const left = /^markers\s+(.+): conflict (\d+): (.+)$/.exec(line);
429
    if (left) {
430
      out.left.push({ path: left[1], conflict: Number(left[2]), why: left[3] });
431
    }
432
  }
433
  return out;
434
}
435
436
/** `oxy tlog verify --json`: the checkpoint verified, who cosigned it, and the entries listed. */
437
export interface TlogInfo {
438
  hub: string;
439
  origin: string;
440
  /** Entries in the log the checkpoint covers. */
441
  size: number;
442
  root: string;
443
  witnesses: { name: string; time_ms: number }[];
444
  entries: { index: number; kind: string; repo: string; object: string; signers: string[]; received_ms: number }[];
445
}
446
447
/**
448
 * A remote's bookmark that `bookmark list --all` adds because there is no
449
 * local bookmark of that name: named `REMOTE/NAME`, never current, with no
450
 * ahead or behind counts. `oxy merge` takes the name as it is.
451
 */
452
export function isRemoteBookmark(b: BookmarkInfo): boolean {
453
  return !!b.remote && b.name.startsWith(`${b.remote}/`) && !b.current && b.ahead === null && b.behind === null;
454
}
455
456
/** What Merge Bookmark offers: the other local bookmarks first, then remotes' bookmarks. */
457
export function mergeChoices(bookmarks: BookmarkInfo[]): { name: string; remote: string | null; heads: number }[] {
458
  const local = bookmarks.filter((b) => !b.current && !isRemoteBookmark(b)).map((b) => ({ name: b.name, remote: null, heads: b.heads.length }));
459
  const remote = bookmarks.filter(isRemoteBookmark).map((b) => ({ name: b.name, remote: b.remote ?? null, heads: b.heads.length }));
460
  return [...local, ...remote];
461
}
462
463
export interface TagInfo {
464
  name: string;
465
  state: string;
466
  heads: string[];
467
  message: string;
468
  signer: string | null;
469
}
470
471
export interface WorkspaceInfo {
472
  id: string;
473
  path: string;
474
  current: boolean;
475
  working_copy: string | null;
476
}
477
478
export interface BlameLine {
479
  line: number;
480
  change_id: string;
481
  hash: string;
482
  index: number;
483
  author: string;
484
  when_ms: number;
485
}
486
487
export interface ShowInfo extends LogEntry {
488
  files: { path: string; kind: string; from: string | null }[];
489
}
490
491
export interface RemoteInfo {
492
  name: string;
493
  url: string;
494
  /** The CA file `remote.NAME.ca` names (a self-signed hub), if any. */
495
  ca?: string | null;
496
  bookmarks: { name: string; heads: string[] }[];
497
}
498
499
export interface FetchInfo {
500
  remote: string;
501
  refs: { name: string; heads: string[]; new: number }[];
502
  new_tags: number;
503
  unverified: boolean;
504
}
505
506
export interface PullInfo {
507
  remote: string;
508
  heads: string[];
509
  changed: boolean;
510
  checked_out: boolean;
511
  conflicted: boolean;
512
}
513
514
export interface PushResult {
515
  name: string;
516
  ok: boolean;
517
  reason: string;
518
}
519
520
export interface HunkInfo {
521
  index: number;
522
  path: string;
523
  text: string;
524
}
525
526
export interface OperationInfo {
527
  id: string;
528
  when_ms: number;
529
  command: string;
530
  snapshot: boolean;
531
  current: boolean;
532
}
533
534
// ---------------------------------------------------------------- types
535
536
export interface VersionInfo {
537
  version: string;
538
  protocol: number;
539
  format: number;
540
}
541
542
export interface RootInfo {
543
  root: string;
544
  workspace: string;
545
  bookmark: string;
546
}
547
548
export type PathStatus = "Added" | "Modified" | "Removed" | "Renamed" | "ModeChanged" | "ConflictEdited" | "Resolved";
549
550
export interface StatusInfo {
551
  bookmark: string;
552
  working_copy: string;
553
  heads: number;
554
  clean: boolean;
555
  conflicted: boolean;
556
  paths: { path: string; status: PathStatus }[];
557
  conflicts: ConflictInfo[];
558
}
559
560
export interface ConflictInfo {
561
  kind: string;
562
  path?: string;
563
  node?: string;
564
  nodes?: string[];
565
  changes?: string[];
566
  resolved?: boolean | "markers";
567
}
568
569
export interface LogEntry {
570
  hash: string;
571
  change_id: string;
572
  author: string;
573
  author_key: string;
574
  when_ms: number;
575
  message: string;
576
  kind: string;
577
  deps: string[];
578
  head: boolean;
579
  working_copy: boolean;
580
  signature: { status: string; key?: string; name?: string; revoked?: boolean; reason?: string } | null;
581
}
582
583
export interface LogInfo {
584
  bookmark: string;
585
  total: number;
586
  changes: LogEntry[];
587
}
588
589
export interface BookmarkInfo {
590
  name: string;
591
  heads: string[];
592
  current: boolean;
593
  ahead: number | null;
594
  behind: number | null;
595
  /** The remote it tracks, or for a remote's bookmark (`--all`) the remote it is on. */
596
  remote?: string | null;
597
}