UNPKG

2.01 kBJavaScriptView Raw
1// Adapted from Vue CLI v2 "init" command
2
3const path = require('path')
4const metadata = require('read-metadata')
5const validateName = require('validate-npm-package-name')
6const exists = require('fs').existsSync
7
8const getGitUser = require('./git-user')
9
10/**
11 * Read prompts metadata.
12 *
13 * @param {String} dir
14 * @return {Object}
15 */
16
17module.exports = function options (name, dir) {
18 const opts = getMetadata(dir)
19
20 setDefault(opts, 'name', name)
21 setValidateName(opts)
22
23 const author = getGitUser()
24 if (author) {
25 setDefault(opts, 'author', author)
26 }
27
28 return opts
29}
30
31/**
32 * Gets the metadata from either a meta.json or meta.js file.
33 *
34 * @param {String} dir
35 * @return {Object}
36 */
37
38function getMetadata (dir) {
39 const json = path.join(dir, 'meta.json')
40 const js = path.join(dir, 'meta.js')
41 let opts = {}
42
43 if (exists(json)) {
44 opts = metadata.sync(json)
45 }
46 else if (exists(js)) {
47 const req = require(path.resolve(js))
48 if (req !== Object(req)) {
49 throw new Error('meta.js needs to expose an object')
50 }
51 opts = req
52 }
53
54 return opts
55}
56
57/**
58 * Set the default value for a prompt question
59 *
60 * @param {Object} opts
61 * @param {String} key
62 * @param {String} val
63 */
64
65function setDefault (opts, key, val) {
66 if (opts.schema) {
67 opts.prompts = opts.schema
68 delete opts.schema
69 }
70
71 const prompts = opts.prompts || (opts.prompts = {})
72
73 if (!prompts[key] || typeof prompts[key] !== 'object') {
74 prompts[key] = {
75 'type': 'string',
76 'default': val
77 }
78 }
79 else {
80 prompts[key]['default'] = val
81 }
82}
83
84function setValidateName (opts) {
85 const
86 name = opts.prompts.name;
87 const customValidate = name.validate
88
89 name.validate = name => {
90 const its = validateName(name)
91
92 if (!its.validForNewPackages) {
93 const errors = (its.errors || []).concat(its.warnings || [])
94 return 'Sorry, ' + errors.join(' and ') + '.'
95 }
96
97 return typeof customValidate === 'function'
98 ? customValidate(name)
99 : true
100 }
101}