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
30 changes: 30 additions & 0 deletions __tests__/version.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';

class ExitCalled extends Error {}

const realArgv = process.argv;

afterEach(() => {
process.argv = realArgv;
vi.restoreAllMocks();
});

describe('anyapi --version', () => {
it('prints the version in package.json, not a second copy', async () => {
const manifest = JSON.parse(readFileSync(join(process.cwd(), 'package.json'), 'utf8'));
let printed = '';
vi.spyOn(process.stdout, 'write').mockImplementation((chunk) => {
printed += String(chunk);
return true;
});
vi.spyOn(process, 'exit').mockImplementation(() => {
throw new ExitCalled();
});
process.argv = ['node', 'anyapi', '--version'];

await expect(import('../src/index.js')).rejects.toBeInstanceOf(ExitCalled);
expect(printed).toBe(`${manifest.version}\n`);
});
});
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { feedbackCommand, reportBugCommand } from "./feedback.js";
import { CliError } from "./errors.js";
import { defaultContext } from "./io.js";
import { normalizeRunCLIOptions } from "./run.js";
import { VERSION } from "./version.js";

const program = new Command();
const ctx = defaultContext();
Expand All @@ -31,7 +32,7 @@ program
"--api-key <apiKey>",
"AnyAPI API key. Overrides ANYAPI_API_KEY and local config.",
)
.version("0.8.0");
.version(VERSION);

program
.command("signup")
Expand Down
12 changes: 12 additions & 0 deletions src/version.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { createRequire } from 'node:module';

/**
* The package version, read from `package.json` rather than authored here.
*
* `../package.json` resolves from both `src/` and the published `dist/`, and npm
* always packs `package.json`, so `anyapi --version` reports the release that is
* actually installed. A hand-kept copy drifted from the published version.
*/
export const VERSION: string = (
createRequire(import.meta.url)('../package.json') as { version: string }
).version;
Loading