-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcli.mjs
90 lines (72 loc) · 2.25 KB
/
cli.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/usr/bin/env node
import { execSync } from "child_process";
import path from "path";
import fs from "fs";
const message = (...messages) => messages.filter(Boolean).join(" ");
const log = (...messages) => console.log(message(...messages));
const warn = (...messages) => console.warn(message(...messages));
function runCommand(command) {
try {
return execSync(command).toString().trim();
} catch (e) {
console.error(`Failed to execute ${command}`, e);
}
}
async function birdUp() {
let directory = path.resolve();
const { root } = path.parse(directory);
while (true) {
try {
const lookingAt = path.resolve(directory, ".nvmrc");
const foundPath = await fs.promises.stat(lookingAt);
const contents = fs.readFileSync(lookingAt, "utf8");
if (foundPath) {
return {
path: lookingAt,
version: contents.startsWith("v") ? contents : `v${contents}`,
};
}
} catch (e) {
if (e.code !== "ENOENT") {
console.error(e);
}
directory = path.dirname(directory);
if (directory === root) {
return "unknown";
}
}
}
}
async function main() {
const args = new Set(process.argv);
const supportEmojis = args.has("-e") || args.has("--emoji");
const exitWithErrorCodeOnFailure = args.has("-f") || args.has("--fail");
const currentNodeVersion = runCommand("node --version");
const closestNvmrcFile = await birdUp();
if (args.has("-v") || args.has("--verbose")) {
log(supportEmojis && "ℹ️", `Current node version ${currentNodeVersion}`);
if (closestNvmrcFile !== "unknown") {
log(
supportEmojis && "ℹ️",
`Found .nvmrc file with ${closestNvmrcFile.version} at ${closestNvmrcFile.path}`
);
}
}
if (closestNvmrcFile === "unknown") {
warn(
supportEmojis && "🚨",
"Cannot find an .nvmrc file in this directory or in any it's parent directories"
);
return;
}
if (currentNodeVersion !== closestNvmrcFile.version) {
warn(supportEmojis && "🚨", "Node version is NOT correct");
if (exitWithErrorCodeOnFailure) {
// exiting with Unix code 1 indicates error
process.exit(1);
}
return;
}
log("Node version is correct", supportEmojis && "🎉");
}
main();