UNPKG

@ywfe/cli

Version:

遥望前端开发命令行工具

344 lines (343 loc) 13.9 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getBuildPageInfoWithChangeId = exports.getViteBuildConfig = exports.checkViteBuildConfig = exports.checkEnvFileExists = exports.generateLibName = exports.firstLetterToUpperCase = exports.getFiles = exports.chooseEnv = exports.chooseDailyEnv = exports.getEnv = exports.transformUrl = exports.isMatchProjectInfo = exports.checkBranchDiffHasPushed = exports.getGitInfo = exports.handleFilePath = exports.getFilePathWithPath = void 0; const chalk_1 = __importDefault(require("chalk")); const fs_extra_1 = require("fs-extra"); const path_1 = require("path"); const inquirer_1 = __importDefault(require("inquirer")); const messages_1 = require("./messages"); const devops_1 = require("../service/devops"); const constants_1 = require("./constants"); const simple_git_1 = require("simple-git"); const path = require("path"); const getFilePathWithPath = (publishInfo) => __awaiter(void 0, void 0, void 0, function* () { const routerFile = path.join(process.cwd(), './src/router/index.tsx'); const exist = (0, fs_extra_1.existsSync)(routerFile); if (!exist) { console.log(chalk_1.default.red(messages_1.MESSAGES.NOT_FOUND_ROUTER_FILE)); process.exit(1); } const data = yield (0, fs_extra_1.readFile)(routerFile); const tempDataStr = data.toString('utf-8').trim(); const tempArr = tempDataStr.split('\n'); const dataArr = []; tempArr.map((item) => { if (item.length > 0 && !item.includes('// ')) { dataArr.push(item); } }); const dataStr = dataArr.join('\n'); let componentWithFilePath = {}; dataArr.map((line) => { var _a, _b; if (line.startsWith('import') && line.indexOf('pages/') > -1) { const newLine = line.replace(';', ''); const componentName = (_b = (_a = newLine.match(/(?<=import).*?(?=from)/)) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.trim(); const index = newLine.indexOf('pages'); const filePath = newLine.substring(index + 6, newLine.length - 1); componentWithFilePath = Object.assign(Object.assign({}, componentWithFilePath), { [`${componentName}`]: filePath }); } }); publishInfo.map((item) => { var _a, _b; const { path } = item; item.file_path = ''; const regStr = new RegExp(`'${path}'.*?/>|"${path}".*?/>`, 's'); const str = (_a = dataStr.match(regStr)) === null || _a === void 0 ? void 0 : _a[0]; if (str) { const reg = /<(.|\n)*?\/>/; const newStr = (_b = str.match(reg)) === null || _b === void 0 ? void 0 : _b[0]; if (newStr) { const arr = newStr .substring(1, newStr.length - 2) .replace(/</g, '') .replace(/>/g, '') .replace(/\n/g, '') .split(' ') .filter((item) => item.length > 0); if (arr.length) { const len = arr.length; for (let i = 0; i < len; i++) { const filePathValue = componentWithFilePath[arr[i]]; if (filePathValue) { item.file_path = (0, exports.handleFilePath)(filePathValue); break; } } } } } return item; }); const found = publishInfo.find((item) => { const { file_path, develop_type } = item; return develop_type === 1 && !file_path; }); if (found) { const { path } = found; console.log(chalk_1.default.red(messages_1.MESSAGES.NOT_FOUND_FILE_PATH(path))); process.exit(1); } return publishInfo; }); exports.getFilePathWithPath = getFilePathWithPath; const handleFilePath = (path) => { return path.replace(/\/index(.tsx)?$/, ''); }; exports.handleFilePath = handleFilePath; const getGitInfo = () => __awaiter(void 0, void 0, void 0, function* () { const options = { baseDir: process.cwd(), binary: 'git', maxConcurrentProcesses: 6, }; const git = (0, simple_git_1.simpleGit)(options); const remote = yield git.listRemote(['--get-url']); const branch = yield git.branchLocal(); const httpRemote = (0, exports.transformUrl)(remote); return { branch: branch.current, remote: httpRemote }; }); exports.getGitInfo = getGitInfo; const checkBranchDiffHasPushed = (isCloudBuild) => __awaiter(void 0, void 0, void 0, function* () { const options = { baseDir: process.cwd(), binary: 'git', maxConcurrentProcesses: 6, }; const git = (0, simple_git_1.simpleGit)(options); const status = yield git.status(); const { modified, staged } = status; if (!isCloudBuild && ((modified && modified.length) || (staged && staged.length))) { console.log(chalk_1.default.red(messages_1.MESSAGES.DIFF_NOT_PUSH)); process.exit(1); } const branch = yield git.branch(); const { branches, current: currentBranch } = branch; const currentBranchInfo = branches[currentBranch]; const remoteBranchInfo = branches[`remotes/origin/${currentBranch}`]; const { commit: localCommitHash } = currentBranchInfo; const { commit: remoteCommitHash } = remoteBranchInfo; if (!isCloudBuild && localCommitHash !== remoteCommitHash) { console.log(chalk_1.default.red(messages_1.MESSAGES.DIFF_NOT_PUSH)); process.exit(1); } return remoteCommitHash.slice(0, 7); }); exports.checkBranchDiffHasPushed = checkBranchDiffHasPushed; const isMatchProjectInfo = (relativeBranch, isCloudBuild) => __awaiter(void 0, void 0, void 0, function* () { const options = { baseDir: process.cwd(), binary: 'git', maxConcurrentProcesses: 6, }; const git = (0, simple_git_1.simpleGit)(options); const branch = yield git.branchLocal(); const currentBranch = branch.current; if (!isCloudBuild && currentBranch !== 'release' && currentBranch !== relativeBranch) { console.log(chalk_1.default.red(messages_1.MESSAGES.NOT_CORRECT_BRANCH)); process.exit(1); } return currentBranch; }); exports.isMatchProjectInfo = isMatchProjectInfo; const transformUrl = (url) => { let newUrl = url.trim(); const reg = /^git@(.+?):(.+?\/.+?\.git)$/; if (reg.test(newUrl)) { newUrl = newUrl.replace(reg, 'https://$1/$2'); } return newUrl; }; exports.transformUrl = transformUrl; const getEnv = (PageEnv, hiddenConfirm) => __awaiter(void 0, void 0, void 0, function* () { let env = PageEnv; if (!env) { let { tag } = yield inquirer_1.default.prompt([ { name: 'tag', type: 'list', message: messages_1.MESSAGES.ENV_SELECT_TIPS, choices: constants_1.evnTagList, }, ]); env = tag; } if ((env === 'prod' || env === 'gray') && !hiddenConfirm) { const { bool } = yield inquirer_1.default.prompt([ { type: 'confirm', name: 'bool', message: messages_1.MESSAGES.PROD_ENV_SUBMIT, default: false, }, ]); if (bool) { return env; } else { console.log(chalk_1.default.red(messages_1.MESSAGES.END_PUBLISH_TIPS)); process.exit(1); } } else { return env; } }); exports.getEnv = getEnv; const chooseDailyEnv = (PageEnv) => __awaiter(void 0, void 0, void 0, function* () { let env = PageEnv; if (!env) { let { tag } = yield inquirer_1.default.prompt([ { name: 'tag', type: 'list', message: messages_1.MESSAGES.DAILY_ENV_SELECT_TIPS, choices: constants_1.dailyEnvTagList, }, ]); env = tag; } return env; }); exports.chooseDailyEnv = chooseDailyEnv; const chooseEnv = (PageEnv, hiddenConfirm) => __awaiter(void 0, void 0, void 0, function* () { let env = PageEnv; if (!env) { let { tag } = yield inquirer_1.default.prompt([ { name: 'tag', type: 'list', message: messages_1.MESSAGES.ENV_SELECT_TIPS, choices: constants_1.chooseEvnTagList, }, ]); env = tag; } if (env === 'prod' && !hiddenConfirm) { const { bool } = yield inquirer_1.default.prompt([ { type: 'confirm', name: 'bool', message: messages_1.MESSAGES.PROD_ENV_SUBMIT, default: false, }, ]); if (bool) { return env; } else { console.log(chalk_1.default.red(messages_1.MESSAGES.END_PUBLISH_TIPS)); process.exit(1); } } else { return env; } }); exports.chooseEnv = chooseEnv; const getFiles = (filePath, pageName) => { const result = []; const tempArr = pageName.split('/'); let tempPageName = tempArr.pop() || ''; tempPageName = tempPageName.replace(/-/g, ''); const findFile = (path) => { let files = (0, fs_extra_1.readdirSync)(path); files.forEach(function (item, index) { let fPath = (0, path_1.join)(path, item); const arr = item.split('/'); const itemFileName = arr[arr.length - 1]; const itemPageName = itemFileName.split('.')[0]; if (itemPageName === tempPageName || fPath.indexOf('style.css') > -1) { result.push(fPath); } }); }; findFile(`${filePath}/${tempArr.join('/')}`); return result; }; exports.getFiles = getFiles; const firstLetterToUpperCase = (letter, otherToLocalLower) => { return letter ? `${letter[0].toUpperCase()}${otherToLocalLower ? letter.substr(1).toLocaleLowerCase() : letter.substr(1)}` : ''; }; exports.firstLetterToUpperCase = firstLetterToUpperCase; const generateLibName = (pageName) => { const tempArr = pageName.split('/'); const libName = tempArr.map((n) => (0, exports.firstLetterToUpperCase)(n, true).replace(/-/g, '')).join(''); return libName; }; exports.generateLibName = generateLibName; const checkEnvFileExists = () => __awaiter(void 0, void 0, void 0, function* () { const filePath = path.join(process.cwd(), '.env'); try { const fileExists = (0, fs_extra_1.existsSync)(filePath); if (!fileExists) { throw messages_1.MESSAGES.PUBLISH_CHECK_FILE_EXISTS('.env'); } const dataStr = yield (0, fs_extra_1.readFile)(filePath); const data = dataStr.toString('utf-8'); if (data.indexOf('NODE_ENV=production') > -1) { return true; } else { throw messages_1.MESSAGES.PUBLISH_CHECK_ENV; } } catch (err) { console.log(chalk_1.default.red('err: ', err)); } }); exports.checkEnvFileExists = checkEnvFileExists; const checkViteBuildConfig = (fileName = 'build.json') => __awaiter(void 0, void 0, void 0, function* () { const filePath = path.join(process.cwd(), `./${fileName}`); const isExist = yield (0, fs_extra_1.existsSync)(filePath); if (!isExist) { console.log(chalk_1.default.red(messages_1.MESSAGES.BUILD_JSON_FILE_NOT_EXTRA(fileName))); process.exit(1); } return isExist; }); exports.checkViteBuildConfig = checkViteBuildConfig; const getViteBuildConfig = (fileName = 'build.json') => __awaiter(void 0, void 0, void 0, function* () { try { const filePath = path.join(process.cwd(), `./${fileName}`); const dataStr = yield (0, fs_extra_1.readFile)(filePath); const data = dataStr.toString('utf-8'); return JSON.parse(data); } catch (error) { console.log(error); process.exit(1); } }); exports.getViteBuildConfig = getViteBuildConfig; const getBuildPageInfoWithChangeId = (fileName = 'build.json', config) => __awaiter(void 0, void 0, void 0, function* () { let outputChangeId = null; if (config === null || config === void 0 ? void 0 : config.inputChangeId) { outputChangeId = config === null || config === void 0 ? void 0 : config.inputChangeId; } else { const { changeId } = yield (0, exports.getViteBuildConfig)(fileName); outputChangeId = changeId; if (!changeId) { const url = (0, devops_1.handleApiUrl)(config); const demandListUrl = `${url}/demandList`; console.log(chalk_1.default.red(messages_1.MESSAGES.NOT_CHANGE_ID(demandListUrl))); process.exit(1); } } const { data } = yield (0, devops_1.getBuildPageInfo)(outputChangeId, config); return data; }); exports.getBuildPageInfoWithChangeId = getBuildPageInfoWithChangeId;