@ygyg/yg-cli
Version:
A simple CLI for front-end engineering automation construction tool.
256 lines (226 loc) • 8.06 kB
JavaScript
const axios = require('axios');
const utils = require('./utils');
const https = require('https');
const devPort = 7001;
const prodPort = 80;
const prodDomain = 'chaos-api.ygego.alpha';
const devDomain = 'localhost';
exports.getBaseUrl = function() {
const isDev = process.env.ISDEV || false;
const port = isDev ? devPort : prodPort;
const domainUrl = isDev ? devDomain : prodDomain;
const baseURL = 'http://' + domainUrl + ':' + port;
return baseURL;
};
exports.lintOption = async function(data, cfg) {
const { lintType = 0, fileCount = -1, errorCount = 0, warningCount = 0 } = data;
const lintInfo = {
fileCount,
errorCount,
warningCount,
};
const infoKey = cfg.eslintType === lintType ? 'eslintInfo' : 'stylelintInfo';
return {
...cfg,
[infoKey]: lintInfo,
};
};
exports.getLintData = async function(postData) {
const commits = await utils.getCommits();
let gitInfo = {
authorName: commits.name,
commitLog: commits.message,
branchName: commits.branch,
projectName: commits.projectName,
};
let lintConfig = {
eslintType: 0,
stylelintType: 1,
};
if (Array.isArray(postData)) {
for (let i = 0; i < postData.length; i += 1) {
const currData = postData[i];
lintConfig = await this.lintOption(currData, lintConfig);
}
} else {
lintConfig = await this.lintOption(postData, lintConfig);
}
const msgParams = {
authorName: gitInfo.authorName,
commitLog: gitInfo.commitLog,
branchName: gitInfo.branchName,
projectName: gitInfo.projectName,
...lintConfig,
};
const isSendMsg = msgParams.eslintInfo.errorCount >= 0 || (msgParams.stylelintInfo && msgParams.stylelintInfo.errorCount >= 0);
utils.logStep(lintConfig, 'lintConfig');
utils.logStep(msgParams, 'msgParams');
return {isSendMsg, msgParams};
};
exports.sendLintInsight = async function(queryParams) {
utils.logStep(`LintinsightData=${JSON.stringify(queryParams)}`);
// ===== 因chaos-api故障 ,直连企业微信
const {isSendMsg, msgParams} = this.getLintData(queryParams);
if (isSendMsg) { // 发送消息
// this.logger.info(msgParams,'msgParams')
const content = await this.esMarkTpl(msgParams);
// await ctx.service.robots.sendDingDing(msgParams);
await this.sendEntWechat(content);
}
// ====暂时关闭chaos-api 发送
// axios.defaults.baseURL = this.getBaseUrl();
// await axios
// .post('/api/v2/lints', queryParams)
// .then((response) => {
// utils.logStep(response.data);
// })
// .catch((error) => {
// if (error.response) {
// // 请求已发出,但服务器响应的状态码不在 2xx 范围内
// utils.logStep('lintinsight', error.response.data);
// utils.logStep('lintinsight', error.response.status);
// // console.log(error.response.headers);
// } else {
// utils.logStep('lintinsight', error.message);
// }
// });
};
/**
* 洞察数据
* @param {string[]} queryParams
*/
exports.sendInsight = async function(queryParams) {
console.log('queryParams', queryParams);
// await this.sendEntWechat(queryParams);
axios.defaults.baseURL = this.getBaseUrl();
utils.logStep(`MsginsightData=${JSON.stringify(queryParams)}`);
await axios
.post('/api/insight/send', queryParams)
.then((response) => {
utils.logStep(response.data);
})
.catch((error) => {
if (error.response) {
// 请求已发出,但服务器响应的状态码不在 2xx 范围内
utils.logStep('msginsight', error.response.data);
utils.logStep('msginsight', error.response.status);
// console.log(error.response.headers);
} else {
utils.logStep('msginsight', error.message);
}
});
};
exports.sendDingDing = async function(params) {
const {
errorCount,
warningCount,
fileCount,
authorName,
commitLog,
} = params;
const totalCount = parseInt(warningCount, 10) + parseInt(errorCount, 10);
const msgTitle = errorCount > 0 ? '不通过' : '通过';
const myMessage = `ESLint 检测${msgTitle} 共${fileCount}个文件,产生了 ${totalCount} 问题(${errorCount} error, ${warningCount} warning),提交人:${authorName} 提交日志: ${commitLog}`;
const queryParams = {
msgtype: 'text',
text: {
content: `[洞察]: ${myMessage}`,
},
at: {
atMobiles: [13581662128],
isAtAll: false,
},
};
const requestData = JSON.stringify(queryParams);
console.log('sendDingDing=', requestData);
const token =
'6f5e5ef94d47c051a16023fab980efa2787837d363c5359082f2817a4093de14'; // SECb6cff4bfc9e83e0c1b15280997a6f64622d69ef548be23ec9ff729fcf27d1d90
// https://oapi.dingtalk.com/robot/send?access_token=6f5e5ef94d47c051a16023fab980efa2787837d363c5359082f2817a4093de14
const url = 'oapi.dingtalk.com';
const req = https.request({
hostname: url,
port: 443,
path: `/robot/send?access_token=${token}`,
method: 'POST',
json: true,
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
});
req.write(requestData);
req.on('error', (err) => {
console.error(err);
});
req.end();
};
/**
* 发送消息支持 stylelint和eslint合并
* @param {*} params 参数 object
* @param {*} content 内容
*/
exports.esMarkTpl = async function(params) {
const content = [];
const {
eslintInfo,
stylelintInfo = {},
authorName,
commitLog,
projectName,
branchName,
// lintType = 0,
} = params;
const { errorCount, warningCount, fileCount } = eslintInfo;
const { errorCount: styleErrorCount, warningCount: styleWarningCount, fileCount: styleFileCount } = stylelintInfo;
const lintTitle = '质量助手';
// const totalCount = parseInt(warningCount, 10) + parseInt(errorCount, 10);
const msgTitle = errorCount > 0 ? '<font color=\"warning\">不合格</font>' : '<font color=\"info\">合格</font>';
const authorMsg =
parseInt(errorCount, 10) === 0 && parseInt(warningCount, 10) < 10
? `恭喜${authorName}`
: `请${authorName}同学及时跟进`;
const result = `> 错误: \`${errorCount}\` ` +
`警告: \`${warningCount}\` \n`;
const styleLintResult = styleErrorCount !== undefined ? `> 错误: \`${styleErrorCount}\` ` +
`警告: \`${styleWarningCount}\` \n` : null;
content.push(`<font color=\"info\">${projectName}</font> 经${lintTitle} 检测,结果为 [${msgTitle}]。\n`);
content.push(`> ${authorMsg} \n`);
// this.logger.info('====>', errorCount === 0);
fileCount && content.push(`**EsLint文件数${fileCount}个:**`);
result && content.push(result);
styleFileCount && content.push(`**StyleLint文件数${styleFileCount}个:**`);
styleLintResult && content.push(styleLintResult);
branchName && content.push(`> 分支:<font color="comment">${branchName}</font>`);
commitLog && content.push(`> ${commitLog}`);
return content;
};
exports.sendEntWechat = async function(msg) {
// const content = [];
// const msg = await this.esMarkTpl(params, content);
const queryParams = {
msgtype: 'markdown',
markdown: {
content: msg.content.join(' \n '),
mentioned_list: ['@all'], // `${params.authorName}`
mentioned_mobile_list: ['@all'],
},
};
const token = '6b2ff37c-990a-4c8c-b33f-b4ebb7e81cc2'; // 洞察 cc32e44a-1d20-4ec5-a204-9e2ea64da164
const url = `https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=${token}`;
await axios.post(url, JSON.stringify(queryParams), {
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
}).then((response) => {
utils.logStep(response.data);
})
.catch((error) => {
if (error.response) {
// 请求已发出,但服务器响应的状态码不在 2xx 范围内
utils.logStep('msginsight', error.response.data);
utils.logStep('msginsight', error.response.status);
// console.log(error.response.headers);
} else {
utils.logStep('msginsight', error.message);
}
});
};