Skip to content

Instantly share code, notes, and snippets.

@zthxxx
Last active April 11, 2019 08:00
Show Gist options
  • Save zthxxx/0a588928c15c5c0f16c7f81503e59493 to your computer and use it in GitHub Desktop.
Save zthxxx/0a588928c15c5c0f16c7f81503e59493 to your computer and use it in GitHub Desktop.
jenkins last build log to markdown table
const fs = require('fs');
const os = require('os');
const path = require('path');
const exec = require('child_process').exec;
const axios = require('axios')
const dayjs = require('dayjs')
const getJobInfo = async job => {
const auth = `${username}:${token}`
const jobInfoUrl = `http://${auth}@jenkins.${domain}/job/${job}/api/json`
const jobInfo = (await axios.get(jobInfoUrl)).data
process.res = jobInfo
const lastJobID = jobInfo.lastBuild.number
const lastBuildInfoUrl = `http://${auth}@jenkins.${domain}/job/${job}/${lastJobID}/api/json`
const lastBuild = (await axios.get(lastBuildInfoUrl)).data
const commits = lastBuild.changeSet.items
const lastCommit = commits[commits.length - 1]
const lastCommitID = lastCommit.commitId
const curJobUrl = `http://jenkins.${domain}/job/${job}/${lastJobID}/`
const prevJobUrl = `http://jenkins.${domain}/job/${job}/${lastJobID-1}/`
const masterHash = `master@${lastCommitID.slice(0,8)}`
const messages = commits.map(commit => commit.msg)
const project = lastBuild.actions.filter(item => item._class === 'hudson.plugins.git.util.BuildData')[0].remoteUrls[0]
const projectName = project.replace(/^git.*?:/, '').replace(/.git$/, '')
const projectUrl = `https://git.${domain}/${projectName}`
const buildTime = dayjs(lastBuild.timestamp).format('YYYY-MM-DD HH:mm')
const publishTable = [
'| xxx | xxx | xxx | xxx | xxx | xxx | xxx | xxx | xxx | xxx |',
'| -- | -- | -- | -- | -- | -- | -- | -- | -- | -- |',
`| ${projectName} | [链接](${curJobUrl}) | [${masterHash}](${projectUrl}@${lastCommitID}) | [链接](${prevJobUrl}) | 无 | - ${messages.join(' <br />- ')} | ${username} | ${username} | ${username} | ${buildTime} |`,
]
const publishLog = publishTable.join('\n')
console.log(publishLog)
openTypora(publishLog)
}
const openTypora = text => {
const tmpFile = path.join(os.tmpdir(), `publishLog-${Math.random().toString(36).slice(2)}.md`)
fs.writeFile(tmpFile, text, err => {
if (err) {
console.log('write in tmp file error', err)
throw err
};
exec(`open -a typora ${tmpFile}`)
});
}
const username = ''
const token = ''
const domain = ''
getJobInfo('')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment