UNPKG

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