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