1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 | 'use strict'
|
11 |
|
12 | const argx = require('argx')
|
13 | const objnest = require('objnest')
|
14 | const Question = require('./question')
|
15 | const questionInterface = require('./question_interface')
|
16 |
|
17 |
|
18 | async function askconfig (props, options = {}) {
|
19 | const args = argx(arguments)
|
20 | if (args.pop('function')) {
|
21 | throw new Error('Callback is no longer supported. Use promise interface instead.')
|
22 | }
|
23 | props = args.shift()
|
24 | options = args.pop('object') || {}
|
25 |
|
26 | const {msg} = options
|
27 | if (msg) {
|
28 | [].concat(msg).forEach((msg) => {
|
29 | console.log(msg)
|
30 | })
|
31 | }
|
32 |
|
33 | const questions = Object.keys(props).map((key) => {
|
34 | return Question.new({
|
35 | key, default: props[key]
|
36 | })
|
37 | })
|
38 |
|
39 | const qi = questionInterface()
|
40 | const result = {}
|
41 | let i = 0
|
42 | for (const question of questions) {
|
43 | const answer = await new Promise((resolve, reject) =>
|
44 | qi.question(question.query(), (answer) => resolve(answer))
|
45 | )
|
46 | const key = question.key || i
|
47 | i++
|
48 | result[key] = String(answer || question.default).trim()
|
49 | }
|
50 | return new Promise((resolve) => {
|
51 | qi.on('close', () => resolve(objnest.expand(result)))
|
52 | qi.close()
|
53 | })
|
54 | }
|
55 |
|
56 | module.exports = askconfig
|