UNPKG

t-comm

Version:

专业、稳定、纯粹的工具库

458 lines (451 loc) 16.9 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var tslib_es6 = require('../tslib.es6-01322ba9.js'); var fs = require('fs'); var path = require('path'); var fs_fs = require('../fs/fs.js'); var node_nodeCommand = require('../node/node-command.js'); var wecomRobot_batchSend = require('../wecom-robot/batch-send.js'); var lint_config = require('./config.js'); var lint_git = require('./git.js'); var lint_helper = require('./helper.js'); var lint_message = require('./message.js'); require('@babel/runtime/helpers/typeof'); require('../wecom-robot/base.js'); require('../wecom-robot/helper.js'); require('axios'); require('../wecom-robot/send-img.js'); require('../node-img/img.js'); require('../git/submodule.js'); require('../git/git.js'); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs); var path__default = /*#__PURE__*/_interopDefaultLegacy(path); var ESLINT_CONFIG_FILE = '.eslintrc.js'; function removeParserOptionsProject(workspace) { var configFile = path__default["default"].resolve(workspace, ESLINT_CONFIG_FILE); if (!fs__default["default"].existsSync(configFile)) { console.log('不存在配置文件'); return; } var content = fs_fs.readFileSync(configFile); var reg = /\s+project:\s+'[^']+json',/; var newContent = content.replace(reg, ''); if (newContent && newContent !== content) { console.log('已删除 parserOptions.project'); fs_fs.writeFileSync(configFile, newContent); } } function parseScssFiles(scssErrorFiles, workspace) { if (!(scssErrorFiles === null || scssErrorFiles === void 0 ? void 0 : scssErrorFiles.length)) { return []; } var parsedFiles = scssErrorFiles.reduce(function (acc, item) { var _a; (_a = item.warnings) === null || _a === void 0 ? void 0 : _a.forEach(function (messageItem) { acc.push(tslib_es6.__assign(tslib_es6.__assign({ filePath: item.source, parsedFilePath: path__default["default"].relative(workspace, item.source) }, messageItem), { message: messageItem.text, ruleId: messageItem.rule })); }); return acc; }, []); return parsedFiles; } function parseJSFiles(jsErrorFiles, workspace) { if (!(jsErrorFiles === null || jsErrorFiles === void 0 ? void 0 : jsErrorFiles.length)) { return []; } var parsedFiles = jsErrorFiles.reduce(function (acc, item) { var _a; (_a = item.messages) === null || _a === void 0 ? void 0 : _a.forEach(function (messageItem) { acc.push(tslib_es6.__assign({ filePath: item.filePath, parsedFilePath: path__default["default"].relative(workspace, item.filePath) }, messageItem)); }); return acc; }, []); return parsedFiles; } function tryCreateMRNote(_a) { var privateToken = _a.privateToken, gitApiPrefix = _a.gitApiPrefix, errorFiles = _a.errorFiles, projectName = _a.projectName, mrId = _a.mrId, workspace = _a.workspace, isScss = _a.isScss; return tslib_es6.__awaiter(this, void 0, void 0, function () { var parsedFiles, _i, parsedFiles_1, file; return tslib_es6.__generator(this, function (_b) { switch (_b.label) { case 0: parsedFiles = isScss ? parseScssFiles(errorFiles, workspace) : parseJSFiles(errorFiles, workspace); console.log('[isScss]', isScss); console.log('[parsedFiles]', parsedFiles); if (!(parsedFiles === null || parsedFiles === void 0 ? void 0 : parsedFiles.length)) return [2 /*return*/]; _i = 0, parsedFiles_1 = parsedFiles; _b.label = 1; case 1: if (!(_i < parsedFiles_1.length)) return [3 /*break*/, 4]; file = parsedFiles_1[_i]; return [4 /*yield*/, lint_git.createMRNote({ projectName: projectName, mrId: mrId, body: "".concat(file.message, "\n\n [").concat(file.ruleId, "]") || '格式错误', line: file.line, path: file.parsedFilePath, privateToken: privateToken, gitApiPrefix: gitApiPrefix })]; case 2: _b.sent(); _b.label = 3; case 3: _i++; return [3 /*break*/, 1]; case 4: return [2 /*return*/]; } }); }); } function checkLint(_a) { var privateToken = _a.privateToken, gitApiPrefix = _a.gitApiPrefix, workspace = _a.workspace, mrUrl = _a.mrUrl, mrId = _a.mrId, buildUrl = _a.buildUrl, repo = _a.repo, repoUrl = _a.repoUrl, sourceBranch = _a.sourceBranch, targetBranch = _a.targetBranch, docLink = _a.docLink, webhookUrl = _a.webhookUrl, _b = _a.chatId, chatId = _b === void 0 ? ['ALL'] : _b, checkAll = _a.checkAll, _c = _a.mentionList, mentionList = _c === void 0 ? [] : _c, _d = _a.lintFiles, lintFiles = _d === void 0 ? Object.keys(lint_config.FILE_TYPE_MAP) : _d, _e = _a.throwError, throwError = _e === void 0 ? true : _e, _f = _a.ignoreSubmodules, ignoreSubmodules = _f === void 0 ? true : _f; return tslib_es6.__awaiter(this, void 0, void 0, function () { var fileMap, diffFilesMap_1, innerExecCommand, errorMap, commentSuccess, message, getPostFix, robotMessage, err_2, _i, _g, key, hasError; return tslib_es6.__generator(this, function (_h) { switch (_h.label) { case 0: if (!checkAll && (!sourceBranch || !targetBranch)) { throw new Error('增量模式,必须提供 sourceBranch 和 targetBranch!'); } if (ignoreSubmodules) { lint_helper.ignoreSubmoduleInESLint(workspace); lint_helper.ignoreSubmoduleInStyleLint(workspace); } fileMap = Object.keys(lint_config.FILE_TYPE_MAP).filter(function (item) { return lintFiles.includes(item); }).reduce(function (acc, key) { var _a; return tslib_es6.__assign(tslib_es6.__assign({}, acc), (_a = {}, _a[key] = lint_config.FILE_TYPE_MAP[key], _a)); }, {}); if (!checkAll) { diffFilesMap_1 = getDiffFile({ sourceBranch: sourceBranch, targetBranch: targetBranch, workspace: workspace }).diffFilesMap; Object.keys(fileMap).forEach(function (key) { fileMap[key].lintKeyword = diffFilesMap_1[key]; }); } innerExecCommand = function innerExecCommand(key, info) { console.log("\u6B63\u5728\u6267\u884C lint ".concat(key, " ...")); if (info.isVue) { removeParserOptionsProject(workspace); } var outputFile = path__default["default"].resolve(workspace, info.outputFileName); if (info.isStyle) { try { // inherit 无法真正捕获错误 var lintResult = node_nodeCommand.execCommand("npx stylelint ".concat(info.lintKeyword, " --quiet -o ").concat(outputFile, " --formatter json || true"), workspace, 'pipe'); console.log('[StyleLint] result: \n', lintResult); } catch (err) { console.log('[StyleLint] error: ', err); } } else { try { var lintResult = node_nodeCommand.execCommand("npx eslint ".concat(info.lintKeyword, " --quiet -o ").concat(outputFile, " --format json || true"), workspace, 'pipe'); console.log('[ESLint] result: \n', lintResult); } catch (err) { console.log('[ESLint] error: ', err); } } return outputFile; }; Object.keys(fileMap).forEach(function (key) { var outputFile = innerExecCommand(key, fileMap[key]); fileMap[key].outputFile = outputFile; }); errorMap = parseResult({ fileMap: fileMap }).errorMap; Object.keys(fileMap).forEach(function (key) { fileMap[key].errorFiles = errorMap[key].errorFiles; fileMap[key].total = errorMap[key].total; }); commentSuccess = false; if (!mrId) return [3 /*break*/, 5]; message = genRobotMessage({ fileMap: fileMap, checkAll: checkAll, mrUrl: mrUrl, sourceBranch: sourceBranch, targetBranch: targetBranch, buildUrl: buildUrl, docLink: docLink, repo: repo, repoUrl: repoUrl, mentionList: mentionList, workspace: workspace }); _h.label = 1; case 1: _h.trys.push([1, 3,, 4]); return [4 /*yield*/, lint_git.createMRComment({ projectName: repo, mrId: mrId, data: message, privateToken: privateToken, gitApiPrefix: gitApiPrefix })]; case 2: commentSuccess = _h.sent(); return [3 /*break*/, 4]; case 3: _h.sent(); return [3 /*break*/, 4]; case 4: console.log('[commentSuccess]', commentSuccess); _h.label = 5; case 5: getPostFix = function getPostFix() { if (!mrId) return ''; return commentSuccess ? '评论成功' : '评论失败'; }; robotMessage = genRobotMessage({ fileMap: fileMap, postFix: getPostFix(), mrUrl: mrUrl, sourceBranch: sourceBranch, targetBranch: targetBranch, buildUrl: buildUrl, docLink: docLink, checkAll: checkAll, repo: repo, repoUrl: repoUrl, mentionList: mentionList, workspace: workspace }); console.log('[robotMessage]: \n', robotMessage); _h.label = 6; case 6: _h.trys.push([6, 8,, 9]); return [4 /*yield*/, wecomRobot_batchSend.batchSendWxRobotMarkdown({ content: robotMessage, chatId: chatId, webhookUrl: webhookUrl })]; case 7: _h.sent(); return [3 /*break*/, 9]; case 8: err_2 = _h.sent(); console.log('[batchSendWxRobotMarkdown] err', err_2); return [3 /*break*/, 9]; case 9: if (!mrId) return [3 /*break*/, 13]; _i = 0, _g = Object.keys(fileMap); _h.label = 10; case 10: if (!(_i < _g.length)) return [3 /*break*/, 13]; key = _g[_i]; return [4 /*yield*/, tryCreateMRNote({ projectName: repo, mrId: mrId, errorFiles: fileMap[key].errorFiles || [], workspace: workspace, privateToken: privateToken, gitApiPrefix: gitApiPrefix, isScss: fileMap[key].isStyle })]; case 11: _h.sent(); _h.label = 12; case 12: _i++; return [3 /*break*/, 10]; case 13: hasError = !!Object.values(fileMap).find(function (item) { return item.total; }); if (throwError && hasError) { throw new Error('Lint 检查不通过!'); } return [2 /*return*/, fileMap]; } }); }); } function getErrorInfo(result) { var errorFiles = result.filter(function (item) { return item.errorCount; }); var total = errorFiles.reduce(function (acc, file) { acc += file.errorCount || 0; return acc; }, 0); return { total: total, errorFiles: errorFiles }; } var readyFile = function readyFile(file) { if (!fs__default["default"].existsSync(file)) { fs_fs.writeFileSync(file, [], true); return []; } return fs_fs.readFileSync(file, true); }; var parseErrorResult = function parseErrorResult(key, info) { if (!info.outputFile || !fs__default["default"].existsSync(info.outputFile)) { return { total: 0, errorFiles: [] }; } var content = readyFile(info.outputFile); console.log("[result] ".concat(key, ": \n"), JSON.stringify(content, null, 2)); var resultTotal = 0; var resultErrorFiles = []; if (info.isStyle) { var parsed = content.filter(function (item) { var _a; return (_a = item.warnings) === null || _a === void 0 ? void 0 : _a.length; }).map(function (item) { return tslib_es6.__assign(tslib_es6.__assign({}, item), { errorCount: item.warnings.filter(function (warn) { return warn.severity === 'error'; }).length }); }); var _a = getErrorInfo(parsed), total = _a.total, errorFiles = _a.errorFiles; resultTotal = total; resultErrorFiles = errorFiles; } else { var _b = getErrorInfo(content), total = _b.total, errorFiles = _b.errorFiles; resultTotal = total; resultErrorFiles = errorFiles; } return { total: resultTotal, errorFiles: resultErrorFiles }; }; function parseResult(_a) { var fileMap = _a.fileMap; var errorMap = {}; Object.keys(fileMap).forEach(function (key) { errorMap[key] = parseErrorResult(key, fileMap[key]); }); return { errorMap: errorMap }; } function genRobotMessage(_a) { var fileMap = _a.fileMap, mrUrl = _a.mrUrl, sourceBranch = _a.sourceBranch, targetBranch = _a.targetBranch, buildUrl = _a.buildUrl, docLink = _a.docLink, repo = _a.repo, repoUrl = _a.repoUrl, postFix = _a.postFix, _b = _a.checkAll, checkAll = _b === void 0 ? false : _b, _c = _a.mentionList, mentionList = _c === void 0 ? [] : _c, workspace = _a.workspace; var postFixList = postFix ? [postFix] : []; var repoAndMrInfo = lint_message.genReportInfo({ workspace: workspace, mrUrl: mrUrl, sourceBranch: sourceBranch, targetBranch: targetBranch, repo: repo, repoUrl: repoUrl, checkAll: checkAll }); var allTotal = Object.values(fileMap).reduce(function (acc, item) { var _a; return acc + ((_a = item.total) !== null && _a !== void 0 ? _a : 0); }, 0); if (!allTotal) { return tslib_es6.__spreadArray(tslib_es6.__spreadArray(tslib_es6.__spreadArray([lint_message.genTitle('✅', checkAll)], repoAndMrInfo, true), ['未发现代码规范异常'], false), postFixList, true).join(','); } var lintErrorMessageList = Object.keys(fileMap).filter(function (item) { return !!fileMap[item].total; }).map(function (key) { var info = fileMap[key]; var total = info.total, errorFiles = info.errorFiles; return "- **".concat(key.toUpperCase(), " \u9519\u8BEF**\uFF1A").concat(total && (errorFiles === null || errorFiles === void 0 ? void 0 : errorFiles.length) ? "".concat(errorFiles === null || errorFiles === void 0 ? void 0 : errorFiles.length, "\u4E2A\u6587\u4EF6").concat(total, "\u4E2A\u9519\u8BEF") : '无'); }); return tslib_es6.__spreadArray([tslib_es6.__spreadArray(tslib_es6.__spreadArray(tslib_es6.__spreadArray([lint_message.genTitle('⚠️', checkAll)], repoAndMrInfo, true), ["\u53EF\u5728[\u6D41\u6C34\u7EBF](".concat(buildUrl, ")\u4E2D\u67E5\u770B\u8BE6\u60C5\uFF0C\u6216\u672C\u5730\u8FD0\u884C `npx eslint --fix file` \u7B49\u547D\u4EE4"), docLink ? "[\u8BF4\u660E\u6587\u6863](".concat(docLink, ")") : '', mentionList.map(function (mention) { return "<@".concat(mention, ">"); }).join('')], false), postFixList, true).filter(function (item) { return item; }).join(',')], lintErrorMessageList, true).join('\n'); } function getDiffFile(_a) { var sourceBranch = _a.sourceBranch, targetBranch = _a.targetBranch, workspace = _a.workspace; node_nodeCommand.execCommand("git clean -df && git reset --hard HEAD && git checkout ".concat(targetBranch, " && git pull && git submodule update --init"), workspace, 'inherit'); node_nodeCommand.execCommand("git checkout ".concat(sourceBranch, " && git reset --hard \"origin/").concat(sourceBranch, "\" && git pull"), workspace, 'inherit'); var list = node_nodeCommand.execCommand("git diff --name-only ".concat(sourceBranch, " ").concat(targetBranch), workspace, { stdio: 'pipe', line: -1 }).split('\n').map(function (item) { return item.trim(); }).filter(function (item) { return item; }).filter(function (item) { return fs__default["default"].existsSync(path__default["default"].resolve(workspace, item)); }); console.log('diff list: ', JSON.stringify(list, null, 2)); var diffFilesMap = {}; Object.keys(lint_config.FILE_TYPE_MAP).forEach(function (key) { var reg = lint_config.FILE_TYPE_MAP[key].reg; var files = list.filter(function (item) { return reg.test(item); }); diffFilesMap[key] = files.join(' '); }); return { diffFilesMap: diffFilesMap }; } exports.checkLint = checkLint;