-
Notifications
You must be signed in to change notification settings - Fork 1
/
rl-utils.ts
91 lines (84 loc) · 2.3 KB
/
rl-utils.ts
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
import { Writable } from "stream";
import * as readline from "readline";
export const mutableStdout = new Writable({
write: function (chunk, encoding, callback) {
//@ts-ignore
if (!this.muted) process.stdout.write(chunk, encoding);
callback();
},
});
export const rl = readline.createInterface({
input: process.stdin,
output: mutableStdout,
terminal: true,
});
export const rlQuestion = (question: string) =>
new Promise<string>((resolve, reject) =>
rl.question(question, (answer) => resolve(answer))
);
export const rlPasword = (question: string) =>
new Promise<string>((resolve, reject) => {
//@ts-ignore
mutableStdout.muted = false;
rl.question(question, (answer) => {
//@ts-ignore
mutableStdout.muted = false;
resolve(answer);
});
//@ts-ignore
mutableStdout.muted = true;
});
export const rlConfirm = (question: string, defaultAnswer = "n") =>
new Promise<boolean>((resolve, reject) => {
const defaultTrue = "y" === defaultAnswer;
const nonDefault = defaultTrue ? "n" : "y";
rl.question(
question + ` (${defaultTrue ? "Y" : "y"}/${!defaultTrue ? "N" : "n"}) `,
(answer) => {
if (answer.toLowerCase() === nonDefault) {
resolve(!defaultTrue);
} else {
resolve(defaultTrue);
}
}
);
});
export const assertConfirm = async (
question: string,
defaultAnswer?: string
) => {
if (await rlConfirm(question, defaultAnswer)) {
return;
} else {
console.log("Nicht bestätigt, beende das Programm.");
process.exit();
}
};
export const selection = async <T>(
text: string,
options: T[],
mapOption: (option: T) => any = (e: T) => e,
allowNone = false
) => {
console.log(text);
options.forEach((option, index) =>
console.log(`${index}) `, mapOption(option))
);
if (allowNone) {
console.log(`${options.length}) Nichts davon.`);
}
let answer = parseInt(await rlQuestion(`Auswahl: `));
while (
isNaN(answer) ||
answer < 0 ||
answer >= (allowNone ? options.length + 1 : options.length)
) {
console.log(
`Diese Antwort ist ungültig. Wähle eine Zahl zwischen 0 und ${
allowNone ? options.length : options.length - 1
}`
);
answer = parseInt(await rlQuestion(`Auswahl: `));
}
return options[answer] || null;
};