iterate.com / kernel

git clone https://git.iterate.com/repos/kernel

kernel / core / lib / src / cli / cli.test.tsmain at 949894f

import { spawnSync } from "node:child_process";
import { mkdirSync, mkdtempDisposableSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { createCli, os } from "trpc-cli";
import { expect, test } from "vitest";
import { z } from "zod";
import { LoginInput, loginArgvOf, packageVersionOf } from "./cli.ts";

/** `iterate <argv>` as the CLI parses it, with a `login` that signs in nowhere: what the handler
 *  got, the exit code and what was printed. */
const parsedLogin = async (argv: string[]) => {
  const inputs: z.infer<typeof LoginInput>[] = [];
  const printed: string[] = [];
  let exitCode: number | undefined;
  const cli = createCli({
    name: "iterate",
    router: {
      login: os.input(LoginInput).handler(({ input }) => {
        inputs.push(input);
        return "signed in";
      }),
    },
  });
  await cli
    .run({
      argv: loginArgvOf(argv),
      prompts: false,
      logger: {
        info: (line) => printed.push(String(line)),
        error: (line) => printed.push(String(line)),
      },
      process: {
        exit: (code) => {
          exitCode ??= code;
          return undefined as never;
        },
      },
    })
    .catch(() => {});
  return { inputs, exitCode, printed: printed.join("\n") };
};

test.for<{ argv: string[]; input: z.infer<typeof LoginInput> }>([
  { argv: ["login", "--device", "example.com"], input: { address: "example.com", device: true } },
  { argv: ["login", "example.com", "--device"], input: { address: "example.com", device: true } },
  { argv: ["login", "example.com"], input: { address: "example.com" } },
  {
    argv: ["login", "--device", "true", "example.com"],
    input: { address: "example.com", device: true },
  },
  {
    argv: ["login", "--device", "false", "example.com"],
    input: { address: "example.com", device: false },
  },
  {
    argv: ["login", "example.com", "--device", "false"],
    input: { address: "example.com", device: false },
  },
  {
    argv: ["login", "--device=false", "example.com"],
    input: { address: "example.com", device: false },
  },
  {
    argv: ["login", "--device", "--expect-user", "a@example.com", "example.com"],
    input: { address: "example.com", device: true, expectUser: "a@example.com" },
  },
])("iterate $argv hands login $input", async ({ argv, input }) => {
  const { inputs, exitCode } = await parsedLogin(argv);
  expect({ inputs, exitCode }).toEqual({ inputs: [input], exitCode: 0 });
});

test.for([["login", "--device"], ["login", "--device", "false"], ["login"]])(
  "iterate %s names the missing address and signs in nowhere",
  async (...[argv]) => {
    const { inputs, exitCode, printed } = await parsedLogin(argv);
    expect({ inputs, exitCode }).toEqual({ inputs: [], exitCode: 1 });
    expect(printed).toContain("missing required argument 'address'");
  },
);

test("only login's --device is spelled anew", () => {
  expect(loginArgvOf(["run", "--device", "x"])).toEqual(["run", "--device", "x"]);
  expect(loginArgvOf(["login", "--device", "example.com"])).toEqual([
    "login",
    "--device=true",
    "example.com",
  ]);
});

test("iterate login --help shows the flag as it is taken", async () => {
  expect((await parsedLogin(["login", "--help"])).printed).toContain("--device [boolean]");
});

test("iterate --version and -v print the package version and exit 0", () => {
  const pkg = z
    .object({ version: z.string().min(1) })
    .parse(JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")));
  expect(packageVersionOf()).toBe(pkg.version);

  const bin = fileURLToPath(new URL("../../bin/iterate.js", import.meta.url));
  for (const flag of ["--version", "-v", "-V"]) {
    const result = spawnSync(process.execPath, [bin, flag], { encoding: "utf8" });
    expect({ flag, status: result.status, stdout: result.stdout.trim() }).toEqual({
      flag,
      status: 0,
      stdout: pkg.version,
    });
  }
});

test("the bin runs its own package in a folder that holds another iterate CLI", () => {
  // git runs `iterate git-credential` in git's own working folder: a checkout with an older CLI
  // there must not answer for this one
  using folder = mkdtempDisposableSync(join(tmpdir(), "iterate-test-"));
  const decoy = `export const runCli = () => console.log("the decoy ran");`;
  writeFileSync(join(folder.path, "pnpm-workspace.yaml"), "packages: []\n");
  for (const [file, text] of [
    ["core/lib/bin/iterate.js", ""],
    ["core/lib/package.json", "{}"],
    ["core/lib/src/cli/cli.ts", decoy],
    ["node_modules/.bin/iterate", ""],
    ["node_modules/iterate/bin/iterate.js", ""],
    ["node_modules/iterate/dist/cli.mjs", decoy],
  ] as const) {
    mkdirSync(dirname(join(folder.path, file)), { recursive: true });
    writeFileSync(join(folder.path, file), text);
  }
  const bin = fileURLToPath(new URL("../../bin/iterate.js", import.meta.url));
  const result = spawnSync(process.execPath, [bin, "--version"], {
    encoding: "utf8",
    cwd: folder.path,
    // not as `npx` runs it: the old launcher looked for another CLI only then
    env: { ...process.env, npm_command: "", npm_lifecycle_event: "" },
  });
  expect({ status: result.status, stdout: result.stdout.trim() }).toEqual({
    status: 0,
    stdout: packageVersionOf(),
  });
});