t-comm
Version:
专业、稳定、纯粹的工具库
569 lines (562 loc) • 21.2 kB
JavaScript
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var _classCallCheck = require('@babel/runtime/helpers/classCallCheck');
var _createClass = require('@babel/runtime/helpers/createClass');
var _regeneratorRuntime = require('@babel/runtime/regenerator');
var tslib_es6 = require('../tslib.es6-0d92ef81.js');
var bite_formatBite = require('../bite/format-bite.js');
var canvas_imgText = require('../canvas/img-text.js');
var git_git = require('../git/git.js');
var nodeImg_img = require('../node-img/img.js');
var nodejs_fs = require('../nodejs/fs.js');
var nodejs_path = require('../nodejs/path.js');
var tencentCloud_cos_cos = require('../tencent-cloud/cos/cos.js');
var tencentCloud_cos_link = require('../tencent-cloud/cos/link.js');
var thirdParty_miniprogramCi = require('../third-party/miniprogram-ci.js');
var time_time = require('../time/time.js');
var wecomRobot_base = require('../wecom-robot/base.js');
var mpCi_config = require('./config.js');
var mpCi_helper = require('./helper.js');
require('../third-party/image-size.js');
require('../canvas/get-canvas.js');
require('../third-party/canvas.js');
require('../node/node-command.js');
require('@babel/runtime/helpers/typeof');
require('../nodejs/child_process.js');
require('../validate/validate.js');
require('../nodejs/crypto.js');
require('../nodejs/request.js');
require('../tencent-cloud/cos/helper.js');
require('../third-party/cos-nodejs-sdk-v5.js');
require('../wecom-robot/helper.js');
require('axios');
require('../wecom-robot/message.js');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var _toConsumableArray__default = /*#__PURE__*/_interopDefaultLegacy(_toConsumableArray);
var _classCallCheck__default = /*#__PURE__*/_interopDefaultLegacy(_classCallCheck);
var _createClass__default = /*#__PURE__*/_interopDefaultLegacy(_createClass);
var _regeneratorRuntime__default = /*#__PURE__*/_interopDefaultLegacy(_regeneratorRuntime);
function getFullPackageSize(result) {
var obj = mpCi_helper.flattenSubPackages(result);
return bite_formatBite.formatBite(obj.__FULL__.size);
}
function getMainPackageSize(result) {
var obj = mpCi_helper.flattenSubPackages(result);
return bite_formatBite.formatBite(obj.__APP__.size);
}
var MpCI = /*#__PURE__*/function () {
/**
* 小程序自动化构建工具
* @param {object} options 选项
*
* @example
*
* const { MpCI, fetchRainbowConfig } = require('t-comm');
*
* const env = "${env}"
* const branch = "${branch}"
*
* const root = "${WORKSPACE}";
*
* async function getCIConfig() {
* let res = {};
* const str = await fetchRainbowConfig('mp_ci', {
* appId: '',
* envName: 'x',
* groupName: 'x',
* });
* try {
* res = JSON.parse(str);
* } catch (err) {}
* return res;
* }
*
* function getRobot(config = {}) {
* return config?.robotMap?.[branch]?.[env] || 1;
* }
*
* async function main() {
* const config = await getCIConfig();
* console.log('config: \n', config, typeof config);
* const {
* appName,
* appId,
* webhookUrl,
* chatId,
* cosInfo,
* } = config;
*
* const ci = new MpCI({
* appName,
* appId,
* root,
* env,
* robotNumber: getRobot(config),
*
* webhookUrl,
* chatId,
*
* cosInfo,
* });
*
* await ci.upload();
* await ci.preview();
* await ci.sendRobotMsg();
* }
*
* main();
*/
function MpCI(options) {
_classCallCheck__default["default"](this, MpCI);
this.webhookUrl = '';
this.chatId = '';
this.projectPath = '';
this.privateKeyPath = '';
this.buildDesc = '';
this.version = '';
this.errorLink = '';
this.pagePath = '';
this.searchQuery = '';
this.tryTimesMap = {
UPLOAD: 1,
PREVIEW: 1
};
var ci = options.ci;
if (!ci) {
try {
ci = thirdParty_miniprogramCi.getMiniprogramCi();
} catch (err) {
console.log('[MpCI] err', err);
}
}
this.ciLib = ci;
this.options = options;
this.projectCI = null;
this.previewResult = {
subPackageInfo: []
};
this.savePreviewPath = nodejs_path.getPath().resolve(process.cwd(), 'mp_ci_preview_destination.png');
var appId = options.appId,
appName = options.appName,
projectPath = options.projectPath,
privateKeyPath = options.privateKeyPath,
ignores = options.ignores,
type = options.type,
root = options.root,
env = options.env,
robotNumber = options.robotNumber,
buildSetting = options.buildSetting,
webhookUrl = options.webhookUrl,
chatId = options.chatId,
cosInfo = options.cosInfo,
errorLink = options.errorLink,
pagePath = options.pagePath,
searchQuery = options.searchQuery;
this.appId = appId;
this.appName = appName || '';
this.type = type || 'miniProgram';
this.pagePath = pagePath || '';
this.searchQuery = searchQuery || '';
this.root = root || process.cwd();
this.ignores = ignores || ['node_modules/**/*'];
this.pkgFile = nodejs_path.getPath().resolve(this.root, './package.json');
this.env = env || 'test';
this.robotNumber = robotNumber || 30;
this.webhookUrl = webhookUrl;
this.chatId = chatId;
this.buildSetting = Object.assign(Object.assign({}, mpCi_config.DEFAULT_BUILD_SETTING), buildSetting || {});
this.projectPath = projectPath || '';
this.privateKeyPath = privateKeyPath || '';
this.cosInfo = cosInfo || {};
this.errorLink = errorLink || '';
this.validateOptions();
if (this.ciLib) {
this.init();
}
this.initBaseInfo();
}
return _createClass__default["default"](MpCI, [{
key: "validateOptions",
value: function validateOptions() {
if (!this.projectPath) {
this.projectPath = nodejs_path.getPath().resolve(this.root, 'dist/build/mp-weixin');
}
if (!this.privateKeyPath) {
this.privateKeyPath = nodejs_path.getPath().resolve(this.root, 'private.key');
}
if (this.ciLib && !nodejs_fs.getFs().existsSync(this.privateKeyPath)) {
throw new Error('ERROR: privateKeyPath 位置不存在');
}
if (!nodejs_fs.getFs().existsSync(this.projectPath)) {
throw new Error('ERROR: projectPath 位置不存在');
}
// if (!getFs().existsSync(this.pkgFile)) {
// throw new Error('ERROR: package.json 不存在');
// }
}
}, {
key: "initBaseInfo",
value: function initBaseInfo() {
this.getBuildTime();
if (!this.options.commitInfo) {
this.commitInfo = git_git.getGitCommitInfo(this.root, false, false, false);
} else {
this.commitInfo = this.options.commitInfo;
}
if (!this.options.buildDesc) {
this.buildDesc = mpCi_helper.getBundleBuildDesc({
root: this.root,
env: this.env
}) || '';
} else {
this.buildDesc = this.options.buildDesc;
}
if (!this.options.version) {
this.version = mpCi_helper.getBundleVersion(this.root);
} else {
this.version = this.options.version;
}
}
}, {
key: "init",
value: function init() {
var appId = this.appId,
projectPath = this.projectPath,
privateKeyPath = this.privateKeyPath,
ignores = this.ignores,
type = this.type;
this.projectCI = new this.ciLib.Project({
appid: appId,
type: type,
projectPath: projectPath,
privateKeyPath: privateKeyPath,
ignores: ignores
});
}
}, {
key: "getBuildTime",
value: function getBuildTime() {
this.buildTime = time_time.timeStampFormat(Date.now(), 'yyyy-MM-dd hh:mm:ss');
}
/**
* 上传
*/
}, {
key: "upload",
value: function upload() {
return tslib_es6.__awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee() {
var _t;
return _regeneratorRuntime__default["default"].wrap(function (_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
_context.prev = 0;
_context.next = 1;
return this.tryUpload();
case 1:
_context.next = 5;
break;
case 2:
_context.prev = 2;
_t = _context["catch"](0);
if (!(this.tryTimesMap.UPLOAD < mpCi_config.MAX_TRY_TIMES_MAP.UPLOAD)) {
_context.next = 4;
break;
}
this.tryTimesMap.UPLOAD += 1;
_context.next = 3;
return this.tryUpload();
case 3:
_context.next = 5;
break;
case 4:
throw new Error(_t);
case 5:
case "end":
return _context.stop();
}
}, _callee, this, [[0, 2]]);
}));
}
}, {
key: "tryUpload",
value: function tryUpload() {
return tslib_es6.__awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee2() {
var robotNumber, version, buildDesc, uploadResult;
return _regeneratorRuntime__default["default"].wrap(function (_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
robotNumber = this.robotNumber, version = this.version, buildDesc = this.buildDesc;
_context2.next = 1;
return this.ciLib.upload({
project: this.projectCI,
version: version,
desc: buildDesc,
robot: robotNumber,
setting: this.buildSetting
});
case 1:
uploadResult = _context2.sent;
this.getBuildTime();
_context2.next = 2;
return this.ciLib.getDevSourceMap({
project: this.projectCI,
robot: robotNumber,
sourceMapSavePath: './sm.zip'
});
case 2:
console.log('[MpCI] UploadResult:\n', uploadResult);
case 3:
case "end":
return _context2.stop();
}
}, _callee2, this);
}));
}
}, {
key: "preview",
value: function preview() {
return tslib_es6.__awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee3() {
return _regeneratorRuntime__default["default"].wrap(function (_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
_context3.prev = 0;
_context3.next = 1;
return this.tryPreview();
case 1:
_context3.next = 3;
break;
case 2:
_context3.prev = 2;
_context3["catch"](0);
if (!(this.tryTimesMap.UPLOAD < mpCi_config.MAX_TRY_TIMES_MAP.UPLOAD)) {
_context3.next = 3;
break;
}
this.tryTimesMap.UPLOAD += 1;
_context3.next = 3;
return this.tryPreview();
case 3:
case "end":
return _context3.stop();
}
}, _callee3, this, [[0, 2]]);
}));
}
/**
* 预览
*/
}, {
key: "tryPreview",
value: function tryPreview() {
return tslib_es6.__awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee4() {
var previewParam, previewResult;
return _regeneratorRuntime__default["default"].wrap(function (_context4) {
while (1) switch (_context4.prev = _context4.next) {
case 0:
previewParam = {
project: this.projectCI,
desc: this.buildDesc,
setting: this.buildSetting,
qrcodeFormat: 'image',
qrcodeOutputDest: this.savePreviewPath,
robot: this.robotNumber,
pagePath: this.pagePath || undefined,
searchQuery: this.searchQuery || undefined
// pagePath: 'pages/index/index', // 预览页面
// searchQuery: 'a=1&b=2', // 预览参数 [注意!]这里的`&`字符在命令行中应写成转义字符`&`
};
_context4.next = 1;
return this.ciLib.preview(previewParam);
case 1:
previewResult = _context4.sent;
console.log('[MpCI] PreviewResult:\n', previewResult);
this.previewResult = previewResult;
_context4.next = 2;
return this.uploadPreviewImg(previewResult);
case 2:
case "end":
return _context4.stop();
}
}, _callee4, this);
}));
}
/**
* 上传预览图片到COS
*/
}, {
key: "uploadPreviewImg",
value: function uploadPreviewImg(previewResult) {
return tslib_es6.__awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee5() {
var robotNumber, env, buildTime, commitInfo, version, textList, newPreviewImg;
return _regeneratorRuntime__default["default"].wrap(function (_context5) {
while (1) switch (_context5.prev = _context5.next) {
case 0:
robotNumber = this.robotNumber, env = this.env, buildTime = this.buildTime, commitInfo = this.commitInfo, version = this.version;
textList = ['[CI RESULT]', "VERSION: ".concat(version), "UPLOADER: CI ROBOT ".concat(robotNumber), "ENV: ".concat(env), "BRANCH: ".concat(commitInfo.branch), "BUILD TIME: ".concat(buildTime), "LAST COMMIT: ".concat(commitInfo.author, " - ").concat(commitInfo.message, " - ").concat(commitInfo.hash)].concat(_toConsumableArray__default["default"](mpCi_helper.parseUploadResult(previewResult))).map(function (item) {
if (item.length > mpCi_config.PREVIEW_IMG_MAX_WORD_LENGTH) return "".concat(item.slice(0, mpCi_config.PREVIEW_IMG_MAX_WORD_LENGTH), "...");
return item;
});
_context5.next = 1;
return canvas_imgText.addTextForImg({
width: 300,
height: 300,
imgPath: this.savePreviewPath,
textList: textList
});
case 1:
newPreviewImg = _context5.sent;
_context5.next = 2;
return nodeImg_img.saveBase64ImgToFile({
imgUrl: newPreviewImg,
savePath: this.savePreviewPath
});
case 2:
this.uploadFiles([{
key: this.getCosKey(),
path: this.savePreviewPath
}]);
case 3:
case "end":
return _context5.stop();
}
}, _callee5, this);
}));
}
}, {
key: "getCosKey",
value: function getCosKey() {
var cosInfo = this.cosInfo,
env = this.env,
commitInfo = this.commitInfo;
return "".concat(cosInfo.dir, "/").concat(commitInfo.branch.replace(/\//g, '-'), "_").concat(env, ".png");
}
}, {
key: "getCOSFilePath",
value: function getCOSFilePath() {
var _this$cosInfo = this.cosInfo,
bucket = _this$cosInfo.bucket,
region = _this$cosInfo.region;
var cosKey = this.getCosKey();
return tencentCloud_cos_link.getCosUrlLink({
bucket: bucket,
region: region,
dir: '',
fileName: cosKey
});
}
/**
* 发送机器人消息
*/
}, {
key: "sendRobotMsg",
value: function sendRobotMsg() {
var hasImg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
return tslib_es6.__awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee6() {
var robotNumber, webhookUrl, env, commitInfo, version, previewResult, appName, chatId, descList, buildUrl, template;
return _regeneratorRuntime__default["default"].wrap(function (_context6) {
while (1) switch (_context6.prev = _context6.next) {
case 0:
robotNumber = this.robotNumber, webhookUrl = this.webhookUrl, env = this.env, commitInfo = this.commitInfo, version = this.version, previewResult = this.previewResult, appName = this.appName;
chatId = this.chatId;
if (webhookUrl) {
_context6.next = 1;
break;
}
return _context6.abrupt("return");
case 1:
if (!chatId) {
chatId = undefined;
}
descList = ["\u5206\u652F\uFF1A".concat(commitInfo.branch), "\u73AF\u5883\uFF1A".concat(env), "\u7248\u672C\uFF1A".concat(version || ''), "\u673A\u5668\u4EBA\uFF1A".concat(robotNumber), "\u6700\u540E\u63D0\u4EA4: ".concat(commitInfo.author, " - ").concat(commitInfo.message, " - ").concat(commitInfo.hash), "\u603B\u5305\uFF1A".concat(getFullPackageSize(previewResult)), "\u4E3B\u5305\uFF1A".concat(getMainPackageSize(previewResult)) // `${buildTime || ''}`,
];
if (hasImg) {
descList.push("[\u9884\u89C8\u56FE\u7247](".concat(this.getCOSFilePath(), ")"));
}
buildUrl = process.env.BK_CI_BUILD_URL;
if (buildUrl) {
descList.push("[\u6784\u5EFA\u5730\u5740](".concat(buildUrl, ")"));
}
template = "> \u2705\u3010".concat(appName || '', " WX MP\u3011").concat(descList.join(','));
wecomRobot_base.sendWxRobotMarkdown({
webhookUrl: webhookUrl,
content: template,
chatId: chatId
});
case 2:
case "end":
return _context6.stop();
}
}, _callee6, this);
}));
}
}, {
key: "uploadAndPreview",
value: function uploadAndPreview() {
return tslib_es6.__awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee7() {
var webhookUrl, errorLink, commitInfo, env, appName, chatId, descList, errorContent, _t3;
return _regeneratorRuntime__default["default"].wrap(function (_context7) {
while (1) switch (_context7.prev = _context7.next) {
case 0:
_context7.prev = 0;
_context7.next = 1;
return Promise.all([this.upload(), this.preview()]);
case 1:
_context7.next = 4;
break;
case 2:
_context7.prev = 2;
_t3 = _context7["catch"](0);
console.log('[MpCI] err', _t3);
webhookUrl = this.webhookUrl, errorLink = this.errorLink, commitInfo = this.commitInfo, env = this.env, appName = this.appName;
chatId = this.chatId;
if (webhookUrl) {
_context7.next = 3;
break;
}
return _context7.abrupt("return");
case 3:
if (!chatId) {
chatId = undefined;
}
descList = ["\u5206\u652F\uFF1A".concat(commitInfo.branch), "\u73AF\u5883\uFF1A".concat(env), _t3.toString()];
errorContent = "".concat(errorLink ? "[".concat(appName || '', "\u6784\u5EFA\u5931\u8D25](").concat(errorLink, ")") : '').concat(descList.join(','));
wecomRobot_base.sendWxRobotMarkdown({
webhookUrl: webhookUrl,
content: errorContent,
chatId: chatId
});
case 4:
case "end":
return _context7.stop();
}
}, _callee7, this, [[0, 2]]);
}));
}
}, {
key: "uploadFiles",
value: function uploadFiles(files) {
return tslib_es6.__awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee8() {
var _ref, secretId, secretKey, bucket, region;
return _regeneratorRuntime__default["default"].wrap(function (_context8) {
while (1) switch (_context8.prev = _context8.next) {
case 0:
_ref = this.cosInfo || {}, secretId = _ref.secretId, secretKey = _ref.secretKey, bucket = _ref.bucket, region = _ref.region;
_context8.next = 1;
return tencentCloud_cos_cos.uploadCOSFile({
files: files,
secretId: secretId,
secretKey: secretKey,
bucket: bucket,
region: region
});
case 1:
case "end":
return _context8.stop();
}
}, _callee8, this);
}));
}
}]);
}();
exports.MpCI = MpCI;