Skip to content

Commit

Permalink
support conditional prompts
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed Apr 8, 2016
1 parent 4a94053 commit 1ee27c2
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 11 deletions.
5 changes: 5 additions & 0 deletions lib/ask.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
var async = require('async')
var inquirer = require('inquirer')
var evaluate = require('./eval')

// Support types from prompt-for which was used before
var promptMapping = {
Expand Down Expand Up @@ -31,6 +32,10 @@ module.exports = function ask (schema, data, done) {
*/

function prompt (data, key, prompt, done) {
// skip prompts whose when condition is not met
if (prompt.when && !evaluate(prompt.when, data)) {
return done()
}
inquirer.prompt([{
type: promptMapping[prompt.type] || prompt.type,
name: key,
Expand Down
14 changes: 14 additions & 0 deletions lib/eval.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/**
* Evaluate an expression in meta.json in the context of
* prompt answers data.
*/

module.exports = function evalualte (exp, data) {
/* eslint-disable no-new-func */
var fn = new Function('data', 'with (data) { return ' + exp + '}')
try {
return fn(data)
} catch (e) {
console.error(chalk.red('Error when evaluating filter condition: ' + exp))
}
}
13 changes: 2 additions & 11 deletions lib/filter.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
var match = require('minimatch')
var chalk = require('chalk')
var evaluate = require('./eval')

module.exports = function (files, filters, data, done) {
if (!filters) {
Expand All @@ -10,21 +11,11 @@ module.exports = function (files, filters, data, done) {
fileNames.forEach(function (file) {
if (match(file, glob)) {
var condition = filters[glob]
if (!evalualte(condition, data)) {
if (!evaluate(condition, data)) {
delete files[file]
}
}
})
})
done()
}

function evalualte (exp, data) {
/* eslint-disable no-new-func */
var fn = new Function('data', 'with (data) { return ' + exp + '}')
try {
return fn(data)
} catch (e) {
console.error(chalk.red('Error when evaluating filter condition: ' + exp))
}
}

0 comments on commit 1ee27c2

Please sign in to comment.