-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·56 lines (50 loc) · 1.56 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/usr/bin/env node
'use strict'
const { resolve } = require('path')
const { readFileSync, writeFileSync } = require('fs')
const inquirer = require('inquirer')
const userHome = require('user-home')
require('yargs')
.command('* [choices] [answer]', 'run the quiz described in choices.txt', (yargs) => {
yargs
.positional('choices', {
describe: 'where should we read the quiz file from?',
default: resolve(userHome, './.quiz/choices.txt')
})
.positional('answer', {
describe: 'where should the answer.txt be output?',
default: resolve(userHome, './.quiz/answer.txt')
})
}, async argv => {
try {
const choicesText = readFileSync(argv.choices, 'utf8').trim()
const choices = choicesText.split('\n')
if (choices.length < 2) {
console.error(`${argv.choices} must contain a question and at least one choice`)
process.exit(1)
}
const answer = await runQuiz(choicesText.split('\n'))
writeFileSync(argv.answer, answer.selection)
if (argv.exitMessage) console.info(argv.exitMessage)
} catch (err) {
if (err.code === 'ENOENT') {
console.error(`could not find ${argv.choices}`)
} else {
throw err
}
}
})
.option('exit-message', {
describe: 'optional message to output when exiting'
})
.parse()
async function runQuiz (choices) {
const question = choices.shift()
const prompt = inquirer.createPromptModule()
return prompt({
name: 'selection',
message: question,
choices: choices,
type: 'list'
})
}