@osdlc/wayfinder 0.7.1 → 0.7.2

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/dist/cli.js CHANGED
@@ -1,25 +1,23 @@
1
1
  /**
2
2
  * `way`: browse and run every task in a repository.
3
3
  *
4
- * wayfinder is willing to run a repository's tools in principle (`allowExec:
5
- * true` by default): you are standing in your own repository, and a task
6
- * browser that cannot see the build graph is not much of a browser.
7
- * `--no-exec` opts out.
4
+ * wayfinder's `allowExec` default is `true`. You usually run it in your own
5
+ * repository, and a task browser that cannot see the build graph is of little
6
+ * use. `--no-exec` turns execution off.
8
7
  *
9
- * The default is not the gate. Per-repository trust is: `@osdlc/trust-repo`'s
10
- * `policyExecGate` combines the configured value with the marker store and the
11
- * user file's `trust.paths`/`trust.owners` policy, so willingness becomes
12
- * execution only once a person, or a policy they configured, has said yes to
13
- * this repository. A configured `false` means no exec however trusted the
14
- * repository is.
8
+ * The default alone does not allow execution. The repository must also be
9
+ * trusted. `@osdlc/trust-repo`'s `policyExecGate` combines the configured value
10
+ * with the marker store and the user file's `trust.paths`/`trust.owners`
11
+ * policy. Execution happens only once a person, or a policy they configured,
12
+ * has trusted this repository. A configured `false` means no execution, however
13
+ * trusted the repository is.
15
14
  */
16
- import { homedir } from 'node:os';
17
15
  import { EXIT, defineCli, processIo } from '@osdlc/cli-tool';
18
16
  import { runDevCli } from '@osdlc/cli-tool/devlink';
19
17
  import { tasks as allTasks, } from '@osdlc/system-model/detect';
20
18
  import { humanAge, humanMs } from '@osdlc/system-model/duration';
21
19
  import { matchEntry, terms as searchTerms } from '@osdlc/system-model/match';
22
- import { policyExecGate, withheldHint } from '@osdlc/trust-repo';
20
+ import { homeDir, policyExecGate, withheldHint } from '@osdlc/trust-repo';
23
21
  import { APP, BIN, PROJECT_CONFIG_FILENAME } from "./app.js";
24
22
  import { cacheDir } from "./cache.js";
25
23
  import { collectAndCache, freshStates, fromStore, makeProject, orderedCatalog, readCachedCatalog, } from "./catalog.js";
@@ -34,6 +32,7 @@ import { runProvidersCommand } from "./providers-command.js";
34
32
  import { serve } from "./serve.js";
35
33
  import { loadTools, ToolModuleError } from "./tools.js";
36
34
  import { runTrustCommand } from "./trust-command.js";
35
+ import { jsonText, safeJsonStdout, safeStderr, safeStdout, terminalSafe } from "./terminal-text.js";
37
36
  import { runTui } from "./tui.js";
38
37
  /** The prose under the flag list in the complete help. */
39
38
  const PROSE = `Defaults come from ${PROJECT_CONFIG_FILENAME} in the project root and from the user file
@@ -64,7 +63,7 @@ In the terminal UI:
64
63
  enter run ^y copy tab runner ^e exact ^t services ^s trust ^r refresh esc quit
65
64
  `;
66
65
  /**
67
- * The surface and subcommand names, for both help tiers. A generated flag
66
+ * The surface and subcommand names, for both help levels. A generated flag
68
67
  * list cannot say which surface you are choosing, or name a subcommand that
69
68
  * has its own flag list.
70
69
  */
@@ -79,14 +78,13 @@ subcommands
79
78
  trust allow this repository's runners to be read by running them; see trust --help
80
79
  providers the registered tools, built-in and your own; see providers --help
81
80
  guide how to use and extend this tool, in Markdown; see guide --help
82
- clean remove the data this tool stores outside your repositories; see clean --help
83
- dev run the installed ${BIN} from a development checkout; see dev --help`;
81
+ clean remove the data this tool stores outside your repositories; see clean --help`;
84
82
  /**
85
- * wayfinder's own `true` default for exec lives in {@link main}, below the
86
- * config layer — which is why `exec` and the collection lists are declared
87
- * absent-unless-given, per `TristateFlag` in `@osdlc/cli-tool`. `autoHelp`
88
- * is off for the reason `CliDecl.autoHelp` gives: `help` and `all` are
89
- * declared below as ordinary flags.
83
+ * wayfinder's own `true` default for exec is applied in {@link main}, below
84
+ * the config layer. So `exec` and the collection lists are absent unless
85
+ * given, per `TristateFlag` in `@osdlc/cli-tool`. `autoHelp` is off for the
86
+ * reason `CliDecl.autoHelp` gives: `help` and `all` are declared below as
87
+ * ordinary flags.
90
88
  */
91
89
  const cli = defineCli({
92
90
  name: BIN,
@@ -187,12 +185,12 @@ Until then they are withheld and every surface says so.
187
185
 
188
186
  ${PROSE}`,
189
187
  });
190
- /** The complete help tier. */
188
+ /** The complete help. */
191
189
  const USAGE = cli.help();
192
190
  /**
193
- * The default help tier. Nothing in it is the only place a fact lives, and
194
- * every deeper tier is named. The trust paragraph is in it because a reader
195
- * who does not know about the gate sees a shorter catalog and no reason why.
191
+ * The default, short help. Every fact in it is also stated in the complete
192
+ * help, and it names the longer forms. The trust paragraph is here because a
193
+ * reader who does not know about trust sees a shorter catalog and no reason why.
196
194
  */
197
195
  const SHORT_USAGE = cli.help({ all: false });
198
196
  /** What the `guide` command needs: the complete help, and what it cannot say. */
@@ -215,10 +213,10 @@ ${APP} supplies \`allowExec: true\` as its own default, below any config file:
215
213
  willing in principle, still gated on trust.`,
216
214
  };
217
215
  /**
218
- * `query` is claimed before the flag parse like `config` and `trust` (see
219
- * {@link main}), but only because it changes what a positional MEANS, from a
220
- * directory to search terms. Every collection flag still applies after it,
221
- * which is why it is not a command with its own flag list.
216
+ * `query` is matched before the flags are parsed, like `config` and `trust`
217
+ * (see {@link main}), because it changes what a positional means: search terms
218
+ * instead of a directory. Every collection flag still applies after it, so it
219
+ * is not a command with its own flag list.
222
220
  */
223
221
  export function parseArgs(argv, io, cwd = process.cwd()) {
224
222
  const isQuery = argv[0] === 'query';
@@ -228,8 +226,8 @@ export function parseArgs(argv, io, cwd = process.cwd()) {
228
226
  if (parsed.status === 'error')
229
227
  return { error: parsed.message };
230
228
  const v = parsed.values;
231
- // Under `query` these choose the OUTPUT FORM rather than the surface:
232
- // letting them set the mode would silently drop the terms.
229
+ // Under `query` these choose the output form, not the surface. Letting them
230
+ // set the mode would silently drop the terms.
233
231
  const mode = isQuery
234
232
  ? 'query'
235
233
  : v.serve
@@ -273,18 +271,18 @@ export function parseArgs(argv, io, cwd = process.cwd()) {
273
271
  return { error: '--services only applies to query' };
274
272
  }
275
273
  else {
276
- // The mode ternary above short-circuits on `isQuery`, so a serve flag
277
- // under `query` would otherwise be read by nothing at all.
274
+ // The mode ternary above stops at `isQuery`, so nothing else would read a
275
+ // serve flag under `query`.
278
276
  if (v.serve)
279
277
  return { error: '--serve does not apply to query' };
280
278
  if (v.port !== undefined)
281
279
  return { error: '--port only applies to --serve' };
282
280
  }
283
281
  if (v.port !== undefined) {
284
- // Digits only, before coercing: `Number('')` and `Number(' ')` are 0,
285
- // `Number('0x10')` is 16 and `Number('1e3')` is 1000 — every one an
286
- // integer in range, so a bare `Number()` would accept a port nobody typed,
287
- // and port 0 means "let the OS pick", which is what --port exists to stop.
282
+ // Check for digits before converting. `Number('')` and `Number(' ')` are
283
+ // 0, `Number('0x10')` is 16 and `Number('1e3')` is 1000. Each is an integer
284
+ // in range, so a bare `Number()` would accept a port nobody typed. Port 0
285
+ // means "let the OS pick", which is what --port exists to prevent.
288
286
  if (!/^\d+$/.test(v.port.trim())) {
289
287
  return { error: '--port needs a port number' };
290
288
  }
@@ -308,12 +306,12 @@ export function parseArgs(argv, io, cwd = process.cwd()) {
308
306
  /**
309
307
  * wayfinder's own defaults, applied only where no config file answered.
310
308
  *
311
- * One constant, read in two places: {@link main} resolves the run with it, and
312
- * `config list` / `config get` are handed it so they report the value this tool
313
- * would really use rather than the library's.
309
+ * One constant, read in two places. {@link main} resolves the run with it, and
310
+ * `config list` / `config get` receive it, so they report the value this tool
311
+ * really uses rather than the library default.
314
312
  *
315
- * `allowExec: true` means WILLING IN PRINCIPLE, not "run this repository's
316
- * code"; trust is the gate, and a configured `false` still means no exec.
313
+ * `allowExec: true` does not mean "run this repository's code". The repository
314
+ * must also be trusted, and a configured `false` still means no execution.
317
315
  */
318
316
  const WAYFINDER_DEFAULTS = { allowExec: true };
319
317
  /** `allowExec` from the config files, or wayfinder's default when none sets it. */
@@ -324,8 +322,8 @@ function configuredAllowExec(cfg) {
324
322
  }
325
323
  /**
326
324
  * The single stderr line `--cached` prints, or null when there is nothing to
327
- * say. Where this repo has never measured a runner's probe cost it says so
328
- * rather than inventing a number.
325
+ * say. When this repo has never measured a runner's probe time, the line says
326
+ * so rather than guessing a number.
329
327
  */
330
328
  function cacheNote(rows) {
331
329
  const stale = rows.filter((r) => r.state === 'stale');
@@ -385,16 +383,19 @@ async function projectFor(toolModules, cfg, home, projectAllowed) {
385
383
  * `env` and `home` are injectable so a test never reads the developer's own
386
384
  * config, cache or trust store. `io` defaults to the real process streams.
387
385
  */
388
- export async function main(argv, env = process.env, home = homedir(), io = processIo) {
389
- // Subcommands are claimed before the flag parse: their arguments are not
390
- // this parser's flags. The root is found with the built-in tools only.
386
+ export async function main(argv, env = process.env, home = homeDir(), io = processIo) {
387
+ // Every stderr line is human text that can quote repository content.
388
+ io = safeStderr(io);
389
+ // Subcommands are matched before the flags are parsed, because their
390
+ // arguments are not this parser's flags. The root is found with the
391
+ // built-in tools only.
391
392
  const findRoot = (dir) => makeProject().findRoot(dir);
392
393
  const usageError = (message) => {
393
394
  io.stderr(`${APP}: ${message}\n\n${SHORT_USAGE}`);
394
395
  return EXIT.usage;
395
396
  };
396
397
  if (argv[0] === 'config' || argv[0] === 'trust' || argv[0] === 'providers') {
397
- // -C has to work here: pointing at another directory must show THAT
398
+ // -C has to work here, so pointing at another directory shows that
398
399
  // directory's configuration, trust and tools.
399
400
  const taken = takeConfigDir(argv.slice(1));
400
401
  if ('error' in taken)
@@ -422,13 +423,18 @@ export async function main(argv, env = process.env, home = homedir(), io = proce
422
423
  return runCleanCommand(APP, argv.slice(1), { ...io, env, home });
423
424
  if (argv[0] === 'guide')
424
425
  return runGuideCommand(GUIDE_TOOL, argv.slice(1), io);
425
- // `self` is this checkout, so `dev install` and a bare `dev link` know what
426
- // to point at.
426
+ // `dev` is a contributor tool, so the help does not list it. `self` is this
427
+ // checkout, so `dev install` and a bare `dev link` know what to point at.
427
428
  if (argv[0] === 'dev') {
428
- return runDevCli(WAYFINDER_SPEC, argv.slice(1), { io, env, self: checkoutRoot() });
429
+ const devArgs = argv.slice(1);
430
+ return runDevCli(WAYFINDER_SPEC, devArgs, {
431
+ io: devArgs.includes('--json') ? safeJsonStdout(io) : safeStdout(io),
432
+ env,
433
+ self: checkoutRoot(),
434
+ });
429
435
  }
430
436
  const parsed = parseArgs(argv, io);
431
- // The short form on a typo: the error is the part the reader came for.
437
+ // A usage error prints the short help, so the error is easy to find.
432
438
  if ('error' in parsed)
433
439
  return usageError(parsed.error);
434
440
  if (parsed.help) {
@@ -449,11 +455,12 @@ export async function main(argv, env = process.env, home = homedir(), io = proce
449
455
  }
450
456
  for (const warning of cfg.warnings)
451
457
  io.stderr(`warning: ${warning}\n`);
452
- // Precedence for allowExec, highest first: --exec / --no-exec; allowExec in
453
- // the project file, then the user file; wayfinder's own default (true). Only
454
- // `sources` separates "a file said false" from "nobody said anything".
458
+ // Precedence for allowExec, highest first: --exec / --no-exec, then
459
+ // allowExec in the project file (false only), then the user file, then
460
+ // wayfinder's own default (true). Only `sources` tells "a file said false"
461
+ // apart from "no file set it".
455
462
  const configured = configuredAllowExec(cfg);
456
- // The trust seam. Collection never reads the store.
463
+ // Trust is decided here. Collection never reads the trust store.
457
464
  const trustStoreInstance = appTrustStore({ env, home });
458
465
  const gate = await policyExecGate(trustStoreInstance, trustPolicyFromConfig(cfg.effective), { root, configured, flag: parsed.allowExec }, trustPolicyOptions(home));
459
466
  // A project module runs code on import, so it needs execution allowed as
@@ -482,15 +489,15 @@ export async function main(argv, env = process.env, home = homedir(), io = proce
482
489
  ...(parsed.excludePaths ? { excludePaths: parsed.excludePaths } : {}),
483
490
  ...(parsed.discovery !== undefined ? { discovery: parsed.discovery } : {}),
484
491
  };
485
- // The config keys a flag already answered. `serve` re-derives the file's
486
- // slice after a save from the page and leaves these alone.
492
+ // The config keys a flag already set. When the page saves the config,
493
+ // `serve` re-reads the file's options and leaves these alone.
487
494
  const pinnedByFlag = [
488
495
  ...(parsed.exclude ? ['exclude'] : []),
489
496
  ...(parsed.excludePaths ? ['excludePaths'] : []),
490
497
  ...(parsed.discovery !== undefined ? ['discovery'] : []),
491
498
  ];
492
- // Said once for all runners, and only by the non-interactive modes: the TUI
493
- // and the page have their own affordance.
499
+ // Printed once for all runners, and only by the non-interactive modes. The
500
+ // TUI and the page show their own trust prompt.
494
501
  const reportWithheld = (catalog) => {
495
502
  const withheld = catalog.reports.filter((r) => r.skippedForExec).length;
496
503
  if (gate.reason !== 'untrusted' || withheld === 0)
@@ -500,10 +507,10 @@ export async function main(argv, env = process.env, home = homedir(), io = proce
500
507
  const store = cacheDir(env, home);
501
508
  const order = cfg.effective.runners?.order;
502
509
  /**
503
- * The catalog for a data surface, plus the cache verdict when one was read.
504
- * Fresh by default, since a script must not get a quietly old answer; the
505
- * probe still writes the store. --cached reads the store and says so on
506
- * stderr.
510
+ * The catalog for a data surface, plus the cache states when the store was
511
+ * read. Probed fresh by default, since a script must not get an old answer
512
+ * without being told. The probe still writes the store. --cached reads the
513
+ * store and says so on stderr.
507
514
  */
508
515
  const dataCatalog = async () => {
509
516
  if (!parsed.cached) {
@@ -516,7 +523,7 @@ export async function main(argv, env = process.env, home = homedir(), io = proce
516
523
  const fresh = await collectAndCache(project, root, options, store);
517
524
  return { catalog: orderedCatalog(fresh, order), cache: freshStates(fresh) };
518
525
  }
519
- // A miss is a gap in the cache: the missing runners alone are probed.
526
+ // A miss is a runner with nothing stored. Only the missing runners are probed.
520
527
  const missing = stored.runners.filter((r) => r.state === 'miss').map((r) => r.runner);
521
528
  const merged = missing.length === 0
522
529
  ? stored.catalog
@@ -550,13 +557,13 @@ export async function main(argv, env = process.env, home = homedir(), io = proce
550
557
  });
551
558
  case 'json': {
552
559
  const { catalog, cache } = await dataCatalog();
553
- io.stdout(`${JSON.stringify(catalogJson(catalog, cache), null, 2)}\n`);
560
+ io.stdout(`${jsonText(catalogJson(catalog, cache), 2)}\n`);
554
561
  reportWithheld(catalog);
555
562
  return EXIT.ok;
556
563
  }
557
564
  case 'list': {
558
565
  const { catalog } = await dataCatalog();
559
- const lines = allTasks(catalog).map((t) => t.display);
566
+ const lines = allTasks(catalog).map((t) => terminalSafe(t.display));
560
567
  if (lines.length > 0)
561
568
  io.stdout(`${lines.join('\n')}\n`);
562
569
  reportWithheld(catalog);
@@ -583,13 +590,13 @@ export async function main(argv, env = process.env, home = homedir(), io = proce
583
590
  if (queryTerms.length > 0)
584
591
  hits.sort((a, b) => b.score - a.score);
585
592
  if (parsed.json) {
586
- io.stdout(`${JSON.stringify(hits.map((h) => h.task), null, 2)}\n`);
593
+ io.stdout(`${jsonText(hits.map((h) => h.task), 2)}\n`);
587
594
  }
588
595
  else if (hits.length > 0) {
589
- io.stdout(`${hits.map((h) => h.task.display).join('\n')}\n`);
596
+ io.stdout(`${hits.map((h) => terminalSafe(h.task.display)).join('\n')}\n`);
590
597
  }
591
598
  reportWithheld(catalog);
592
- // grep's contract: a search with terms that matched nothing exits 1.
599
+ // As with grep, a search with terms that matched nothing exits 1.
593
600
  return queryTerms.length > 0 && hits.length === 0 ? 1 : 0;
594
601
  }
595
602
  case 'tui':
@@ -6,13 +6,15 @@
6
6
  import { type TaskConfig } from './config.ts';
7
7
  import { type CliIo } from '@osdlc/cli-tool';
8
8
  /**
9
- * A VIEW of `CliIo`: the same output seam, plus the environment this command
10
- * needs injected.
9
+ * `CliIo` plus the environment this command needs injected.
11
10
  */
12
11
  export interface ConfigCommandIO extends CliIo {
13
- /** Defaults to `process.env`. Supplies `WAYFINDER_CONFIG` (or the old `WAYPOST_CONFIG`) and `XDG_CONFIG_HOME`. */
12
+ /**
13
+ * Defaults to `process.env`. Supplies `WAYFINDER_CONFIG` (or the old
14
+ * `WAYPOST_CONFIG`) and `XDG_CONFIG_HOME`.
15
+ */
14
16
  env?: Record<string, string | undefined>;
15
- /** Defaults to `os.homedir()`. The base for the non-XDG user path. */
17
+ /** Defaults to `homeDir()` from `@osdlc/trust-repo`. The base for the non-XDG user path. */
16
18
  home?: string;
17
19
  /**
18
20
  * wayfinder's own defaults, between `DEFAULT_CONFIG` and the user file
@@ -37,16 +39,15 @@ export declare function takeConfigDir(argv: string[]): {
37
39
  * `<tool> config <sub> …`. `root` is the resolved project root. Returns the
38
40
  * exit code.
39
41
  *
40
- * Exit codes: 0 succeeded. 2 means the
41
- * command cannot be run as typed — an unknown subcommand or option, a wrong
42
- * argument count, contradictory flags, an unknown setting name, a value of the
43
- * wrong type for its setting. Every one of those is decided from the argument
44
- * list and the static schema alone, with no file involved, so re-running it can
45
- * only produce the same answer. 1 means a well-formed command that FAILED: a
46
- * file that will not parse, a key that is not set where you asked to unset it,
47
- * a `get` that found nothing.
42
+ * Exit codes: 0 means success. 2 means the command cannot run as typed: an
43
+ * unknown subcommand or option, a wrong number of arguments, conflicting
44
+ * flags, an unknown setting name, or a value of the wrong type. Each is
45
+ * decided from the arguments and the schema alone, with no file involved, so
46
+ * running it again gives the same answer. 1 means a valid command that
47
+ * failed: a file that will not parse, a key that is not set where you asked
48
+ * to unset it, or a `get` that found nothing.
48
49
  *
49
- * The split matters because a script can act on it — 2 means fix the command,
50
- * 1 means look at the state.
50
+ * A script can act on the difference: 2 means fix the command, 1 means look
51
+ * at the state.
51
52
  */
52
53
  export declare function runConfigCommand(toolName: string, root: string, argv: string[], io: ConfigCommandIO): Promise<number>;
@@ -4,10 +4,11 @@
4
4
  * developer's own config.
5
5
  */
6
6
  import { access } from 'node:fs/promises';
7
- import { homedir } from 'node:os';
8
7
  import { BIN } from "./app.js";
9
- import { CONFIG_ENV_VAR, ConfigError, configLocations, DEFAULT_CONFIG, getConfigValue, loadConfig, mergeConfig, parseConfigValue, readRawConfigFile, setConfigValue, unsetConfigValue, validateConfig, writeConfigFile, } from "./config.js";
8
+ import { CONFIG_ENV_VAR, ConfigError, configLocations, envIgnoredWarning, DEFAULT_CONFIG, getConfigValue, loadConfig, mergeConfig, parseConfigValue, readRawConfigFile, setConfigValue, unsetConfigValue, validateConfig, writeConfigFile, } from "./config.js";
9
+ import { jsonText, terminalSafe } from "./terminal-text.js";
10
10
  import { EXIT } from '@osdlc/cli-tool';
11
+ import { homeDir } from '@osdlc/trust-repo';
11
12
  function usage() {
12
13
  return `${BIN} config — read and write the layered task configuration
13
14
 
@@ -33,11 +34,11 @@ location and nothing else.
33
34
  `;
34
35
  }
35
36
  /**
36
- * `loadConfig`, with the calling tool's defaults slid in under the file layers.
37
+ * `loadConfig`, with the calling tool's defaults placed under the file layers.
37
38
  *
38
- * `sources` is left alone on purpose: a value the tool defaulted still came
39
- * from no file, so `(default)` remains the honest attribution. Only the VALUE
40
- * that label is attached to changes.
39
+ * `sources` is left as it is on purpose. A value from the tool's defaults
40
+ * still came from no file, so `(default)` is still the right label. Only the
41
+ * value next to that label changes.
41
42
  */
42
43
  async function load(toolName, root, env, home, defaults) {
43
44
  const loaded = await loadConfig(root, env, home);
@@ -56,9 +57,9 @@ async function exists(file) {
56
57
  return false;
57
58
  }
58
59
  }
59
- /** `<path> (exists)` / `<path> (missing)` — the question `config path` is asked to answer. */
60
+ /** `<path> (exists)` or `<path> (missing)`, which is what `config path` reports. */
60
61
  async function describeFile(file) {
61
- return `${file} ${(await exists(file)) ? '(exists)' : '(missing)'}`;
62
+ return `${terminalSafe(file)} ${(await exists(file)) ? '(exists)' : '(missing)'}`;
62
63
  }
63
64
  function pad(text, width) {
64
65
  return text.length >= width ? text : text + ' '.repeat(width - text.length);
@@ -66,9 +67,8 @@ function pad(text, width) {
66
67
  /**
67
68
  * Split `--user` / `--project` off the argument list, leaving the positionals.
68
69
  *
69
- * The two contradict each other, and both callers WRITE, so a last-one-wins
70
- * reading would silently edit a file the user named the other of. A pair is a
71
- * usage error instead.
70
+ * The two name different files, and both callers write. If the last flag won,
71
+ * a typo could silently edit the wrong file. Giving both is a usage error.
72
72
  */
73
73
  function takeTarget(argv) {
74
74
  let target;
@@ -130,21 +130,20 @@ export function takeConfigDir(argv) {
130
130
  * `<tool> config <sub> …`. `root` is the resolved project root. Returns the
131
131
  * exit code.
132
132
  *
133
- * Exit codes: 0 succeeded. 2 means the
134
- * command cannot be run as typed — an unknown subcommand or option, a wrong
135
- * argument count, contradictory flags, an unknown setting name, a value of the
136
- * wrong type for its setting. Every one of those is decided from the argument
137
- * list and the static schema alone, with no file involved, so re-running it can
138
- * only produce the same answer. 1 means a well-formed command that FAILED: a
139
- * file that will not parse, a key that is not set where you asked to unset it,
140
- * a `get` that found nothing.
133
+ * Exit codes: 0 means success. 2 means the command cannot run as typed: an
134
+ * unknown subcommand or option, a wrong number of arguments, conflicting
135
+ * flags, an unknown setting name, or a value of the wrong type. Each is
136
+ * decided from the arguments and the schema alone, with no file involved, so
137
+ * running it again gives the same answer. 1 means a valid command that
138
+ * failed: a file that will not parse, a key that is not set where you asked
139
+ * to unset it, or a `get` that found nothing.
141
140
  *
142
- * The split matters because a script can act on it — 2 means fix the command,
143
- * 1 means look at the state.
141
+ * A script can act on the difference: 2 means fix the command, 1 means look
142
+ * at the state.
144
143
  */
145
144
  export async function runConfigCommand(toolName, root, argv, io) {
146
145
  const env = io.env ?? process.env;
147
- const home = io.home ?? homedir();
146
+ const home = io.home ?? homeDir();
148
147
  const fail = (message) => {
149
148
  io.stderr(`${toolName}: ${message}\n`);
150
149
  return EXIT.error;
@@ -152,8 +151,7 @@ export async function runConfigCommand(toolName, root, argv, io) {
152
151
  const [sub, ...rest] = argv;
153
152
  try {
154
153
  switch (sub) {
155
- // Usage on stdout with exit 0: `--help` is what was asked for, not a
156
- // misuse of the command.
154
+ // Usage on stdout with exit 0, because `--help` asked for it.
157
155
  case '-h':
158
156
  case '--help':
159
157
  io.stdout(usage());
@@ -175,9 +173,9 @@ export async function runConfigCommand(toolName, root, argv, io) {
175
173
  }
176
174
  }
177
175
  catch (error) {
178
- // A ConfigError names its file and its problem, and that is the whole point
179
- // of it: a setting that quietly did not apply is worse than one that
180
- // refused to load, so this never degrades to a silent fallback.
176
+ // A ConfigError names its file and its problem. A setting that quietly did
177
+ // not apply is worse than one that refused to load, so there is no silent
178
+ // fallback.
181
179
  if (error instanceof ConfigError)
182
180
  return fail(error.message);
183
181
  throw error;
@@ -198,12 +196,14 @@ async function listCommand(toolName, root, argv, io, env, home) {
198
196
  const sources = {};
199
197
  for (const [key, layer] of loaded.sources)
200
198
  sources[key] = layer;
201
- io.stdout(`${JSON.stringify({ effective: loaded.effective, sources, locations: loaded.locations }, null, 2)}\n`);
199
+ io.stdout(`${jsonText({ effective: loaded.effective, sources, locations: loaded.locations }, 2)}\n`);
202
200
  }
203
201
  else {
202
+ // JSON.stringify leaves DEL and C1 characters raw, so the human listing
203
+ // still goes through terminalSafe.
204
204
  const rows = [...loaded.sources].map(([key, layer]) => ({
205
- key,
206
- value: JSON.stringify(getConfigValue(loaded.effective, key)),
205
+ key: terminalSafe(key),
206
+ value: terminalSafe(JSON.stringify(getConfigValue(loaded.effective, key))),
207
207
  layer,
208
208
  }));
209
209
  const keyWidth = rows.reduce((n, r) => Math.max(n, r.key.length), 0);
@@ -230,16 +230,16 @@ async function getCommand(toolName, root, argv, io, env, home) {
230
230
  }
231
231
  const loaded = await load(toolName, root, env, home, io.defaults);
232
232
  const value = getConfigValue(loaded.effective, key);
233
- // Warnings go to stderr rather than being suppressed: `get` stays scriptable
234
- // because its STDOUT is only the value, and a file with an ignored key is
235
- // something the user wants told wherever they read from it.
233
+ // Warnings go to stderr rather than being hidden. `get` stays scriptable
234
+ // because its stdout is only the value, and the user should hear about an
235
+ // ignored key wherever they read the config.
236
236
  for (const warning of loaded.warnings)
237
237
  io.stderr(`warning: ${warning}\n`);
238
238
  if (value === undefined) {
239
239
  io.stderr(`${toolName}: no value for ${key}\n`);
240
240
  return EXIT.error;
241
241
  }
242
- io.stdout(`${JSON.stringify(value)}\n`);
242
+ io.stdout(`${jsonText(value)}\n`);
243
243
  return EXIT.ok;
244
244
  }
245
245
  async function setCommand(toolName, root, argv, io, env, home) {
@@ -253,38 +253,39 @@ async function setCommand(toolName, root, argv, io, env, home) {
253
253
  io.stderr(`${toolName}: config set takes a key and a value\n\n${usage()}`);
254
254
  return EXIT.usage;
255
255
  }
256
- // configLocations rather than loadConfig: resolving where to write must not
257
- // depend on the OTHER layer parsing, and `set --user` has to work when
256
+ // configLocations rather than loadConfig: where to write must not depend on
257
+ // the other layer parsing, and `set --user` has to work when
258
258
  // WAYFINDER_CONFIG names a file that does not exist yet.
259
259
  const locations = configLocations(root, env, home);
260
260
  const file = taken.target === 'user' ? locations.user : locations.project;
261
- // The RAW record, not the validated one: validation drops keys this version
262
- // does not know, so writing a validated document back would silently delete a
263
- // setting a newer version had written into the same file.
261
+ // The raw record, not the validated one. Validation drops keys this version
262
+ // does not know, so writing a validated document back would silently delete
263
+ // a setting a newer version had written to the same file.
264
264
  const document = (await readRawConfigFile(file)) ?? {};
265
265
  let next;
266
266
  try {
267
267
  next = setConfigValue(document, key, parseConfigValue(raw));
268
268
  }
269
269
  catch (error) {
270
- // A ConfigError carrying no file is about what was TYPED — an unknown
271
- // setting name, or a value of the wrong type for a known one. `file` is
272
- // what separates those from the errors below, which are about a file.
270
+ // A ConfigError with no file is about what was typed: an unknown setting
271
+ // name, or a value of the wrong type. An empty `file` tells these apart
272
+ // from the errors below, which are about a file.
273
273
  if (error instanceof ConfigError && error.file === '') {
274
274
  io.stderr(`${toolName}: ${error.message}\n\n${usage()}`);
275
275
  return EXIT.usage;
276
276
  }
277
277
  throw error;
278
278
  }
279
- // Validate the whole document before it reaches disk. A refused value is a
280
- // message; a written one is a file that fails to load on every later run.
281
- // A failure HERE names the file — a bad value already in it — so it exits 1.
279
+ // Validate the whole document before writing it. A refused value is only a
280
+ // message, but a bad written value makes the file fail to load on every
281
+ // later run. A failure here is a bad value already in the file, so the
282
+ // error names the file and exits 1.
282
283
  validateConfig(next, file);
283
284
  await writeConfigFile(file, next);
284
- // Written, then contradicted. Refusing the write would be a stranger failure
285
- // — the key is real and the value is valid — but a silent write would leave
286
- // the author believing the setting took effect, and only `loadConfig`'s
287
- // warning, which they may never read, would say otherwise.
285
+ // Written, then warned about. Refusing the write would be odd, since the key
286
+ // is real and the value is valid. But a silent write would let the author
287
+ // believe the setting took effect, with only `loadConfig`'s warning, which
288
+ // they may never read, saying otherwise.
288
289
  if (taken.target === 'project' && key === 'allowExec' && getConfigValue(next, key) === true) {
289
290
  io.stderr(`${toolName}: warning: allowExec: true in a project file is ignored — a repository cannot grant itself permission to run subprocesses; run "${BIN} trust" to trust this repository\n`);
290
291
  }
@@ -294,7 +295,7 @@ async function setCommand(toolName, root, argv, io, env, home) {
294
295
  io.stderr(`${toolName}: warning: ${key} in a project file is ignored — a repository cannot grant itself trust; set it in your user config instead\n`);
295
296
  }
296
297
  }
297
- io.stdout(`${file}: ${key} = ${JSON.stringify(getConfigValue(next, key))}\n`);
298
+ io.stdout(terminalSafe(`${file}: ${key} = ${JSON.stringify(getConfigValue(next, key))}`) + '\n');
298
299
  return EXIT.ok;
299
300
  }
300
301
  async function unsetCommand(toolName, root, argv, io, env, home) {
@@ -312,28 +313,31 @@ async function unsetCommand(toolName, root, argv, io, env, home) {
312
313
  const file = taken.target === 'user' ? locations.user : locations.project;
313
314
  const document = await readRawConfigFile(file);
314
315
  if (document === null || getConfigValue(document, key) === undefined) {
315
- // Reported rather than shrugged off: "unset" succeeding on a key that was
316
- // never there reads as "the setting is gone from where I meant", which is
317
- // wrong whenever the value actually lives in the other layer.
316
+ // Reported as an error. Succeeding on a key that was not there would
317
+ // suggest the setting is gone, which is wrong when the value is set in
318
+ // the other layer.
318
319
  io.stderr(`${toolName}: ${key} is not set in ${file}\n`);
319
320
  return EXIT.error;
320
321
  }
321
322
  const next = unsetConfigValue(document, key);
322
323
  await writeConfigFile(file, next);
323
- io.stdout(`${file}: removed ${key}\n`);
324
+ io.stdout(terminalSafe(`${file}: removed ${key}`) + '\n');
324
325
  return EXIT.ok;
325
326
  }
326
327
  async function pathCommand(toolName, argv, io, env, home, root) {
327
- // Every sibling rejects arguments it does not understand. `path` swallowing
328
- // them silently would make it the one place a typo looks like it worked.
328
+ // Every other subcommand rejects arguments it does not understand. If `path`
329
+ // ignored them, a typo here would look like it worked.
329
330
  if (argv.length > 0) {
330
331
  io.stderr(`${toolName}: config path takes no arguments\n\n${usage()}`);
331
332
  return EXIT.usage;
332
333
  }
333
- // Locations are resolved without reading or parsing either file's CONTENTS —
334
- // existence is all this checks. `config path` is the command you reach for
335
- // when a file will not load, so it must not fail on the file it names.
334
+ // Locations are resolved without reading either file's contents. Only
335
+ // existence is checked. You use `config path` when a file will not load, so
336
+ // it must not fail on the file it names.
336
337
  const locations = configLocations(root, env, home);
338
+ const ignored = envIgnoredWarning(locations);
339
+ if (ignored !== null)
340
+ io.stderr(`warning: ${ignored}\n`);
337
341
  io.stdout(`user: ${await describeFile(locations.user)}\n`);
338
342
  if (locations.userEnvVar !== null)
339
343
  io.stdout(` (from ${locations.userEnvVar})\n`);