UNPKG

2.85 kBJavaScriptView Raw
1const childProcess = require('child_process')
2const inquirer = require('inquirer')
3const validateName = require('validate-npm-package-name')
4const semver = require('semver')
5const rc = require('rc')
6
7const defaultPrompts = {
8 name: { type: 'input', message: 'name' }
9}
10
11const npmrc = rc('npm', {
12 'init-author-name': '',
13 'init-author-email': '',
14 'init-author-url': '',
15 'init-version': '0.1.0',
16 'init-license': 'MIT'
17})
18
19const setNameValidate = item => {
20 const customValidate = item.validate
21
22 item.validate = input => {
23 const result = validateName(input)
24 if (!result.validForNewPackages) {
25 const messages = (result.errors || []).concat(result.warnings || [])
26 return `Sorry, ${messages.join(' and ')}.`
27 }
28
29 return typeof customValidate !== 'function' ? true : customValidate(input)
30 }
31}
32
33const setVersionValidate = item => {
34 const customValidate = item.validate
35
36 item.validate = input => {
37 const result = semver.valid(input)
38 if (!result) {
39 return `Sorry, The '${input}' is not a semantic version.`
40 }
41
42 return typeof customValidate !== 'function' ? true : customValidate(input)
43 }
44}
45
46const getAuthor = () => {
47 const name = npmrc['init-author-name']
48 const email = npmrc['init-author-email']
49 const url = npmrc['init-author-url']
50 let author = name
51 email && (author += ` <${email}>`)
52 url && (author += ` (${url})`)
53 return author
54}
55
56const getRepository = dir => {
57 // TODO: get repository uri
58 try {
59 return childProcess.execSync(`cd ${dir} && git config --local --get remote.origin.url`).toString().trim()
60 } catch (e) {
61 }
62}
63
64const setDefaults = (dest, exists, name) => item => {
65 switch (item.name) {
66 case 'name':
67 item.default = item.default || name
68 // TODO: need valdate?
69 setNameValidate(item)
70 break
71 case 'author':
72 item.default = item.default || getAuthor()
73 break
74 case 'version':
75 item.default = item.default || npmrc['init-version']
76 setVersionValidate(item)
77 break
78 case 'license':
79 item.default = item.default || npmrc['init-license']
80 break
81 case 'repo':
82 case 'repository':
83 if (exists) item.default = item.default || getRepository(dest)
84 break
85 }
86 return item
87}
88
89/**
90 * Prompt all questions
91 * @param {Object} prompts Prompts
92 * @param {String} dest Destination path
93 * @param {Boolean} exists Destination path exists
94 * @param {String} name Default name
95 * @return {Promise} Prompt promise
96 */
97module.exports = (prompts, dest, exists, name) => {
98 prompts = Object.assign({}, defaultPrompts, prompts)
99
100 const questions = Object.keys(prompts)
101 .map(key => Object.assign({}, prompts[key], { name: key }))
102 .map(setDefaults(dest, exists, name))
103
104 console.log('\n🍭 Press ^C at any time to quit.\n')
105
106 return inquirer.prompt(questions)
107}