jiuye-cli
Version:
A simple CLI for scaffolding Jiuye projects.
216 lines (196 loc) • 5.67 kB
JavaScript
#!/usr/bin/env node
const download = require('download-git-repo')
const program = require('commander')
const exists = require('fs').existsSync
const path = require('path')
const ora = require('ora')
const home = require('user-home')
const tildify = require('tildify')
const chalk = require('chalk')
const inquirer = require('inquirer')
const rimraf = require('rimraf').sync // 删除文件
const logger = require('../lib/logger')
const generate = require('../lib/generate')
const checkVersion = require('../lib/check-version')
const localPath = require('../lib/local-path')
const {
PC_TEMPLATE,
PC_TEMPLATE3,
MOBILE_H5_TEMPLATE,
WECHAT_TEMPLATE
} = require('../config')
const isLocalPath = localPath.isLocalPath
const getTemplatePath = localPath.getTemplatePath
/**
* Usage.
*/
program
.usage('<template-name> [project-name]')
.option('-c, --clone', 'use git clone')
.option('--offline', 'use cached template')
/**
* Help
*/
program.on('--help', () => {
console.log(' Examples:')
console.log()
console.log(
chalk.gray(' # create a new project with an official template')
)
console.log(' $ vue init webpack my-project')
console.log()
console.log(
chalk.gray(' # create a new project straight from a github template')
)
console.log(' $ vue init username/repo my-project')
console.log()
})
/**
* Help.
*/
function help () {
program.parse(process.argv)
if (program.args.length < 1) return program.help()
}
help()
/**
* Settings.
*/
let gitTemplateUrl
let template = program.args[0] // 模板参数
const hasSlash = template.indexOf('/') > -1
const rawName = program.args[1]
const inPlace = !rawName || rawName === '.'
const name = inPlace ? path.relative('../', process.cwd()) : rawName
const to = path.resolve(rawName || '.') // 转化为绝对路径
const clone = program.clone || true
const tmp = path.join(home, '.vue-templates', template.replace(/[\/:]/g, '-'))
if (program.offline) {
console.log(`> Use cached template at ${chalk.yellow(tildify(tmp))}`)
template = tmp
}
process.on('exit', () => {
console.log('-----exit-----')
})
inquirer
.prompt([
{
type: 'list',
message: '请选择项目生成终端',
name: 'terminal',
choices: ['PC', 'PC3', 'MobileH5', 'Wechat', 'No'],
filter: function (val) {
return val.toLowerCase()
}
}
])
.then(answers => {
if (answers.terminal === 'pc') {
gitTemplateUrl = PC_TEMPLATE
createTemplate()
} else if (answers.terminal === 'pc3') {
gitTemplateUrl = PC_TEMPLATE3
createTemplate()
} else if (answers.terminal === 'mobileh5') {
gitTemplateUrl = MOBILE_H5_TEMPLATE
createTemplate()
} else if (answers.terminal === 'wechat') {
gitTemplateUrl = WECHAT_TEMPLATE
createTemplate()
}
})
.catch(logger.fatal)
function createTemplate () {
if (inPlace || exists(to)) {
console.log(inPlace, exists(to), to)
inquirer
.prompt([
{
type: 'confirm',
message: inPlace ? '在当前目录中生成项目?' : '目标目录的存在。继续?',
name: 'ok'
}
])
.then(answers => {
console.log(chalk.yellow('在当前目录中生成项目'))
if (answers.ok) {
run()
}
})
.catch(logger.fatal)
} else {
run()
}
}
/**
* Check, download and generate the project.
*/
function run () {
if (isLocalPath(template)) {
// 检查模板是否是本地的
const templatePath = getTemplatePath(template) // 获取绝对路径
if (exists(templatePath)) {
// 判断模板所在路径是否存在
// 渲染模板
generate(name, templatePath, to, err => {
if (err) logger.fatal(err)
logger.success('Generated "%s".', name)
})
} else {
// 打印错误日志,提示本地模板不存在
logger.fatal('Local template "%s" not found.', template)
}
} else {
checkVersion(() => {
// 检查版本号
if (!hasSlash) {
// 官方模板还是第三方模板
const officialTemplate = gitTemplateUrl
downloadAndGenerate(officialTemplate) // 下载模板
} else {
downloadAndGenerate(template) // 下载模板
}
})
}
}
/**
* 下载generate
*
* @param {String} template
*/
function downloadAndGenerate (template) {
const spinner = ora('downloading jiuye template...')
console.log(chalk.yellow('template: ' + template))
spinner.start() // 显示加载状态
if (exists(tmp)) rimraf(tmp) // 当前模板库是否存在该模板,存在就删除
// 下载模板 template-模板名 tmp- 模板路径 clone-是否采用git clone模板 err-错误短信
download(
template,
tmp,
{
clone
},
err => {
// 隐藏加载状态
spinner.stop()
// 如果有错误,打印错误日志
if (err) {
logger.fatal(
'Failed to download repo ' + template + ': ' + err.message.trim()
)
}
// 渲染模板
generate(name, tmp, to, err => {
if (err) {
console.log(
chalk.red('-----------------error-start-----------------')
)
console.log(chalk.red(err))
console.log(chalk.red('-----------------error-end-----------------'))
}
console.log()
logger.success('Generated "%s".', name)
})
}
)
}