diff --git a/bin/codepact.js b/bin/codepact.js index 8ac4cee..1287ab2 100644 --- a/bin/codepact.js +++ b/bin/codepact.js @@ -25,6 +25,7 @@ Options: --write-baseline Record current findings as accepted. --baseline Report and fail only on findings not in the baseline. -h, --help Show this message. + -v, --version Show the package version. Exit codes: 0 no errors (and no warnings when --strict is set) @@ -43,6 +44,7 @@ function parseArguments(argv) { baseline: null, writeBaseline: null, help: false, + version: false, } for (let i = 0; i < argv.length; i++) { @@ -52,6 +54,10 @@ function parseArguments(argv) { case "--help": options.help = true break + case "-v": + case "--version": + options.version = true + break case "--json": options.json = true break @@ -136,6 +142,12 @@ function main() { return 0 } + if (options.version) { + const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")) + process.stdout.write(`${version}\n`) + return 0 + } + const config = options.config ? JSON.parse(readFileSync(options.config, "utf8")) : {} const enums = [] diff --git a/test/cli.test.js b/test/cli.test.js index 4ae25f8..3877f73 100644 --- a/test/cli.test.js +++ b/test/cli.test.js @@ -1,6 +1,6 @@ import test from "node:test" import assert from "node:assert/strict" -import { mkdtempSync, rmSync, writeFileSync } from "node:fs" +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs" import { tmpdir } from "node:os" import { join } from "node:path" import { spawnSync } from "node:child_process" @@ -24,3 +24,14 @@ test("CLI scans qualified attributes and detects collisions", () => { rmSync(dir, { recursive: true, force: true }) } }) + +for (const flag of ["--version", "-v"]) { + test(`CLI ${flag} prints the package version without a scan path`, () => { + const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")) + const cwd = fileURLToPath(new URL("../examples/broken/", import.meta.url)) + const result = spawnSync(process.execPath, [cli, flag], { cwd, encoding: "utf8" }) + assert.equal(result.status, 0, result.stderr) + assert.equal(result.stdout, `${version}\n`) + assert.equal(result.stderr, "") + }) +}