gitlab-to-irc/index.js

127 lines
3.3 KiB
JavaScript

var irc = require('irc');
var express = require('express');
var bodyParser = require('body-parser');
var config = require('./config');
var client = new irc.Client(config.server, config.nick, {
//debug: true,
channels: config.channels,
userName: config.userName,
realName: config.realName,
retryDelay: 120000
});
var say = client.say.bind(client);
var app = express();
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
function formatCommit(commit) {
return commit.message + ' ' + commit.url;
}
var handlers = {
push: function(body) {
var user = body.user_name;
var projectName = body.project.name;
var commits = body.commits;
var msg = ['push on ' + projectName + ': ' + user + ' pushed ' + commits.length + ' commits.'];
if (commits.length < 4) {
msg = msg.concat(commits.map(formatCommit));
} else {
msg.push(formatCommit(commits[0]) + ' ...');
msg.push(formatCommit(commits[commits.length - 1]));
}
return msg;
},
issue: function(body) {
var user = body.user.name;
var projectName = body.project.name;
var issue = body.object_attributes;
var issueNumber = issue.iid;
var issueTitle = issue.title;
var issueState = issue.state;
var url = issue.url;
var msg = [projectName + ': issue #' + issueNumber + ' has changed state ("' + issueState + '")'];
msg.push(issueTitle + ' ' + url);
return msg;
},
merge_request: function(body) {
var user = body.user.name;
var request = body.object_attributes;
var projectName = request.target.name;
var from = request.source_branch;
var to = request.target_branch;
var id = request.iid;
var title = request.title;
var url = request.url;
var state = request.state;
var msg = [projectName + ': merge request (' + from + ':' + to + ') #' + id + ' has changed state ("' + state + '")'];
msg.push(title + ' ' + url);
return msg;
},
build: function(body) {
var id = body.build_id;
var status = body.build_status;
var isFinished = body.build_finished_at !== null;
var duration = body.build_duration;
var projectName = body.project_name;
var stage = body.build_stage;
var msg = [];
msg.push(projectName + ': build #' + id + ' (' + stage + ') changed status: ' + status);
if (isFinished)
msg.push('build finished in ' + duration + ' seconds. ');
return msg;
}
};
app.post('/', function(req, res) {
var body = req.body || {};
var msgs = null;
if (body.object_kind && handlers[body.object_kind])
msgs = handlers[body.object_kind](body);
else
console.log("Unexpected object_kind:", body.object_kind);
if (msgs) {
if (msgs instanceof Array) {
for (var i = 0; i < msgs.length; i++)
say(config.channels, msgs[i]);
} else {
say(config.channels, msgs);
}
}
res.sendStatus(200);
});
app.listen(config.port, config.hostname, function() {
console.log('gitlab-to-irc running.');
});