var express = require('express'); var router = express.Router(); var moment = require('moment') const {spawn} = require('child_process'); const _info='info' const _error='error' const access_token='' function log(param,message){ console[param](`${moment().utcOffset(480).format('yyyy-MM-DD HH:mm:ss')}:${message}`) } function info(message){ log(_info,message) } function error(message){ log(_error,message) } function dingding(message){ info(message) fetch(`https://oapi.dingtalk.com/robot/send?access_token=${access_token}`,{ method:'POST', headers:{ 'Content-Type':'application/json' }, body:{ msgtype:'text', text:{ content:message } } }).then(res=>res.json()).then(res=>info(`钉钉推送结果:${res}`)).catch(err=>error(err)) } //记录开始部署的时间 const startDeploy={} //web钩子事件 //git@gogs.kirito.cool:panqihua/RiskCloudMock.git push事件 router.post('/deploy', function(req, res, next) { //提交日志,多次提交只取第一个 const commitsMsg=req.body.commits[0].message //更新时间 const updated_at=req.body.repository.updated_at //仓库名字 const name=req.body.repository.name //仓库描述信息 const description=req.body.repository.description try { startDeploy[name] = { startTime: moment(), description: description } dingding(`开始自动部署${c.repository.description}|${name},更新日志${commitsMsg}`) const promise = new Promise((resolve, reject) => { const spawnObj = spawn('updateRisk', [name], {encoding: 'utf-8'}); spawnObj.stdout.on('data', function (chunk) { info(chunk.toString()); }); spawnObj.stderr.on('data', (data) => { error(data); }); spawnObj.on('close', function (code) { info('close code : ' + code); }) spawnObj.on('exit', (code) => { info('exit code : ' + code); resolve(true) }) }) res.json({message: `仓库代码${req.body.repository.ssh_url}部署中`}) } catch (e) { error(e) res.json({message: `仓库代码${req.body.repository.ssh_url}部署出现异常`}) } }); //部署完毕事件 router.get('/finsh', function(req, res, next) { dingding(`${req.query.name}|${startDeploy[req.query.name].description}自动部署成功, 花费时间:${moment().diff(startDeploy[req.query.name].startTime,'seconds')}秒`) res.json({message:`仓库代码${req.query.name}部署成功`}) }); module.exports = router;