@kaynooo/cli-git 0.13.1 → 0.14.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/gst.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/gst.ts
5
- import process16 from "process";
5
+ import process18 from "process";
6
6
  // ../kit/src/args.ts
7
7
  import process9 from "process";
8
8
  import { parseArgs } from "util";
@@ -10,6 +10,24 @@ import { parseArgs } from "util";
10
10
  // ../kit/src/format.ts
11
11
  import process7 from "process";
12
12
 
13
+ // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rxztfxgv.js
14
+ var N = new Map;
15
+ var Nt = /\s+\S*$/;
16
+ var Y = /\s/;
17
+ function ko(t, e, r = "...") {
18
+ let { suffix: n = "...", includeSuffix: s = false, wordBoundary: o = false } = typeof r === "string" ? { suffix: r } : r;
19
+ if (t.length <= e)
20
+ return t;
21
+ let l = Math.max(0, e), c = t.substring(0, Math.max(0, s ? l - n.length : l));
22
+ if (o && !Y.test(t[c.length] ?? " "))
23
+ c = c.replace(Nt, "") || c;
24
+ if (o)
25
+ c = c.trimEnd();
26
+ return s ? (c + n).slice(0, l) : c + n;
27
+ }
28
+ var be = new Map(["\u20AC", "", "\u201A", "\u0192", "\u201E", "\u2026", "\u2020", "\u2021", "\u02C6", "\u2030", "\u0160", "\u2039", "\u0152", "", "\u017D", "", "", "\u2018", "\u2019", "\u201C", "\u201D", "\u2022", "\u2013", "\u2014", "\u02DC", "\u2122", "\u0161", "\u203A", "\u0153", "", "\u017E", "\u0178"].map((t, e) => [t, 128 + e]).filter(([t]) => t));
29
+ var z = new Map;
30
+
13
31
  // ../kit/src/mode.ts
14
32
  import process2 from "process";
15
33
  var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
@@ -35,10 +53,10 @@ function isInteractive(streams = process2) {
35
53
  import process6 from "process";
36
54
 
37
55
  // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
38
- var G = /^[a-f0-9]+$/i;
56
+ var G2 = /^[a-f0-9]+$/i;
39
57
  function b(r) {
40
58
  let e = r.startsWith("#") ? r.slice(1) : r;
41
- if (!G.test(e))
59
+ if (!G2.test(e))
42
60
  return [0, 0, 0];
43
61
  if (e.length === 3 || e.length === 4)
44
62
  return [Number.parseInt(e[0] + e[0], 16), Number.parseInt(e[1] + e[1], 16), Number.parseInt(e[2] + e[2], 16)];
@@ -46,7 +64,7 @@ function b(r) {
46
64
  throw Error(`Invalid hex color length: ${e.length}`);
47
65
  return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
48
66
  }
49
- var B = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
67
+ var B2 = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
50
68
  let [l, n, c] = b(r);
51
69
  return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
52
70
  }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
@@ -64,7 +82,7 @@ function f(r, e = []) {
64
82
  l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
65
83
  let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
66
84
  return new Proxy(c, { get(t, i) {
67
- let a = B[i];
85
+ let a = B2[i];
68
86
  if (Array.isArray(a)) {
69
87
  let s = g.get(i);
70
88
  if (s === undefined)
@@ -304,12 +322,22 @@ function activeTheme() {
304
322
  }
305
323
 
306
324
  // ../kit/src/style.ts
325
+ var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
307
326
  function takesControlCodes(stream, env = process6.env) {
308
327
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
309
328
  }
310
329
  function paint(stream, env = process6.env) {
311
330
  return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
312
331
  }
332
+ function marked(mark, text, stream, detail, env = process6.env) {
333
+ const colors = paint(stream, env);
334
+ let head = MARK_WORDS[mark];
335
+ if (takesControlCodes(stream, env)) {
336
+ const { theme } = activeTheme();
337
+ head = tinted(colors.bold, theme.colors[mark], env)(theme.glyphs[mark]);
338
+ }
339
+ return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
340
+ }
313
341
  function role(name, stream, env = process6.env) {
314
342
  const colors = paint(stream, env);
315
343
  return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
@@ -349,7 +377,53 @@ function formatAge(date, now = Date.now()) {
349
377
  const seconds = (now - at) / 1000;
350
378
  return seconds < 60 ? "just now" : `${upTo(formatSeconds(seconds), " ")} ago`;
351
379
  }
380
+ function truncate(text, width) {
381
+ return ko(text, width, { suffix: "\u2026", includeSuffix: true });
382
+ }
383
+ var LINE_BREAKS = /\s*\n\s*/g;
352
384
  var ESCAPE = String.fromCharCode(27);
385
+ function textWidth(text) {
386
+ return Bun.stringWidth(text);
387
+ }
388
+ function table(rows, { cellWidth, header = false, align = [], fit, stream = process7.stdout, env = process7.env } = {}) {
389
+ const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
390
+ if (outputMode(stream, env) === "agent")
391
+ return cells.map((row) => row.map((cell) => Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g, " ")).join("\t")).join(`
392
+ `);
393
+ const widths = [];
394
+ for (const row of cells) {
395
+ for (const [index, cell] of row.entries())
396
+ widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
397
+ }
398
+ const shown = fit === undefined ? cells : narrow(cells, widths, fit);
399
+ const colors = paint(stream);
400
+ const lines = shown.map((row) => row.map((cell, index) => {
401
+ const width = widths[index] ?? 0;
402
+ const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
403
+ if (align[index] === "right")
404
+ return `${gap}${cell}`;
405
+ return index === row.length - 1 ? cell : `${cell}${gap}`;
406
+ }).join(" ").trimEnd());
407
+ const rule = header && takesControlCodes(stream) && lines.length > 1 ? [colors.dim("\u2500".repeat(Math.max(...lines.map(textWidth))))] : [];
408
+ return lines.flatMap((line, index) => header && index === 0 ? [colors.bold(line), ...rule] : [line]).join(`
409
+ `);
410
+ }
411
+ function narrow(rows, widths, limit) {
412
+ const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
413
+ const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
414
+ const floor = 8;
415
+ while (used() > limit) {
416
+ let widest = -1;
417
+ for (const [index, width] of widths.entries()) {
418
+ if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
419
+ widest = index;
420
+ }
421
+ if (widest === -1)
422
+ break;
423
+ widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
424
+ }
425
+ return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
426
+ }
353
427
  function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
354
428
  return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
355
429
  }
@@ -672,9 +746,33 @@ function nearestOption(message, options, allowNegative) {
672
746
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
673
747
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
674
748
  }
749
+ // ../kit/src/argv.ts
750
+ import { readFileSync as readFileSync2, realpathSync } from "fs";
751
+ import { resolve as resolve3 } from "path";
752
+ import process10 from "process";
753
+ function commandLine() {
754
+ try {
755
+ return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
756
+ } catch {
757
+ return;
758
+ }
759
+ }
760
+ function realPath(word) {
761
+ try {
762
+ return realpathSync(resolve3(word));
763
+ } catch {
764
+ return;
765
+ }
766
+ }
767
+ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
768
+ const target = script === undefined ? undefined : realPath(script) ?? script;
769
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
770
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
771
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
772
+ }
675
773
  // ../kit/src/process.ts
676
774
  import { constants } from "os";
677
- import process10 from "process";
775
+ import process11 from "process";
678
776
  var KILL_GRACE_MS = 2000;
679
777
  var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
680
778
  function exitCodeOf(code, signal) {
@@ -696,7 +794,7 @@ function holdSignals(cleanup) {
696
794
  },
697
795
  release: () => {
698
796
  for (const signal of SIGNALS)
699
- process10.off(signal, onSignal);
797
+ process11.off(signal, onSignal);
700
798
  }
701
799
  };
702
800
  function onSignal(signal) {
@@ -709,10 +807,10 @@ function holdSignals(cleanup) {
709
807
  return;
710
808
  held.release();
711
809
  cleanup(signal);
712
- process10.kill(process10.pid, signal);
810
+ process11.kill(process11.pid, signal);
713
811
  }
714
812
  for (const signal of SIGNALS)
715
- process10.on(signal, onSignal);
813
+ process11.on(signal, onSignal);
716
814
  return held;
717
815
  }
718
816
  async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
@@ -726,7 +824,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
726
824
  return;
727
825
  try {
728
826
  if (grouped)
729
- process10.kill(-proc.pid, killing);
827
+ process11.kill(-proc.pid, killing);
730
828
  else
731
829
  proc.kill(killing);
732
830
  } catch {}
@@ -800,15 +898,15 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
800
898
  var RESET_STYLE = `${ESC}[0m`;
801
899
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
802
900
  // ../kit/src/cli.ts
803
- import { readFileSync as readFileSync2, realpathSync } from "fs";
901
+ import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
804
902
  import { dirname as dirname3, join as join5 } from "path";
805
- import process12 from "process";
903
+ import process13 from "process";
806
904
 
807
905
  // ../kit/src/usage.ts
808
906
  import { appendFileSync, mkdirSync } from "fs";
809
907
  import { homedir as homedir3 } from "os";
810
908
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
811
- import process11 from "process";
909
+ import process12 from "process";
812
910
 
813
911
  // ../kit/src/logs.ts
814
912
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -822,14 +920,14 @@ var usageError;
822
920
  function noteUsageError(message) {
823
921
  usageError = message;
824
922
  }
825
- function stateHome(env = process11.env) {
923
+ function stateHome(env = process12.env) {
826
924
  const dir = env.XDG_STATE_HOME;
827
925
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
828
926
  }
829
- function usagePath(env = process11.env) {
927
+ function usagePath(env = process12.env) {
830
928
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
831
929
  }
832
- function usageRecorded(env = process11.env) {
930
+ function usageRecorded(env = process12.env) {
833
931
  const off = env.KAYNOOO_CLI_NO_USAGE;
834
932
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
835
933
  }
@@ -843,7 +941,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
843
941
  usageError = undefined;
844
942
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
845
943
  }
846
- function recordUsage(entry, env = process11.env) {
944
+ function recordUsage(entry, env = process12.env) {
847
945
  if (!usageRecorded(env))
848
946
  return;
849
947
  try {
@@ -861,8 +959,8 @@ var LEVEL_OPTIONS = {
861
959
  };
862
960
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
863
961
  function printError(prefix, message, hint, cause) {
864
- const colors = paint(process12.stderr);
865
- const styled = takesControlCodes(process12.stderr);
962
+ const colors = paint(process13.stderr);
963
+ const styled = takesControlCodes(process13.stderr);
866
964
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
867
965
  const under = (label, text, tint) => text === undefined ? "" : `
868
966
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -909,24 +1007,24 @@ function candidateLine(candidate) {
909
1007
  }
910
1008
  function positionalBeingTyped(before, { options, positionals }) {
911
1009
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
912
- let index = 0;
1010
+ const typed = [];
913
1011
  let at = 0;
914
1012
  while (at < before.length) {
915
1013
  const word = before[at];
916
1014
  if (word === "--") {
917
- index += before.length - at - 1;
1015
+ typed.push(...before.slice(at + 1));
918
1016
  break;
919
1017
  }
920
1018
  if (!word.startsWith("-"))
921
- index++;
1019
+ typed.push(word);
922
1020
  else if (takesValue(word))
923
1021
  at++;
924
1022
  at++;
925
1023
  }
926
1024
  const last = positionals.at(-1);
927
- if (index < positionals.length)
928
- return positionals[index];
929
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
1025
+ if (typed.length < positionals.length)
1026
+ return { name: positionals[typed.length], typed };
1027
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
930
1028
  }
931
1029
  async function leafCandidates(run, words) {
932
1030
  const completing = await completingOf(run);
@@ -934,12 +1032,12 @@ async function leafCandidates(run, words) {
934
1032
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
935
1033
  const flag = words.at(-2);
936
1034
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1035
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
937
1036
  if (option?.type === "string") {
938
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
1037
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
939
1038
  return values === undefined ? [FILES] : values.map(candidateLine);
940
1039
  }
941
- const name = positionalBeingTyped(words.slice(0, -1), completing);
942
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
1040
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
943
1041
  return values === undefined ? [FILES] : values.map(candidateLine);
944
1042
  }
945
1043
  async function printCandidates(found) {
@@ -948,9 +1046,9 @@ async function printCandidates(found) {
948
1046
  return 0;
949
1047
  }
950
1048
  function packageVersion(entry = Bun.main) {
951
- for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
1049
+ for (let dir = dirname3(realpathSync2(entry));; dir = dirname3(dir)) {
952
1050
  try {
953
- const { version } = JSON.parse(readFileSync2(join5(dir, "package.json"), "utf8"));
1051
+ const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
954
1052
  if (typeof version === "string")
955
1053
  return version;
956
1054
  } catch {}
@@ -958,7 +1056,7 @@ function packageVersion(entry = Bun.main) {
958
1056
  return "0.0.0";
959
1057
  }
960
1058
  }
961
- async function runMain({ name, version, run, redact, usage }, argv = process12.argv.slice(2)) {
1059
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
962
1060
  if (argv[0] === COMPLETE)
963
1061
  return printCandidates(leafCandidates(run, argv.slice(1)));
964
1062
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -987,7 +1085,7 @@ var {Glob } = globalThis.Bun;
987
1085
  var SESSION_FILES = new Glob("*.json");
988
1086
  var ACCOUNT_DIRS = new Glob("*/sessions");
989
1087
  // ../kit/src/watch.ts
990
- import process13 from "process";
1088
+ import process14 from "process";
991
1089
  import { format } from "util";
992
1090
  var CLEAR_SCREEN = "\x1B[H\x1B[2J";
993
1091
  var DEFAULT_SECONDS = 2;
@@ -1009,7 +1107,7 @@ function withoutWatch(args) {
1009
1107
  }
1010
1108
  return rest;
1011
1109
  }
1012
- async function watching(value, step, stream = process13.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1110
+ async function watching(value, step, stream = process14.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1013
1111
  const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
1014
1112
  if (!takesControlCodes(stream))
1015
1113
  badUsage("--watch redraws the screen, so it needs a terminal");
@@ -1017,12 +1115,12 @@ async function watching(value, step, stream = process13.stdout, sleep = Bun.slee
1017
1115
  for (let round = 0;round < rounds; round++) {
1018
1116
  const held = [];
1019
1117
  const { log, info } = console;
1020
- const write = process13.stdout.write.bind(process13.stdout);
1118
+ const write = process14.stdout.write.bind(process14.stdout);
1021
1119
  const hold = (...parts) => void held.push(`${format(...parts)}
1022
1120
  `);
1023
1121
  console.log = hold;
1024
1122
  console.info = hold;
1025
- process13.stdout.write = (text) => {
1123
+ process14.stdout.write = (text) => {
1026
1124
  held.push(typeof text === "string" ? text : Buffer.from(text).toString());
1027
1125
  return true;
1028
1126
  };
@@ -1031,7 +1129,7 @@ async function watching(value, step, stream = process13.stdout, sleep = Bun.slee
1031
1129
  } finally {
1032
1130
  console.log = log;
1033
1131
  console.info = info;
1034
- process13.stdout.write = write;
1132
+ process14.stdout.write = write;
1035
1133
  }
1036
1134
  stream.write(`${CLEAR_SCREEN}${held.join("")}`);
1037
1135
  await sleep(interval);
@@ -1039,8 +1137,8 @@ async function watching(value, step, stream = process13.stdout, sleep = Bun.slee
1039
1137
  return code;
1040
1138
  }
1041
1139
  // src/colour.ts
1042
- import process15 from "process";
1043
- function letter(status, stream = process15.stdout) {
1140
+ import process16 from "process";
1141
+ function letter(status, stream = process16.stdout) {
1044
1142
  const colors = paint(stream);
1045
1143
  const tint = { A: colors.green, M: colors.yellow, D: colors.red, U: colors.red, R: colors.cyan, C: colors.cyan }[status] ?? colors.dim;
1046
1144
  return tint(status);
@@ -1053,6 +1151,11 @@ async function git2(args, env) {
1053
1151
  return { code: ran.code, stdout: text("stdout"), stderr: text("stderr") };
1054
1152
  }
1055
1153
 
1154
+ // src/repos.ts
1155
+ import { readdir } from "fs/promises";
1156
+ import { join as join6, relative, resolve as resolve4 } from "path";
1157
+ import process17 from "process";
1158
+
1056
1159
  // src/status.ts
1057
1160
  var AHEAD_BEHIND = /\+(\d+) -(\d+)/;
1058
1161
  var OCTAL = /[0-7]/;
@@ -1125,30 +1228,122 @@ function summary(status, head) {
1125
1228
  return `${on}, ${tracking}; ${files} files${last}`;
1126
1229
  }
1127
1230
 
1231
+ // src/repos.ts
1232
+ var SKIPPED = new Set(["node_modules", "vendor", "dist"]);
1233
+ var DEPTH = 4;
1234
+ async function reposUnder(root, depth = DEPTH) {
1235
+ const found = [];
1236
+ async function walk(dir, left) {
1237
+ let entries;
1238
+ try {
1239
+ entries = await readdir(dir, { withFileTypes: true });
1240
+ } catch {
1241
+ return;
1242
+ }
1243
+ if (entries.some((entry) => entry.name === ".git"))
1244
+ found.push(dir);
1245
+ if (left === 0)
1246
+ return;
1247
+ await Promise.all(entries.filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && !SKIPPED.has(entry.name)).map(async (entry) => walk(join6(dir, entry.name), left - 1)));
1248
+ }
1249
+ await walk(resolve4(root), depth);
1250
+ return found.sort();
1251
+ }
1252
+ async function toplevelOf(dir) {
1253
+ const read = await git2(["-C", dir, "rev-parse", "--show-toplevel"]);
1254
+ return read.code === 0 ? read.stdout.trim() : undefined;
1255
+ }
1256
+ async function reposOf(roots) {
1257
+ const starts = roots.length > 0 ? roots : [await toplevelOf(".") ?? process17.cwd()];
1258
+ const found = await Promise.all(starts.map(async (root) => reposUnder(root)));
1259
+ return [...new Set(found.flat())].sort();
1260
+ }
1261
+ async function repoState(dir) {
1262
+ const [read, log] = await Promise.all([git2(["-C", dir, "status", "--porcelain=v2", "--branch"]), git2(["-C", dir, "log", "-1", "--format=%h%x00%s"])]);
1263
+ const [sha, title = ""] = log.code === 0 && log.stdout.trim() !== "" ? log.stdout.trim().split("\x00") : [];
1264
+ return { path: relative(process17.cwd(), dir) || ".", dir, status: read.code === 0 ? parseStatus(read.stdout) : null, head: sha === undefined ? null : { sha, title } };
1265
+ }
1266
+ function trackingOf(status) {
1267
+ if (status.upstream === null)
1268
+ return "no upstream";
1269
+ if (status.aheadBehind === null)
1270
+ return "upstream gone";
1271
+ const { ahead, behind } = status.aheadBehind;
1272
+ const parts = [ahead > 0 ? `${ahead} ahead` : "", behind > 0 ? `${behind} behind` : ""].filter(Boolean);
1273
+ return parts.length === 0 ? "up to date" : parts.join(", ");
1274
+ }
1275
+ function changesOf(status) {
1276
+ const { changes, untracked, conflicted } = status;
1277
+ const parts = [changes.length > 0 ? `${changes.length} changed` : "", untracked.length > 0 ? `${untracked.length} untracked` : "", conflicted.length > 0 ? `${conflicted.length} conflicted` : ""].filter(Boolean);
1278
+ return parts.length === 0 ? "clean" : parts.join(", ");
1279
+ }
1280
+ function branchOf(status) {
1281
+ return status.branch === "(detached)" ? `detached at ${status.oid.slice(0, 7)}` : status.branch;
1282
+ }
1283
+
1128
1284
  // src/gst.ts
1129
1285
  var USAGE = `gst [-n N]: the repository's branch, upstream, changed files and HEAD in one line, then the changed paths by staged, unstaged and untracked
1130
1286
 
1287
+ gst --repos [dir]... lists every repository at and below the current one's toplevel (or below each dir given, the current directory outside a repository), four levels down, past node_modules, vendor, dist and hidden folders: one line each with its path, branch, how it stands against its upstream as of the last fetch, and the files left to commit.
1288
+
1131
1289
  Exits 0 when it printed the status, 2 outside a git repository or on a usage error.`;
1132
1290
  var OPTIONS = {
1133
1291
  limit: { type: "string", short: "n", description: "add the last N commits as <sha7> <title>" },
1134
1292
  log: { type: "string", short: "l", description: "the former spelling of --limit" },
1293
+ repos: { type: "boolean", short: "r", description: "one line for each repository nested below, the current one included", conflicts: ["limit", "log"] },
1135
1294
  watch: watchOption("the status"),
1136
- json: jsonOption("{branch, oid, upstream, ahead, behind, head, staged, unstaged, untracked, conflicted, commits}")
1295
+ json: jsonOption("{branch, oid, upstream, ahead, behind, head, staged, unstaged, untracked, conflicted, commits}; with --repos an array of them, each with its path and no commits, a repository git cannot read being {path, error}")
1137
1296
  };
1297
+ function jsonOf(status, head, commits) {
1298
+ return {
1299
+ branch: status.branch,
1300
+ oid: status.oid,
1301
+ upstream: status.upstream,
1302
+ ahead: status.aheadBehind?.ahead ?? null,
1303
+ behind: status.aheadBehind?.behind ?? null,
1304
+ head,
1305
+ staged: status.changes.filter((change) => change.index !== ".").map(({ index, path, from }) => ({ status: index, path, ...from === undefined ? {} : { from } })),
1306
+ unstaged: status.changes.filter((change) => change.worktree !== ".").map(({ worktree, path }) => ({ status: worktree, path })),
1307
+ untracked: status.untracked,
1308
+ conflicted: status.conflicted,
1309
+ ...commits === undefined ? {} : { commits: commits.map(([commitSha = "", commitTitle = ""]) => ({ sha: commitSha, title: commitTitle })) }
1310
+ };
1311
+ }
1312
+ async function listRepos(roots, json) {
1313
+ const dirs = await reposOf(roots);
1314
+ if (dirs.length === 0)
1315
+ fail(`no git repository at or below ${roots.length === 0 ? "the current directory" : roots.join(", ")}`);
1316
+ const repos = await Promise.all(dirs.map(repoState));
1317
+ if (json) {
1318
+ printJson(repos.map(({ path, status, head }) => status === null ? { path, error: "git could not read it" } : { path, ...jsonOf(status, head) }));
1319
+ return 0;
1320
+ }
1321
+ const dim = paint(process18.stdout).dim;
1322
+ const cells = (repo) => {
1323
+ if (repo.status === null)
1324
+ return [role("path", process18.stdout)(repo.path), "", "", "git could not read it"];
1325
+ const changes = changesOf(repo.status);
1326
+ return [role("path", process18.stdout)(repo.path), branchOf(repo.status), trackingOf(repo.status), changes === "clean" ? dim(changes) : changes];
1327
+ };
1328
+ console.log(table(repos.map(cells)));
1329
+ return 0;
1330
+ }
1138
1331
  function group(title, lines) {
1139
- return lines.length === 0 ? [] : [paint(process16.stdout).bold(`${title}:`), ...lines.map((line) => ` ${line}`)];
1332
+ return lines.length === 0 ? [] : [paint(process18.stdout).bold(`${title}:`), ...lines.map((line) => ` ${line}`)];
1140
1333
  }
1141
1334
  function staged({ index, from, path }) {
1142
1335
  return `${letter(index)} ${from === undefined ? "" : `${from} -> `}${path}`;
1143
1336
  }
1144
1337
  async function main(argv) {
1145
- const parsed = parse(argv, USAGE, OPTIONS, { replaces: "git status --short and git log --oneline", examples: ["gst", ["gst -n 5", "with the last five commits"]] });
1146
- if (parsed.positionals.length > 0)
1147
- fail(`gst takes no paths
1338
+ const parsed = parse(argv, USAGE, OPTIONS, { positionals: ["[dir]..."], replaces: "git status --short, git log --oneline and a git -C <repo> status per nested repository", examples: ["gst", ["gst -n 5", "with the last five commits"], ["gst --repos", "the repositories nested in this one"]] });
1339
+ if (parsed.positionals.length > 0 && parsed.values.repos !== true)
1340
+ fail(`gst takes dirs with --repos alone
1148
1341
 
1149
1342
  ${USAGE}`);
1150
1343
  if (parsed.values.watch !== undefined)
1151
1344
  return watching(parsed.values.watch, async () => main(withoutWatch(argv)));
1345
+ if (parsed.values.repos === true)
1346
+ return listRepos(parsed.positionals, parsed.values.json === true);
1152
1347
  if (parsed.values.limit !== undefined && parsed.values.log !== undefined)
1153
1348
  fail("--limit and --log are the same flag, give one");
1154
1349
  const asked = parsed.values.limit ?? parsed.values.log;
@@ -1165,31 +1360,19 @@ ${USAGE}`);
1165
1360
  `).filter(Boolean).map((line) => line.split("\x00")) : [];
1166
1361
  if (parsed.values.json === true) {
1167
1362
  const [sha, title] = head.code === 0 && head.stdout.trim() !== "" ? head.stdout.trim().split("\x00") : [];
1168
- printJson({
1169
- branch: status.branch,
1170
- oid: status.oid,
1171
- upstream: status.upstream,
1172
- ahead: status.aheadBehind?.ahead ?? null,
1173
- behind: status.aheadBehind?.behind ?? null,
1174
- head: sha === undefined ? null : { sha, title: title ?? "" },
1175
- staged: status.changes.filter((change) => change.index !== ".").map(({ index, path, from }) => ({ status: index, path, ...from === undefined ? {} : { from } })),
1176
- unstaged: status.changes.filter((change) => change.worktree !== ".").map(({ worktree, path }) => ({ status: worktree, path })),
1177
- untracked: status.untracked,
1178
- conflicted: status.conflicted,
1179
- commits: commits.map(([commitSha = "", commitTitle = ""]) => ({ sha: commitSha, title: commitTitle }))
1180
- });
1363
+ printJson(jsonOf(status, sha === undefined ? null : { sha, title: title ?? "" }, commits));
1181
1364
  return 0;
1182
1365
  }
1183
1366
  const lines = [
1184
1367
  summary(status, head.code === 0 ? head.stdout : ""),
1185
1368
  ...group("staged", status.changes.filter((change) => change.index !== ".").map(staged)),
1186
1369
  ...group("unstaged", status.changes.filter((change) => change.worktree !== ".").map((change) => `${letter(change.worktree)} ${change.path}`)),
1187
- ...group("untracked", status.untracked.map((file) => paint(process16.stdout).dim(file))),
1188
- ...group("conflicted", status.conflicted.map((file) => paint(process16.stdout).red(file))),
1189
- ...group("commits", commits.map(([commitSha = "", commitTitle = ""]) => `${role("id", process16.stdout)(commitSha)} ${commitTitle}`))
1370
+ ...group("untracked", status.untracked.map((file) => paint(process18.stdout).dim(file))),
1371
+ ...group("conflicted", status.conflicted.map((file) => paint(process18.stdout).red(file))),
1372
+ ...group("commits", commits.map(([commitSha = "", commitTitle = ""]) => `${role("id", process18.stdout)(commitSha)} ${commitTitle}`))
1190
1373
  ];
1191
1374
  console.log(lines.join(`
1192
1375
  `));
1193
1376
  return 0;
1194
1377
  }
1195
- process16.exitCode = await runMain({ name: "gst", run: main });
1378
+ process18.exitCode = await runMain({ name: "gst", run: main });
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-git",
3
3
  "type": "module",
4
- "version": "0.13.1",
5
- "description": "gst, gc and gb: a repository's state in one call, a commit of exactly the paths given, its message checked before anything is staged, and a branch picked.",
4
+ "version": "0.14.0",
5
+ "description": "gst, gc, gb and gp: a repository's state in one call, a commit of exactly the paths given, its message checked before anything is staged, a branch picked, and the branches of nested repositories pushed.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
8
8
  "homepage": "https://git.kaynooo.fr/kaynooo/cli/src/branch/main/packages/git#readme",
@@ -25,7 +25,8 @@
25
25
  "bin": {
26
26
  "gst": "./dist/gst.js",
27
27
  "gc": "./dist/gc.js",
28
- "gb": "./dist/gb.js"
28
+ "gb": "./dist/gb.js",
29
+ "gp": "./dist/gp.js"
29
30
  },
30
31
  "files": [
31
32
  "dist",
@@ -38,12 +39,13 @@
38
39
  "registry": "https://git.kaynooo.fr/api/packages/kaynooo/npm/"
39
40
  },
40
41
  "scripts": {
41
- "build": "$npm_execpath build src/gst.ts src/gc.ts src/gb.ts --target bun --outdir dist",
42
+ "build": "$npm_execpath build src/gst.ts src/gc.ts src/gb.ts src/gp.ts --target bun --outdir dist",
42
43
  "gst": "$npm_execpath src/gst.ts",
43
44
  "gc": "$npm_execpath src/gc.ts",
44
- "gb": "$npm_execpath src/gb.ts"
45
+ "gb": "$npm_execpath src/gb.ts",
46
+ "gp": "$npm_execpath src/gp.ts"
45
47
  },
46
48
  "devDependencies": {
47
- "@kaynooo/cli-kit": "0.37.0"
49
+ "@kaynooo/cli-kit": "0.38.1"
48
50
  }
49
51
  }