Skip to content

Commit 1ee27c2

Browse files
committed
support conditional prompts
1 parent 4a94053 commit 1ee27c2

File tree

3 files changed

+21
-11
lines changed

3 files changed

+21
-11
lines changed

lib/ask.js

+5
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
var async = require('async')
22
var inquirer = require('inquirer')
3+
var evaluate = require('./eval')
34

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

3334
function prompt (data, key, prompt, done) {
35+
// skip prompts whose when condition is not met
36+
if (prompt.when && !evaluate(prompt.when, data)) {
37+
return done()
38+
}
3439
inquirer.prompt([{
3540
type: promptMapping[prompt.type] || prompt.type,
3641
name: key,

lib/eval.js

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
/**
2+
* Evaluate an expression in meta.json in the context of
3+
* prompt answers data.
4+
*/
5+
6+
module.exports = function evalualte (exp, data) {
7+
/* eslint-disable no-new-func */
8+
var fn = new Function('data', 'with (data) { return ' + exp + '}')
9+
try {
10+
return fn(data)
11+
} catch (e) {
12+
console.error(chalk.red('Error when evaluating filter condition: ' + exp))
13+
}
14+
}

lib/filter.js

+2-11
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
var match = require('minimatch')
22
var chalk = require('chalk')
3+
var evaluate = require('./eval')
34

45
module.exports = function (files, filters, data, done) {
56
if (!filters) {
@@ -10,21 +11,11 @@ module.exports = function (files, filters, data, done) {
1011
fileNames.forEach(function (file) {
1112
if (match(file, glob)) {
1213
var condition = filters[glob]
13-
if (!evalualte(condition, data)) {
14+
if (!evaluate(condition, data)) {
1415
delete files[file]
1516
}
1617
}
1718
})
1819
})
1920
done()
2021
}
21-
22-
function evalualte (exp, data) {
23-
/* eslint-disable no-new-func */
24-
var fn = new Function('data', 'with (data) { return ' + exp + '}')
25-
try {
26-
return fn(data)
27-
} catch (e) {
28-
console.error(chalk.red('Error when evaluating filter condition: ' + exp))
29-
}
30-
}

0 commit comments

Comments
 (0)