forked from NativeScript/nativescript-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprompter.ts
229 lines (199 loc) · 5.67 KB
/
prompter.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
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
import * as prompt from "prompts";
import * as helpers from "./helpers";
import * as readline from "readline";
import { ReadStream } from "tty";
import {
IAllowEmpty,
IPrompterAnswers,
IPrompterOptions,
IPrompterQuestion,
} from "./declarations";
import { injector } from "./yok";
const MuteStream = require("mute-stream");
import * as _ from "lodash";
export class Prompter implements IPrompter {
private ctrlcReader: readline.ReadLine;
private muteStreamInstance: any = null;
public dispose() {
if (this.ctrlcReader) {
this.ctrlcReader.close();
}
}
public async get(questions: IPrompterQuestion[]): Promise<any> {
try {
this.muteStdout();
if (!helpers.isInteractive()) {
if (_.some(questions, (s) => !s.default)) {
throw new Error(
"Console is not interactive and no default action specified."
);
} else {
const result: any = {};
_.each(questions, (s) => {
// Curly brackets needed because s.default() may return false and break the loop
result[s.name] = s.default();
});
return result;
}
} else {
const result = await prompt.prompt(questions);
return result;
}
} finally {
this.unmuteStdout();
}
}
public async getPassword(
message: string,
options?: IAllowEmpty
): Promise<string> {
const schema: IPrompterQuestion = {
message,
type: "password",
name: "password",
validate: (value: any) => {
const allowEmpty = options && options.allowEmpty;
return !allowEmpty && !value ? "Password must be non-empty" : true;
},
};
const result = await this.get([schema]);
return result.password;
}
public async getString(
message: string,
options?: IPrompterOptions
): Promise<string> {
const schema: IPrompterQuestion = {
message,
type: "text",
name: "inputString",
validate: (value: any) => {
const doesNotAllowEmpty =
options && _.has(options, "allowEmpty") && !options.allowEmpty;
return doesNotAllowEmpty && !value
? `${message} must be non-empty`
: true;
},
default: options && options.defaultAction,
};
const result = await this.get([schema]);
return result.inputString;
}
public async promptForChoice(
promptMessage: string,
choices: string[]
): Promise<string> {
const schema: IPrompterAnswers = {
message: promptMessage,
type: "select",
name: "userAnswer",
choices,
};
const result = await this.get([schema]);
return choices[result.userAnswer];
}
public async promptForDetailedChoice(
promptMessage: string,
choices: { key: string; description: string }[]
): Promise<string> {
const inquirerChoices = choices.map((choice) => {
return {
title: choice.key,
value: choice.key,
description: choice.description,
};
});
const schema: any = {
message: promptMessage,
type: "select",
name: "userAnswer",
choices: inquirerChoices,
};
const result = await this.get([schema]);
return result.userAnswer;
}
public async confirm(
message: string,
defaultAction?: () => boolean
): Promise<boolean> {
const schema = {
type: "confirm",
name: "prompt",
default: defaultAction,
message,
};
const result = await this.get([schema]);
return result.prompt;
}
private muteStdout(): void {
if (helpers.isInteractive()) {
(<ReadStream>process.stdin).setRawMode(true); // After setting rawMode to true, Ctrl+C doesn't work for non node.js events loop i.e device log command
// We need to create mute-stream and to pass it as output to ctrlcReader
// This will prevent the prompter to show the user's text twice on the console
this.muteStreamInstance = new MuteStream();
this.muteStreamInstance.pipe(process.stdout);
this.muteStreamInstance.mute();
this.ctrlcReader = readline.createInterface(<any>{
input: process.stdin,
output: this.muteStreamInstance,
});
this.ctrlcReader.on("SIGINT", process.exit);
}
}
private unmuteStdout(): void {
if (helpers.isInteractive()) {
(<ReadStream>process.stdin).setRawMode(false);
if (this.muteStreamInstance) {
// We need to clean the event listeners from the process.stdout because the MuteStream.pipe function calls the pipe function of the Node js Stream which adds event listeners and this can cause memory leak if we display more than ~10 prompts.
this.cleanEventListeners(process.stdout);
this.muteStreamInstance.unmute();
this.muteStreamInstance = null;
this.dispose();
}
}
}
private cleanEventListeners(stream: NodeJS.WritableStream): void {
// The events names and listeners names can be found here https://github.com/nodejs/node/blob/master/lib/stream.js
// Which event cause memory leak can be tested with stream.listeners("event-name") and if the listeners count keeps increasing with each prompt we need to remove the listener.
const memoryLeakEvents: IMemoryLeakEvent[] = [
{
eventName: "close",
listenerName: "cleanup",
},
{
eventName: "error",
listenerName: "onerror",
},
{
eventName: "drain",
listenerName: "ondrain",
},
];
_.each(memoryLeakEvents, (memoryleakEvent: IMemoryLeakEvent) =>
this.cleanListener(
stream,
memoryleakEvent.eventName,
memoryleakEvent.listenerName
)
);
}
private cleanListener(
stream: NodeJS.WritableStream,
eventName: string,
listenerName: string
): void {
const eventListeners: any[] = process.stdout.listeners(eventName);
const listenerFunction: (...args: any[]) => void = _.find(
eventListeners,
(func: any) => func.name === listenerName
);
if (listenerFunction) {
stream.removeListener(eventName, listenerFunction);
}
}
}
interface IMemoryLeakEvent {
eventName: string;
listenerName: string;
}
injector.register("prompter", Prompter);