1 | const async = require('async')
|
2 | const inquirer = require('inquirer')
|
3 | const evaluate = require('./eval')
|
4 |
|
5 |
|
6 | const promptMapping = {
|
7 | string: 'input',
|
8 | boolean: 'confirm'
|
9 | }
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 | module.exports = function ask (prompts, data, done) {
|
20 | async.eachSeries(Object.keys(prompts), (key, next) => {
|
21 | prompt(data, key, prompts[key], next)
|
22 | }, done)
|
23 | }
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 | function prompt (data, key, prompt, done) {
|
35 |
|
36 | if (prompt.when && !evaluate(prompt.when, data)) {
|
37 | return done()
|
38 | }
|
39 |
|
40 | let promptDefault = prompt.default
|
41 | if (typeof prompt.default === 'function') {
|
42 | promptDefault = function () {
|
43 | return prompt.default.bind(this)(data)
|
44 | }
|
45 | }
|
46 |
|
47 | inquirer.prompt([{
|
48 | type: promptMapping[prompt.type] || prompt.type,
|
49 | name: key,
|
50 | message: prompt.message || prompt.label || key,
|
51 | default: promptDefault,
|
52 | choices: prompt.choices || [],
|
53 | validate: prompt.validate || (() => true)
|
54 | }]).then(answers => {
|
55 | if (Array.isArray(answers[key])) {
|
56 | data[key] = {}
|
57 | answers[key].forEach(multiChoiceAnswer => {
|
58 | data[key][multiChoiceAnswer] = true
|
59 | })
|
60 | } else if (typeof answers[key] === 'string') {
|
61 | data[key] = answers[key].replace(/"/g, '\\"')
|
62 | } else {
|
63 | data[key] = answers[key]
|
64 | }
|
65 | done()
|
66 | }).catch(done)
|
67 | }
|