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
55 changes: 50 additions & 5 deletions src/cli.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
#!/usr/bin/env node

import { realpathSync } from "node:fs";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { dirname, extname, resolve } from "node:path";
import process from "node:process";
import { pathToFileURL } from "node:url";
import { fileURLToPath } from "node:url";
import initSqlJs from "sql.js";
import { cdbToSql } from "./cdbToSql";
import { sqlToCdb } from "./sqlToCdb";
Expand Down Expand Up @@ -241,10 +242,54 @@ export async function run(argv: string[]): Promise<void> {
}
}

const isDirectRun =
typeof process.argv[1] === "string" &&
import.meta.url === pathToFileURL(resolve(process.argv[1])).href;
/**
* Resolve a path to its real location, tolerating paths that do not exist
* (realpathSync throws on those) by falling back to the resolved path.
*/
function safeRealpath(path: string): string {
try {
return realpathSync(path);
} catch {
return path;
}
}

/**
* Path comparison for the entry-point check. Windows paths are compared
* case-insensitively: the drive letter casing of argv[1] and of the module path
* can differ for the very same file.
*/
function samePath(a: string, b: string): boolean {
return process.platform === "win32"
? a.toLowerCase() === b.toLowerCase()
: a === b;
}

/**
* True when this module is the process entry point, false when it is merely
* imported (by the test suite, or by anything that loads the file directly),
* in which case importing it must not run a conversion.
*
* Both sides must be dereferenced: npm installs the bin as a symlink
* (node_modules/.bin/cdb-converter -> ../cdb-converter/dist/cli.mjs), and Node
* puts the *symlink* path in process.argv[1] while import.meta.url points at
* the real file. Comparing them without realpath makes the check always false,
* so the CLI silently does nothing when run via npx or the installed binary.
*/
export function isDirectRun(
argv1: string | undefined,
moduleUrl: string,
): boolean {
if (typeof argv1 !== "string" || argv1.length === 0) {
return false;
}

return samePath(
safeRealpath(resolve(argv1)),
safeRealpath(fileURLToPath(moduleUrl)),
);
}

if (isDirectRun) {
if (isDirectRun(process.argv[1], import.meta.url)) {
void run(process.argv.slice(2));
}
133 changes: 133 additions & 0 deletions test/cliEntrypoint.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import { execFileSync } from "node:child_process";
import { existsSync } from "node:fs";
import {
copyFile,
mkdir,
mkdtemp,
rm,
symlink,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { afterAll, beforeAll, describe, expect, it } from "vitest";

/**
* End-to-end guard for the CLI entry-point check.
*
* These tests must spawn the built CLI *through a symlink*, because that is how
* npm/npx invoke it (node_modules/.bin/cdb-converter -> dist/cli.mjs). Calling
* run() in-process cannot observe the bug: Node reports the symlink path in
* process.argv[1] but the real path in import.meta.url, and a comparison that
* does not dereference both makes the CLI exit 0 without doing anything.
*
* The symlink suite is skipped on Windows: fs.symlink() there needs admin
* rights or developer mode, and npm does not symlink "bin" entries anyway (it
* generates .cmd/.ps1 shims), so the scenario under test does not exist.
*/

const isWindows = process.platform === "win32";
const npmCommand = isWindows ? "npm.cmd" : "npm";
const repoRoot = resolve(fileURLToPath(import.meta.url), "../..");
const cliPath = join(repoRoot, "dist", "cli.mjs");
const fixture = join(repoRoot, "test", "fixtures", "OfficialRelease-2014.cdb");
Comment thread
mpicciolli marked this conversation as resolved.

let workDir: string;
let linkPath: string;

function runCli(args: string[]): { status: number; stdout: string } {
let stdout = "";
let status = 0;

try {
stdout = execFileSync(process.execPath, [linkPath, ...args], {
cwd: workDir,
encoding: "utf8",
});
} catch (error) {
const failure = error as { status?: number; stdout?: string };
status = failure.status ?? 1;
stdout = failure.stdout ?? "";
}

return { status, stdout };
}

beforeAll(async () => {
execFileSync(npmCommand, ["run", "build"], {
cwd: repoRoot,
stdio: "ignore",
});

workDir = await mkdtemp(join(tmpdir(), "cdb-converter-cli-"));
await copyFile(fixture, join(workDir, "input.cdb"));
}, 120_000);

afterAll(async () => {
if (workDir) {
await rm(workDir, { recursive: true, force: true });
}
});

describe.skipIf(isWindows)("CLI invoked through a symlink", () => {
beforeAll(async () => {
await mkdir(join(workDir, "bin"));

// Mirrors what `npm install` creates for the "bin" entry.
linkPath = join(workDir, "bin", "cdb-converter");
await symlink(cliPath, linkPath, "file");
});

it("converts a real .cdb and writes the output file", () => {
const { status, stdout } = runCli(["input.cdb", "output.sqlite"]);

expect(status).toBe(0);
expect(existsSync(join(workDir, "output.sqlite"))).toBe(true);
expect(stdout).toContain("Output :");
expect(stdout).toMatch(/Tables : \d+/);
}, 120_000);

it("converts back from .sqlite to .cdb", () => {
expect(runCli(["input.cdb", "roundtrip.sqlite"]).status).toBe(0);

const { status } = runCli(["roundtrip.sqlite", "roundtrip.cdb"]);

expect(status).toBe(0);
expect(existsSync(join(workDir, "roundtrip.cdb"))).toBe(true);
}, 120_000);

it("prints help and version", () => {
const help = runCli(["--help"]);
expect(help.status).toBe(0);
expect(help.stdout).toContain("Usage:");

const version = runCli(["--version"]);
expect(version.status).toBe(0);
expect(version.stdout.trim()).toMatch(/^\d+\.\d+\.\d+/);
}, 60_000);

it("exits non-zero on a missing input file", () => {
expect(runCli([]).status).toBe(1);
}, 60_000);
});

describe("CLI imported as a library", () => {
it("does not run the converter on import", async () => {
const importer = join(workDir, "importer.mjs");
await writeFile(
importer,
`import { run } from ${JSON.stringify(cliPath)};\n` +
`console.log(typeof run);\n`,
);

const stdout = execFileSync(
process.execPath,
[importer, "input.cdb", "should-not-exist.sqlite"],
{ cwd: workDir, encoding: "utf8" },
);

expect(stdout.trim()).toBe("function");
expect(existsSync(join(workDir, "should-not-exist.sqlite"))).toBe(false);
}, 60_000);
});