UNPKG

@lvl/wxapp-cli

Version:

wxapp-cli

131 lines (114 loc) 3.05 kB
const { execSync } = require('child_process') const fse = require('fs-extra') const { resolve } = require('path') const LRU = require('lru-cache') const chalk = require('chalk') const { cliRoot } = require('../config/wxapp-cli.config') let _hasGit const _gitProjects = new LRU({ max: 10, maxAge: 1000 }) exports.hasGit = () => { if (_hasGit != null) { return _hasGit } try { execSync('git --version', { stdio: 'ignore' }) return (_hasGit = true) } catch (e) { return (_hasGit = false) } } exports.hasProjectGit = (cwd) => { if (_gitProjects.has(cwd)) { return _gitProjects.get(cwd) } let result try { execSync('git status', { stdio: 'ignore', cwd }) result = true } catch (e) { result = false } _gitProjects.set(cwd, result) return result } exports.setProjectGit = (cwd, val) => { _gitProjects.set(cwd, val) } exports.getAppCtx = (cwd = '') => { let res = null while (cwd && cwd !== '/') { res = fse.pathExistsSync(resolve(`${cwd}`, 'wxapp-cli.config.js')) if (res) { return cwd } else { cwd = resolve(cwd, '../') } } return null } exports.prepareEnv = async () => { const appCtx = exports.getAppCtx(process.cwd()) if (!appCtx) { console.error(chalk.red(`请在 wxapp-cli 创建的项目中执行此命令`)) process.exit(1) } const cliTplConfig = require(resolve(appCtx, 'wxapp-cli.config')) const tplModuleName = cliTplConfig.template.module const version = cliTplConfig.template.version let cliTemplate = null try { cliTemplate = require(tplModuleName) } catch (err) {} if (!cliTemplate || cliTemplate.version !== version) { // 将模版切换到项目指定的版本 execSync(`npm install ${tplModuleName}@${version} --no-save --unsafe-perm`, { cwd: cliRoot, stdio: 'inherit' }) purgeCache(tplModuleName) cliTemplate = require(tplModuleName) } return { appCtx, cliTplConfig, cliTemplate } } /** * 从缓存中移除module */ function purgeCache(moduleName) { // 遍历缓存来找到通过指定模块名载入的文件 searchCache(moduleName, function (mod) { delete require.cache[mod.id]; }); // 删除模块缓存的路径 Object.keys(module.constructor._pathCache).forEach(function (cacheKey) { if (cacheKey.indexOf(moduleName) > 0) { delete module.constructor._pathCache[cacheKey]; } }); }; /** * 遍历缓存来查找通过特定模块名缓存下的模块 */ function searchCache(moduleName, callback) { // 通过指定的名字resolve模块 var mod = require.resolve(moduleName); // 检查该模块在缓存中是否被resolved并且被发现 if (mod && ((mod = require.cache[mod]) !== undefined)) { // 递归的检查结果 (function traverse(mod) { // 检查该模块的子模块并遍历它们 mod.children.forEach(function (child) { traverse(child); }); // 调用指定的callback方法,并将缓存的module当做参数传入 callback(mod); }(mod)); } }; exports.purgeCache = purgeCache