OXYGENHUB

Coverage / src/oxy.ts 62.0%

310 of 500 lines run, 65 of 75 functions, 82 of 96 branches · run #22 on main · run missed

10×
// The oxy process wrapper: one function per command the extension uses,
20×
// all through `oxy --plain --json` (spec §4). This module never imports
30×
// the vscode API so it can be tested with plain Node.
41×
51×
import { execFile } from "node:child_process";
61×
import { SigningInfo, parseIdentityShow } from "./commitbox";
71×
import { existsSync } from "node:fs";
81×
import { homedir } from "node:os";
91×
import { join } from "node:path";
101×
111×
export interface RunResult {
121×
  code: number;
131×
  stdout: Buffer;
141×
  stderr: string;
151×
}
161×
171×
export class OxyError extends Error {
181×
  constructor(
193×
    public readonly args: string[],
203×
    public readonly code: number,
213×
    public readonly stderr: string,
223×
  ) {
233×
    super(stderr.trim() || `oxy ${args.join(" ")} exited with status ${code}`);
243×
    this.name = "OxyError";
253×
  }
260×
}
270×
280×
/** Where to find `oxy`: the configured path, else `oxy` on PATH, else ~/.local/bin/oxy. */
290×
export function findBinary(configured: string | undefined): string {
300×
  if (configured && configured.trim()) {
310×
    return configured.trim();
320×
  }
330×
  const local = join(homedir(), ".local", "bin", "oxy");
340×
  return existsSync(local) ? local : "oxy";
350×
}
361×
371×
export type Logger = (line: string) => void;
381×
391×
export class Oxy {
401×
  constructor(
411×
    public readonly binary: string,
421×
    private readonly logger: Logger = () => {},
431×
  ) {}
441×
451×
  /** Run oxy in `cwd`; resolves with the exit status, never rejects on a non-zero status. */
461×
  run(cwd: string, args: string[]): Promise<RunResult> {
4782×
    const started = Date.now();
4882×
    const full = ["--plain", ...args];
4982×
    return new Promise((resolve, reject) => {
5082×
      execFile(
5182×
        this.binary,
5282×
        full,
5382×
        { cwd, maxBuffer: 256 * 1024 * 1024, encoding: "buffer", env: { ...process.env, NO_COLOR: "1" } },
5482×
        (error, stdout, stderr) => {
5582×
          const err = stderr.toString("utf8");
5682×
          const code = error && typeof (error as NodeJS.ErrnoException).code === "number" ? ((error as NodeJS.ErrnoException).code as unknown as number) : error ? -1 : 0;
5782×
          this.logger(`oxy ${args.join(" ")} (${cwd}) → ${code} in ${Date.now() - started} ms${err.trim() ? `: ${err.trim()}` : ""}`);
5882×
          if (error && (error as NodeJS.ErrnoException).code === "ENOENT") {
590×
            reject(new OxyError(full, -1, `oxy not found at ${this.binary}`));
600×
            return;
610×
          }
6282×
          resolve({ code, stdout: stdout as Buffer, stderr: err });
6382×
        },
6482×
      );
6582×
    });
6682×
  }
671×
681×
  /** Run and require success (exit 0, or one of `okCodes`). */
691×
  async check(cwd: string, args: string[], okCodes: number[] = [0]): Promise<RunResult> {
7079×
    const r = await this.run(cwd, args);
7179×
    if (!okCodes.includes(r.code)) {
723×
      throw new OxyError(args, r.code, r.stderr);
733×
    }
7479×
    return r;
7579×
  }
761×
771×
  async json<T>(cwd: string, args: string[], okCodes: number[] = [0]): Promise<T> {
7839×
    const r = await this.check(cwd, [...args, "--json"], okCodes);
7939×
    const text = r.stdout.toString("utf8").trim();
8039×
    try {
8139×
      return JSON.parse(text) as T;
8239×
    } catch (e) {
830×
      throw new OxyError(args, r.code, `oxy ${args.join(" ")} did not print JSON: ${text.slice(0, 200)}`);
840×
    }
8539×
  }
861×
871×
  // ---------------------------------------------------------------- commands
881×
891×
  async version(): Promise<VersionInfo> {
901×
    return this.json<VersionInfo>(process.cwd(), ["version"]);
911×
  }
921×
931×
  /** The repository containing `cwd`, or null when there is none. */
941×
  async root(cwd: string): Promise<RootInfo | null> {
952×
    const r = await this.run(cwd, ["root", "--json"]);
962×
    if (r.code !== 0) {
971×
      return null;
981×
    }
991×
    const v = JSON.parse(r.stdout.toString("utf8"));
1002×
    return v === null ? null : (v as RootInfo);
1012×
  }
1021×
1031×
  status(root: string): Promise<StatusInfo> {
1046×
    return this.json<StatusInfo>(root, ["status"], [0, 2]);
1056×
  }
1061×
1071×
  async prompt(root: string, format?: string): Promise<string> {
1081×
    const args = ["prompt", "--glyphs"];
1091×
    if (format) {
1100×
      args.push("--format", format);
1110×
    }
1121×
    const r = await this.run(root, args);
1131×
    return r.code === 0 ? r.stdout.toString("utf8").trim() : "";
1141×
  }
1151×
1161×
  /** File content at a state; `change` may be a hash prefix, id prefix, bookmark, or tag. */
1171×
  async cat(root: string, path: string, change?: string): Promise<Buffer> {
1185×
    const args = ["cat", path];
1195×
    if (change) {
1200×
      args.push("-r", change);
1210×
    }
1225×
    return (await this.check(root, args)).stdout;
1235×
  }
1241×
1251×
  log(root: string, limit?: number, path?: string): Promise<LogInfo> {
12610×
    const args = ["log"];
12710×
    if (limit !== undefined) {
12810×
      args.push("-n", String(limit));
12910×
    }
13010×
    if (path) {
1311×
      args.push("--path", path);
1321×
    }
13310×
    return this.json<LogInfo>(root, args);
13410×
  }
1351×
1361×
  commit(root: string, message: string, paths: string[] = []): Promise<void> {
1377×
    return this.check(root, ["commit", "-m", message, ...paths]).then(() => undefined);
1387×
  }
1391×
1401×
  bookmarks(root: string): Promise<BookmarkInfo[]> {
1414×
    return this.json<BookmarkInfo[]>(root, ["bookmark", "list"]);
1424×
  }
1431×
1441×
  /** Restore paths to the working copy's base. */
1451×
  discard(root: string, paths: string[]): Promise<void> {
1461×
    return this.check(root, ["discard", ...paths]).then(() => undefined);
1471×
  }
1481×
1491×
  discardHunks(root: string, hunks: number[]): Promise<void> {
1500×
    return this.check(root, ["discard", "--hunks", hunks.join(",")]).then(() => undefined);
1510×
  }
1521×
1531×
  hunks(root: string): Promise<HunkInfo[]> {
1541×
    return this.json<HunkInfo[]>(root, ["hunks"]);
1551×
  }
1561×
1571×
  commitHunks(root: string, message: string, hunks: number[]): Promise<void> {
1581×
    return this.check(root, ["commit", "-m", message, "--hunks", hunks.join(",")]).then(() => undefined);
1591×
  }
1601×
1611×
  amend(root: string, message?: string): Promise<void> {
1621×
    const args = ["amend"];
1631×
    if (message) {
1641×
      args.push("-m", message);
1651×
    }
1661×
    return this.check(root, args).then(() => undefined);
1671×
  }
1681×
1691×
  undo(root: string): Promise<string> {
1702×
    return this.check(root, ["undo"]).then((r) => r.stdout.toString("utf8").trim());
1712×
  }
1721×
1731×
  opLog(root: string): Promise<OperationInfo[]> {
1741×
    return this.json<OperationInfo[]>(root, ["op", "log"]);
1751×
  }
1761×
1771×
  // ---------------------------------------------------------------- bookmarks
1781×
1791×
  bookmarkCreate(root: string, name: string, changes: string[] = []): Promise<void> {
1801×
    return this.check(root, ["bookmark", "create", name, ...changes]).then(() => undefined);
1811×
  }
1821×
1831×
  bookmarkSwitch(root: string, name: string, discard = false): Promise<void> {
1843×
    const args = ["bookmark", "switch", name];
1853×
    if (discard) {
1860×
      args.push("--discard");
1870×
    }
1883×
    return this.check(root, args).then(() => undefined);
1893×
  }
1901×
1911×
  bookmarkDelete(root: string, name: string): Promise<void> {
1921×
    return this.check(root, ["bookmark", "delete", name]).then(() => undefined);
1931×
  }
1941×
1951×
  merge(root: string, name: string): Promise<string> {
1961×
    return this.check(root, ["merge", name]).then((r) => r.stdout.toString("utf8").trim());
1971×
  }
1981×
1991×
  // ---------------------------------------------------------------- remotes and sync
2001×
2011×
  remotes(root: string): Promise<RemoteInfo[]> {
2021×
    return this.json<RemoteInfo[]>(root, ["remote", "list"]);
2031×
  }
2041×
2051×
  fetch(root: string, remote?: string): Promise<FetchInfo> {
2061×
    return this.json<FetchInfo>(root, ["fetch", ...(remote ? [remote] : [])]);
2071×
  }
2081×
2091×
  pull(root: string, remote?: string): Promise<PullInfo> {
2101×
    return this.json<PullInfo>(root, ["pull", ...(remote ? [remote] : [])]);
2111×
  }
2121×
2131×
  push(root: string, remote?: string, bookmark?: string, force = false): Promise<PushResult[]> {
2143×
    const args = ["push", ...(remote ? [remote] : [])];
2153×
    if (bookmark) {
2161×
      args.push("-b", bookmark);
2171×
    }
2183×
    if (force) {
2190×
      args.push("--force");
2200×
    }
2213×
    return this.json<PushResult[]>(root, args, [0, 1]);
2223×
  }
2231×
2241×
  clone(cwd: string, url: string, dest: string): Promise<void> {
2251×
    return this.check(cwd, ["clone", url, dest]).then(() => undefined);
2261×
  }
2271×
2281×
  // ---------------------------------------------------------------- history and blame
2291×
2301×
  blame(root: string, path: string): Promise<BlameLine[]> {
2311×
    return this.json<BlameLine[]>(root, ["blame", path]);
2321×
  }
2331×
2341×
  show(root: string, change: string): Promise<ShowInfo> {
2352×
    return this.json<ShowInfo>(root, ["show", change]);
2362×
  }
2371×
2381×
  /** The rendered diff of a change (or the working copy), as `oxy diff` prints it. */
2391×
  diffText(root: string, change?: string): Promise<string> {
2401×
    return this.check(root, ["diff", ...(change ? [change] : [])]).then((r) => r.stdout.toString("utf8"));
2411×
  }
2421×
2431×
  describe(root: string, change: string, message: string): Promise<void> {
2440×
    return this.check(root, ["describe", change, "-m", message]).then(() => undefined);
2450×
  }
2461×
2471×
  abandon(root: string, change: string): Promise<string> {
2480×
    return this.check(root, ["abandon", change]).then((r) => r.stdout.toString("utf8").trim());
2490×
  }
2501×
2511×
  /** The configured identity and how commits are signed; `null` without one. */
2521×
  identity(root: string): Promise<SigningInfo | null> {
2532×
    return this.check(root, ["identity", "show"]).then((r) => parseIdentityShow(r.stdout.toString("utf8")));
2542×
  }
2551×
2561×
  /** Split a head: the edits to `paths` become a separate first change. Returns oxy's summary line. */
2571×
  split(root: string, change: string, paths: string[]): Promise<string> {
2581×
    return this.check(root, ["split", change, ...paths]).then((r) => r.stdout.toString("utf8").trim());
2591×
  }
2601×
2611×
  /** Fold `change` into its dependency `into`, which keeps its ChangeId. */
2621×
  squash(root: string, change: string, into: string): Promise<string> {
2631×
    return this.check(root, ["squash", change, "--into", into]).then((r) => r.stdout.toString("utf8").trim());
2641×
  }
2651×
2661×
  /** Re-express `change` against the state of `onto` (changes, a bookmark or a tag). */
2671×
  rebase(root: string, change: string, onto: string[]): Promise<string> {
2681×
    return this.check(root, ["rebase", change, "--onto", ...onto]).then((r) => r.stdout.toString("utf8").trim());
2691×
  }
2701×
2711×
  checkout(root: string, changes: string[], discard = false): Promise<void> {
2720×
    return this.check(root, ["checkout", ...changes, ...(discard ? ["--discard"] : [])]).then(() => undefined);
2730×
  }
2741×
2751×
  tagCreate(root: string, name: string, changes: string[] = [], message = ""): Promise<void> {
2761×
    return this.check(root, ["tag", "create", name, ...changes, "-m", message]).then(() => undefined);
2771×
  }
2781×
2791×
  // ---------------------------------------------------------------- subrepos, bisect, trust, tags, workspaces
2801×
2811×
  submodules(root: string): Promise<SubrepoInfo[]> {
2821×
    return this.json<SubrepoInfo[]>(root, ["submodule", "status"]);
2831×
  }
2841×
2851×
  submoduleUpdate(root: string, init: boolean, paths: string[] = []): Promise<string> {
2860×
    return this.check(root, ["submodule", "update", ...(init ? ["--init"] : []), ...paths], [0, 1]).then((r) => r.stdout.toString("utf8"));
2870×
  }
2881×
2891×
  bisectStatus(root: string): Promise<BisectStatus | null> {
2902×
    return this.json<BisectStatus | null>(root, ["bisect", "status"]);
2912×
  }
2921×
2931×
  bisectStart(root: string): Promise<void> {
2941×
    return this.check(root, ["bisect", "start"]).then(() => undefined);
2951×
  }
2961×
2971×
  bisectMark(root: string, verdict: "good" | "bad" | "skip", changes: string[] = []): Promise<string> {
2980×
    return this.check(root, ["bisect", verdict, ...changes]).then((r) => r.stdout.toString("utf8").trim());
2990×
  }
3001×
3011×
  bisectRun(root: string, command: string[]): Promise<string> {
3020×
    return this.check(root, ["bisect", "run", ...command], [0, 1]).then((r) => r.stdout.toString("utf8").trim());
3030×
  }
3041×
3051×
  bisectReset(root: string): Promise<void> {
3061×
    return this.check(root, ["bisect", "reset"]).then(() => undefined);
3071×
  }
3081×
3091×
  policyShow(root: string): Promise<PolicyInfo | null> {
3101×
    return this.json<PolicyInfo | null>(root, ["policy", "show"]);
3111×
  }
3121×
3131×
  verify(root: string, change?: string): Promise<VerifyInfo[]> {
3141×
    return this.json<VerifyInfo[]>(root, ["verify", ...(change ? [change] : [])], [0, 1]);
3151×
  }
3161×
3171×
  tags(root: string): Promise<TagInfo[]> {
3181×
    return this.json<TagInfo[]>(root, ["tag", "list"]);
3191×
  }
3201×
3211×
  workspaces(root: string): Promise<WorkspaceInfo[]> {
3221×
    return this.json<WorkspaceInfo[]>(root, ["workspace", "list"]);
3231×
  }
3241×
3251×
  workspaceAdd(root: string, path: string, changes: string[] = []): Promise<void> {
3260×
    return this.check(root, ["workspace", "add", path, ...changes]).then(() => undefined);
3270×
  }
3281×
}
3291×
3300×
export interface SubrepoInfo {
3310×
  path: string;
3320×
  pin: PinInfo;
3330×
  actual: PinInfo | null;
3340×
  at_pin: boolean;
3350×
  dirty: boolean;
3360×
  url: string | null;
3370×
}
3381×
3390×
export type PinInfo = { kind: "oxy"; repo: string; heads: string[]; bookmark: string } | { kind: "git"; sha: string; branch: string };
3401×
3410×
export type BisectStatus =
3420×
  | { state: "need-marks"; good: number; bad: number }
3430×
  | { state: "testing"; heads: string[]; remaining: number; steps_left: number }
3440×
  | { state: "found"; culprit: string }
3450×
  | { state: "inconclusive"; candidates: string[] };
3461×
3470×
export interface PolicyInfo {
3480×
  hash: string;
3490×
  serial: number;
3500×
  expires_ms: number;
3510×
  expired: boolean;
3520×
  root_threshold: number;
3530×
  roots: { key: string; name: string; email: string }[];
3540×
  rules: { pattern: string; keys: { key: string; name: string; email: string }[]; threshold: number; require: string; allow_conflicts: boolean }[];
3550×
  revoked: { key: string; name: string; email: string }[];
3560×
}
3571×
3580×
export interface VerifyInfo {
3590×
  hash: string;
3600×
  change_id: string;
3610×
  status: string;
3620×
  key: string | null;
3630×
  name: string | null;
3640×
  revoked: boolean;
3650×
  reason: string | null;
3660×
}
3671×
3680×
export interface TagInfo {
3690×
  name: string;
3700×
  state: string;
3710×
  heads: string[];
3720×
  message: string;
3730×
  signer: string | null;
3740×
}
3751×
3760×
export interface WorkspaceInfo {
3770×
  id: string;
3780×
  path: string;
3790×
  current: boolean;
3800×
  working_copy: string | null;
3810×
}
3821×
3830×
export interface BlameLine {
3840×
  line: number;
3850×
  change_id: string;
3860×
  hash: string;
3870×
  index: number;
3880×
  author: string;
3890×
  when_ms: number;
3900×
}
3911×
3920×
export interface ShowInfo extends LogEntry {
3930×
  files: { path: string; kind: string; from: string | null }[];
3940×
}
3951×
3960×
export interface RemoteInfo {
3970×
  name: string;
3980×
  url: string;
3990×
  /** The CA file `remote.NAME.ca` names (a self-signed hub), if any. */
4000×
  ca?: string | null;
4010×
  bookmarks: { name: string; heads: string[] }[];
4020×
}
4031×
4040×
export interface FetchInfo {
4050×
  remote: string;
4060×
  refs: { name: string; heads: string[]; new: number }[];
4070×
  new_tags: number;
4080×
  unverified: boolean;
4090×
}
4101×
4110×
export interface PullInfo {
4120×
  remote: string;
4130×
  heads: string[];
4140×
  changed: boolean;
4150×
  checked_out: boolean;
4160×
  conflicted: boolean;
4170×
}
4181×
4190×
export interface PushResult {
4200×
  name: string;
4210×
  ok: boolean;
4220×
  reason: string;
4230×
}
4241×
4250×
export interface HunkInfo {
4260×
  index: number;
4270×
  path: string;
4280×
  text: string;
4290×
}
4301×
4310×
export interface OperationInfo {
4320×
  id: string;
4330×
  when_ms: number;
4340×
  command: string;
4350×
  snapshot: boolean;
4360×
  current: boolean;
4370×
}
4381×
4390×
// ---------------------------------------------------------------- types
4401×
4410×
export interface VersionInfo {
4420×
  version: string;
4430×
  protocol: number;
4440×
  format: number;
4450×
}
4461×
4470×
export interface RootInfo {
4480×
  root: string;
4490×
  workspace: string;
4500×
  bookmark: string;
4510×
}
4521×
4530×
export type PathStatus = "Added" | "Modified" | "Removed" | "Renamed" | "ModeChanged" | "ConflictEdited" | "Resolved";
4541×
4550×
export interface StatusInfo {
4560×
  bookmark: string;
4570×
  working_copy: string;
4580×
  heads: number;
4590×
  clean: boolean;
4600×
  conflicted: boolean;
4610×
  paths: { path: string; status: PathStatus }[];
4620×
  conflicts: ConflictInfo[];
4630×
}
4641×
4650×
export interface ConflictInfo {
4660×
  kind: string;
4670×
  path?: string;
4680×
  node?: string;
4690×
  nodes?: string[];
4700×
  changes?: string[];
4710×
  resolved?: boolean | "markers";
4720×
}
4731×
4740×
export interface LogEntry {
4750×
  hash: string;
4760×
  change_id: string;
4770×
  author: string;
4780×
  author_key: string;
4790×
  when_ms: number;
4800×
  message: string;
4810×
  kind: string;
4820×
  deps: string[];
4830×
  head: boolean;
4840×
  working_copy: boolean;
4850×
  signature: { status: string; key?: string; name?: string; revoked?: boolean; reason?: string } | null;
4860×
}
4871×
4880×
export interface LogInfo {
4890×
  bookmark: string;
4900×
  total: number;
4910×
  changes: LogEntry[];
4920×
}
4931×
4940×
export interface BookmarkInfo {
4950×
  name: string;
4960×
  heads: string[];
4970×
  current: boolean;
4980×
  ahead: number | null;
4990×
  behind: number | null;
5000×
}