UNPKG

jiuye-cli

Version:

A simple CLI for scaffolding Jiuye projects.

93 lines (80 loc) 2.5 kB
const path = require('path') const metadata = require('read-metadata') // 用于读取json或者yaml元数据文件并返回一个对象 const exists = require('fs').existsSync // node自带fs模块的existsSync方法,用于检测路径是否存在 const getGitUser = require('./git-user') // 获取本地的git配置 const validateName = require('validate-npm-package-name') // 用于npm包的名字是否是合法的 /** * Read prompts metadata. * * @param {String} dir * @return {Object} */ module.exports = function options (name, dir) { const opts = getMetadata(dir) // 获取json数据 setDefault(opts, 'name', name) // 设置默认值 setValidateName(opts) // 用于检测配置对象中name字段是否合法 const author = getGitUser() if (author) { setDefault(opts, 'author', author) } return opts } /** * Gets the metadata from either a meta.json or meta.js file. * * @param {String} dir * @return {Object} */ // 获取meta.js或则meta.json中的配置信息 function getMetadata (dir) { const json = path.join(dir, 'meta.json') const js = path.join(dir, 'meta.js') let opts = {} if (exists(json)) { opts = metadata.sync(json) } else if (exists(js)) { const req = require(path.resolve(js)) if (req !== Object(req)) { throw new Error('meta.js needs to expose an object') } opts = req } return opts } /** * Set the default value for a prompt question * * @param {Object} opts * @param {String} key * @param {String} val */ // 用于向配置对象中添加一下默认字段 function setDefault (opts, key, val) { if (opts.schema) { opts.prompts = opts.schema delete opts.schema } const prompts = opts.prompts || (opts.prompts = {}) if (!prompts[key] || typeof prompts[key] !== 'object') { prompts[key] = { type: 'string', default: val } } else { prompts[key]['default'] = val } } // 用于检测配置对象中name字段是否合法 function setValidateName (opts) { const name = opts.prompts.name const customValidate = name.validate name.validate = name => { const its = validateName(name) if (!its.validForNewPackages) { const errors = (its.errors || []).concat(its.warnings || []) return 'Sorry, ' + errors.join(' and ') + '.' } if (typeof customValidate === 'function') return customValidate(name) return true } }