-
Notifications
You must be signed in to change notification settings - Fork 6
/
run-pty.js
executable file
·2597 lines (2365 loc) · 74 KB
/
run-pty.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
"use strict";
const fs = require("fs");
const path = require("path");
const os = require("os");
const pty = require("@lydell/node-pty");
const Codec = require("tiny-decoders");
/**
* @typedef {
| { tag: "Waiting" }
| { tag: "Running", terminal: import("@lydell/node-pty").IPty }
| { tag: "Killing", terminal: import("@lydell/node-pty").IPty, slow: boolean, lastKillPress: number | undefined, restartAfterKill: boolean }
| { tag: "Exit", exitCode: number, wasKilled: boolean }
} Status
*
* @typedef {
| { tag: "Command", index: number }
| { tag: "Dashboard", previousRender: Array<string> }
} Current
*/
const IS_WINDOWS = process.platform === "win32";
const IS_WINDOWS_TERMINAL = "WT_SESSION" in process.env; // https://github.com/microsoft/terminal/issues/1040
const SUPPORTS_EMOJI = !IS_WINDOWS || IS_WINDOWS_TERMINAL;
// https://github.com/sindresorhus/ansi-escapes/blob/2b3b59c56ff77a2afdee946bff96f1779d10d775/index.js#L5
const IS_TERMINAL_APP = process.env.TERM_PROGRAM === "Apple_Terminal";
const SLOW_KILL = 100; // ms
// This is apparently what Windows uses for double clicks.
const DOUBLE_PRESS = 500; // ms
const MAX_HISTORY_DEFAULT = 1000000;
const MAX_HISTORY = (() => {
const env = process.env.RUN_PTY_MAX_HISTORY;
return env !== undefined && /^\d+$/.test(env)
? Number(env)
: MAX_HISTORY_DEFAULT;
})();
const NO_COLOR = "NO_COLOR" in process.env;
const KEYS = {
kill: "ctrl+c",
restart: "enter",
dashboard: "ctrl+z",
navigate: "↑↓←→",
navigateVerticallyOnly: "↑↓",
enter: "enter",
unselect: "escape",
};
const KEY_CODES = {
kill: "\x03",
restart: "\r",
dashboard: "\x1a",
up: "\x1B[A",
down: "\x1B[B",
left: "\x1B[D",
right: "\x1B[C",
enter: "\r",
esc: "\x1B",
};
const ALPHABET = "abcdefghijklmnopqrstuvwxyz";
const LABEL_GROUPS = ["123456789", ALPHABET, ALPHABET.toUpperCase()];
const ALL_LABELS = LABEL_GROUPS.join("");
const HIDE_CURSOR = "\x1B[?25l";
const SHOW_CURSOR = "\x1B[?25h";
const ENABLE_ALTERNATE_SCREEN = "\x1B[?1049h";
const DISABLE_ALTERNATE_SCREEN = "\x1B[?1049l";
const ALTERNATE_SCREEN_REGEX = /(\x1B\[\?1049[hl])/;
const DISABLE_BRACKETED_PASTE_MODE = "\x1B[?2004l";
const DISABLE_APPLICATION_CURSOR_KEYS = "\x1B[?1l"; // https://www.vt100.net/docs/vt510-rm/DECCKM.html
const ENABLE_MOUSE = "\x1B[?1000;1006h";
const DISABLE_MOUSE = "\x1B[?1000;1006l";
const RESET_COLOR = "\x1B[m";
const CLEAR = "\x1B[2J\x1B[3J\x1B[H";
const CLEAR_LEFT = "\x1B[1K";
const CLEAR_RIGHT = "\x1B[K";
const CLEAR_DOWN = "\x1B[J";
// These save/restore cursor position _and graphic renditions._
const SAVE_CURSOR = IS_TERMINAL_APP ? "\u001B7" : "\x1B[s";
const RESTORE_CURSOR = IS_TERMINAL_APP ? "\u001B8" : "\x1B[u";
const CLEAR_REGEX = (() => {
const goToTopLeft = /(?:[01](?:;[01])?)?[fH]/;
const clearDown = /0?J/;
const clearScreen = /2J/;
const clearScrollback = /3J/;
/**
* @template T
* @param {Array<T>} items
* @returns {Array<Array<T>>}
*/
const permutations = (items) =>
items.length <= 1
? [items]
: items.flatMap((first, index) =>
permutations([
...items.slice(0, index),
...items.slice(index + 1),
]).map((rest) => [first, ...rest]),
);
const variants = [
...permutations([clearScreen, clearScrollback, goToTopLeft]),
[clearScrollback, goToTopLeft, clearDown],
[goToTopLeft, clearDown, clearScrollback],
[goToTopLeft, clearScrollback, clearDown],
].map((parts) => parts.map((part) => `\\x1B\\[${part.source}`).join(""));
return RegExp(`(?:${variants.join("|")})`);
})();
const waitingIndicator = NO_COLOR
? "■"
: !SUPPORTS_EMOJI
? `\x1B[93m■${RESET_COLOR}`
: "🥱";
const runningIndicator = NO_COLOR
? "›"
: !SUPPORTS_EMOJI
? `\x1B[92m●${RESET_COLOR}`
: "🟢";
const killingIndicator = NO_COLOR
? "○"
: !SUPPORTS_EMOJI
? `\x1B[91m○${RESET_COLOR}`
: "⭕";
const restartingIndicator = NO_COLOR
? "◌"
: !SUPPORTS_EMOJI
? `\x1B[96m◌${RESET_COLOR}`
: "🔄";
const abortedIndicator = NO_COLOR
? "▲"
: !SUPPORTS_EMOJI
? `\x1B[91m▲${RESET_COLOR}`
: "⛔️";
/**
* @param {number} exitCode
* @returns {string}
*/
const exitIndicator = (exitCode) =>
// 130 (128 + 2 (SIGINT)) commonly means exit by ctrl+c.
exitCode === 0 || exitCode === 130
? NO_COLOR
? "●"
: !SUPPORTS_EMOJI
? `\x1B[97m●${RESET_COLOR}`
: "⚪"
: NO_COLOR
? "×"
: !SUPPORTS_EMOJI
? `\x1B[91m●${RESET_COLOR}`
: "🔴";
const folder = NO_COLOR
? "⌂"
: !SUPPORTS_EMOJI
? `\x1B[2m⌂${RESET_COLOR}`
: "📂";
/**
* @param {number} n
* @returns {string}
*/
const cursorUp = (n) => `\x1B[${n}A`;
/**
* @param {number} n
* @returns {string}
*/
const cursorDown = (n) => `\x1B[${n}B`;
/**
* @param {number} n
* @returns {string}
*/
const cursorHorizontalAbsolute = (n) => `\x1B[${n}G`;
/**
* @param {number} y
* @param {number} x
* @returns {string}
*/
const cursorAbsolute = (y, x) => `\x1B[${y};${x}H`;
/**
* @param {string} string
* @returns {string}
*/
const bold = (string) => (NO_COLOR ? string : `\x1B[1m${string}${RESET_COLOR}`);
/**
* @param {string} string
* @returns {string}
*/
const dim = (string) => (NO_COLOR ? string : `\x1B[2m${string}${RESET_COLOR}`);
/**
* @param {string} string
* @returns {string}
*/
const invert = (string) => {
const inverted = string
// Split on RESET_COLOR and stop invert (27).
.split(/(\x1B\[(?:0?|27)m)/)
.map((part, index) => (index % 2 === 0 ? `\x1B[7m${part}` : part))
.join("");
return NO_COLOR ? string : `${inverted}${RESET_COLOR}`;
};
/**
* @param {string} string
* @param {{ pad?: boolean, highlight?: boolean }} pad
*/
const shortcut = (string, { pad = true } = {}) =>
dim("[") +
bold(string) +
dim("]") +
(pad ? " ".repeat(Math.max(0, KEYS.kill.length - string.length)) : "");
const runPty = bold("run-pty");
const pc = dim("%");
const at = dim("@");
const et = dim("&&");
const [ICON_WIDTH, EMOJI_WIDTH_FIX] =
!SUPPORTS_EMOJI || NO_COLOR ? [1, ""] : [2, cursorHorizontalAbsolute(3)];
/**
* @param {Array<string | undefined>} labels
* @returns {string}
*/
const summarizeLabels = (labels) => {
const numLabels = labels.length;
return LABEL_GROUPS.flatMap((group, index) => {
const previousLength = LABEL_GROUPS.slice(0, index).reduce(
(sum, previousGroup) => sum + previousGroup.length,
0,
);
const currentLength = previousLength + group.length;
return numLabels > previousLength
? numLabels < currentLength
? group.slice(0, numLabels - previousLength)
: group
: [];
})
.map((group) =>
group.length === 1 ? group[0] : `${group[0]}-${group[group.length - 1]}`,
)
.join("/");
};
const autoExitHelp = `
--auto-exit=<number> auto exit when done, with at most <number> parallel processes
--auto-exit=auto uses the number of logical CPU cores
--auto-exit defaults to auto
`
.slice(1)
.trimEnd();
const help = `
Run several commands concurrently.
Show output for one command at a time.
Kill all at once.
Separate the commands with a character of choice:
${runPty} ${pc} npm start ${pc} make watch ${pc} some_command arg1 arg2 arg3
${runPty} ${at} ./report_progress.bash --root / --unit % ${at} ping localhost
Alternatively, specify the commands in a JSON file:
${runPty} run-pty.json
You can tell run-pty to exit once all commands have exited with status 0:
${runPty} --auto-exit ${pc} npm ci ${pc} dotnet restore ${et} node build.js
${autoExitHelp}
Keyboard shortcuts:
${shortcut(KEYS.dashboard)} Dashboard
${shortcut(KEYS.kill)} Kill all or focused command
Other keyboard shortcuts are shown as needed.
Environment variables:
${bold("RUN_PTY_MAX_HISTORY")}
Number of characters of output to remember.
Higher → more command scrollback
Lower → faster switching between commands
Default: ${MAX_HISTORY_DEFAULT}
${bold("NO_COLOR")}
Disable colored output.
`.trim();
/**
* @param {Array<Command>} commands
* @returns {string}
*/
const killAllLabel = (commands) =>
commands.some((command) => command.status.tag === "Killing")
? `kill all ${dim("(double-press to force) ")}`
: commands.every((command) => !("terminal" in command.status))
? "exit"
: "kill all";
/**
* @param {Array<Command>} commands
* @param {Selection} selection
* @param {{ width: number, useSeparateKilledIndicator: boolean }} options
* @returns {Array<{ line: string, length: number }>}
*/
const drawDashboardCommandLines = (
commands,
selection,
{ width, useSeparateKilledIndicator },
) => {
const lines = commands.map((command) => {
const [icon, status] = statusText(command.status, {
statusFromRules: command.statusFromRules ?? runningIndicator,
useSeparateKilledIndicator,
});
const { label = " " } = command;
return {
label: shortcut(label, { pad: false }),
icon,
status,
title: command.titlePossiblyWithGraphicRenditions,
};
});
const separator = " ";
const widestStatus = Math.max(
0,
...lines.map(({ status }) => (status === undefined ? 0 : status.length)),
);
const selectedIndicator =
selection.tag === "ByIndicator" ? selection.indicator : undefined;
return lines.map(({ label, icon, status, title }, index) => {
const finalIcon =
icon === selectedIndicator
? NO_COLOR
? `${separator.slice(0, -1)}→${icon}`
: // Add spaces at the end to make sure that two terminal slots get
// inverted, no matter the actual width of the icon (which may even
// be the empty string).
`${separator.slice(0, -1)}${invert(
` ${icon}${" ".repeat(ICON_WIDTH)}`,
)}`
: `${separator}${icon}`;
const start = truncate(`${label}${finalIcon}`, width);
const startLength =
removeGraphicRenditions(label).length + separator.length + ICON_WIDTH;
const end =
status === undefined
? title
: `${status.padEnd(widestStatus, " ")}${separator}${title}`;
const truncatedEnd = truncate(end, width - startLength - separator.length);
const length =
startLength +
separator.length +
removeGraphicRenditions(truncatedEnd).length;
const highlightedSeparator =
icon === selectedIndicator && !NO_COLOR
? invert(" ") + separator.slice(1)
: separator;
const finalEnd =
(selection.tag === "Mousedown" || selection.tag === "Keyboard") &&
index === selection.index
? NO_COLOR
? `${highlightedSeparator.slice(0, -1)}→${truncatedEnd}`
: `${highlightedSeparator}${invert(truncatedEnd)}`
: `${highlightedSeparator}${truncatedEnd}`;
return {
line: `${start}${RESET_COLOR}${cursorHorizontalAbsolute(
startLength + 1,
)}${CLEAR_RIGHT}${finalEnd}${RESET_COLOR}`,
length,
};
});
};
/**
* @param {{
commands: Array<Command>,
width: number,
attemptedKillAll: boolean,
autoExit: AutoExit,
selection: Selection,
}} options
* @returns {string}
*/
const drawDashboard = ({
commands,
width,
attemptedKillAll,
autoExit,
selection,
}) => {
const done = isDone({ commands, attemptedKillAll, autoExit });
const finalLines = drawDashboardCommandLines(
commands,
done ? { tag: "Invisible", index: 0 } : selection,
{
width,
useSeparateKilledIndicator: autoExit.tag === "AutoExit",
},
)
.map(({ line }) => line)
.join("\n");
if (done) {
return `${finalLines}\n`;
}
const label = summarizeLabels(commands.map((command) => command.label));
// Clicks might be supported in Windows 11, but not Windows 10.
// https://github.com/microsoft/terminal/issues/376
const click = IS_WINDOWS ? "" : ` ${dim("(or click)")}`;
const enter =
selection.tag === "Keyboard"
? `${shortcut(KEYS.enter)} focus selected${getPid(
commands[selection.index],
)}\n${shortcut(KEYS.unselect)} unselect`
: selection.tag === "ByIndicator"
? `${shortcut(KEYS.enter)} ${
commands.some(
(command) =>
getIndicatorChoice(command) === selection.indicator &&
command.status.tag === "Killing",
)
? "force "
: ""
}restart selected\n${shortcut(KEYS.unselect)} unselect`
: autoExit.tag === "AutoExit"
? commands.some(
(command) =>
command.status.tag === "Exit" &&
(command.status.exitCode !== 0 || command.status.wasKilled),
)
? `${shortcut(KEYS.enter)} restart failed`
: ""
: commands.some((command) => command.status.tag === "Exit")
? `${shortcut(KEYS.enter)} restart exited`
: "";
const navigationKeys =
autoExit.tag === "AutoExit" ? KEYS.navigateVerticallyOnly : KEYS.navigate;
const sessionEnds = "The session ends automatically once all commands are ";
const autoExitText =
autoExit.tag === "AutoExit"
? [
enter === "" ? undefined : "",
`At most ${autoExit.maxParallel} ${
autoExit.maxParallel === 1 ? "command runs" : "commands run"
} at a time.`,
`${sessionEnds}${exitIndicator(0)}${cursorHorizontalAbsolute(
sessionEnds.length + ICON_WIDTH + 1,
)} ${bold("exit 0")}.`,
]
.filter((x) => x !== undefined)
.join("\n")
: "";
return `
${finalLines}
${shortcut(label)} focus command${click}
${shortcut(KEYS.kill)} ${killAllLabel(commands)}
${shortcut(navigationKeys)} move selection
${enter}
${autoExitText}
`.trim();
};
/**
* @param {Array<Command>} commands
* @returns {string}
*/
const drawSummary = (commands) => {
const summary = commands.every(
(command) =>
command.status.tag === "Exit" &&
command.status.exitCode === 0 &&
!command.status.wasKilled,
)
? "success"
: commands.some(
(command) =>
command.status.tag === "Exit" &&
command.status.exitCode !== 0 &&
!command.status.wasKilled,
)
? "failure"
: "aborted";
const lines = commands.map((command) => {
const [indicator, status] = statusText(command.status, {
statusFromRules: runningIndicator,
useSeparateKilledIndicator: true,
});
return `${indicator}${EMOJI_WIDTH_FIX} ${
status === undefined ? "" : `${status} `
}${command.titlePossiblyWithGraphicRenditions}${RESET_COLOR}`;
});
return `${bold(`Summary – ${summary}:`)}\n${lines.join("\n")}\n`;
};
/**
* @param {{
commands: Array<Command>,
attemptedKillAll: boolean,
autoExit: AutoExit,
}} options
* @returns {boolean}
*/
const isDone = ({ commands, attemptedKillAll, autoExit }) =>
// All commands are killed:
(attemptedKillAll &&
commands.every((command) => !("terminal" in command.status))) ||
// --auto-exit and all commands are “exit 0”:
(autoExit.tag === "AutoExit" &&
commands.every(
(command) =>
command.status.tag === "Exit" &&
command.status.exitCode === 0 &&
!command.status.wasKilled,
));
/**
* @param {Command} command
* @returns {string}
*/
const getPid = (command) =>
"terminal" in command.status
? ` ${dim(`(pid ${command.status.terminal.pid})`)}`
: "";
/**
* @param {Command} command
* @returns {string}
*/
const getIndicatorChoice = (command) =>
statusText(command.status, {
statusFromRules: command.statusFromRules ?? runningIndicator,
useSeparateKilledIndicator: false,
})[0];
/**
* @param {Array<Command>} commands
* @returns {Array<string>}
*/
const getIndicatorChoices = (commands) => [
...new Set(commands.map(getIndicatorChoice)),
];
/**
* @typedef {Pick<Command, "formattedCommandWithTitle" | "title" | "titlePossiblyWithGraphicRenditions" | "cwd" | "history">} CommandText
*/
/**
* @param {CommandText} command
* @returns {string}
*/
const cwdText = (command) =>
path.resolve(command.cwd) === process.cwd()
? ""
: `${folder}${EMOJI_WIDTH_FIX} ${dim(command.cwd)}\n`;
/**
* @param {string} indicator
* @param {CommandText} command
* @returns {string}
*/
const historyStart = (indicator, command) =>
`${commandTitleWithIndicator(indicator, command)}\n${cwdText(command)}`;
/**
* Used in interactive mode.
*
* @param {string} indicator
* @param {CommandText} command
* @returns {string}
*/
const commandTitleWithIndicator = (indicator, command) =>
`${indicator}${EMOJI_WIDTH_FIX} ${command.formattedCommandWithTitle}${RESET_COLOR}`;
/**
* Similar to `commandTitleWithIndicator`. Used in non-interactive mode. This
* does not print the full command, only the title. In interactive mode, the
* dashboard only prints the title too – if you want the full thing, you need to
* enter that command, because the command can be very long. In non-interactive
* mode, it can be very spammy if a long command is printed once when started,
* once when exited and once in the summary – interesting output (such as
* errors) gets lost in a sea of command stuff.
*
* @param {string} indicator
* @param {CommandText} command
* @returns {string}
*/
const commandTitleOnlyWithIndicator = (indicator, command) =>
`${indicator}${EMOJI_WIDTH_FIX} ${command.titlePossiblyWithGraphicRenditions}${RESET_COLOR}`;
/**
* @param {Array<Command>} commands
* @returns {string}
*/
const waitingText = (commands) =>
`
Waiting for other commands to finish before starting.
${shortcut(KEYS.kill)} ${killAllLabel(commands)}
${shortcut(KEYS.dashboard)} dashboard
`.trim();
/**
* @param {number} pid
* @returns {string}
*/
const runningText = (pid) =>
`
${shortcut(KEYS.kill)} kill ${dim(`(pid ${pid})`)}
${shortcut(KEYS.dashboard)} dashboard
`.trim();
/**
* @param {number} pid
* @returns {string}
*/
const killingText = (pid) =>
`
${shortcut(KEYS.kill)} kill ${dim(`(double-press to force) (pid ${pid})`)}
${shortcut(KEYS.dashboard)} dashboard
`.trim();
/**
* @param {Array<Command>} commands
* @param {CommandText} command
* @param {Extract<Status, {tag: "Exit"}>} status
* @param {AutoExit} autoExit
* @returns {string}
*/
const exitText = (commands, command, status, autoExit) => {
const titleWithIndicator = commandTitleWithIndicator(
status.wasKilled && autoExit.tag === "AutoExit"
? abortedIndicator
: exitIndicator(status.exitCode),
command,
);
const restart =
autoExit.tag === "AutoExit" && status.exitCode === 0 && !status.wasKilled
? ""
: `${shortcut(KEYS.enter)} restart\n`;
return `
${titleWithIndicator}
${cwdText(command)}exit ${status.exitCode}
${restart}${shortcut(KEYS.kill)} ${killAllLabel(commands)}
${shortcut(KEYS.dashboard)} dashboard
`.trim();
};
/**
* @param {{ command: CommandText, exitCode: number, numExited: number, numTotal: number }} options
* @returns {string}
*/
const exitTextAndHistory = ({ command, exitCode, numExited, numTotal }) => {
const lastLine = removeGraphicRenditions(getLastLine(command.history));
const newline =
// If the last line is empty, no extra newline is needed.
lastLine.trim() === "" ? "" : "\n";
return `
${commandTitleOnlyWithIndicator(exitIndicator(exitCode), command)}
${cwdText(command)}${command.history}${CLEAR_DOWN}${newline}${bold(
`exit ${exitCode}`,
)} ${dim(`(${numExited}/${numTotal} exited)`)}
`.trimStart();
};
/**
* @param {Status} status
* @param {{ statusFromRules: string, useSeparateKilledIndicator: boolean }} options
* @returns {[string, string | undefined]}
*/
const statusText = (
status,
{ statusFromRules, useSeparateKilledIndicator },
) => {
switch (status.tag) {
case "Waiting":
return [waitingIndicator, undefined];
case "Running":
return [statusFromRules, undefined];
case "Killing":
return [
status.restartAfterKill ? restartingIndicator : killingIndicator,
undefined,
];
case "Exit":
return [
status.wasKilled && useSeparateKilledIndicator
? abortedIndicator
: exitIndicator(status.exitCode),
bold(`exit ${status.exitCode}`),
];
}
};
// If a command moves the cursor to another line it’s not considered a “simple
// log”. Then it’s not safe to print the keyboard shortcuts.
//
// - A, B: Cursor up/down. Moving down should be safe. So is `\n1A` (move to
// start of new line, then up one line) – docker-compose does that
// to update the previous line. We always print on the next line so it’s safe.
// - C, D: Cursor left/right. Should be safe! Parcel does this.
// - E, F: Cursor down/up, and to the start of the line. Moving down should be safe.
// - G: Cursor absolute position within line. Should be safe! Again, Parcel.
// - H, f: Cursor absolute position, both x and y. Exception: Moving to the
// top-left corner and clearing the screen (ctrl+l).
// - I, Z: Cursor forward/backward by tab stops. Should be safe.
// - J: Clear the screen in different ways. Should be safe.
// - K: Erase in line. Should be safe.
// - L: Insert lines.
// - M: Delete lines.
// - S: Scroll up.
// - T: Scroll down.
// - s: Save cursor position.
// - u: Restore cursor position.
//
// This includes the regexes for clearing the screen, since they also affect “is
// simple log”: They reset it to `true` sometimes.
const NOT_SIMPLE_LOG_ESCAPE_RAW =
/(\x1B\[0?J)|\x1B\[(?:\d*[FLMST]|[su]|(?!(?:[01](?:;[01])?)?[fH]\x1B\[[02]?J)(?:\d+(?:;\d+)?)?[fH])|(?!\n\x1B\[1?A)(?:^|[^])\x1B\[\d*A/;
const NOT_SIMPLE_LOG_ESCAPE = RegExp(
`(${CLEAR_REGEX.source})|${NOT_SIMPLE_LOG_ESCAPE_RAW.source}`,
"g",
);
// These escapes should be printed when they first occur, but not when
// re-printing history. They result in getting a response on stdin. The
// commands might not be in a state where they expect such stdin at the time we
// re-print history. For example, Vim asks for the terminal
// background/foreground colors on startup. But if it receives such a response
// later, it treats it as if the user typed those characters.
//
// When using `conptyInheritCursor` (Windows only), the pty writes a 6n escape
// to get the cursor position, and then waits for the response before actually
// starting the command. There used to be a problem where the commands
// effectively wouldn’t start executing until focused. That’s solved by handling
// requests and responses this way. The pty then writes a cursor move like
// `5;1H`. The line (5) varies depending on how many lines have been printed so
// far. The column seems to always be 1. For some reason, replacing this cursor
// move with two newlines seems to always make the cursor end up where we want,
// in my testing. Note: The `5;1H` stuff seems to only be triggered when using
// `npm run`. `run-pty % npx prettier --check .` does not trigger it, but
// `run-pty % npm run prettier` (with `"prettier": "prettier --check ."` in
// package.json) does. `run-pty % timeout 3` also uses 6n and cursor moves, and
// should not be affected by this workaround.
//
// https://xfree86.org/current/ctlseqs.html
//
// - 6n and ?6n: Report Cursor Position. Reply uses `R` instead of `n`.
// - t: Report window position, size, title etc.
// - ]10;? and ]11;?: Report foreground/background color. https://unix.stackexchange.com/a/172674
// - ]4;NUM;?: Report color NUM in the palette.
const ESCAPES_REQUEST =
/(\x1B\[(?:\??6n|\d*(?:;\d*){0,2}t)|\x1B\](?:1[01]|4;\d+);\?(?:\x07|\x1B\\))/g;
const ESCAPES_RESPONSE =
/(\x1B\[(?:\??\d+;\d+R|\d*(?:;\d*){0,2}t)|\x1B\](?:1[01]|4;\d+);[^\x07\x1B]+(?:\x07|\x1B\\))/g;
const CURSOR_POSITION_RESPONSE = /(\x1B\[\??)\d+;\d+R/g;
const CONPTY_CURSOR_MOVE = /\x1B\[\d+;1H/;
const CONPTY_CURSOR_MOVE_REPLACEMENT = "\n\n";
/**
* @param {string} request
* @returns {string}
*/
const respondToRequestFake = (request) =>
request.endsWith("6n")
? "\x1B[1;1R"
: request.endsWith("t")
? "\x1B[3;0;0t"
: request.startsWith("\x1B]10;") || request.startsWith("\x1B]4;")
? request.replace("?", "rgb:ffff/ffff/ffff")
: request.startsWith("\x1B]11;")
? request.replace("?", "rgb:0000/0000/0000")
: "";
// Inspired by this well researched Stack Overflow answer:
// https://stackoverflow.com/a/14693789
//
// First, let’s talk about ANSI escapes. They start with `\x1B`.
//
// - Some escapes are followed by just one more character.
// - CSI escapes have a `[` and then 0 or more parameter characters, followed by
// a final character. There is no overlap between the parameter characters and
// the final character.
// - OSC escapes have a `]` and then 1 or more characters, followed by either
// `\x07` or `\x1B\\`.
//
// So a `\x1B` followed by zero or more parameter characters at the very end
// indicates an unfinished escape. But if that’s followed by anything else
// (valid or invalid final character), it’s finished.
//
// This is needed because we can’t print any extra things in the middle of an
// unfinished escape: That breaks the escape and causes things like “6m” to be
// printed – parts of the escape ends up as text. The Elm compiler does this:
// Run `elm make --output=/dev/null MyFile.elm` where MyFile.elm has a syntax
// error, and most of the time you’ll get color codes split in half. It prints
// the next half the same millisecond.
//
// It’s also needed because it is valid to print half an escape code for moving
// the cursor up, and then the other half. By buffering the escape code, we can
// pretend that escape codes always come in full in the rest of the code.
//
// Note: The terminals I’ve tested with seem to wait forever for the end of
// escape sequences – they don’t have a timeout or anything.
const UNFINISHED_ESCAPE = /\x1B(?:\[[0-?]*[ -/]*|\][^\x1B\x07]*)?$/;
const GRAPHIC_RENDITIONS = /(\x1B\[(?:\d+(?:;\d+)*)?m)/g;
/**
* @param {string} string
* @returns {string}
*/
const removeGraphicRenditions = (string) =>
string.replace(GRAPHIC_RENDITIONS, "");
/**
* @param {string} string
* @param {number} maxLength
* @returns {string}
*/
const truncate = (string, maxLength) => {
let result = "";
let length = 0;
for (const [index, part] of string.split(GRAPHIC_RENDITIONS).entries()) {
if (index % 2 === 0) {
const diff = maxLength - length - part.length;
if (diff < 0) {
return `${result + part.slice(0, diff - 1)}…`;
} else {
result += part;
length += part.length;
}
} else {
result += part;
}
}
return result;
};
/**
* @param {Array<string>} command
* @returns {string}
*/
const commandToPresentationName = (command) =>
command
.map((part) =>
part === ""
? "''"
: part
.split(/(')/)
.map((subPart) =>
subPart === ""
? ""
: subPart === "'"
? "\\'"
: /^[\w.,:/=@%+-]+$/.test(subPart)
? subPart
: `'${subPart}'`,
)
.join(""),
)
.join(" ");
/**
* @param {string} arg
* @returns {string}
*/
const cmdEscapeMetaChars = (arg) =>
// https://qntm.org/cmd
arg.replace(/[()%!^"<>&|;, ]/g, "^$&");
/**
* @param {string} arg
* @returns {string}
*/
const cmdEscapeArg = (arg) =>
// https://qntm.org/cmd
cmdEscapeMetaChars(
`"${arg.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, "$1$1")}"`,
);
const AUTO_EXIT_REGEX = /^--auto-exit(?:=(\d+|auto))?$/;
/**
* @typedef {
| { tag: "Help" }
| { tag: "NoCommands" }
| { tag: "Error", message: string }
| { tag: "Parsed", commands: Array<CommandDescription>, autoExit: AutoExit }
} ParseResult
*
* @typedef {{
title: string,
cwd: string,
command: Array<string>,
status: Array<[RegExp, [string, string] | undefined]>,
defaultStatus?: [string, string] | undefined,
killAllSequence: string,
}} CommandDescription
*
* @typedef {
| { tag: "NoAutoExit" }
| { tag: "AutoExit", maxParallel: number }
} AutoExit
*/
/**
* @param {Array<string>} args
* @returns {ParseResult}
*/
const parseArgs = (args) => {
if (args.length === 0) {
return { tag: "Help" };
}
const [flags, restArgs] = partitionArgs(args);
/** @type {AutoExit} */
let autoExit = { tag: "NoAutoExit" };
for (const flag of flags) {
if (flag === "-h" || flag === "--help") {
return { tag: "Help" };
}
const match = AUTO_EXIT_REGEX.exec(flag);
if (match !== null) {
const maxParallel =
match[1] === undefined || match[1] === "auto"
? os.cpus().length
: Number(match[1]);
if (maxParallel === 0) {
return { tag: "Error", message: "--auto-exit=0 will never finish." };
}
autoExit = {
tag: "AutoExit",
maxParallel,
};
} else {
return {
tag: "Error",
message: [
`Bad flag: ${flag}`,
"Only these forms are accepted:",
autoExitHelp,
].join("\n"),
};
}
}
if (restArgs.length === 1) {
try {
const commands = parseInputFile(fs.readFileSync(restArgs[0], "utf8"));
return commands.length === 0
? { tag: "NoCommands" }
: { tag: "Parsed", commands, autoExit };
} catch (errorAny) {
/** @type {Error & {code?: string} | undefined} */