1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
| const Jenkins = require('jenkins') const fs = require('fs') const path = require('path') const { exec } = require('child_process') const package = require('../package.json')
const auth = {} let jobName = ''
let jenkins let branchName = 'test'
function deploy (name, branch) { jobName = name if (branch) { branchName = branch initJenkins() } else { getGitBranch() .then(res => { branchName = res initJenkins() }) } }
async function initJenkins() { try { const data = fs.readFileSync(path.join(__dirname, '../session', 'token.json'), 'utf8') Object.assign(auth, JSON.parse(data)) try { jenkins = new Jenkins({ baseUrl: `https://${auth.account}:${auth.token}@jenkins-test.xxx.com`, }) triggerBuild() } catch (error) { console.log(error); process.exit(0) } } catch (error) { console.error(`配置文件未找到,请先运行 ${package.name} jk 生成配置文件`) process.exit(0) } }
function getGitBranch() { return new Promise((resolve, reject) => { exec('git rev-parse --abbrev-ref HEAD', (error, stdout, stderr) => { if (error) { console.error(`exec error: ${error}`) reject() return; } resolve(stdout.trim()) }) }) }
async function triggerBuild() { try { const result = await jenkins.job.build({ name: jobName, parameters: { branch: branchName, merge: true }, token: auth.token }) console.log('准备构建...', result) waitOnQueue(result) } catch (error) { console.error('error: ', error); } }
async function waitOnQueue(id) { const result = await jenkins.queue.item(id) if (result.executable) { console.log('开始构建: ', jobName); setTimeout(() => { logBuild(result.executable.number) }, 500); } else if (result.cancelled) { console.log('构建已取消') } else { setTimeout(() => { waitOnQueue(id) }, 500); } }
function logBuild(id) { console.log('构建中...', id) const log = jenkins.build.logStream(jobName, id);
log.on("data", (text) => { process.stdout.write(text); });
log.on("error", (err) => { console.log("error", err); });
log.on("end", () => { console.log("success: 构建完成."); }); }
module.exports = deploy
|