UNPKG

@erchoc/node-deploy

Version:

新一代 Nodejs 跨平台通用构建和部署方案

115 lines (99 loc) 3.29 kB
/** * 构建部署时, 将当前应用信息上报到指定地址做数据采集分析 */ import { join } from 'path'; import { cpus, totalmem } from 'os'; import { execSync } from 'child_process'; import { readFileSync, existsSync } from 'fs'; // 仓库信息 function getGitInfo() { try { return { gitRepo: execSync('git config --get remote.origin.url').toString().trim(), gitBranch: execSync('git rev-parse --abbrev-ref HEAD').toString().trim(), gitCommitId: execSync('git rev-parse HEAD').toString().trim(), }; } catch (error) { console.error('获取 Git 信息失败', error); return {}; } } // 分析依赖 function analyzeDependencies() { try { const packageJsonPath = join(process.cwd(), 'package.json'); const nodeModulesPath = join(process.cwd(), 'node_modules'); if (!existsSync(packageJsonPath) || !existsSync(nodeModulesPath)) { console.error('package.json 或 node_modules 不存在: ', packageJsonPath, nodeModulesPath); return {}; } const { dependencies = {}, devDependencies = {} } = JSON.parse(readFileSync(packageJsonPath, 'utf-8')); // 依赖大小 (node_modules 目录大小) const sizeInBytes = execSync('du -sh node_modules').toString().trim(); const dependencySize = sizeInBytes.split('\t')[0]; // 过时依赖 return { // 生产依赖不易过多 dependencyCount: Object.keys(dependencies).length, devDependencyCount: Object.keys(devDependencies).length, // 依赖包体积不宜过大 dependencySize, // 怎么判断主要依赖? majorDependencies: [], // 怎么判断过时依赖? outdatedDependencies: [], }; } catch (error) { console.error('分析依赖信息失败', error); return {}; } } const defaultParams = { // 基础信息 appType: '', appName: '', nodeVersion: process.version, npmVersion: execSync('npm -v').toString().trim(), // tnpmVersion: execSync('tnpm -v').toString().trim(), pnpmVersion: execSync('pnpm -v').toString().trim(), os: process.platform, cpuCore: cpus().length, memoryTotal: Math.round(totalmem() / (1024*1024*1024)) + 'GB', environment: process.env.NODE_ENV || 'development', gitRepo: '', gitBranch: '', gitCommitId: '', // 依赖分析 dependencyCount: '', devDependencyCount: '', dependencySize: '', majorDependencies: [], outdatedDependencies: [], // 构建相关 buildTool: 'tnpm', buildPerson: '', buildDuring: '', buildPlatform: '', buildTimestamp: '', buildNodeVersion: '', buildResult: '', buildFailReason: '', buildArtifactSize: '', // 部署相关 deployPlatform: '', deployBaseImage: '', }; export function report(customParams) { const gitInfo = getGitInfo(); const dependencyInfo = analyzeDependencies(); const postData = { ...defaultParams, ...gitInfo, ...dependencyInfo, ...customParams, }; console.warn('发送埋点参数', postData); // TODO 发送请求 } // 非开发环境才上报 report({});