* fix(#437): restore defaults.run.shell at job level (step-level matrix expr rejected by GHA) Per actions/runner workflow-v1.0.json schema, `jobs.<job_id>.defaults.run.shell` allows `matrix` context (job-defaults-run has context:[matrix,...]); step-level `shell:` does not (run-step's shell field is plain string with no context array). PR #434 used step-level shell:${{matrix.shell}}, which GHA's parser rejects with "Unrecognized named-value: 'matrix'" — blocking every push to next and every release.yml dispatch. This commit: - Removes step-level `shell: ${{ matrix.shell }}` from test-full (test.yml) and smoke (install-smoke.yml) jobs (17 directives). - Adds `defaults.run.shell: ${{ matrix.shell }}` at job level in those two jobs. - Fixes pre-existing shellcheck SC2129 in test.yml (individual >> redirects → grouped brace form) and SC2010 in install-smoke.yml (ls|grep → glob loop). Verified locally with actionlint 1.7.12 (exit 0). Policy linter still 0 violations (matrix.shell now resolves via job.defaults.run.shell which the linter already handles per workflow-policy.cjs:effectiveShell). Refs: actions/runner#444 (open since 2020), GHA contexts page section "Context availability". * fix(#439): inline ci-smoke-skip back to shell (Node port required pre-checkout file resolution) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(#440): use platform-correct npm.cmd on Windows for spawn (and surface-check other Node ports) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(#437): use 'zsh {0}' format string in matrix.shell for macOS (zsh not in GHA built-ins) Per https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions (jobs.<job_id>.defaults.run.shell section): "You can use built-in shell keywords like bash, pwsh, python, sh, cmd, and powershell, or define a custom set of shell options." zsh is not in the built-ins list. GHA accepts custom shells via a format string containing '{0}', which it replaces with the temporary script file path at runtime (same pattern as the perl {0} example in the docs). Bare `shell: zsh` triggers: "Invalid shell option. Shell must be a valid built-in or a format string containing '{0}'". Precursor: 514cb429 introduced the matrix shell-pinning pattern; this completes it by switching the macOS rows from the bare value to the required format string. Also updates scripts/workflow-policy.cjs to normalise 'zsh {0}' to 'zsh' before the policy comparison, so the repo-baseline test continues to pass (the linter was correctly treating 'zsh {0}' as a distinct value from the policy 'zsh'). Affects: - .github/workflows/test.yml: test-full matrix (node 22 + node 24 macOS rows) - .github/workflows/install-smoke.yml: smoke matrix (macOS node 24 row) - scripts/workflow-policy.cjs: detectViolation strips ' {0}' format suffix * fix(#440): add shell:true to spawnSync on Windows for .cmd files (Node docs requirement) Per https://nodejs.org/docs/latest-v22.x/api/child_process.html: ".bat and .cmd files require a terminal to run and cannot be launched directly with execFile(). To run these scripts on Windows, use child_process.spawn() with the shell option, child_process.exec(), or spawn cmd.exe with the script as an argument." "On Windows, .bat and .cmd files require a shell to execute. Use child_process.exec() or child_process.spawn() with the shell: true option." On Windows, npm is installed as npm.cmd (a batch wrapper). Without shell: true, spawnSync resolves the binary directly and fails with ENOENT / "npm binary not found on PATH" because the OS cannot execute a .cmd file without cmd.exe as the intermediary. The fix uses `shell: process.platform === 'win32'` so the shell spawning is only activated on Windows; macOS/Linux continue to resolve the plain npm binary directly with shell: false, preserving the existing behaviour on non-Windows platforms. Updated both spawnSync(npmCmd, ...) call sites: - npm --version check (line 182) - npm ci --dry-run lockfile-sync check (line 215) * fix(#437): bug-410 defaults test — set USERPROFILE for Windows os.homedir() redirect On Windows, os.homedir() reads USERPROFILE (not HOME), so the test's process.env.HOME = FAKE_HOME redirect was silently ignored. finishInstall's path.join(os.homedir(), '.gsd') resolved to the real user home and the defaults.json write either failed (permissions) or landed outside the temp dir, causing the existsSync assertion to return false. Fix: also set process.env.USERPROFILE = FAKE_HOME so os.homedir() returns the sandboxed directory on Windows. Node.js docs (os.homedir): https://nodejs.org/docs/latest-v22.x/api/os.html#oshomedir Refs: #437 (fix/437-restore-defaults-run-shell), Windows pwsh compat Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(#437): precommit-alias-drift hook test — use path.delimiter for PATH Hardcoded ':' PATH separator breaks Windows where process.env.PATH uses ';'. The malformed PATH passed to bash caused the mock git/npm stubs in binDir to be invisible to the hook script; npm was never called and the marker file never written. Fix: replace ':' with path.delimiter in both PATH constructions so the env var is well-formed on Windows (';') and POSIX (':') alike. Refs: #437 (fix/437-restore-defaults-run-shell), Windows pwsh compat Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(#437): prepush-enterprise-email hook test — use path.delimiter for PATH Same root cause as precommit-alias-drift: hardcoded ':' PATH separator is invalid on Windows (';' required). The malformed PATH meant bash ran the real git binary instead of the mock stub, which rejected the placeholder SHAs 'refs-local-sha' / 'refs-remote-sha' with a fatal ambiguous-argument error rather than returning the fixture commit list. Fix: replace ':' with path.delimiter in both execFileSync PATH env values. Refs: #437 (fix/437-restore-defaults-run-shell), Windows pwsh compat Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(#437): set MSYS2_PATH_TYPE=inherit so mock stubs take precedence in Git Bash PATH Root cause: Git Bash (MSYS2) on Windows prepends its own system directories (/mingw64/bin, /usr/bin, /bin) to the PATH at process startup before the user-supplied Windows PATH entries. This placed the real git/npm binaries ahead of the mock stubs in binDir even though binDir was first in the Windows PATH passed to execFileSync. The path.delimiter fix (0042fe0d) made the PATH syntactically correct for Windows (semicolons) but did not change the MSYS2 system-dir prepend order. The real git rejected placeholder SHAs (refs-local-sha, refs-remote-sha) with "fatal: ambiguous argument", producing the observed Windows CI failure. For the pre-commit test, the real git output nothing (no staged files on a fresh checkout), so the grep match failed and npm was never called. Fix: set MSYS2_PATH_TYPE=inherit in the env passed to both bash spawns. With inherit, MSYS2 uses only the converted Windows PATH without prepending system directories, so binDir (converted from Windows to POSIX) is first in the search path and the mock stubs are found. grep/tr/printf remain available: the GHA Windows runner PATH includes C:\Program Files\Git\usr\bin which contains these utilities; MSYS2 converts that Windows entry to a POSIX path on startup. The /usr/bin/env shebang in mock stubs resolves through MSYS2's virtual filesystem mount (not via PATH) and is always accessible regardless of MSYS2_PATH_TYPE. On macOS/Linux this variable is ignored; no behaviour change on those platforms. Source: https://www.msys2.org/wiki/MSYS2-introduction/#path (MSYS2_PATH_TYPE controls whether system dirs are prepended to converted PATH) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(#437): hook test mocks — use cmd-shim pattern for Windows bin resolution On Windows, bash (Git Bash / MSYS2) resolves PATH commands by scanning for extensionless files, but cmd.exe and Win32 process creation resolve via PATHEXT (.CMD, .BAT, .EXE). When execFileSync('bash', [hookPath]) runs a hook that calls `git` or `npm`, both resolution paths may fire. The previous approach set MSYS2_PATH_TYPE=inherit in the child env, but that variable is only read in /etc/profile (login-shell path) — bash launched without --login never sources /etc/profile, so the variable had no effect: https://github.com/msys2/MSYS2-packages/blob/master/filesystem/profile Fix: adopt the cmd-shim three-file pattern used by npm itself: https://github.com/npm/cmd-shim For each mock binary, write: <name> extensionless bash script (bash PATH scan) <name>.cmd batch wrapper delegating to bash (PATHEXT / cmd.exe) <name>.ps1 PowerShell wrapper (completeness) This is the same approach used by stevemao/mock-bin for test mocking with Windows CI green on AppVeyor: https://github.com/stevemao/mock-bin The .cmd and .ps1 files are only written on process.platform === 'win32'. MSYS2_PATH_TYPE is removed from the child env — it was ineffective and is no longer needed with the shim files in place. * fix(#437): tarball-smoke — raise CHILD_TIMEOUT_MS on Windows to 600 s The CI failure showed a test duration of 120003.1812 ms — matching the previous CHILD_TIMEOUT_MS = 120_000 exactly. When spawnSync hits its timeout, it sends SIGTERM and returns { status: null, stdout: '', stderr: '' } per the Node.js docs: https://nodejs.org/docs/latest-v22.x/api/child_process.html "status: <number> | <null> — The exit code of the subprocess, or null if the subprocess terminated due to a signal." The installResult check is `status !== 0`; null !== 0 is true, so the timeout fired the INSTALL_FAILED path with empty stdout/stderr, which made the root cause invisible in CI logs. GitHub-hosted Windows runners are slower than Linux/macOS for filesystem-heavy operations (npm install -g of a 1499-file tarball): https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners/about-github-hosted-runners#standard-github-hosted-runners-for-public-repositories Fix: use 600_000 ms (10 min) on Windows, keeping 120_000 ms on POSIX. 600 s matches the SLOW_HOST_TIMEOUT already used in the test before() helper for the pack + install fixture step. Also expose `signal` and `installError` in the INSTALL_FAILED details object so a future timeout (status=null, signal='SIGTERM', stdout='') is immediately diagnosable in CI logs without guesswork. * fix(#437): chmod +x via bash on Windows for hook test mocks (root cause: fs.writeFileSync mode=0o755 no-op on NTFS) Root cause: Node's fs.writeFileSync mode=0o755 is a no-op for the execute bit on Windows NTFS. Per https://nodejs.org/docs/latest-v22.x/api/fs.html: "on Windows only the write permission can be changed." Bash's access(X_OK) therefore skips the mock file; the real git/npm binary is found later in PATH and the hook runs against real state instead of the test double. Fix: after writeFileSync, invoke Git Bash's chmod via the POSIX emulation layer (Cygwin/MSYS2), which sets the NTFS execute ACL that Node cannot reach: const posixPath = filePath.replace(/\\/g, '/'); execFileSync('bash', ['-c', `chmod +x "${posixPath}"`], { stdio: 'pipe' }); execFileSync('bash', ...) works because Git for Windows ships bash on PATH in all GHA Windows runners. Forward-slash conversion is required because MSYS2 bash auto-converts /c/foo paths but not mixed-separator paths. Why prior approaches didn't take effect: - MSYS2_PATH_TYPE=inherit: only read in /etc/profile (login-shell path); execFileSync('bash', ...) launches non-interactively without --login, so /etc/profile is never sourced. Ref: https://github.com/msys2/MSYS2-packages/blob/master/filesystem/profile - .cmd/.ps1 cmd-shim wrappers: bash does POSIX command resolution and does not honor PATHEXT, so wrappers are not found by bash's own PATH scan. They are not wrong (kept for non-bash callers) but do not fix bash's X_OK. Files changed: tests/precommit-alias-drift-hook.test.cjs, tests/prepush-enterprise-email-hook.test.cjs * refactor(#437): hooks use GIT_OVERRIDE/NPM_OVERRIDE env-var DI; tests drop PATH-mocking Four prior rounds (path.delimiter join, MSYS2_PATH_TYPE=inherit, cmd-shim .cmd/.ps1 wrappers, chmod-via-bash post-write) all failed to make MSYS2 bash's PATH-lookup find the mock executables. The root cause is that none of those approaches can reliably override bash's own command-resolution on NTFS without fighting NTFS execute-ACLs or login-shell profile sourcing. The simplest robust solution is to bypass PATH entirely: Hooks: each hook now binds GIT_CMD="${GIT_OVERRIDE:-git}" (and NPM_CMD for pre-commit) at the top. When env vars are unset the hooks invoke bare `git`/`npm` exactly as before — zero behavior change for users. Tests: writeMockBin/binDir/PATH manipulation replaced by writeMock(), which writes a .sh mock to a tmpDir and passes its absolute path via GIT_OVERRIDE / NPM_OVERRIDE in the execFileSync env. Bash inside the hook executes the path directly via the seam — no PATH scan, no NTFS ACL check, no MSYS2 profile dependency. Test-rigor principle: the new seam (env-var injection) is platform- independent and doesn't rely on bash's command-resolution mechanism on the host OS. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> --------- Co-authored-by: CI Rebase Check <ci@gsd-redux> Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
303 lines
11 KiB
JavaScript
303 lines
11 KiB
JavaScript
#!/usr/bin/env node
|
|
'use strict';
|
|
// scripts/check-env.cjs — Environment parity validator for contributors (issue #117).
|
|
//
|
|
// Node.js port of scripts/check-env.sh. Behaviorally identical output and
|
|
// exit codes; shell-agnostic so it runs on Windows, macOS, and Linux.
|
|
//
|
|
// Checks that the developer's environment matches project requirements before
|
|
// running tests or audits. Designed to catch mismatches early rather than
|
|
// through cryptic test failures.
|
|
//
|
|
// Exit codes:
|
|
// 0 All checks passed
|
|
// 1 One or more checks failed
|
|
// 2 Tool error (missing required tool, corrupt package.json, etc.)
|
|
//
|
|
// Usage:
|
|
// node scripts/check-env.cjs # Human-readable report
|
|
// node scripts/check-env.cjs --json # Structured JSON report
|
|
// node scripts/check-env.cjs --help # This message
|
|
//
|
|
// Sources:
|
|
// npm engines: https://docs.npmjs.com/cli/v10/configuring-npm/package-json#engines
|
|
// Reproducible builds: https://reproducible-builds.org/docs/source-tree/
|
|
// npm ci docs: https://docs.npmjs.com/cli/v10/commands/npm-ci
|
|
// gsd-test-runner: https://github.com/open-gsd/gsd-test-runner
|
|
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const { execFileSync, spawnSync } = require('child_process');
|
|
|
|
// On Windows, npm ships as npm.cmd (a batch wrapper); spawnSync without
|
|
// shell:true requires the exact filename including extension.
|
|
const npmCmd = process.platform === 'win32' ? 'npm.cmd' : 'npm';
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Argument parsing
|
|
// ---------------------------------------------------------------------------
|
|
let jsonMode = false;
|
|
|
|
for (const arg of process.argv.slice(2)) {
|
|
if (arg === '--json') {
|
|
jsonMode = true;
|
|
} else if (arg === '--help' || arg === '-h') {
|
|
process.stdout.write(
|
|
'scripts/check-env.cjs — Environment parity validator for contributors (issue #117).\n' +
|
|
'\n' +
|
|
'Checks that the developer\'s environment matches project requirements before\n' +
|
|
'running tests or audits. Designed to catch mismatches early rather than\n' +
|
|
'through cryptic test failures.\n' +
|
|
'\n' +
|
|
'Exit codes:\n' +
|
|
' 0 All checks passed\n' +
|
|
' 1 One or more checks failed\n' +
|
|
' 2 Tool error (missing required tool, corrupt package.json, etc.)\n' +
|
|
'\n' +
|
|
'Usage:\n' +
|
|
' node scripts/check-env.cjs # Human-readable report\n' +
|
|
' node scripts/check-env.cjs --json # Structured JSON report\n' +
|
|
' node scripts/check-env.cjs --help # This message\n'
|
|
);
|
|
process.exit(0);
|
|
} else {
|
|
process.stderr.write(`Unknown option: ${arg}\n`);
|
|
process.exit(2);
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Locate the project root (directory containing package.json)
|
|
// ---------------------------------------------------------------------------
|
|
const PROJECT_ROOT = process.cwd();
|
|
const PACKAGE_JSON = path.join(PROJECT_ROOT, 'package.json');
|
|
|
|
if (!fs.existsSync(PACKAGE_JSON)) {
|
|
process.stderr.write(`ERROR: package.json not found in ${PROJECT_ROOT}\n`);
|
|
process.exit(2);
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Helpers
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/** @type {Array<{name: string, status: 'pass'|'fail'|'skip', message: string}>} */
|
|
const checks = [];
|
|
|
|
function addCheck(name, status, message) {
|
|
checks.push({ name, status, message });
|
|
}
|
|
|
|
/**
|
|
* Semver comparison: does `version` satisfy `constraint`?
|
|
* Constraint forms: >=X.Y.Z, >X.Y.Z, <=X.Y.Z, <X.Y.Z, =X.Y.Z, X.Y.Z
|
|
* Returns true if satisfied, false otherwise.
|
|
*/
|
|
function satisfiesConstraint(version, constraint) {
|
|
// Strip leading 'v' and pre-release/build suffixes
|
|
version = version.replace(/^v/, '').replace(/-.*$/, '').replace(/\+.*$/, '');
|
|
|
|
let op, reqVer;
|
|
const opMatch = constraint.match(/^(>=|>|<=|<|=)(.+)$/);
|
|
if (opMatch) {
|
|
op = opMatch[1];
|
|
reqVer = opMatch[2];
|
|
} else {
|
|
op = '=';
|
|
reqVer = constraint;
|
|
}
|
|
reqVer = reqVer.replace(/^v/, '').replace(/-.*$/, '').replace(/\+.*$/, '');
|
|
|
|
function parseTuple(v) {
|
|
const parts = (v + '.0.0').split('.');
|
|
return [
|
|
parseInt(parts[0], 10) || 0,
|
|
parseInt(parts[1], 10) || 0,
|
|
parseInt(parts[2], 10) || 0,
|
|
];
|
|
}
|
|
|
|
const [vMaj, vMin, vPat] = parseTuple(version);
|
|
const [rMaj, rMin, rPat] = parseTuple(reqVer);
|
|
|
|
const vNum = vMaj * 1_000_000 + vMin * 1_000 + vPat;
|
|
const rNum = rMaj * 1_000_000 + rMin * 1_000 + rPat;
|
|
|
|
switch (op) {
|
|
case '>=': return vNum >= rNum;
|
|
case '>': return vNum > rNum;
|
|
case '<=': return vNum <= rNum;
|
|
case '<': return vNum < rNum;
|
|
case '=': return vNum === rNum;
|
|
default: return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Read a field from package.json using dot-notation (e.g. 'engines.node').
|
|
* Returns the string value or empty string if absent.
|
|
* Uses './package.json' so Node resolves relative to CWD on all platforms.
|
|
*/
|
|
function pkgField(fieldPath) {
|
|
try {
|
|
const pkg = JSON.parse(fs.readFileSync(path.join(PROJECT_ROOT, 'package.json'), 'utf8'));
|
|
let val = pkg;
|
|
for (const key of fieldPath.split('.')) {
|
|
if (val == null || typeof val !== 'object') return '';
|
|
val = val[key];
|
|
}
|
|
return val != null ? String(val) : '';
|
|
} catch {
|
|
return '';
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Check 1: Node version vs engines.node
|
|
// ---------------------------------------------------------------------------
|
|
const enginesNode = pkgField('engines.node');
|
|
let currentNode = '';
|
|
try {
|
|
currentNode = process.version.replace(/^v/, '');
|
|
} catch { /* ignore */ }
|
|
|
|
if (!currentNode) {
|
|
addCheck('node-version', 'fail', 'node binary not found on PATH');
|
|
} else if (!enginesNode) {
|
|
addCheck('node-version', 'fail', 'engines.node missing from package.json — add it (see D2 in docs/contributing/bootstrap.md)');
|
|
} else {
|
|
if (satisfiesConstraint(currentNode, enginesNode)) {
|
|
addCheck('node-version', 'pass', `Node ${currentNode} satisfies ${enginesNode}`);
|
|
} else {
|
|
addCheck('node-version', 'fail', `Node ${currentNode} does NOT satisfy engines.node ${enginesNode}`);
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Check 2: npm version vs engines.npm (skip if field absent)
|
|
// ---------------------------------------------------------------------------
|
|
const enginesNpm = pkgField('engines.npm');
|
|
let currentNpm = '';
|
|
try {
|
|
const res = spawnSync(npmCmd, ['--version'], { encoding: 'utf8', timeout: 10_000, shell: process.platform === 'win32' });
|
|
if (res.status === 0 && res.stdout) {
|
|
currentNpm = res.stdout.trim();
|
|
}
|
|
} catch { /* ignore */ }
|
|
|
|
if (!enginesNpm) {
|
|
addCheck('npm-version', 'skip', 'engines.npm not set in package.json — skipping');
|
|
} else if (!currentNpm) {
|
|
addCheck('npm-version', 'fail', 'npm binary not found on PATH');
|
|
} else {
|
|
if (satisfiesConstraint(currentNpm, enginesNpm)) {
|
|
addCheck('npm-version', 'pass', `npm ${currentNpm} satisfies ${enginesNpm}`);
|
|
} else {
|
|
addCheck('npm-version', 'fail', `npm ${currentNpm} does NOT satisfy engines.npm ${enginesNpm}`);
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Check 3: Lockfile presence
|
|
// ---------------------------------------------------------------------------
|
|
const LOCKFILE = path.join(PROJECT_ROOT, 'package-lock.json');
|
|
if (fs.existsSync(LOCKFILE)) {
|
|
addCheck('lockfile-present', 'pass', 'package-lock.json exists');
|
|
} else {
|
|
addCheck('lockfile-present', 'fail', "package-lock.json missing — run 'npm install' to generate it");
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Check 4: Lockfile sync (npm ci --dry-run)
|
|
// ---------------------------------------------------------------------------
|
|
if (fs.existsSync(LOCKFILE)) {
|
|
try {
|
|
const res = spawnSync(npmCmd, ['ci', '--dry-run'], {
|
|
cwd: PROJECT_ROOT,
|
|
encoding: 'utf8',
|
|
shell: process.platform === 'win32',
|
|
});
|
|
if (res.status === 0) {
|
|
addCheck('lockfile-sync', 'pass', 'package-lock.json is in sync with package.json');
|
|
} else {
|
|
addCheck('lockfile-sync', 'fail', "package-lock.json is out of sync — run 'npm ci' to restore");
|
|
}
|
|
} catch {
|
|
addCheck('lockfile-sync', 'fail', "package-lock.json is out of sync — run 'npm ci' to restore");
|
|
}
|
|
} else {
|
|
addCheck('lockfile-sync', 'skip', 'skipped — lockfile missing');
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Check 5: Version manager pin vs active Node
|
|
// Looks for .nvmrc, .node-version, or .tool-versions at project root.
|
|
// ---------------------------------------------------------------------------
|
|
const NVMRC = path.join(PROJECT_ROOT, '.nvmrc');
|
|
const NODE_VERSION_FILE = path.join(PROJECT_ROOT, '.node-version');
|
|
const TOOL_VERSIONS = path.join(PROJECT_ROOT, '.tool-versions');
|
|
|
|
let pinnedMajor = '';
|
|
let pinSource = '';
|
|
|
|
if (fs.existsSync(NVMRC)) {
|
|
const content = fs.readFileSync(NVMRC, 'utf8').split('\n')[0].trim().replace(/^v/, '');
|
|
pinnedMajor = content.split('.')[0];
|
|
pinSource = '.nvmrc';
|
|
} else if (fs.existsSync(NODE_VERSION_FILE)) {
|
|
const content = fs.readFileSync(NODE_VERSION_FILE, 'utf8').split('\n')[0].trim().replace(/^v/, '');
|
|
pinnedMajor = content.split('.')[0];
|
|
pinSource = '.node-version';
|
|
} else if (fs.existsSync(TOOL_VERSIONS)) {
|
|
const lines = fs.readFileSync(TOOL_VERSIONS, 'utf8').split('\n');
|
|
const nodeLine = lines.find(l => /^nodejs\s+/.test(l));
|
|
if (nodeLine) {
|
|
const ver = nodeLine.split(/\s+/)[1] || '';
|
|
pinnedMajor = ver.replace(/^v/, '').split('.')[0];
|
|
pinSource = '.tool-versions';
|
|
}
|
|
}
|
|
|
|
if (!pinnedMajor) {
|
|
addCheck('version-manager-pin', 'skip', 'no .nvmrc, .node-version, or .tool-versions found — skipping');
|
|
} else if (process.env.CI === 'true') {
|
|
addCheck('version-manager-pin', 'skip', 'CI=true — version-manager pin check skipped (matrix tests multiple Node majors)');
|
|
} else {
|
|
const activeMajor = process.version.replace(/^v/, '').split('.')[0];
|
|
if (activeMajor === pinnedMajor) {
|
|
addCheck('version-manager-pin', 'pass', `Active Node major (${activeMajor}) matches ${pinSource} pin (${pinnedMajor})`);
|
|
} else {
|
|
addCheck('version-manager-pin', 'fail', `Active Node major (${activeMajor}) does NOT match ${pinSource} pin (${pinnedMajor}) — run 'nvm use' or equivalent`);
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Output
|
|
// ---------------------------------------------------------------------------
|
|
const overallPass = checks.every(c => c.status !== 'fail');
|
|
|
|
if (jsonMode) {
|
|
// Structured JSON: {pass: bool, checks: [{name, status, message}]}
|
|
const out = {
|
|
pass: overallPass,
|
|
checks: checks.map(c => ({ name: c.name, status: c.status, message: c.message })),
|
|
};
|
|
process.stdout.write(JSON.stringify(out, null, 2) + '\n');
|
|
} else {
|
|
// Human-readable report
|
|
process.stdout.write('=== Environment Check ===\n');
|
|
for (const { name, status, message } of checks) {
|
|
const icon = status === 'pass' ? '[PASS]' : status === 'fail' ? '[FAIL]' : '[SKIP]';
|
|
const namePadded = name.padEnd(25);
|
|
process.stdout.write(` ${icon} ${namePadded} ${message}\n`);
|
|
}
|
|
process.stdout.write('\n');
|
|
if (overallPass) {
|
|
process.stdout.write('Result: ALL CHECKS PASSED\n');
|
|
} else {
|
|
process.stdout.write('Result: ONE OR MORE CHECKS FAILED — see above\n');
|
|
}
|
|
}
|
|
|
|
process.exit(overallPass ? 0 : 1);
|