UNPKG

itoolbox-cli

Version:

iToolBox CLI 工具,用于创建扩展,打包扩展.

105 lines (98 loc) 3.67 kB
const path = require('path'); const fs = require('fs'); const logger = require('./logger'); let JSZIP = require('jszip'); let zip = new JSZIP(); const del = require('del'); const { isHaveFile, isHaveFolder, readFile, copyFile, writeFile, getLocalTip } = require('../common/utils'); const projectPath = path.resolve(process.cwd(), './'); const TIP_INFO = getLocalTip().pack; const checkParam = (PKG) => { if (!PKG.extInfo) { logger.errorTip(TIP_INFO.extInfoError); return false; } if (!PKG.extInfo.rarName) { logger.errorTip(TIP_INFO.rarNameError); return false; } return true; }; //读取目录及文件 function readDir(obj, nowPath) { let files = fs.readdirSync(nowPath); //读取目录中的所有文件及文件夹(同步操作) files.forEach(function (fileName, index) { //遍历检测目录中的文件 let fillPath = nowPath + '/' + fileName; let file = fs.statSync(fillPath); //获取一个文件的属性 if (file.isDirectory()) { //如果是目录的话,继续查询 let dirlist = zip.folder(fileName); //压缩对象中生成该目录 readDir(dirlist, fillPath); //重新检索目录文件 } else { obj.file(fileName, fs.readFileSync(fillPath)); //压缩目录添加文件 } }); } //开始压缩文件 function compressFolder(name) { const folderPath = path.join(projectPath, './dist'); const targetPath = path.join(projectPath, `./dist/${name}.zip`); readDir(zip, folderPath); zip.generateAsync({ //设置压缩格式,开始打包 type: 'nodebuffer', //nodejs用 compression: 'DEFLATE', //压缩算法 compressionOptions: { //压缩级别 level: 9 } }).then(function (content) { // 删除文件 del.sync([`${folderPath}/logo.png`]); del.sync([`${folderPath}/ext.json`]); fs.writeFileSync(targetPath, content, 'utf-8'); //将打包的内容写入 当前目录下的 result.zip中 logger.successTip(TIP_INFO.success); }); } const createExtJsonFile = (PKG) => { if (checkParam(PKG)) { let extInfo = Object.assign({ name: PKG.name, description: PKG.dependencies || '', version: PKG.version, author: PKG.author, index: 'index.html', width: 700, height: 700, }, PKG.extInfo); if (extInfo.logo) { // 移动复制logo文件到根目录 const logoPath = path.join(projectPath, `./${extInfo.logo}`); const logoTargetPath = path.join(projectPath, './dist/logo.png'); isHaveFile(logoPath) && copyFile(logoPath, logoTargetPath); } const filePath = path.join(projectPath, './dist/ext.json'); writeFile(filePath, JSON.stringify(extInfo, null, '\t'), (flag) => { if (flag) { // 执行压缩打包 compressFolder(extInfo.rarName); } else { logger.errorTip(TIP_INFO.fail); } }) } }; module.exports = function (args) { logger.infoTip(TIP_INFO.info); const pkgFilePath = path.join(projectPath, './package.json'); const isProject = isHaveFile(pkgFilePath); if (!isProject) { logger.errorTip(TIP_INFO.noPkg); return false; } const pkgContent = readFile(pkgFilePath); const PKG = JSON.parse(`${pkgContent}`); const packDir = path.resolve(process.cwd(), `./dist`); if (isHaveFolder(packDir)) { createExtJsonFile(PKG) } else { logger.errorTip(TIP_INFO.emptyDist); } };