-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
397 lines (356 loc) · 10.5 KB
/
index.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
const chalk = require('chalk')
const fs = require('fs-extra')
const path = require('path')
const _ = require('lodash')
const InputPrompt = require('inquirer/lib/prompts/input')
let histories = {}
let historyIndexes = {}
const autoCompleters = {}
let historyFile
let context
let globalConfig
const ELLIPSIS = '…'
let rl
class CommandPrompt extends InputPrompt {
static initHistory(context) {
if (!historyFile && globalConfig && globalConfig.history && globalConfig.history.save) {
const historyFolder = globalConfig.history.folder
fs.ensureDirSync(historyFolder)
historyFile = path.join(historyFolder, 'inquirer-command-prompt-history.json')
if (fs.existsSync(historyFile)) {
const previousHistories = JSON.parse(fs.readFileSync(historyFile))
CommandPrompt.setHistoryFromPreviousSavedHistories(previousHistories)
}
}
if (!histories[context]) {
histories[context] = []
historyIndexes[context] = 0
}
}
static setHistoryFromPreviousSavedHistories(previousHistory) {
try {
histories = previousHistory.histories
for (let c in histories) {
historyIndexes[c] = histories[c].length
}
} catch (e) {
console.error('inquirer-command-promt ERROR: Invalid history file.')
}
}
async initAutoCompletion(context, autoCompletion) {
if (!autoCompleters[context]) {
if (thiz.isAsyncFunc(autoCompletion)) {
autoCompleters[context] = async l => this.asyncAutoCompleter(l, autoCompletion)
} else if (autoCompletion) {
autoCompleters[context] = l => this.autoCompleter(l, autoCompletion)
} else {
autoCompleters[context] = () => []
}
}
}
static addToHistory(context, value) {
thiz.initHistory(context)
if (histories[context][histories[context].length - 1] !== value) {
if (globalConfig && globalConfig.history && (globalConfig.history.blacklist || []).includes(value)) {
return
}
histories[context].push(value)
historyIndexes[context]++
if (historyFile) {
const savedHistory = CommandPrompt.getLimitedHistories(histories)
fs.writeFileSync(historyFile,
JSON.stringify({
histories: savedHistory
}, null, 2)
)
}
}
}
static getLimitedHistories() {
const limitedHistories = _.clone(histories)
const limit = globalConfig.history.limit
if (limit) {
for (let c in limitedHistories) {
const len = limitedHistories[c].length
if (len > limit) {
limitedHistories[c] = limitedHistories[c].slice(len - limit)
}
}
}
return limitedHistories
}
static formatIndex(i) {
let len = globalConfig.history.limit.toString().length
return ' '.repeat(len - `${i}`.length) + i
}
async onKeypress(e) {
if (this.opt.onBeforeKeyPress) {
this.opt.onBeforeKeyPress(e)
}
const rewrite = line => {
if (this.opt.onBeforeRewrite) {
line = this.opt.onBeforeRewrite(line)
}
this.rl.line = line
this.rl.write(null, {ctrl: true, name: 'e'})
}
context = this.opt.context ? this.opt.context : '_default'
thiz.initHistory(context)
await this.initAutoCompletion(context, this.opt.autoCompletion)
/** go up commands history */
if (e.key.name === 'up') {
if (historyIndexes[context] > 0) {
historyIndexes[context]--
rewrite(histories[context][historyIndexes[context]])
}
}
/** go down commands history */
else if (e.key.name === 'down') {
if (histories[context][historyIndexes[context] + 1]) {
historyIndexes[context]++
rewrite(histories[context][historyIndexes[context]])
} else {
rewrite('')
}
}
/** search for command at an autoComplete option
* which can be an array or a function which returns an array
* */
if (e.key.name === 'tab') {
let line = this.rl.line.replace(/^ +/, '').replace(/\t/, '').replace(/ +/g, ' ')
try {
var ac
if (thiz.isAsyncFunc(this.opt.autoCompletion)) {
ac = await autoCompleters[context](line)
} else {
ac = autoCompleters[context](line)
}
if (ac.match) {
rewrite(ac.match)
} else if (ac.matches) {
console.log()
process.stdout.cursorTo(0)
console.log(this.opt.autocompletePrompt || chalk.red('>> ') + chalk.grey('Available commands:'))
console.log(thiz.formatList(
this.opt.short
? (
typeof this.opt.short === 'function'
? this.opt.short(line, ac.matches)
: thiz.short(line, ac.matches)
)
: ac.matches,
this.opt.maxSize,
this.opt.ellipsize,
this.opt.ellipsis
))
rewrite(line)
}
} catch (err) {
console.error(err)
rewrite(line)
}
} else if (e.key.name === 'right' && e.key.shift) {
if (e.key.ctrl) {
let i = parseInt(this.rl.line)
if (!isNaN(i)) {
let history = histories[context]
rewrite(history[i])
} else {
rewrite('')
}
} else {
// shows the history
let history = histories[context]
console.log(chalk.bold('History'))
for (let i = 0; i < history.length; i++) {
console.log(`${chalk.grey(thiz.formatIndex(i))} ${history[i]}`)
}
rewrite('')
}
} else if (e.key.name === 'end' && e.key.ctrl) {
// execute onCtrlEnd if defined
if (globalConfig && typeof globalConfig.onCtrlEnd === 'function') {
rewrite(globalConfig.onCtrlEnd(this.rl.line))
} else {
rewrite('')
}
}
this.render()
}
static short(l, m) {
if (l) {
l = l.replace(/ $/, '')
for (let i = 0; i < m.length; i++) {
if (m[i] === l) {
m.splice(i, 1)
i--
} else {
if (m[i][l.length] === ' ') {
m[i] = m[i].replace(RegExp(l + ' '), '')
} else {
m[i] = m[i].replace(RegExp(l.replace(/ [^ ]+$/, '') + ' '), '')
}
}
}
}
return m
}
static isFunc(func) {
return typeof func === 'function'
}
static isAsyncFunc(func) {
return thiz.isFunc(func) && func.constructor.name === 'AsyncFunction'
}
async asyncAutoCompleter(line, cmds) {
cmds = await cmds(line)
return this.autoCompleterFormatter(line, cmds)
}
autoCompleter(line, cmds) {
if (typeof cmds === 'function') {
cmds = cmds(line)
}
return this.autoCompleterFormatter(line, cmds)
}
autoCompleterFormatter(line, cmds) {
let max = 0
// first element in cmds can be an object with special instructions
let options = {
filter: str => str
}
if (typeof cmds[0] === 'object') {
const f = cmds[0].filter
if (typeof f === 'function') {
options.filter = f
}
cmds = cmds.slice(1)
}
cmds = cmds.reduce((sum, el) => {
let sanitizedLine = line.replace(/[\\\.\+\*\?\^\$\[\]\(\)\{\}\/\'\#\:\!\=\|]/ig, "\\$&")
RegExp(`^${sanitizedLine}`).test(el) && sum.push(el) && (max = Math.max(max, el.length))
return sum
}, [])
if (cmds.length > 1) {
let commonStr = ''
LOOP: for (let i = line.length; i < max; i++) {
let c = null
for (let l of cmds) {
if (!l[i]) {
break LOOP
} else if (!c) {
c = l[i]
} else if (c !== l[i]) {
break LOOP
}
}
commonStr += c
}
if (commonStr) {
return {match: options.filter(line + commonStr)}
} else {
return {matches: cmds}
}
} else if (cmds.length === 1) {
return {match: options.filter(cmds[0])}
} else {
return {match: options.filter(line)}
}
}
run() {
return new Promise(function (resolve) {
this._run(function (value) {
thiz.addToHistory(context, value)
historyIndexes[context] = histories[context].length
resolve(value)
})
}.bind(this))
}
static formatList(elems, maxSize = 32, ellipsized, ellipsis) {
const cols = process.stdout.columns
let ratio = Math.floor((cols - 1) / maxSize)
let remainder = (cols - 1) % maxSize
maxSize += Math.floor(remainder / ratio)
let max = 0
for (let elem of elems) {
max = Math.max(max, elem.length + 4)
}
if (ellipsized && max > maxSize) {
max = maxSize
}
let columns = (cols / max) | 0
let str = ''
let c = 1
for (let elem of elems) {
str += thiz.setSpaces(elem, max, ellipsized, ellipsis)
if (c === columns) {
str += ' '.repeat(cols - max * columns)
c = 1
} else {
c++
}
}
return str
}
static setSpaces(str, len, ellipsized, ellipsis) {
if (ellipsized && str.length > len - 1) {
str = thiz.ellipsize(str, len - 1, ellipsis)
}
return str + ' '.repeat(len - thiz.decolorize(str).length)
}
static ellipsize(str, len, ellipsis = ELLIPSIS) {
if (str.length > len) {
let l = thiz.decolorize(ellipsis).length + 1
return str.substring(0, len - l) + ellipsis
}
}
static decolorize(str) {
return str.replace(/\x1b\[[0-9;]*m/g, '')
}
static setConfig(config) {
if (typeof config === 'object') {
globalConfig = config
}
}
static getRl() {
return rl
}
static getHistory(context) {
if (!context) {
context = '_default'
}
return histories[`${context}`]
}
static getHistories(useLimit) {
return {
histories: useLimit ? CommandPrompt.getLimitedHistories() : histories
}
}
render(error) {
rl = this.rl
let bottomContent = ''
let appendContent = ''
let message = this.getQuestion()
let transformer = this.opt.transformer
let isFinal = this.status === 'answered'
if (isFinal) {
appendContent = this.answer
} else {
appendContent = this.rl.line
}
if (transformer) {
message += transformer(appendContent, this.answers, {isFinal})
} else {
message += isFinal && !this.opt.noColorOnAnswered ? chalk[this.opt.colorOnAnswered || 'cyan'](appendContent) : appendContent
}
if (error) {
bottomContent = chalk.red('>> ') + error
}
this.screen.render(message, bottomContent)
}
close() {
if (typeof this.opt.onClose === 'function') {
this.opt.onClose()
}
}
}
let thiz = CommandPrompt
module.exports = CommandPrompt