From fcaf7ab43691731b241554ee091f9fa26973f2ca Mon Sep 17 00:00:00 2001 From: Marvin Date: Sat, 4 Jun 2022 17:37:18 +0800 Subject: [PATCH 1/2] =?UTF-8?q?refactor:core=E3=80=81ui?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/cli/lib/init-web-component.js | 141 ++++++++++++++++++ packages/web-core-cli/src/cli/lib/init.js | 141 ++++++++++++++++++ packages/web-core-cli/src/cli/lib/install.js | 37 +++++ packages/web-core-cli/src/cli/lib/list.js | 32 ++++ packages/web-core-cli/src/cli/lib/update.js | 75 ++++++++++ 5 files changed, 426 insertions(+) create mode 100644 packages/web-core-cli/src/cli/lib/init-web-component.js create mode 100644 packages/web-core-cli/src/cli/lib/init.js create mode 100644 packages/web-core-cli/src/cli/lib/install.js create mode 100644 packages/web-core-cli/src/cli/lib/list.js create mode 100644 packages/web-core-cli/src/cli/lib/update.js diff --git a/packages/web-core-cli/src/cli/lib/init-web-component.js b/packages/web-core-cli/src/cli/lib/init-web-component.js new file mode 100644 index 00000000..466f4628 --- /dev/null +++ b/packages/web-core-cli/src/cli/lib/init-web-component.js @@ -0,0 +1,141 @@ +const path = require("path"); +const join = path.join; +const basename = path.basename; +const fs = require("fs"); +const vfs = require("vinyl-fs"); +const renameSync = fs.renameSync; +const existsSync = fs.existsSync; +const chalk = require("chalk"); +const through = require("through2"); +const emptyDir = require("empty-dir"); +const info = require("../utils/logger").info; +const error = require("../utils/logger").error; +const success = require("../utils/logger").success; +const isCnFun = require("../utils/utils").isCnFuc; +const isSafeToCreateProjectIn = require("../utils/utils").isSafeToCreateProjectIn; + +function init(args) { + const tCli = chalk.bold.cyan("t-cli"); + const isCn = isCnFun(args.language); + const customPrjName = args.project || ""; + const tpl = join(__dirname, "../template/webComponent"); + const dest = join(process.cwd(), customPrjName); + const componentName = basename(dest); + const mirror = args.mirror; + + console.log(); + console.log(tCli + (!isCn ? " is booting... " : " 正在启动...")); + console.log( + tCli + + (!isCn ? " will execute init command... " : " 即将执行 init 命令...") + ); + if (existsSync(dest) && !emptyDir.sync(dest)) { + if (!isSafeToCreateProjectIn(dest, componentName)) { + process.exit(1); + } + } + + createApp(); + + function createApp() { + console.log(); + console.log( + chalk.bold.cyan("T-Cli") + + (!isCn + ? " will creating a new app in " + : " 即将创建一个新的应用在 ") + + dest + ); + + vfs + .src(["**/*", "!node_modules/**/*"], { + cwd: tpl, + cwdbase: true, + dot: true, + }) + .pipe(template(dest, tpl)) + .pipe(vfs.dest(dest)) + .on("end", function () { + try { + // rename gitignore file as .gitignore if `gitignore` exist + // (this was actually exist in app-ts-old) + if (existsSync(join(dest, "gitignore"))) { + info("Rename", "gitignore -> .gitignore"); + renameSync(join(dest, "gitignore"), join(dest, ".gitignore")); + } + + if (existsSync(join(dest, "package.json"))) { + + replaceSync(join(dest, "package.json"), { + files_to_be_replace: 'files', + counter_to_be_replace: componentName, + }); + } + + if (customPrjName) { + try { + process.chdir(customPrjName); + } catch (err) { + console.log(error(err)); + } + } + info( + "Install", + "We will install dependencies, if you refuse, press ctrl+c to abort, and install dependencies by yourself. :>" + ); + console.log(); + // require("./install")(mirror, done); + done() + } catch (e) { + console.log(error(e)); + } + }) + .resume(); + } + + function replaceSync(file, map) { + let contents = fs.readFileSync(file).toString(); + Object.keys(map).forEach(fromKey => { + contents = contents.replace(fromKey, map[fromKey]); + fs.writeFileSync(file, contents); + }) + } + + function done() { + success(`Congratulation! "${componentName}" has been created successfully! `); + console.log(); + console.log(); + + console.log("Change directory command:"); + success(`cd ${componentName}`); + console.log(); + console.log(); + + console.log("install:"); + success(`npm install`); + console.log(); + console.log(); + console.log("Development command:"); + success("npm run dev:package"); + console.log(); + console.log(); + console.log("Release command:"); + success("npm run build:package"); + console.log(); + console.log(); + } +} + +function template(dest, cwd) { + return through.obj(function (file, enc, cb) { + if (!file.stat.isFile()) { + return cb(); + } + + info("Copy", file.path.replace(cwd + "/", "")); + this.push(file); + cb(); + }); +} + +module.exports = init; diff --git a/packages/web-core-cli/src/cli/lib/init.js b/packages/web-core-cli/src/cli/lib/init.js new file mode 100644 index 00000000..af47a9ca --- /dev/null +++ b/packages/web-core-cli/src/cli/lib/init.js @@ -0,0 +1,141 @@ +const templateList = require('../config/template.json').templateList; +const categoryList = require('../config/category.json').categoryList; +const log = require('../utils/log'); +const inquirer = require('inquirer'); +const fs = require("fs"); +const ora = require('ora'); +const downloadFile = require("../utils/download"); +const template = 'template'; +const category = 'category'; +const isTest = process.env.NODE_ENV; +/** + * 初始化工程模板 + * @param pluginToAdd + * @param options + * @param context + * @returns {Promise} + */ +async function init (pluginToAdd, options = {}, context = process.cwd()) { + let projectCategory = options[category] + let projectTemplate = options[template] + let projectName = pluginToAdd; + if (!options.hasOwnProperty(category)){ + projectCategory = await selectCategory() + } + if (!options.hasOwnProperty(template)){ + projectTemplate = await selectTemplate(projectCategory) + } + const templateInfo = templateList.find((item) => item.type === projectCategory && item.name === projectTemplate); + if (!templateInfo) { + return log('WARING', 'no template'); + } + const {url} = templateInfo; + const packageInfo = await getUserInputPackageMessage(projectName); + const downloadSpinner = ora({ text: 'start download template...', color: 'blue'}).start(); + const {dir, name, flag} = await downloadFile(url[0], projectName, context) + if (flag) { + downloadSpinner.succeed('download success'); + const editConfigSpinner = ora({ text: 'start edit config...', color: 'blue'}).start(); + // 下载完成后修改配置信息 + const successFlag = await downloadSuccess(dir, name, packageInfo); + if (successFlag) { + editConfigSpinner.succeed('create success'); + }else { + editConfigSpinner.fail('create fail'); + } + } else { + downloadSpinner.fail('download fail'); + } +} + +/** + * 选择工程类型 + * @returns {Promise} + */ +async function selectCategory() { + return new Promise(resolve => { + inquirer.prompt([ + { type: 'list', message: 'please select category:', name: category, choices: categoryList } + ]).then((answers) => { + console.log(answers); + resolve(answers[category]) + }) + }) +} + +/** + * 选择工程模板名称 + * @returns {Promise} + */ +async function selectTemplate(projectCategory) { + try { + const list = templateList.filter(item => item.type === projectCategory).map((item) => item.name) + if (!list.length || !list) { + return log('WARING', 'no template'); + } + return new Promise(resolve => { + inquirer.prompt([ + { type: 'list', message: 'please select template:', name: template, choices: list } + ]).then((answers) => { + resolve(answers[template]) + }) + }) + }catch (e){ + log('ERROR', e); + } + +} + +/** + * 模板下载成功 + * @param dir + * @param name + * @param packageInfo + * @returns {Promise} + */ +async function downloadSuccess(dir, name, packageInfo) { + return new Promise((resolve) => { + fs.readFile(dir + '/package.json', 'utf8', (err, data) => { + if (err) { + resolve(false); + } + const packageFile = {...JSON.parse(data), ...packageInfo} + fs.writeFile(dir + '/package.json', JSON.stringify(packageFile, null, 4), 'utf8', (err) => { + if (err) { + resolve(false); + } + resolve(true); + }); + }) + }) +} + +/** + * 用户自己输入一些配置信息 + * @param name + * @returns {Promise} + */ +async function getUserInputPackageMessage(name) { + return new Promise(async (resolve, reject) => { + if(isTest) { + return resolve({name, author: '', description: '', version: '1.0.0' }) + } + try { + const messageInfoList = await Promise.all([ + inquirer.prompt([ + { type: 'input', message: "what's your name?", name: 'author', default: '' }, + { type: 'input', message: "please enter version?", name: 'version', default: '1.0.0' }, + { type: 'input', message: "please enter description.", name: 'description', default: '' }, + ]) + ]); + resolve({...messageInfoList[0], name}); + }catch (e) { + resolve({name, author: '', description: '', version: '1.0.0' }) + } + }) +} +module.exports = { + create: (...args) => { + return init(...args).catch(err => {}) + }, +} diff --git a/packages/web-core-cli/src/cli/lib/install.js b/packages/web-core-cli/src/cli/lib/install.js new file mode 100644 index 00000000..e7277a31 --- /dev/null +++ b/packages/web-core-cli/src/cli/lib/install.js @@ -0,0 +1,37 @@ +const spawn = require("cross-spawn"); +const ora = require("ora"); +const which = require("which"); + +module.exports = function(mirror, done) { + let registry, + resolved, + pkgtool = "npm"; + mirror = mirror.toLowerCase(); + if (mirror === "yarn" || mirror === "cnpm") { + try { + resolved = which.sync(mirror); + if (resolved) pkgtool = mirror; + } catch (e) { + console.log(e); + return secede(spawn(pkgtool, ["install"], { stdio: "inherit" }), done); + } + } else if (mirror !== "default") { + registry = ["--registry", require("../config/mirror")[mirror]]; + } + return secede( + spawn(pkgtool, registry ? [].concat(["install"], registry) : ["install"], { + stdio: "inherit" + }), done + ); +}; + +function secede(line, done) { + line.on("close", function(code) { + done && typeof done === 'function' && done(); + process.exit(code); + }); + + line.on("error", function(reason) { + console.log("An error occured while executing the NPM command.", reason); + }); +} diff --git a/packages/web-core-cli/src/cli/lib/list.js b/packages/web-core-cli/src/cli/lib/list.js new file mode 100644 index 00000000..c193512b --- /dev/null +++ b/packages/web-core-cli/src/cli/lib/list.js @@ -0,0 +1,32 @@ +const templateList = require('../config/template.json').templateList; +const log = require('../utils/log'); +const category = 'category'; +const query = 'query'; +/** + * 列出模板列表 + * @param options + * @param context + * @returns {Promise} + */ +async function list (options = {}, context = process.cwd()) { + let projectCategory = options[category]; + let projectQuery = options[query]; + let templateLogList = templateList; + if (projectCategory){ + templateLogList = templateList.filter(item => item.type === projectCategory); + } + if (projectQuery) { + templateLogList = templateLogList.filter(item => item.name.indexOf(projectQuery) > -1) + } + for (let i = 0; i < templateLogList.length; i ++) { + const str = `${templateLogList[i].name}`; + log('TEXT', str ); + } + if (!templateLogList.length) { + log('WARING', 'No matching template !!!'); + } + process.exit(0); +} +module.exports = (...args) => { + return list(...args).catch(err => {}) +} diff --git a/packages/web-core-cli/src/cli/lib/update.js b/packages/web-core-cli/src/cli/lib/update.js new file mode 100644 index 00000000..90cb89da --- /dev/null +++ b/packages/web-core-cli/src/cli/lib/update.js @@ -0,0 +1,75 @@ +const https = require('https'); +const path = require("path"); +const fs = require("fs"); +const ora = require('ora'); +const log = require('../utils/log'); +const configUrl = 'https://gitee.com/canyuegongzi/t-cli-templatt-cli-templatee/raw/t-cli-template-config/t-cli-templatt-cli-templatee.json'; +/** + * 获取模板 + * @param options + * @param context + * @returns {Promise} + */ +async function getList(options = {}, context = process.cwd()) { + return new Promise(resolve => { + https.get(configUrl, (response) => { + let data = ''; + response.on('data', (chunk) => { + data += chunk; + }); + response.on('end', () => { + resolve(JSON.parse(data)); + }); + + }).on("error", (error) => { + log('ERROR', error.message); + }); + }) +} + +/** + * 更新模板 + * @param data + * @returns {Promise} + */ +async function update(data) { + const updateSpinner = ora({ text: 'start update config...', color: 'blue'}).start(); + const errorCallback = (err) => { + updateSpinner.fail('update fail!!!!'); + log('ERROR', err); + } + return new Promise(async resolve => { + const configData = await getList(); + // 修改类型配置文件 + fs.readFile(path.join(__dirname, '../config/', 'category.json'), 'utf8',(err, fileData) => { + if (err) { + errorCallback(err); + resolve(false); + } + fs.writeFile(path.join(__dirname, '../config/', 'category.json'), JSON.stringify({categoryList: configData.categoryList}, null, 4), 'utf8', (err) => { + if (err) { + errorCallback(err); + resolve(false); + } + fs.readFile(path.join(__dirname, '../config/', 'template.json'), 'utf8',(err, fileData) => { + if (err) { + errorCallback(err); + resolve(false); + } + fs.writeFile(path.join(__dirname, '../config/', 'template.json'), JSON.stringify({templateList: configData.templateList}, null, 4), 'utf8', (err) => { + if (err) { + errorCallback(err); + resolve(false); + } + updateSpinner.succeed('update success!!!'); + resolve(true); + }); + }) + }); + }) + }) + +} +module.exports = (...args) => { + return update(...args).catch(err => {}) +} From 04a5a7ded8f65d106711d99fe10bff31c9bc2182 Mon Sep 17 00:00:00 2001 From: Marvin Date: Sat, 4 Jun 2022 17:37:35 +0800 Subject: [PATCH 2/2] =?UTF-8?q?refactor:core=E3=80=81ui?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 673b10d0..e5641a1e 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,7 @@ # node_modules/ **/node_modules/ -**/lib/* +packages/web-plus-ui/**/lib/* **/dist/ .idea/* npm-debug.log