@barqjs/cli 0.0.0-stage → 0.2.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1,212 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `barq`: the command line of the framework.
4
+ *
5
+ * No dependencies beyond the compiler it drives. The argument parsing is
6
+ * smaller than a library that would do it.
7
+ */
8
+
9
+ import { realpathSync } from "node:fs";
10
+ import { stdout } from "node:process";
11
+ import { fileURLToPath } from "node:url";
12
+
13
+ import { check, codes, formatText, projectOptions, type Paint } from "./check.ts";
14
+
15
+ export { applyFixes, check, codes, formatText, projectOptions } from "./check.ts";
16
+ export type {
17
+ CheckOptions,
18
+ CheckResult,
19
+ CodeEntry,
20
+ Edit,
21
+ Finding,
22
+ Paint,
23
+ Severity,
24
+ } from "./check.ts";
25
+
26
+ const HELP = `\
27
+ barq check [paths...] Report the compiler's findings for a project
28
+ barq codes List every code the compiler can raise
29
+
30
+ check options:
31
+ --json One JSON document on stdout, for a program to read
32
+ --fix Apply the fixes the findings carry, then report what is left
33
+ --root <dir> The project root (default: the current directory)
34
+ --routes <dir> The file routes, for checking links (default: src/routes)
35
+ --level <CODE=level> Set a code to suppress, note, warning or error; repeatable
36
+ --max-warnings <n> Exit 1 when there are more warnings than this
37
+
38
+ codes options:
39
+ --json The list as JSON
40
+
41
+ A project sets its own defaults under "barq": { "check": { ... } } in
42
+ package.json: paths, routes, extraRoutes (patterns beside the file routes) and
43
+ levels ({ "BARQ004": "error" }).
44
+
45
+ Exit status: 0 clean, 1 findings at error level or past --max-warnings, 2 a
46
+ command line this does not understand.
47
+ `;
48
+
49
+ const LEVELS = new Set(["suppress", "note", "warning", "error"]);
50
+
51
+ class UsageError extends Error {}
52
+
53
+ interface Parsed {
54
+ command: string | undefined;
55
+ paths: string[];
56
+ json: boolean;
57
+ fix: boolean;
58
+ root: string;
59
+ routes: string | undefined;
60
+ levels: [string, string][];
61
+ maxWarnings: number | undefined;
62
+ help: boolean;
63
+ }
64
+
65
+ export function parse(argv: readonly string[]): Parsed {
66
+ const parsed: Parsed = {
67
+ command: undefined,
68
+ paths: [],
69
+ json: false,
70
+ fix: false,
71
+ root: process.cwd(),
72
+ routes: undefined,
73
+ levels: [],
74
+ maxWarnings: undefined,
75
+ help: false,
76
+ };
77
+ const value = (flag: string, index: number): string => {
78
+ const next = argv[index];
79
+ if (next === undefined || next.startsWith("--")) {
80
+ throw new UsageError(`\`${flag}\` takes a value, and none follows it.`);
81
+ }
82
+ return next;
83
+ };
84
+ for (let index = 0; index < argv.length; index++) {
85
+ const arg = argv[index] as string;
86
+ switch (arg) {
87
+ case "--help":
88
+ case "-h":
89
+ parsed.help = true;
90
+ break;
91
+ case "--json":
92
+ parsed.json = true;
93
+ break;
94
+ case "--fix":
95
+ parsed.fix = true;
96
+ break;
97
+ case "--root":
98
+ parsed.root = value(arg, ++index);
99
+ break;
100
+ case "--routes":
101
+ parsed.routes = value(arg, ++index);
102
+ break;
103
+ case "--level": {
104
+ const pair = value(arg, ++index);
105
+ const [code, level] = pair.split("=");
106
+ if (code === undefined || level === undefined || !LEVELS.has(level)) {
107
+ throw new UsageError(
108
+ `\`--level ${pair}\` is not \`CODE=level\`, where level is one of suppress, note, warning, error. Write it as \`--level BARQ004=error\`.`,
109
+ );
110
+ }
111
+ parsed.levels.push([code.toUpperCase(), level]);
112
+ break;
113
+ }
114
+ case "--max-warnings": {
115
+ const text = value(arg, ++index);
116
+ const count = Number(text);
117
+ if (!Number.isInteger(count) || count < 0) {
118
+ throw new UsageError(
119
+ `\`--max-warnings ${text}\` is not a whole number. Write it as \`--max-warnings 0\`.`,
120
+ );
121
+ }
122
+ parsed.maxWarnings = count;
123
+ break;
124
+ }
125
+ default:
126
+ if (arg.startsWith("-")) {
127
+ throw new UsageError(`\`${arg}\` is not an option of barq. Run \`barq --help\`.`);
128
+ }
129
+ if (parsed.command === undefined) parsed.command = arg;
130
+ else parsed.paths.push(arg);
131
+ }
132
+ }
133
+ return parsed;
134
+ }
135
+
136
+ function painter(): Paint {
137
+ const styled = stdout.isTTY && process.env["NO_COLOR"] === undefined;
138
+ const code =
139
+ (open: string) =>
140
+ (text: string): string =>
141
+ styled ? `\u001B[${open}m${text}\u001B[0m` : text;
142
+ return {
143
+ error: code("31"),
144
+ warning: code("33"),
145
+ note: code("36"),
146
+ dim: code("2"),
147
+ bold: code("1"),
148
+ };
149
+ }
150
+
151
+ /** Run one command line and answer with the exit status. */
152
+ export function main(argv: readonly string[], write: (text: string) => void): number {
153
+ let parsed: Parsed;
154
+ try {
155
+ parsed = parse(argv);
156
+ } catch (error) {
157
+ if (!(error instanceof UsageError)) throw error;
158
+ write(`${error.message}\n`);
159
+ return 2;
160
+ }
161
+ if (parsed.help || parsed.command === undefined) {
162
+ write(HELP);
163
+ return parsed.help ? 0 : 2;
164
+ }
165
+ switch (parsed.command) {
166
+ case "check": {
167
+ const set = projectOptions(parsed.root);
168
+ const result = check({
169
+ ...set,
170
+ root: parsed.root,
171
+ fix: parsed.fix,
172
+ // A level on the command line is added after the project's, and the
173
+ // compiler takes the last one named for a code.
174
+ levels: [...(set.levels ?? []), ...parsed.levels],
175
+ ...(parsed.paths.length > 0 ? { paths: parsed.paths } : {}),
176
+ ...(parsed.routes !== undefined ? { routes: parsed.routes } : {}),
177
+ });
178
+ write(
179
+ parsed.json ? `${JSON.stringify(result, null, 2)}\n` : `${formatText(result, painter())}\n`,
180
+ );
181
+ const { errors, warnings } = result.summary;
182
+ const over = parsed.maxWarnings !== undefined && warnings > parsed.maxWarnings;
183
+ return errors > 0 || over ? 1 : 0;
184
+ }
185
+ case "codes": {
186
+ const list = codes();
187
+ write(
188
+ parsed.json
189
+ ? `${JSON.stringify(list, null, 2)}\n`
190
+ : `${list.map((entry) => `${entry.code} ${entry.level.padEnd(7)} ${entry.summary}`).join("\n")}\n`,
191
+ );
192
+ return 0;
193
+ }
194
+ default:
195
+ write(`\`${parsed.command}\` is not a command of barq. Run \`barq --help\`.\n`);
196
+ return 2;
197
+ }
198
+ }
199
+
200
+ /**
201
+ * The guard compares the script node was asked to run with this module rather
202
+ * than reading `import.meta.main`, which node defines only from 24.2. `argv[1]`
203
+ * is the `.bin` symlink under a package manager, hence the realpath.
204
+ */
205
+ function invokedDirectly(): boolean {
206
+ const script = process.argv[1];
207
+ return script !== undefined && realpathSync(script) === fileURLToPath(import.meta.url);
208
+ }
209
+
210
+ if (invokedDirectly()) {
211
+ process.exitCode = main(process.argv.slice(2), (text) => stdout.write(text));
212
+ }