Skip to content

Commit 8dc7441

Browse files
committed
fix(ui): return correct default value for list prompts
1 parent d110a2a commit 8dc7441

File tree

2 files changed

+53
-4
lines changed

2 files changed

+53
-4
lines changed

lib/ui/index.js

+21-4
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,19 @@ const defaultOptions = {
2525
auto: false
2626
};
2727

28+
function hasDefault(prompt = {}) {
29+
return isObject(prompt) && prompt.hasOwnProperty('default');
30+
}
31+
32+
function getDefault(prompt = {}) {
33+
if (prompt.choices && prompt.choices.length) {
34+
const defaultChoice = prompt.choices[prompt.default];
35+
return isObject(defaultChoice) ? defaultChoice.value : defaultChoice;
36+
}
37+
38+
return prompt.default;
39+
}
40+
2841
/**
2942
* UI class. Handles all interaction with the user via the terminal
3043
*
@@ -136,18 +149,22 @@ class UI {
136149

137150
if (this.auto) {
138151
if (Array.isArray(prompts)) {
139-
const defaultedPrompts = prompts.filter(prompt => Boolean(prompt.default)).reduce(
140-
(obj, prompt) => Object.assign({}, obj, {[prompt.name]: prompt.default}),
152+
const defaultedPrompts = prompts.filter(hasDefault).reduce(
153+
(obj, prompt) => Object.assign({}, obj, {[prompt.name]: getDefault(prompt)}),
141154
{}
142155
);
143-
const promptsToAsk = prompts.filter(prompt => !prompt.default);
156+
const promptsToAsk = prompts.filter(prompt => !hasDefault(prompt));
157+
158+
if (!promptsToAsk.length) {
159+
return Promise.resolve(defaultedPrompts);
160+
}
144161

145162
return this.noSpin(() => this.inquirer(promptsToAsk))
146163
.then(answers => Object.assign(answers, defaultedPrompts));
147164
}
148165

149166
/* istanbul ignore else */
150-
if (isObject(prompts) && prompts.default) {
167+
if (hasDefault(prompts)) {
151168
return Promise.resolve({[prompts.name]: prompts.default});
152169
}
153170
}

test/unit/ui/index-spec.js

+32
Original file line numberDiff line numberDiff line change
@@ -296,6 +296,38 @@ describe('Unit: UI', function () {
296296
});
297297
});
298298

299+
it('returns default if auto is true and prompt type is list/expand', function () {
300+
const ui = new UI();
301+
ui.auto = true;
302+
303+
const prompts = [{
304+
type: 'rawlist',
305+
name: 'a',
306+
choices: ['small', 'medium', 'large'],
307+
default: 2
308+
}, {
309+
type: 'rawlist',
310+
name: 'b',
311+
choices: ['small', 'medium', 'large'],
312+
default: 0
313+
}, {
314+
type: 'expand',
315+
name: 'c',
316+
choices: ['small', 'medium', 'large'],
317+
default: 1
318+
}];
319+
320+
const noSpinStub = sinon.stub(ui, 'noSpin');
321+
return ui.prompt(prompts).then((results) => {
322+
expect(results).to.deep.equal({
323+
a: 'large',
324+
b: 'small',
325+
c: 'medium'
326+
});
327+
expect(noSpinStub.called).to.be.false;
328+
});
329+
});
330+
299331
it('passes options to prompt method', function () {
300332
const ui = new UI();
301333
ui.allowPrompt = true;

0 commit comments

Comments
 (0)