@hz-lib/hz-build-cli
Version:
hz-build-cli 脚手架
127 lines (104 loc) • 3.6 kB
JavaScript
/*
* @Author: your name
* @Date: 2021-10-21 10:06:45
* @LastEditTime: 2021-10-22 14:13:09
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: \cli\hz-cli\lib\Generator.js
*/
// lib/Generator.js
const path = require('path')
const { getRepoList, getTagList } = require('./http')
const inquirer = require('inquirer')
const util = require('util')
const chalk = require('chalk')
const downloadGitRepo = require('download-git-repo') // 不支持 Promise
const cmd = require('./cmd')
const { wrapLoading } = require('./util')
class Generator {
constructor (name, targetDir){
// 目录名称
this.name = name;
// 创建位置
this.targetDir = targetDir;
// 对 download-git-repo 进行 promise 化改造
this.downloadGitRepo = util.promisify(downloadGitRepo);
}
// 下载远程模板
// 1)拼接下载地址
// 2)调用下载方法
async download(repo, tag){
// 1)拼接下载地址
// const requestUrl = `${repo}${tag?'#'+tag:''}`;
const requestUrl = `hz-bulid/${repo}`;
// 2)调用下载方法
await wrapLoading(
this.downloadGitRepo, // 远程下载方法
'waiting download template', // 加载提示信息
requestUrl, // 参数1: 下载地址
path.resolve(process.cwd(), this.targetDir)) // 参数2: 创建位置
}
// 核心创建逻辑
// 1)获取模板名称
// 2)获取 tag 名称
// 3)下载模板到模板目录
// 4)下载依赖
async create(){
// 1)获取模板名称
const repo = await this.getRepo()
// 2) 获取 tag 名称
// const tag = await this.getTag(repo)
// 3)下载模板到模板目录
await this.download(repo)
// 4)下载依赖
await this.dowDependency()
return true;
}
// 下载依赖
async dowDependency(){
console.log(`> 正在自动安装依赖,请稍等...`);
console.log('');
await cmd(this.targetDir,'inherit', 'npm', ['install'])
}
// 获取用户选择的模板
// 1)从远程拉取模板数据
// 2)用户选择自己新下载的模板名称
// 3)return 用户选择的名称
async getRepo() {
// 1)从远程拉取模板数据
const repoList = await wrapLoading(getRepoList, 'waiting fetch template');
if (!repoList) return;
// 过滤我们需要的模板名称
const repos = repoList.map(item => item.name);
// 2)用户选择自己新下载的模板名称
const { repo } = await inquirer.prompt({
name: 'repo',
type: 'list',
choices: repos,
message: '请选择要创建项目的模板'
})
// 3)return 用户选择的名称
return repo;
}
// 获取用户选择的版本
// 1)基于 repo 结果,远程拉取对应的 tag 列表
// 2)用户选择自己需要下载的 tag
// 3)return 用户选择的 tag
async getTag(repo) {
// 1)基于 repo 结果,远程拉取对应的 tag 列表
const tags = await wrapLoading(getTagList, 'waiting fetch tag', repo);
if (!tags) return;
// 过滤我们需要的 tag 名称
const tagsList = tags.map(item => item.name);
// 2)用户选择自己需要下载的 tag
const { tag } = await inquirer.prompt({
name: 'tag',
type: 'list',
choices: tagsList,
message: '请选择需要安装的版本'
})
// 3)return 用户选择的 tag
return tag
}
}
module.exports = Generator;