1 |
|
2 |
|
3 | const path = require('path')
|
4 | const metadata = require('read-metadata')
|
5 | const validateName = require('validate-npm-package-name')
|
6 | const exists = require('fs').existsSync
|
7 |
|
8 | const getGitUser = require('./git-user')
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | module.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 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 | function 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 |
|
59 |
|
60 |
|
61 |
|
62 |
|
63 |
|
64 |
|
65 | function 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 |
|
84 | function 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 | }
|