Skip to content

Instantly share code, notes, and snippets.

@dohse
Last active December 31, 2015 17:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dohse/8019691 to your computer and use it in GitHub Desktop.
Save dohse/8019691 to your computer and use it in GitHub Desktop.
#!/usr/bin/env node
var assert = require('assert');
var childProcess = require('child_process');
var express = require('express');
var request = require('request');
var app = express();
app.get('/', function(req, res, next) {
var uri = req.query.url;
console.log(uri);
function errorResponse(reason) {
return '<h1><a href="' + uri + '">' + reason + '</a></h1>';
}
var repository;
function start() {
if (uri.match(/\?url=([^&=]+)/)) {
return res.redirect(uri);
}
// https://github.com/dohse/test/pull/1
var match = uri.match(/github\.com\/([^\/]+\/[^\/]+)\/pull\/(\d+)/);
if (!match) {
return res.send(errorResponse('Invalid Site'));
}
repository = match[1];
var pullRequestNumber = match[2];
// GET /repos/:owner/:repo/pulls/:number
var pullRequestUrl = 'https://api.github.com/repos/' + repository +
'/pulls/' + pullRequestNumber;
var options = {
method: 'get',
url: pullRequestUrl,
qs: {
access_token: process.env.GITHUB_TOKEN
},
headers: {
'user-agent': 'Rebasematic'
},
json: true
};
request(options, handlePullRequest);
}
function handlePullRequest(err, githubRes) {
if (err) {
return next(err);
}
if (githubRes.statusCode !== 200) {
return res.send(errorResponse('Github API access failed'));
}
var branch = githubRes.body.head.ref;
var command = [
'mkdir -p $1',
'exec {LOCK}<$1',
'flock -x $LOCK',
'[[ -e $1/.git ]] || git clone github.com:$1 $1',
'cd $1',
'git fetch',
'git checkout -B rebase origin/$2',
'if ! git rebase origin/master',
'then',
' git rebase --abort',
' false',
'fi',
'git push -f origin HEAD:$2'
].join('\n');
var args = ['-euc', command, '-', repository, branch];
var options = {
cwd: process.env.REBASEMATIC_WORKDIR,
stdio: 'inherit'
};
childProcess.spawn('/bin/bash', args, options).once('exit', handleDone);
}
function handleDone(code, signal) {
if (code !== 0) {
return res.send(errorResponse('Rebase failed'));
}
res.redirect(uri);
}
start();
});
app.listen(Number(process.env.REBASEMATIC_PORT || '19585'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment