Commit 4cbcd50e authored by Auto Backup's avatar Auto Backup

feat: 添加环境检测脚本,检查git、node、ss3ops安装状态并自动安装

parent 79095866
...@@ -58,28 +58,24 @@ pipeline { ...@@ -58,28 +58,24 @@ pipeline {
steps { steps {
script { script {
try { try {
// 1. 打印 Jenkins 内部变量 echo "🚀 开始运行环境检测..."
echo "--- Jenkins 内部变量 ---"
// runPowerShellWithOutput("set")
// 使用新创建的环境检测脚本
def envCheckResult = runPowerShellWithOutput("node ./check-environment.js")
// 3. 检查 Git 版本 echo "环境检测结果:"
echo "--- Git 版本检查 ---" echo envCheckResult
runPowerShellWithOutput("git --version")
// 4. 检查 Node.js 版本
echo "--- Node.js 版本检查 ---"
runPowerShellWithOutput("node --version")
// 5. 检查 npm 版本 // 如果脚本返回非零退出码,这里会抛出异常
echo "--- npm 版本检查 ---" // 所以我们不需要额外检查
runPowerShellWithOutput("npm --version")
} catch (Exception e) { } catch (Exception e) {
echo "环境排查阶段发生错误: ${e.message}" echo "环境排查阶段发生错误: ${e.message}"
echo "⚠️ 环境检测失败,请确保以下组件已安装:"
echo "1. Git (https://git-scm.com/downloads)"
echo "2. Node.js (https://nodejs.org/)"
echo "3. ss3ops (会自动安装,如失败请手动安装)"
currentBuild.result = 'FAILURE'
error("环境检测失败: ${e.message}")
} }
} }
} }
......
#!/usr/bin/env node
const { exec, spawn } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);
const fs = require('fs');
const os = require('os');
// Platform detection
const isWindows = os.platform() === 'win32';
const isMacOS = os.platform() === 'darwin';
const isLinux = os.platform() === 'linux';
console.log(`Platform: ${os.platform()} (${isWindows ? 'Windows' : isMacOS ? 'macOS' : isLinux ? 'Linux' : 'Other'})`);
/**
* Execute command and return result
* @param {string} command - Command to execute
* @returns {Promise<{success: boolean, stdout: string, stderr: string}>}
*/
async function executeCommand(command) {
try {
const { stdout, stderr } = await execAsync(command);
return { success: true, stdout: stdout.trim(), stderr: stderr.trim() };
} catch (error) {
return {
success: false,
stdout: error.stdout ? error.stdout.trim() : '',
stderr: error.stderr ? error.stderr.trim() : error.message
};
}
}
/**
* Check if git is installed
*/
async function checkGit() {
console.log('🔍 Checking Git installation...');
// Try git --version
const result = await executeCommand('git --version');
if (result.success) {
console.log(`✅ Git is installed: ${result.stdout}`);
return true;
} else {
console.log('❌ Git is not installed or not in PATH');
// For Windows, try common git paths
if (isWindows) {
const commonPaths = [
'C:\\Program Files\\Git\\bin\\git.exe',
'C:\\Program Files (x86)\\Git\\bin\\git.exe',
'D:\\Git\\bin\\git.exe'
];
for (const path of commonPaths) {
if (fs.existsSync(path)) {
console.log(`✅ Git found at: ${path}`);
return true;
}
}
}
return false;
}
}
/**
* Check if Node.js is installed
*/
async function checkNode() {
console.log('🔍 Checking Node.js installation...');
// Try node --version
const result = await executeCommand('node --version');
if (result.success) {
console.log(`✅ Node.js is installed: ${result.stdout}`);
// Also check npm
const npmResult = await executeCommand('npm --version');
if (npmResult.success) {
console.log(`✅ npm is installed: ${npmResult.stdout}`);
} else {
console.log('⚠️ npm is not installed or not in PATH');
}
return true;
} else {
console.log('❌ Node.js is not installed or not in PATH');
// For Windows, try common node paths
if (isWindows) {
const commonPaths = [
'C:\\Program Files\\nodejs\\node.exe',
'C:\\Program Files (x86)\\nodejs\\node.exe'
];
for (const path of commonPaths) {
if (fs.existsSync(path)) {
console.log(`✅ Node.js found at: ${path}`);
return true;
}
}
}
return false;
}
}
/**
* Check if ss3ops is globally installed
*/
async function checkSs3ops() {
console.log('🔍 Checking ss3ops global installation...');
// Method 1: Try to run ss3ops command
const versionResult = await executeCommand('ss3ops --version');
if (versionResult.success) {
console.log(`✅ ss3ops is available: ${versionResult.stdout}`);
return true;
}
// Method 2: Check npm global packages
// Use npm list -g --json for easier parsing
const npmListResult = await executeCommand('npm list -g --json --depth=0');
if (npmListResult.success) {
try {
const packages = JSON.parse(npmListResult.stdout);
// Check dependencies object
if (packages.dependencies) {
for (const pkgName in packages.dependencies) {
if (pkgName.includes('ss3ops') || pkgName.includes('client-s3')) {
console.log(`✅ ss3ops found in global packages: ${pkgName}@${packages.dependencies[pkgName].version}`);
return true;
}
}
}
} catch (parseError) {
// JSON parsing failed, fallback to string search
console.log('⚠️ Could not parse npm list output, using string search');
}
}
// Method 3: Simple string search in npm list output
let command = 'npm list -g';
if (isWindows) {
command = 'npm list -g --depth=0';
}
const result = await executeCommand(command);
if (result.success) {
// Check if ss3ops or client-s3 appears in the output
const lines = result.stdout.split('\n');
for (const line of lines) {
if (line.includes('ss3ops') || line.includes('client-s3')) {
console.log(`✅ ss3ops found in npm list: ${line.trim()}`);
return true;
}
}
}
console.log('❌ ss3ops is not globally installed');
return false;
}
/**
* Install ss3ops globally
*/
async function installSs3ops() {
console.log('📦 Installing ss3ops globally...');
const installUrl = 'git+ssh://git@git.youdatasum.com:ljg/client-s3.git';
const command = `npm install -g ${installUrl}`;
console.log(`Running: ${command}`);
const result = await executeCommand(command);
if (result.success) {
console.log('✅ ss3ops installed successfully');
if (result.stdout) {
console.log(`Output: ${result.stdout.substring(0, 200)}...`);
}
return true;
} else {
console.log('❌ Failed to install ss3ops');
if (result.stderr) {
console.log(`Error: ${result.stderr}`);
}
return false;
}
}
/**
* Main function
*/
async function main() {
console.log('🚀 Starting environment check...\n');
let allChecksPassed = true;
// Check Git
const gitInstalled = await checkGit();
if (!gitInstalled) {
console.log('⚠️ Git is required for this environment');
allChecksPassed = false;
}
console.log();
// Check Node.js
const nodeInstalled = await checkNode();
if (!nodeInstalled) {
console.log('⚠️ Node.js is required for this environment');
allChecksPassed = false;
}
console.log();
// Check ss3ops
const ss3opsInstalled = await checkSs3ops();
if (!ss3opsInstalled) {
console.log('\n📦 ss3ops is not installed. Attempting to install...');
const installed = await installSs3ops();
if (!installed) {
console.log('❌ Failed to install ss3ops');
allChecksPassed = false;
} else {
// Verify installation
const verified = await checkSs3ops();
if (!verified) {
console.log('❌ ss3ops installation verification failed');
allChecksPassed = false;
}
}
}
console.log('\n' + '='.repeat(50));
if (allChecksPassed) {
console.log('✅ All environment checks passed!');
process.exit(0);
} else {
console.log('❌ Some environment checks failed');
console.log('\nPlease install the missing components:');
if (!gitInstalled) console.log('- Git: https://git-scm.com/downloads');
if (!nodeInstalled) console.log('- Node.js: https://nodejs.org/');
process.exit(1);
}
}
// Handle errors
process.on('unhandledRejection', (error) => {
console.error('Unhandled rejection:', error);
process.exit(1);
});
// Run main function
main().catch(error => {
console.error('Fatal error:', error);
process.exit(1);
});
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment