Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 79 additions & 2 deletions packages/cli/src/commands/doctor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,23 @@ import {
mkdirSync,
mkdtempSync,
readFileSync,
realpathSync,
rmSync,
utimesSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { delimiter, join } from "node:path";
import type { ExecFileSyncOptions } from "node:child_process";
import { pathToFileURL } from "node:url";
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import { describe, it, expect, beforeEach, afterEach, onTestFinished, vi } from "vitest";
import { optionalPackageDir } from "../utils/optionalPackages.js";
import {
TESTED_FFMPEG_VERSION,
buildDoctorReport,
ffmpegDoctorDetail,
checkDocker,
checkDockerRunning,
checkFramesCache,
checkOptionalPackage,
redactHome,
Expand Down Expand Up @@ -84,6 +88,79 @@ describe("redactHome", () => {
});
});

describe("Docker checks", () => {
const dockerName = process.platform === "win32" ? "docker.exe" : "docker";

type RunFile = (file: string, args: string[], options: ExecFileSyncOptions) => string;

function dir(prefix: string): string {
const path = realpathSync(mkdtempSync(join(tmpdir(), prefix)));
onTestFinished(() => rmSync(path, { recursive: true, force: true }));
return path;
}

function projectWithDocker(): { projectBin: string; projectDocker: string } {
const project = dir("hf-doctor-project-");
const projectBin = join(project, "node_modules", ".bin");
mkdirSync(projectBin, { recursive: true });
const projectDocker = join(projectBin, dockerName);
writeFileSync(projectDocker, "#!/bin/sh\n", { mode: 0o755 });
vi.spyOn(process, "cwd").mockReturnValue(project);
onTestFinished(() => {
vi.restoreAllMocks();
vi.unstubAllEnvs();
});
return { projectBin, projectDocker };
}

it("runs docker by its absolute path from a folder outside the project, with no shell", () => {
const { projectBin } = projectWithDocker();
const outside = dir("hf-doctor-bin-");
const docker = join(outside, dockerName);
writeFileSync(docker, "#!/bin/sh\n", { mode: 0o755 });
vi.stubEnv("PATH", [projectBin, outside].join(delimiter));
const run = vi.fn<RunFile>(() => "Docker version 27.0.0\n");

expect(checkDocker(undefined, run)).toEqual({ ok: true, detail: "Docker version 27.0.0" });
expect(checkDockerRunning(undefined, run)).toEqual({ ok: true, detail: "Running" });

expect(run.mock.calls.map(([file, args]) => [file, args])).toEqual([
[docker, ["--version"]],
[docker, ["info"]],
]);
for (const [, , options] of run.mock.calls) expect(options).not.toHaveProperty("shell");
});

it("reports a docker found only inside the project as missing and says it was skipped", () => {
const { projectBin, projectDocker } = projectWithDocker();
vi.stubEnv("PATH", [projectBin, "."].join(delimiter));
const run = vi.fn<RunFile>(() => "");

const result = checkDocker(undefined, run);

expect(result.ok).toBe(false);
expect(result.detail).toBe("Not found");
expect(result.hint).toContain(projectDocker);
expect(result.hint).toContain("outside the project");
expect(result.hint).toContain("https://docs.docker.com/get-docker/");
expect(checkDockerRunning(undefined, run)).toMatchObject({ ok: false, detail: "Not running" });
expect(run).not.toHaveBeenCalled();
});

it("keeps the plain install hint when there is no docker anywhere", () => {
vi.spyOn(process, "cwd").mockReturnValue(dir("hf-doctor-empty-"));
onTestFinished(() => {
vi.restoreAllMocks();
});

expect(checkDocker(() => undefined)).toEqual({
ok: false,
detail: "Not found",
hint: "https://docs.docker.com/get-docker/",
});
});
});

describe("parseToolVersion", () => {
it("extracts ffmpeg version from full copyright line", () => {
expect(
Expand Down
50 changes: 36 additions & 14 deletions packages/cli/src/commands/doctor.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
// fallow-ignore-file complexity
import { defineCommand } from "../utils/defineCommand.js";
import { execSync } from "node:child_process";
import { execFileSync, type ExecFileSyncOptions } from "node:child_process";
import * as fs from "node:fs";
import { existsSync } from "node:fs";
import { platform } from "node:os";
import { dirname } from "node:path";
import { dirname, join } from "node:path";
import { resolveExtractCacheDir } from "@hyperframes/engine";
import { findTrustedExecutable } from "@hyperframes/parsers/ff-binaries";
import type { Example } from "./_examples.js";
Expand Down Expand Up @@ -62,22 +62,44 @@ export function ffmpegDoctorDetail(detail: string): string {
: `${detail}; loudness numbers are only comparable on ${TESTED_FFMPEG_VERSION}`;
}

function checkDocker(): CheckResult {
const DOCKER_INSTALL_HINT = "https://docs.docker.com/get-docker/";

type RunFile = (file: string, args: string[], options: ExecFileSyncOptions) => string | Buffer;

const findDocker = (): string | undefined => findTrustedExecutable("docker");

function dockerInsideProject(cwd = process.cwd()): string | undefined {
const names = process.platform === "win32" ? ["docker.exe", "docker.cmd"] : ["docker"];
return names.map((name) => join(cwd, "node_modules", ".bin", name)).find(existsSync);
}

function dockerNotFound(): CheckResult {
const skipped = dockerInsideProject();
return {
ok: false,
detail: "Not found",
hint: skipped
? `Skipped ${skipped}: the CLI only runs helper programs from folders outside the project. ${DOCKER_INSTALL_HINT}`
: DOCKER_INSTALL_HINT,
};
}

export function checkDocker(find = findDocker, run: RunFile = execFileSync): CheckResult {
const docker = find();
if (!docker) return dockerNotFound();
try {
const version = execSync("docker --version", { encoding: "utf-8", timeout: 5000 }).trim();
return { ok: true, detail: version };
const version = run(docker, ["--version"], { encoding: "utf-8", timeout: 5000 });
return { ok: true, detail: version.toString().trim() };
} catch {
return {
ok: false,
detail: "Not found",
hint: "https://docs.docker.com/get-docker/",
};
return dockerNotFound();
}
}

function checkDockerRunning(): CheckResult {
export function checkDockerRunning(find = findDocker, run: RunFile = execFileSync): CheckResult {
try {
execSync("docker info", { stdio: "pipe", timeout: 5000 });
const docker = find();
if (!docker) throw new Error("docker not found");
run(docker, ["info"], { stdio: "pipe", timeout: 5000 });
return { ok: true, detail: "Running" };
} catch {
return {
Expand Down Expand Up @@ -432,8 +454,8 @@ export default defineCommand({
});
}
for (const check of [
{ name: "Docker", run: checkDocker },
{ name: "Docker running", run: checkDockerRunning },
{ name: "Docker", run: () => checkDocker() },
{ name: "Docker running", run: () => checkDockerRunning() },
]) {
const result = await check.run();
outcomes.push({
Expand Down
19 changes: 6 additions & 13 deletions packages/cli/src/commands/media-use.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { defineCommand } from "../utils/defineCommand.js";
import { delimiter, dirname, join, resolve } from "node:path";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { spawnSync } from "node:child_process";
import { existsSync } from "node:fs";
import { finishCommand } from "../utils/commandResult.js";
import { withMediaAuthEnvironment } from "../auth/media-environment.js";
import { trustedPathDirs } from "@hyperframes/parsers/ff-binaries";
import { skipWorkingDirectoryInExeSearch } from "../utils/windowsExeSearch.js";
import {
skipWorkingDirectoryInExeSearch,
withOnlyTrustedPathFolders,
} from "../utils/windowsExeSearch.js";

const MEDIA_USE_ARGS = {
type: { type: "string", description: "What to find: bgm, sfx, image, icon, logo, voice" },
Expand Down Expand Up @@ -77,21 +79,12 @@ export function mediaUseVerbFlags(verb: MediaUseVerb): string[] {
return verb === "resolve" ? [] : [`--${verb}`];
}

const NEVER_CREATED_PATH_FOLDER = fileURLToPath(new URL("no-trusted-path-folder", import.meta.url));

function withOnlyTrustedPathFolders(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
const pathKey = Object.keys(env).find((name) => name.toUpperCase() === "PATH");
if (!pathKey) return { ...env };
const dirs = trustedPathDirs(env[pathKey]);
return { ...env, [pathKey]: dirs.length > 0 ? dirs.join(delimiter) : NEVER_CREATED_PATH_FOLDER };
}

export function mediaUseEngineEnv(
env: NodeJS.ProcessEnv,
entry: string | undefined = process.argv[1],
platform: NodeJS.Platform = process.platform,
): NodeJS.ProcessEnv {
const scoped = withOnlyTrustedPathFolders(env);
const scoped = withOnlyTrustedPathFolders(env, platform);
skipWorkingDirectoryInExeSearch(scoped, platform);
if (!entry || /\.[cm]?ts$/.test(entry)) return scoped;
return { ...scoped, HYPERFRAMES_CLI_ENTRY: resolve(entry) };
Expand Down
34 changes: 31 additions & 3 deletions packages/cli/src/utils/installerDetection.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { delimiter, dirname, join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

// The module inspects `process.argv[1]` + `realpathSync`. We stub both so
// each test describes a hypothetical install layout without touching the
Expand Down Expand Up @@ -266,9 +266,13 @@ describe("runningInstall: which binary runs, and the command that updates it", (

describe("shadowingInstall: the older global install a plain `npx hyperframes` runs instead", () => {
const saved = { argv1: process.argv[1], path: process.env["PATH"] };
beforeEach(() => {
vi.resetModules();
});
afterEach(() => {
process.argv[1] = saved.argv1 ?? "";
process.env["PATH"] = saved.path;
vi.restoreAllMocks();
});

/** An npx copy running now, and a global npm install of `globalVersion` first on PATH. */
Expand Down Expand Up @@ -335,18 +339,42 @@ describe("shadowingInstall: the older global install a plain `npx hyperframes` r
});
});

it("still sees an older copy in the project's node_modules/.bin after startup trims PATH", async () => {
const root = layout(null);
const pkg = onPathInstead(root, "app/node_modules/hyperframes");
writeFileSync(join(root, "app/bun.lock"), "");
const projectBin = join(root, "app/node_modules/.bin");
mkdirSync(projectBin, { recursive: true });
symlinkSync(join(pkg, "bin/hyperframes.mjs"), join(projectBin, "hyperframes"));
const [npxBin] = (process.env["PATH"] ?? "").split(delimiter);
process.env["PATH"] = [npxBin, projectBin].join(delimiter);
vi.spyOn(process, "cwd").mockReturnValue(join(root, "app"));

const { shadowingInstall } = await import("./installerDetection.js");

expect(process.env["PATH"]).toBe(npxBin);
expect(shadowingInstall("0.9.29")).toEqual({
version: "0.9.8",
updateCommand: "bun add hyperframes@0.9.29",
});
});

it("stays quiet when no manager is known to move the older install", async () => {
const root = layout(null);
onPathInstead(root, "opt/hyperframes");
const { shadowingInstall } = await import("./installerDetection.js");
expect(shadowingInstall("0.9.29")).toBeNull();
});

it("stays quiet when the global install is not older, or there is none", async () => {
const { shadowingInstall } = await import("./installerDetection.js");
it("stays quiet when the global install is not older", async () => {
layout("0.9.29");
const { shadowingInstall } = await import("./installerDetection.js");
expect(shadowingInstall("0.9.29")).toBeNull();
});

it("stays quiet when there is no global install", async () => {
layout(null);
const { shadowingInstall } = await import("./installerDetection.js");
expect(shadowingInstall("0.9.29")).toBeNull();
});

Expand Down
5 changes: 3 additions & 2 deletions packages/cli/src/utils/installerDetection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { existsSync, readFileSync, realpathSync } from "node:fs";
import { delimiter, dirname, join, posix } from "node:path";
import { compareVersions } from "compare-versions";
import { isSafeVersion } from "./safeVersion.js";
import { originalPath } from "./windowsExeSearch.js";

export type InstallerKind = "npm" | "bun" | "pnpm" | "brew" | "skip";

Expand Down Expand Up @@ -327,8 +328,8 @@ function resolvedOrNull(path: string): string | null {
}

/** The first `hyperframes` on PATH that is neither this copy nor another npx/bunx cache copy. */
function firstGlobalOnPath(self: string | null): string | null {
for (const dir of (process.env["PATH"] ?? "").split(delimiter)) {
function firstGlobalOnPath(self: string | null, pathValue = originalPath()): string | null {
for (const dir of pathValue.split(delimiter)) {
const real = dir ? resolvedOrNull(join(dir, "hyperframes")) : null;
if (real && real !== self && !isEphemeralExec(real)) return real;
}
Expand Down
Loading
Loading