@kaynooo/cli-check 0.9.1 → 0.10.0

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
@@ -2,10 +2,10 @@
2
2
  // @bun
3
3
 
4
4
  // src/cli.ts
5
- import process11 from "process";
5
+ import process14 from "process";
6
6
 
7
7
  // ../kit/src/args.ts
8
- import process3 from "process";
8
+ import process5 from "process";
9
9
  import { parseArgs } from "util";
10
10
 
11
11
  // ../kit/src/format.ts
@@ -375,6 +375,55 @@ function printJson(value) {
375
375
  console.log(JSON.stringify(value, undefined, 2));
376
376
  }
377
377
 
378
+ // ../kit/src/help.ts
379
+ import process3 from "process";
380
+ var OPTIONAL = /\[[^\]]+\]/g;
381
+ var USAGE_PREFIX = /^usage:\s*/i;
382
+ var FULL_STOP = /\.$/;
383
+ function usageLine(usage, colors = paint(process3.stdout)) {
384
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
385
+ }
386
+ function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
387
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
388
+ `);
389
+ }
390
+ function replacesRows(replaces, colors = paint(process3.stdout)) {
391
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
392
+ }
393
+ function wantsHelpJson(env = process3.env) {
394
+ return env.KIT_HELP === "json";
395
+ }
396
+ function description(usage, { examples = [], replaces } = {}) {
397
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
398
+ `);
399
+ const first = lines[0];
400
+ const colon = first.indexOf(": ");
401
+ const prose = lines[lines.indexOf("") + 1] ?? "";
402
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
403
+ return {
404
+ synopsis: colon === -1 ? first : first.slice(0, colon),
405
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
406
+ ...replaces === undefined ? {} : { replaces },
407
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
408
+ };
409
+ }
410
+ function exampleRows(examples, colors = paint(process3.stdout)) {
411
+ if (examples.length === 0)
412
+ return [];
413
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
414
+ }
415
+ function optionRows(options, colors = paint(process3.stdout)) {
416
+ const rows = Object.entries(options).map(([name, option]) => {
417
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
418
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
419
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
420
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
421
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
422
+ });
423
+ const width = Math.max(0, ...rows.map((row) => row.width));
424
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
425
+ }
426
+
378
427
  // ../kit/src/text.ts
379
428
  var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
380
429
  function stripAnsi(text) {
@@ -397,8 +446,33 @@ function closest(name, names) {
397
446
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
398
447
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
399
448
  }
449
+ // ../kit/src/input.ts
450
+ import process4 from "process";
451
+ var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
452
+ var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
453
+ function duration(value, name, fallback, unit = "s") {
454
+ if (value === undefined)
455
+ return fallback;
456
+ const match = DURATION.exec(value.trim());
457
+ const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
458
+ if (ms < 1)
459
+ badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
460
+ return ms;
461
+ }
462
+ async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
463
+ if (path === "-") {
464
+ if (process4.stdin.isTTY)
465
+ fail(noStdin);
466
+ return Bun.stdin.text();
467
+ }
468
+ const file = Bun.file(path);
469
+ if (!await file.exists())
470
+ fail(`no file ${path}`);
471
+ return file.text();
472
+ }
400
473
 
401
474
  // ../kit/src/args.ts
475
+ var DASHES = /^-+/;
402
476
  function jsonOption(holds) {
403
477
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
404
478
  }
@@ -442,58 +516,11 @@ class Completing {
442
516
  }
443
517
  }
444
518
  var completion = { active: false };
445
- var OPTIONAL = /\[[^\]]+\]/g;
446
- var USAGE_PREFIX = /^usage:\s*/i;
447
- var FULL_STOP = /\.$/;
448
- var DASHES = /^-+/;
449
- function usageLine(usage, colors = paint(process3.stdout)) {
450
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
451
- }
452
- function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
453
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
454
- `);
455
- }
456
- function replacesRows(replaces, colors = paint(process3.stdout)) {
457
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
458
- }
459
- function wantsHelpJson(env = process3.env) {
460
- return env.KIT_HELP === "json";
461
- }
462
- function description(usage, { examples = [], replaces } = {}) {
463
- const lines = usage.replace(USAGE_PREFIX, "").split(`
464
- `);
465
- const first = lines[0];
466
- const colon = first.indexOf(": ");
467
- const prose = lines[lines.indexOf("") + 1] ?? "";
468
- const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
469
- return {
470
- synopsis: colon === -1 ? first : first.slice(0, colon),
471
- summary: colon === -1 ? fallback : first.slice(colon + 2),
472
- ...replaces === undefined ? {} : { replaces },
473
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
474
- };
475
- }
476
- function exampleRows(examples, colors = paint(process3.stdout)) {
477
- if (examples.length === 0)
478
- return [];
479
- return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
480
- }
481
- function optionRows(options, colors = paint(process3.stdout)) {
482
- const rows = Object.entries(options).map(([name, option]) => {
483
- const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
484
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
485
- const placeholder = option.optional === undefined ? named : `[${named}]`;
486
- const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
487
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
488
- });
489
- const width = Math.max(0, ...rows.map((row) => row.width));
490
- return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
491
- }
492
519
  var OUTPUT_OPTIONS = {
493
520
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
494
521
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
495
522
  };
496
- function applyOutput(color, plain, env = process3.env) {
523
+ function applyOutput(color, plain, env = process5.env) {
497
524
  const when = plain === true ? "never" : color ?? "auto";
498
525
  if (when === "auto")
499
526
  return;
@@ -650,31 +677,9 @@ function nearestOption(message, options, allowNegative) {
650
677
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
651
678
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
652
679
  }
653
- var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
654
- var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
655
- function duration(value, name, fallback, unit = "s") {
656
- if (value === undefined)
657
- return fallback;
658
- const match = DURATION.exec(value.trim());
659
- const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
660
- if (ms < 1)
661
- badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
662
- return ms;
663
- }
664
- async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
665
- if (path === "-") {
666
- if (process3.stdin.isTTY)
667
- fail(noStdin);
668
- return Bun.stdin.text();
669
- }
670
- const file = Bun.file(path);
671
- if (!await file.exists())
672
- fail(`no file ${path}`);
673
- return file.text();
674
- }
675
680
  // ../kit/src/process.ts
676
681
  import { constants } from "os";
677
- import process4 from "process";
682
+ import process6 from "process";
678
683
  var KILL_GRACE_MS = 2000;
679
684
  var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
680
685
  function exitCodeOf(code, signal) {
@@ -696,7 +701,7 @@ function holdSignals(cleanup) {
696
701
  },
697
702
  release: () => {
698
703
  for (const signal of SIGNALS)
699
- process4.off(signal, onSignal);
704
+ process6.off(signal, onSignal);
700
705
  }
701
706
  };
702
707
  function onSignal(signal) {
@@ -709,10 +714,10 @@ function holdSignals(cleanup) {
709
714
  return;
710
715
  held.release();
711
716
  cleanup(signal);
712
- process4.kill(process4.pid, signal);
717
+ process6.kill(process6.pid, signal);
713
718
  }
714
719
  for (const signal of SIGNALS)
715
- process4.on(signal, onSignal);
720
+ process6.on(signal, onSignal);
716
721
  return held;
717
722
  }
718
723
  async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
@@ -726,7 +731,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
726
731
  return;
727
732
  try {
728
733
  if (grouped)
729
- process4.kill(-proc.pid, killing);
734
+ process6.kill(-proc.pid, killing);
730
735
  else
731
736
  proc.kill(killing);
732
737
  } catch {}
@@ -800,15 +805,111 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
800
805
  var RESET_STYLE = `${ESC}[0m`;
801
806
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
802
807
  // ../kit/src/cli.ts
803
- import process5 from "process";
808
+ import process9 from "process";
809
+
810
+ // ../kit/src/usage.ts
811
+ import { appendFileSync, mkdirSync } from "fs";
812
+ import { homedir as homedir2 } from "os";
813
+ import { dirname, isAbsolute, join as join2 } from "path";
814
+ import process8 from "process";
815
+
816
+ // ../kit/src/logs.ts
817
+ import { lstatSync, openSync } from "fs";
818
+ import { mkdir, mkdtemp, readdir, rm, stat } from "fs/promises";
819
+ import { homedir, tmpdir } from "os";
820
+ import { join } from "path";
821
+ import process7 from "process";
822
+ var DAY_MS = 24 * 60 * 60 * 1000;
823
+ var CLI_FOLDER = "kaynooo-cli";
824
+ function isPrivateDirectory(path) {
825
+ try {
826
+ const info = lstatSync(path, { throwIfNoEntry: false });
827
+ return info !== undefined && info.isDirectory() && info.uid === (process7.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
828
+ } catch {
829
+ return false;
830
+ }
831
+ }
832
+ async function privateLogDirectory(name, env = process7.env) {
833
+ const runtime = env.XDG_RUNTIME_DIR;
834
+ const base = runtime === undefined || runtime === "" ? join(homedir(), ".cache", CLI_FOLDER) : join(runtime, CLI_FOLDER);
835
+ const path = join(base, name);
836
+ try {
837
+ await mkdir(path, { recursive: true, mode: 448 });
838
+ if (isPrivateDirectory(path))
839
+ return path;
840
+ } catch {}
841
+ return mkdtemp(join(tmpdir(), `${name.replaceAll("/", "-")}-`));
842
+ }
843
+ async function sweepLogs(dir, maxAgeMs = DAY_MS, now = Date.now()) {
844
+ let names;
845
+ try {
846
+ names = await readdir(dir);
847
+ } catch {
848
+ return;
849
+ }
850
+ for (const name of names) {
851
+ const path = join(dir, name);
852
+ try {
853
+ const info = await stat(path);
854
+ if (info.isDirectory())
855
+ await sweepLogs(path, maxAgeMs, now);
856
+ if (now - info.mtimeMs > maxAgeMs)
857
+ await rm(path, { force: true, recursive: info.isDirectory() });
858
+ } catch {
859
+ continue;
860
+ }
861
+ }
862
+ }
863
+
864
+ // ../kit/src/usage.ts
865
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
866
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
867
+ var LONGEST_NAME = 40;
868
+ var usageError;
869
+ function noteUsageError(message) {
870
+ usageError = message;
871
+ }
872
+ function stateHome(env = process8.env) {
873
+ const dir = env.XDG_STATE_HOME;
874
+ return dir !== undefined && isAbsolute(dir) ? dir : join2(homedir2(), ".local", "state");
875
+ }
876
+ function usagePath(env = process8.env) {
877
+ return join2(stateHome(env), CLI_FOLDER, "usage.jsonl");
878
+ }
879
+ function usageRecorded(env = process8.env) {
880
+ const off = env.KAYNOOO_CLI_NO_USAGE;
881
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
882
+ }
883
+ function flagNames(argv) {
884
+ const end = argv.indexOf("--");
885
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
886
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
887
+ }
888
+ function usageEntry(bin, command, argv, code, now = new Date) {
889
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
890
+ usageError = undefined;
891
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
892
+ }
893
+ function recordUsage(entry, env = process8.env) {
894
+ if (!usageRecorded(env))
895
+ return;
896
+ try {
897
+ const path = usagePath(env);
898
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
899
+ appendFileSync(path, `${JSON.stringify(entry)}
900
+ `, { mode: 384 });
901
+ } catch {}
902
+ }
903
+
904
+ // ../kit/src/cli.ts
804
905
  var LEVEL_OPTIONS = {
805
906
  ...OUTPUT_OPTIONS,
806
907
  help: { type: "boolean", short: "h", description: "show this help" }
807
908
  };
808
909
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
809
910
  function printError(prefix, message, hint, cause) {
810
- const colors = paint(process5.stderr);
811
- const styled = takesControlCodes(process5.stderr);
911
+ const colors = paint(process9.stderr);
912
+ const styled = takesControlCodes(process9.stderr);
812
913
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
813
914
  const under = (label, text, tint) => text === undefined ? "" : `
814
915
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -827,6 +928,8 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
827
928
  const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
828
929
  const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
829
930
  const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
931
+ if (error instanceof UsageError)
932
+ noteUsageError(error.message);
830
933
  const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
831
934
  report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
832
935
  return error instanceof Exit ? error.code : 1;
@@ -888,65 +991,22 @@ async function printCandidates(found) {
888
991
  console.log(line);
889
992
  return 0;
890
993
  }
891
- async function runMain({ name, version, run, redact }, argv = process5.argv.slice(2)) {
994
+ async function runMain({ name, version, run, redact, usage }, argv = process9.argv.slice(2)) {
892
995
  if (argv[0] === COMPLETE)
893
996
  return printCandidates(leafCandidates(run, argv.slice(1)));
894
997
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
895
998
  console.log(version);
896
999
  return 0;
897
1000
  }
1001
+ let code;
898
1002
  try {
899
- return await run(argv);
1003
+ code = await run(argv);
900
1004
  } catch (error) {
901
- return reportThrown(name, error, redact, wantsJson(argv));
902
- }
903
- }
904
- // ../kit/src/logs.ts
905
- import { lstatSync, openSync } from "fs";
906
- import { mkdir, mkdtemp, readdir, rm, stat } from "fs/promises";
907
- import { homedir, tmpdir } from "os";
908
- import { join } from "path";
909
- import process6 from "process";
910
- var DAY_MS = 24 * 60 * 60 * 1000;
911
- var CLI_FOLDER = "kaynooo-cli";
912
- function isPrivateDirectory(path) {
913
- try {
914
- const info = lstatSync(path, { throwIfNoEntry: false });
915
- return info !== undefined && info.isDirectory() && info.uid === (process6.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
916
- } catch {
917
- return false;
918
- }
919
- }
920
- async function privateLogDirectory(name, env = process6.env) {
921
- const runtime = env.XDG_RUNTIME_DIR;
922
- const base = runtime === undefined || runtime === "" ? join(homedir(), ".cache", CLI_FOLDER) : join(runtime, CLI_FOLDER);
923
- const path = join(base, name);
924
- try {
925
- await mkdir(path, { recursive: true, mode: 448 });
926
- if (isPrivateDirectory(path))
927
- return path;
928
- } catch {}
929
- return mkdtemp(join(tmpdir(), `${name.replaceAll("/", "-")}-`));
930
- }
931
- async function sweepLogs(dir, maxAgeMs = DAY_MS, now = Date.now()) {
932
- let names;
933
- try {
934
- names = await readdir(dir);
935
- } catch {
936
- return;
937
- }
938
- for (const name of names) {
939
- const path = join(dir, name);
940
- try {
941
- const info = await stat(path);
942
- if (info.isDirectory())
943
- await sweepLogs(path, maxAgeMs, now);
944
- if (now - info.mtimeMs > maxAgeMs)
945
- await rm(path, { force: true, recursive: info.isDirectory() });
946
- } catch {
947
- continue;
948
- }
1005
+ code = reportThrown(name, error, redact, wantsJson(argv));
949
1006
  }
1007
+ if (usage !== false)
1008
+ recordUsage(usageEntry(name, undefined, argv, code));
1009
+ return code;
950
1010
  }
951
1011
  // ../kit/src/secrets.ts
952
1012
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
@@ -955,11 +1015,11 @@ var {Glob } = globalThis.Bun;
955
1015
  var SESSION_FILES = new Glob("*.json");
956
1016
  var ACCOUNT_DIRS = new Glob("*/sessions");
957
1017
  // package.json
958
- var version = "0.9.1";
1018
+ var version = "0.10.0";
959
1019
 
960
1020
  // src/check.ts
961
- import { join as join5 } from "path";
962
- import process10 from "process";
1021
+ import { join as join7 } from "path";
1022
+ import process13 from "process";
963
1023
 
964
1024
  // ../kit/src/shell.ts
965
1025
  var SEPARATORS = new Set([`
@@ -1002,9 +1062,9 @@ function shellQuote(word) {
1002
1062
 
1003
1063
  // src/compose.ts
1004
1064
  import { existsSync } from "fs";
1005
- import { homedir as homedir2 } from "os";
1006
- import { basename, dirname, join as join2, relative, resolve } from "path";
1007
- import process8 from "process";
1065
+ import { homedir as homedir3 } from "os";
1066
+ import { basename, dirname as dirname2, join as join3, relative, resolve } from "path";
1067
+ import process11 from "process";
1008
1068
  var COMPOSE_FILES = ["compose.yaml", "compose.yml", "docker-compose.yaml", "docker-compose.yml"];
1009
1069
  var OVERRIDE_FILES = ["compose.override.yaml", "compose.override.yml", "docker-compose.override.yaml", "docker-compose.override.yml"];
1010
1070
  var PS_TIMEOUT_MS = 20000;
@@ -1033,7 +1093,7 @@ function toolWords(program) {
1033
1093
  }
1034
1094
  async function readFiles(dir, names) {
1035
1095
  for (const name of names) {
1036
- const handle = Bun.file(join2(dir, name));
1096
+ const handle = Bun.file(join3(dir, name));
1037
1097
  if (await handle.exists())
1038
1098
  return { name, text: await handle.text() };
1039
1099
  }
@@ -1048,7 +1108,7 @@ async function variables(composeDir) {
1048
1108
  if (match !== null && !line.trimStart().startsWith("#"))
1049
1109
  env[match[1] ?? ""] = (match[2] ?? "").trim().replace(QUOTED, "$2");
1050
1110
  }
1051
- for (const [key, value] of Object.entries(process8.env)) {
1111
+ for (const [key, value] of Object.entries(process11.env)) {
1052
1112
  if (value !== undefined)
1053
1113
  env[key] = value;
1054
1114
  }
@@ -1068,7 +1128,7 @@ function interpolate(text, env) {
1068
1128
  function bindSource(source, composeDir, env) {
1069
1129
  const path = interpolate(source, env);
1070
1130
  if (path.startsWith("~"))
1071
- return join2(homedir2(), path.slice(1));
1131
+ return join3(homedir3(), path.slice(1));
1072
1132
  if (path.startsWith("/"))
1073
1133
  return resolve(path);
1074
1134
  return path.startsWith(".") ? resolve(composeDir, path) : undefined;
@@ -1115,7 +1175,7 @@ async function composeFiles(composeDir, env) {
1115
1175
  for (const name of listed.split(separator === undefined || separator === "" ? ":" : separator).filter((entry) => entry !== "")) {
1116
1176
  const file = Bun.file(resolve(composeDir, name));
1117
1177
  if (!await file.exists())
1118
- fail(`COMPOSE_FILE names ${join2(composeDir, name)}, which does not exist`, 1, "fix COMPOSE_FILE, or run on the host with --host");
1178
+ fail(`COMPOSE_FILE names ${join3(composeDir, name)}, which does not exist`, 1, "fix COMPOSE_FILE, or run on the host with --host");
1119
1179
  files.push({ name, text: await file.text() });
1120
1180
  }
1121
1181
  return files;
@@ -1137,7 +1197,7 @@ async function readServices(composeDir) {
1137
1197
  try {
1138
1198
  parsed = parseServices(file.text, composeDir, env);
1139
1199
  } catch (error) {
1140
- fail(`cannot read ${join2(composeDir, file.name)}: ${error instanceof Error ? error.message : String(error)}`, 1, "fix the file, or run on the host with --host");
1200
+ fail(`cannot read ${join3(composeDir, file.name)}: ${error instanceof Error ? error.message : String(error)}`, 1, "fix the file, or run on the host with --host");
1141
1201
  }
1142
1202
  for (const [name, extra] of parsed) {
1143
1203
  const known = services.get(name);
@@ -1149,11 +1209,11 @@ async function readServices(composeDir) {
1149
1209
  function climb(dir) {
1150
1210
  const folders = [dir];
1151
1211
  let current = dir;
1152
- while (!existsSync(join2(current, ".git")) && dirname(current) !== current) {
1153
- current = dirname(current);
1212
+ while (!existsSync(join3(current, ".git")) && dirname2(current) !== current) {
1213
+ current = dirname2(current);
1154
1214
  folders.push(current);
1155
1215
  }
1156
- return existsSync(join2(current, ".git")) ? folders : [dir];
1216
+ return existsSync(join3(current, ".git")) ? folders : [dir];
1157
1217
  }
1158
1218
  function containerPath(service, dir) {
1159
1219
  const holding = service.mounts.filter((mount) => {
@@ -1164,7 +1224,7 @@ function containerPath(service, dir) {
1164
1224
  if (deepest === undefined)
1165
1225
  return;
1166
1226
  const inside = relative(deepest.source, dir);
1167
- return inside === "" ? deepest.target : join2(deepest.target, inside);
1227
+ return inside === "" ? deepest.target : join3(deepest.target, inside);
1168
1228
  }
1169
1229
  var noticed = new Set;
1170
1230
  async function place(dir, program, { service, host } = {}) {
@@ -1184,7 +1244,7 @@ async function place(dir, program, { service, host } = {}) {
1184
1244
  fail(`--in ${service}: no compose project mounts ${dir}`);
1185
1245
  return;
1186
1246
  }
1187
- if (Bun.which("docker", { PATH: process8.env.PATH ?? "" }) === null) {
1247
+ if (Bun.which("docker", { PATH: process11.env.PATH ?? "" }) === null) {
1188
1248
  if (service !== undefined)
1189
1249
  fail(`--in ${service}: docker not found`);
1190
1250
  if (!noticed.has(found.composeDir)) {
@@ -1236,7 +1296,7 @@ class Stack {
1236
1296
  }
1237
1297
  static async running(composeDir) {
1238
1298
  try {
1239
- const ran = await runCommand(["docker", "compose", "ps", "--services", "--status", "running"], { cwd: composeDir, env: process8.env, timeoutMs: PS_TIMEOUT_MS });
1299
+ const ran = await runCommand(["docker", "compose", "ps", "--services", "--status", "running"], { cwd: composeDir, env: process11.env, timeoutMs: PS_TIMEOUT_MS });
1240
1300
  if (ran.code !== 0)
1241
1301
  return `docker compose ps failed in ${composeDir}: ${ran.text.trim().split(`
1242
1302
  `).at(-1) ?? `exit ${ran.code}`}`;
@@ -1267,12 +1327,211 @@ function placeSettings(values) {
1267
1327
  return { service: values.in, host: values.host };
1268
1328
  }
1269
1329
 
1270
- // src/run.ts
1271
- import { mkdir as mkdir2, writeFile } from "fs/promises";
1272
- import { basename as basename2, join as join3 } from "path";
1273
- import process9 from "process";
1330
+ // src/narrow.ts
1331
+ import { existsSync as existsSync2 } from "fs";
1332
+ import { basename as basename2, dirname as dirname3, extname, join as join5 } from "path";
1333
+ var {$ } = globalThis.Bun;
1274
1334
 
1275
- // src/e2e.ts
1335
+ // src/steps.ts
1336
+ import { readdir as readdir2 } from "fs/promises";
1337
+ import { join as join4 } from "path";
1338
+ var STEP_NAMES = ["check", "typecheck", "lint", "test"];
1339
+ var TARGET = /^@?([\w-]+)(?:[ \t][^:=\n]*)?:(?!=)/gm;
1340
+ var JUSTFILES = ["justfile", "Justfile", ".justfile"];
1341
+ var MAKEFILES = ["GNUmakefile", "makefile", "Makefile"];
1342
+ var CS_FIXER_CONFIGS = [".php-cs-fixer.php", ".php-cs-fixer.dist.php"];
1343
+ var JUST_TIMEOUT_MS = 1e4;
1344
+ var PHPSTAN_CONFIGS = ["phpstan.neon", "phpstan.neon.dist", "phpstan.dist.neon"];
1345
+ var PHPUNIT_CONFIGS = ["phpunit.xml", "phpunit.xml.dist", "phpunit.dist.xml"];
1346
+ var SKIPPED = new Set(["node_modules", "vendor", "dist", "build", "var", "tmp", "coverage"]);
1347
+ async function readFirst(dir, files) {
1348
+ for (const file of files) {
1349
+ const handle = Bun.file(join4(dir, file));
1350
+ if (await handle.exists())
1351
+ return { file, text: await handle.text() };
1352
+ }
1353
+ return;
1354
+ }
1355
+ async function read(dir, ...files) {
1356
+ for (const file of files) {
1357
+ const handle = Bun.file(join4(dir, file));
1358
+ if (await handle.exists())
1359
+ return handle.text();
1360
+ }
1361
+ return;
1362
+ }
1363
+ function scripts(file, text) {
1364
+ try {
1365
+ const parsed = JSON.parse(text);
1366
+ return parsed.scripts ?? {};
1367
+ } catch {
1368
+ throw new Error(`${file} is not valid JSON`);
1369
+ }
1370
+ }
1371
+ function targets(text) {
1372
+ return [...text.matchAll(TARGET)].map((match) => match[1] ?? "");
1373
+ }
1374
+ async function recipes(dir, file, text) {
1375
+ if (Bun.which("just") === null)
1376
+ return targets(text);
1377
+ try {
1378
+ const ran = await runCommand(["just", "--justfile", file, "--dump", "--dump-format", "json"], { cwd: dir, timeoutMs: JUST_TIMEOUT_MS });
1379
+ const dump = JSON.parse(ran.text);
1380
+ if (ran.code !== 0)
1381
+ return targets(text);
1382
+ return Object.entries(dump.recipes ?? {}).filter(([, recipe]) => recipe.private !== true && (recipe.parameters ?? []).every((parameter) => parameter.default !== null || parameter.kind === "star")).map(([name]) => name);
1383
+ } catch {
1384
+ return targets(text);
1385
+ }
1386
+ }
1387
+ function callsSelf(value, bin) {
1388
+ return typeof value === "string" && (value === bin || value.startsWith(`${bin} `) || value.startsWith(`${bin} `));
1389
+ }
1390
+ async function candidates(dir, bin) {
1391
+ const steps = [];
1392
+ const packageJson = await read(dir, "package.json");
1393
+ const composerJson = await read(dir, "composer.json");
1394
+ const justfile = await readFirst(dir, JUSTFILES);
1395
+ const makefile = await read(dir, ...MAKEFILES);
1396
+ if (packageJson !== undefined) {
1397
+ for (const [name, value] of Object.entries(scripts("package.json", packageJson))) {
1398
+ if (!callsSelf(value, bin))
1399
+ steps.push({ name, command: `bun run ${name}`, source: "package.json" });
1400
+ }
1401
+ }
1402
+ if (composerJson !== undefined) {
1403
+ for (const name of Object.keys(scripts("composer.json", composerJson)))
1404
+ steps.push({ name, command: `composer run ${name}`, source: "composer.json" });
1405
+ }
1406
+ if (justfile !== undefined) {
1407
+ for (const name of await recipes(dir, justfile.file, justfile.text))
1408
+ steps.push({ name, command: `just ${name}`, source: "Justfile" });
1409
+ }
1410
+ for (const name of targets(makefile ?? ""))
1411
+ steps.push({ name, command: `make ${name}`, source: "Makefile" });
1412
+ steps.push(...await phpSteps(dir));
1413
+ return steps;
1414
+ }
1415
+ async function firstFile(dir, names) {
1416
+ for (const name of names) {
1417
+ if (await Bun.file(join4(dir, name)).exists())
1418
+ return name;
1419
+ }
1420
+ return;
1421
+ }
1422
+ async function phpSteps(dir) {
1423
+ const steps = [];
1424
+ const phpstan = await firstFile(dir, PHPSTAN_CONFIGS);
1425
+ const csFixer = await firstFile(dir, CS_FIXER_CONFIGS);
1426
+ const phpunit = await firstFile(dir, PHPUNIT_CONFIGS);
1427
+ if (phpstan !== undefined)
1428
+ steps.push({ name: "typecheck", command: "vendor/bin/phpstan analyse --no-progress --memory-limit=1G", source: phpstan });
1429
+ if (csFixer !== undefined)
1430
+ steps.push({ name: "lint", command: "vendor/bin/php-cs-fixer fix --dry-run -v", source: csFixer });
1431
+ if (phpunit !== undefined)
1432
+ steps.push({ name: "test", command: "vendor/bin/phpunit", source: phpunit });
1433
+ return steps;
1434
+ }
1435
+ async function discoverProjects(dir) {
1436
+ const own = await discover(dir);
1437
+ if (own.length > 0)
1438
+ return [{ dir, steps: own }];
1439
+ const projects = [];
1440
+ const entries = await readdir2(dir, { withFileTypes: true });
1441
+ for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) {
1442
+ if (!entry.isDirectory() || entry.name.startsWith(".") || SKIPPED.has(entry.name))
1443
+ continue;
1444
+ const steps = await discover(join4(dir, entry.name));
1445
+ if (steps.length > 0)
1446
+ projects.push({ name: entry.name, dir: join4(dir, entry.name), steps });
1447
+ }
1448
+ return projects;
1449
+ }
1450
+ async function discover(dir) {
1451
+ const found = await candidates(dir, "check");
1452
+ return STEP_NAMES.flatMap((name) => {
1453
+ const step = found.find((candidate) => candidate.name === name);
1454
+ return step === undefined ? [] : [step];
1455
+ });
1456
+ }
1457
+
1458
+ // src/narrow.ts
1459
+ var LINTERS = /^(?:keslint|eslint|oxlint)\b/;
1460
+ var LINTABLE = new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts", ".vue", ".svelte"]);
1461
+ var TEST_RUNNER = /^(?:bun test|\$npm_execpath test)\b/;
1462
+ var TEST_FILE = /\.(?:test|spec)\.[jt]sx?$/;
1463
+ var WHITESPACE = /\s+/;
1464
+ async function changedPaths(dir) {
1465
+ const tracked = await $`git diff --name-only --relative -z HEAD`.cwd(dir).quiet().nothrow();
1466
+ const untracked = await $`git ls-files -z --others --exclude-standard`.cwd(dir).quiet().nothrow();
1467
+ if (tracked.exitCode !== 0 || untracked.exitCode !== 0)
1468
+ return;
1469
+ return [...new Set([...tracked.stdout.toString().split("\x00"), ...untracked.stdout.toString().split("\x00")])].filter((path) => path !== "" && existsSync2(join5(dir, path)));
1470
+ }
1471
+ function siblingTests(path, exists) {
1472
+ const extension = extname(path);
1473
+ const name = basename2(path, extension);
1474
+ const dir = dirname3(path);
1475
+ const folders = [dir, join5(dir, "tests"), join5(dir, "..", "tests"), join5(dir, "__tests__")];
1476
+ const found = new Set;
1477
+ for (const folder of folders) {
1478
+ for (const kind of ["test", "spec"]) {
1479
+ for (const candidate of [`${name}.${kind}${extension}`, `${name}.${kind}.ts`].map((file) => join5(folder, file))) {
1480
+ if (exists(candidate))
1481
+ found.add(candidate);
1482
+ }
1483
+ }
1484
+ }
1485
+ return [...found];
1486
+ }
1487
+ function isBare(script, tool) {
1488
+ return tool.test(script.trim()) && script.trim().replace(tool, "").split(WHITESPACE).every((word) => word.startsWith("-") || word === "");
1489
+ }
1490
+ async function narrow2(step, dir, changed) {
1491
+ const script = step.source === "package.json" ? (await scriptText(dir, step.name))?.trim() : undefined;
1492
+ const full = (why) => ({ command: step.command, note: `in full, ${why}` });
1493
+ if (script !== undefined && step.name === "lint" && isBare(script, LINTERS)) {
1494
+ const files = changed.filter((path) => LINTABLE.has(extname(path)));
1495
+ return files.length === 0 ? { command: "true", note: "nothing changed to lint" } : { command: `${step.command} -- ${files.map(quote).join(" ")}`, note: `${files.length} changed file${files.length === 1 ? "" : "s"}` };
1496
+ }
1497
+ if (script !== undefined && step.name === "test" && isBare(script, TEST_RUNNER)) {
1498
+ const tests = new Set;
1499
+ for (const path of changed) {
1500
+ if (TEST_FILE.test(path)) {
1501
+ tests.add(path);
1502
+ } else {
1503
+ for (const test of siblingTests(path, (candidate) => existsSync2(join5(dir, candidate)))) {
1504
+ tests.add(test);
1505
+ }
1506
+ }
1507
+ }
1508
+ if (tests.size === 0)
1509
+ return full("no test sits next to the changed files");
1510
+ return { command: `${step.command} -- ${[...tests].map((test) => quote(`./${test}`)).join(" ")}`, note: `${tests.size} test file${tests.size === 1 ? "" : "s"}` };
1511
+ }
1512
+ return full(`${step.name} cannot be narrowed`);
1513
+ }
1514
+ function quote(path) {
1515
+ return `'${path.replaceAll("'", "'\\''")}'`;
1516
+ }
1517
+ async function scriptText(dir, name) {
1518
+ const text = await read(dir, "package.json");
1519
+ if (text === undefined)
1520
+ return;
1521
+ try {
1522
+ const value = JSON.parse(text).scripts?.[name];
1523
+ return typeof value === "string" ? value : undefined;
1524
+ } catch {
1525
+ return;
1526
+ }
1527
+ }
1528
+
1529
+ // src/run.ts
1530
+ import { mkdir as mkdir2, writeFile } from "fs/promises";
1531
+ import { basename as basename3, join as join6 } from "path";
1532
+ import process12 from "process";
1533
+
1534
+ // src/e2e.ts
1276
1535
  var E2E_NOISE = [
1277
1536
  /^(?:Running \d+ tests? using|\(node:\d+\) Warning|\(Use `node|\[\d+\/\d+\] |\s+[-\u2713\u2718\u00B0\u00D7]\s+\d+|To open last HTML|Serving HTML report|\s*npx playwright show-report)/,
1278
1537
  /^[\u00B7F\u00D7\u00B0T\u00B1]+$/,
@@ -1902,14 +2161,14 @@ var LOG_MAX_AGE_MS = 3 * 24 * 60 * 60 * 1000;
1902
2161
  async function logDirectory(cwd) {
1903
2162
  const root = await privateLogDirectory("check");
1904
2163
  await sweepLogs(root, LOG_MAX_AGE_MS);
1905
- const path = join3(root, `${basename2(cwd)}-${Bun.hash(cwd).toString(36)}-${Date.now().toString(36)}-${process9.pid}`);
2164
+ const path = join6(root, `${basename3(cwd)}-${Bun.hash(cwd).toString(36)}-${Date.now().toString(36)}-${process12.pid}`);
1906
2165
  await mkdir2(path, { mode: 448 });
1907
2166
  return path;
1908
2167
  }
1909
2168
  async function saveLog(output) {
1910
2169
  const root = await privateLogDirectory("errs");
1911
2170
  await sweepLogs(root);
1912
- const path = join3(root, `${new Date().toISOString().replaceAll(/[:.]/g, "-")}-${process9.pid}-${crypto.randomUUID().slice(0, 8)}.log`);
2171
+ const path = join6(root, `${new Date().toISOString().replaceAll(/[:.]/g, "-")}-${process12.pid}-${crypto.randomUUID().slice(0, 8)}.log`);
1913
2172
  await writeFile(path, output, { mode: 384, flag: "wx" });
1914
2173
  return path;
1915
2174
  }
@@ -1917,7 +2176,7 @@ async function runStep(command, cwd, logFile, { env = {}, timeoutMs, held } = {}
1917
2176
  const started = Date.now();
1918
2177
  const { code, text, timedOut } = await runCommand(["sh", "-c", `${command} 2>&1`], {
1919
2178
  cwd,
1920
- env: { ...process9.env, NO_COLOR: "1", FORCE_COLOR: "0", ...env },
2179
+ env: { ...process12.env, NO_COLOR: "1", FORCE_COLOR: "0", ...env },
1921
2180
  ...timeoutMs === undefined ? {} : { timeoutMs },
1922
2181
  ...held === undefined ? {} : { onStart: (child) => held.forward(child) }
1923
2182
  });
@@ -1946,136 +2205,14 @@ function printOutcome(name, width, command, logFile, outcome) {
1946
2205
  `));
1947
2206
  }
1948
2207
 
1949
- // src/steps.ts
1950
- import { readdir as readdir2 } from "fs/promises";
1951
- import { join as join4 } from "path";
1952
- var STEP_NAMES = ["check", "typecheck", "lint", "test"];
1953
- var TARGET = /^@?([\w-]+)(?:[ \t][^:=\n]*)?:(?!=)/gm;
1954
- var JUSTFILES = ["justfile", "Justfile", ".justfile"];
1955
- var MAKEFILES = ["GNUmakefile", "makefile", "Makefile"];
1956
- var CS_FIXER_CONFIGS = [".php-cs-fixer.php", ".php-cs-fixer.dist.php"];
1957
- var JUST_TIMEOUT_MS = 1e4;
1958
- var PHPSTAN_CONFIGS = ["phpstan.neon", "phpstan.neon.dist", "phpstan.dist.neon"];
1959
- var PHPUNIT_CONFIGS = ["phpunit.xml", "phpunit.xml.dist", "phpunit.dist.xml"];
1960
- var SKIPPED = new Set(["node_modules", "vendor", "dist", "build", "var", "tmp", "coverage"]);
1961
- async function readFirst(dir, files) {
1962
- for (const file of files) {
1963
- const handle = Bun.file(join4(dir, file));
1964
- if (await handle.exists())
1965
- return { file, text: await handle.text() };
1966
- }
1967
- return;
1968
- }
1969
- async function read(dir, ...files) {
1970
- for (const file of files) {
1971
- const handle = Bun.file(join4(dir, file));
1972
- if (await handle.exists())
1973
- return handle.text();
1974
- }
1975
- return;
1976
- }
1977
- function scripts(file, text) {
1978
- try {
1979
- const parsed = JSON.parse(text);
1980
- return parsed.scripts ?? {};
1981
- } catch {
1982
- throw new Error(`${file} is not valid JSON`);
1983
- }
1984
- }
1985
- function targets(text) {
1986
- return [...text.matchAll(TARGET)].map((match) => match[1] ?? "");
1987
- }
1988
- async function recipes(dir, file, text) {
1989
- if (Bun.which("just") === null)
1990
- return targets(text);
1991
- try {
1992
- const ran = await runCommand(["just", "--justfile", file, "--dump", "--dump-format", "json"], { cwd: dir, timeoutMs: JUST_TIMEOUT_MS });
1993
- const dump = JSON.parse(ran.text);
1994
- if (ran.code !== 0)
1995
- return targets(text);
1996
- return Object.entries(dump.recipes ?? {}).filter(([, recipe]) => recipe.private !== true && (recipe.parameters ?? []).every((parameter) => parameter.default !== null || parameter.kind === "star")).map(([name]) => name);
1997
- } catch {
1998
- return targets(text);
1999
- }
2000
- }
2001
- function callsSelf(value, bin) {
2002
- return typeof value === "string" && (value === bin || value.startsWith(`${bin} `) || value.startsWith(`${bin} `));
2003
- }
2004
- async function candidates(dir, bin) {
2005
- const steps = [];
2006
- const packageJson = await read(dir, "package.json");
2007
- const composerJson = await read(dir, "composer.json");
2008
- const justfile = await readFirst(dir, JUSTFILES);
2009
- const makefile = await read(dir, ...MAKEFILES);
2010
- if (packageJson !== undefined) {
2011
- for (const [name, value] of Object.entries(scripts("package.json", packageJson))) {
2012
- if (!callsSelf(value, bin))
2013
- steps.push({ name, command: `bun run ${name}`, source: "package.json" });
2014
- }
2015
- }
2016
- if (composerJson !== undefined) {
2017
- for (const name of Object.keys(scripts("composer.json", composerJson)))
2018
- steps.push({ name, command: `composer run ${name}`, source: "composer.json" });
2019
- }
2020
- if (justfile !== undefined) {
2021
- for (const name of await recipes(dir, justfile.file, justfile.text))
2022
- steps.push({ name, command: `just ${name}`, source: "Justfile" });
2023
- }
2024
- for (const name of targets(makefile ?? ""))
2025
- steps.push({ name, command: `make ${name}`, source: "Makefile" });
2026
- steps.push(...await phpSteps(dir));
2027
- return steps;
2028
- }
2029
- async function firstFile(dir, names) {
2030
- for (const name of names) {
2031
- if (await Bun.file(join4(dir, name)).exists())
2032
- return name;
2033
- }
2034
- return;
2035
- }
2036
- async function phpSteps(dir) {
2037
- const steps = [];
2038
- const phpstan = await firstFile(dir, PHPSTAN_CONFIGS);
2039
- const csFixer = await firstFile(dir, CS_FIXER_CONFIGS);
2040
- const phpunit = await firstFile(dir, PHPUNIT_CONFIGS);
2041
- if (phpstan !== undefined)
2042
- steps.push({ name: "typecheck", command: "vendor/bin/phpstan analyse --no-progress --memory-limit=1G", source: phpstan });
2043
- if (csFixer !== undefined)
2044
- steps.push({ name: "lint", command: "vendor/bin/php-cs-fixer fix --dry-run -v", source: csFixer });
2045
- if (phpunit !== undefined)
2046
- steps.push({ name: "test", command: "vendor/bin/phpunit", source: phpunit });
2047
- return steps;
2048
- }
2049
- async function discoverProjects(dir) {
2050
- const own = await discover(dir);
2051
- if (own.length > 0)
2052
- return [{ dir, steps: own }];
2053
- const projects = [];
2054
- const entries = await readdir2(dir, { withFileTypes: true });
2055
- for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) {
2056
- if (!entry.isDirectory() || entry.name.startsWith(".") || SKIPPED.has(entry.name))
2057
- continue;
2058
- const steps = await discover(join4(dir, entry.name));
2059
- if (steps.length > 0)
2060
- projects.push({ name: entry.name, dir: join4(dir, entry.name), steps });
2061
- }
2062
- return projects;
2063
- }
2064
- async function discover(dir) {
2065
- const found = await candidates(dir, "check");
2066
- return STEP_NAMES.flatMap((name) => {
2067
- const step = found.find((candidate) => candidate.name === name);
2068
- return step === undefined ? [] : [step];
2069
- });
2070
- }
2071
-
2072
2208
  // src/check.ts
2073
- var usage = `check [--only <steps>] [--timeout <duration>] [--slot] [--in <service> | --host] [--list]
2209
+ var usage2 = `check [--only <steps>] [--changed] [--timeout <duration>] [--slot] [--in <service> | --host] [--list]
2074
2210
 
2075
2211
  Runs the repo's check, typecheck, lint and test steps, from package.json scripts (through bun run), composer.json, a Justfile or a Makefile, and for PHP from phpstan.neon (typecheck), .php-cs-fixer.dist.php (lint, dry-run) and phpunit.xml.dist (test) when composer.json has no such script.
2076
2212
  A folder without steps but with subfolders that have some (api/ and client/) runs each one's, each line naming its subfolder.
2077
2213
  A step runs inside the docker compose service that bind-mounts its folder (found in compose.yml, compose.yaml or docker-compose.yml, up to the repository root), at the matching path; a service that is down is never started, the step fails naming it. --in picks the service, --host forces the host.
2078
2214
  A passing step is one line, a failing one shows only what failed, and each step's full output is saved to the file whose path ends its line.
2215
+ With --changed, lint and test run on the files changed against HEAD (staged, unstaged and untracked) when their script is a bare linter (keslint, eslint, oxlint) or a bare \`bun test\`: lint on the changed source files, test on the changed test files and the tests next to the changed sources. Every other step, and a test step finding no test for the diff, runs in full and the line says so.
2079
2216
  A step still running after --timeout is ended with everything it started, but not what it started inside a container.
2080
2217
  Exits 0 when every step passed, 1 when one failed, 2 on bad usage, when no step is found or when a step timed out.
2081
2218
  --json prints [{name, command, in?, ok, ms, log, failed?}] once every step ran, --list --json [{name, command, source, in?}], in the compose service the step ran in.`;
@@ -2083,6 +2220,7 @@ var options = {
2083
2220
  list: { type: "boolean", short: "l", description: "print the steps found, the commands that run them and where (host or service), without running them" },
2084
2221
  only: { type: "string", short: "o", description: `comma separated steps to run, among ${STEP_NAMES.join(", ")}` },
2085
2222
  timeout: { type: "string", short: "t", description: "longest a step may run before it is ended (30s, 5m, 1h), none by default" },
2223
+ changed: { type: "boolean", short: "c", description: "narrow lint and test to the files changed against HEAD (a bare linter script, a bare bun test script), every other step runs in full and says so" },
2086
2224
  slot: { type: "boolean", description: "run each step through slot, queued behind the machine-wide slots of the other sessions (needs the slot bin)" },
2087
2225
  ...placeOptions,
2088
2226
  json: jsonOption()
@@ -2108,17 +2246,33 @@ async function plan(steps, settings) {
2108
2246
  planned.push({ ...step, dir: project.dir, label: project.name === undefined ? step.name : `${project.name}/${step.name}`, placement: await place(project.dir, programOf(step.command), settings) });
2109
2247
  return planned;
2110
2248
  }
2249
+ async function narrowed(steps) {
2250
+ const cache = new Map;
2251
+ const result = [];
2252
+ for (const step of steps) {
2253
+ if (!cache.has(step.dir)) {
2254
+ const paths = await changedPaths(step.dir);
2255
+ if (paths === undefined)
2256
+ fail("--changed needs a git repository");
2257
+ cache.set(step.dir, paths);
2258
+ }
2259
+ const { command, note } = await narrow2(step, step.dir, cache.get(step.dir) ?? []);
2260
+ result.push({ ...step, command, note });
2261
+ }
2262
+ return result;
2263
+ }
2111
2264
  function launch(step) {
2112
2265
  return step.placement === undefined ? step.command : shellIn(step.placement, step.command);
2113
2266
  }
2114
- async function check(args, cwd = process10.cwd()) {
2115
- const parsed = parse(args, usage, options, { replaces: "chaining docker compose exec <service> bun run check | tail, lint and test by hand, or bun run check && bun run lint && bun run test read through tail", examples: ["check", ["check --only lint,test", "two of the steps"], ["check --in app", "every step inside the app service"]] });
2267
+ async function check(args, cwd = process13.cwd()) {
2268
+ const parsed = parse(args, usage2, options, { replaces: "chaining docker compose exec <service> bun run check | tail, lint and test by hand, or bun run check && bun run lint && bun run test read through tail", examples: ["check", ["check --only lint,test", "two of the steps"], ["check --in app", "every step inside the app service"]] });
2116
2269
  const settings = placeSettings(parsed.values);
2117
2270
  const projects = await discoverProjects(cwd);
2118
2271
  const found = projects.flatMap((project) => project.steps.map((step) => ({ ...step, project })));
2119
2272
  if (found.length === 0)
2120
2273
  fail(`no ${STEP_NAMES.join(", ")} step in package.json, composer.json, a Justfile, a Makefile or a PHP tool's config, nor in a subfolder`);
2121
- const steps = await plan(pick(found, parsed.values.only), settings);
2274
+ const planned = await plan(pick(found, parsed.values.only), settings);
2275
+ const steps = parsed.values.changed === true ? await narrowed(planned) : planned;
2122
2276
  const json = parsed.values.json === true;
2123
2277
  if (parsed.values.list === true) {
2124
2278
  if (json)
@@ -2127,7 +2281,7 @@ async function check(args, cwd = process10.cwd()) {
2127
2281
  console.log(table(steps.map((step) => [step.label, step.command, step.source, step.placement?.service ?? "host"])));
2128
2282
  return 0;
2129
2283
  }
2130
- if (parsed.values.slot === true && Bun.which("slot", { PATH: process10.env.PATH ?? "" }) === null)
2284
+ if (parsed.values.slot === true && Bun.which("slot", { PATH: process13.env.PATH ?? "" }) === null)
2131
2285
  fail("--slot needs the slot bin: bun install -g @kaynooo/cli-wait");
2132
2286
  const timeoutMs = parsed.values.timeout === undefined ? undefined : duration(parsed.values.timeout, "timeout", 0);
2133
2287
  const directory = await logDirectory(cwd);
@@ -2137,12 +2291,12 @@ async function check(args, cwd = process10.cwd()) {
2137
2291
  const outcomes = [];
2138
2292
  try {
2139
2293
  for (const step of steps) {
2140
- const logFile = join5(directory, `${step.label.replaceAll("/", "-")}.log`);
2294
+ const logFile = join7(directory, `${step.label.replaceAll("/", "-")}.log`);
2141
2295
  const down = step.placement === undefined ? undefined : await stack.problem(step.placement);
2142
2296
  const command = parsed.values.slot === true ? slotted(launch(step)) : launch(step);
2143
2297
  const outcome = down === undefined ? await runStep(command, step.dir, logFile, { ...timeoutMs === undefined ? {} : { timeoutMs }, held }) : await refusedStep(down, logFile);
2144
2298
  if (!json)
2145
- printOutcome(step.label, width, step.placement === undefined ? step.command : `${step.command} (in ${step.placement.service})`, logFile, outcome);
2299
+ printOutcome(step.label, width, `${step.command}${step.note === undefined ? "" : ` (${step.note})`}${step.placement === undefined ? "" : ` (in ${step.placement.service})`}`, logFile, outcome);
2146
2300
  outcomes.push(outcomeJson(step.label, step.command, logFile, outcome, step.placement?.service));
2147
2301
  if (held.signal !== undefined)
2148
2302
  break;
@@ -2160,4 +2314,4 @@ async function check(args, cwd = process10.cwd()) {
2160
2314
  }
2161
2315
 
2162
2316
  // src/cli.ts
2163
- process11.exitCode = await runMain({ name: "check", version, run: async (args) => check(args) });
2317
+ process14.exitCode = await runMain({ name: "check", version, run: async (args) => check(args) });