<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    if (counter + step >= length) step = length - counter
    process.stdout.write("\033[2K Writing " + counter + "/" + length + " bytes: " + message + "\r");
    fs.writeSync(outFD, data.slice(counter, counter+step), 0, step)
    child_process.execFileSync('/Applications/Xcode.app/Contents/Developer/usr/bin/git', args)
    var timeout = randomIntFromInterval(0, max_sleep)
    counter = counter + step
<commit_msg>Really commit all the required changes<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    if (counter + step >= length) step = length - counter
    process.stdout.write("\033[2K Writing " + counter + "/" + length + " bytes: " + message + "\r");
    fs.writeSync(outFD, data.slice(counter, counter+step), 0, step)
    child_process.execFileSync('/Applications/Xcode.app/Contents/Developer/usr/bin/git', args)
    var timeout = randomIntFromInterval(0, max_sleep)
    counter = counter + step
 <|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 36<commit_msg>Nearly got it<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 360<|endoftext|>


<commit_before>/* camp.js: server-side Ajax handler that wraps around Node.js.
 * Copyright © 2011 Thaddee Tyl, Jan Keromnes. All rights reserved.
 * Code covered by the LGPL license. */

"use strict";

var Plate = require ('./plate');

var EventEmitter = require ('events').EventEmitter,
    http = require('http'),
    https = require('https'),
    p = require('path'),
    fs = require('fs'),
    url = require('url'),
    qs = require('querystring'),
    zlib = require('zlib');

var mime = require('./mime.json'),
    binaries = [
      'pdf', 'ps', 'odt', 'ods', 'odp', 'xls', 'doc', 'ppt', 'dvi', 'ttf',
      'swf', 'rar', 'zip', 'tar', 'gz', 'ogg', 'mp3', 'mpeg', 'wav', 'wma',
      'gif', 'jpg', 'jpeg', 'png', 'svg', 'tiff', 'ico', 'mp4', 'ogv', 'mov',
      'webm', 'wmv'
];

// We'll need to parse the query (either POST or GET) as a literal.
function parsequery (query, strquery) {
  var items = strquery.split('&');
  for (var item in items) {
    // Each element of key=value is then again split along `=`.
    var elems = items[item].split('=');
    try {
      query[decodeURIComponent(elems[0])] =
        JSON.parse(decodeURIComponent(elems[1]));
    } catch (e) {
      console.log ('query:', JSON.stringify(query), e.toString());
    }
  }
  return query;
}

// Ask is a model of the client's request / response environment.
function Ask (server, req, res) {
  this.server = server;
  this.req = req;
  this.res = res;
  try {
    this.uri = url.parse(decodeURI(req.url), true);
  } catch (e) {     // Using `escape` should not kill the server.
    this.uri = url.parse(unescape(req.url), true);
  }
  this.path = this.uri.pathname;
  this.query = this.uri.query;
}

// Set the mime type of the response.
Ask.prototype.mime = function (type) {
  this.res.setHeader('Content-Type', type);
}

// Camp class is classy.
//
// Camp has a router function that returns the stack of functions to call, one
// after the other, in order to process the request.

function Camp() {
  http.Server.call(this);
  this.stack = [];
  for (var i = 0; i < defaultRoute.length; i++)
    this.stack.push(defaultRoute[i](this));
  this.on('request', listener.bind(this));
}
Camp.prototype = new http.Server();

function SecureCamp(opts) {
  https.Server.call(this, opts);
  this.stack = [];
  for (var i = 0; i < defaultRoute.length; i++)
    this.stack.push(defaultRoute[i](this));
  this.on('request', listener.bind(this));
}
// The following `requestCert` thing seems required by node.
SecureCamp.prototype = new https.Server({requestCert:null});

// Insert a listener after a listener named `listn`.

Camp.prototype.insertListener = SecureCamp.prototype.insertListener =
function addListenerBefore(listn, type, listener) {

  // this._events is an EventEmitter thing, a list of functions.

  if (this._events && this._events[type] && Array.isArray(this._events[type])) {
    var index = 0;
    for (var i = 0; i < this._events[type].length; i++) {
      if (this._events[type][i].name === listn) {
        index = i;
        break;
      }
    }

    // Insertion algorithm from <http://jsperf.com/insert-to-an-array>.
    var l = this._events[type],
        a = l.slice(0, index);
    a.push(listener);
    this._events[type] = a.concat(l.slice(index));

  } else {
    this.on(type, listener);
  }
  return this;
}

// Default request listener.

function listener (req, res) {
  var ask = new Ask(this, req, res);
  bubble(ask, 0);
}

// The bubble goes through each layer of the stack until it reaches the surface.
// The surface is a Server Error, btw.
function bubble (ask, layer) {
  ask.server.stack[layer](ask, function next() {
    if (ask.server.stack.length > layer + 1) bubble(ask, layer + 1);
    else {
      ask.res.statusCode = 500;
      ask.res.end('500\n');
    }
  });
}

// The default routing function:
//
// - if the request is of the form /$socket.io, it runs the socket.io unit.
// - if the request is of the form /$..., it runs the ajax / eventSource unit.
// - if the request is a registered template, it runs the template unit.
// - if the request isn't a registered route, it runs the static unit.
// - else, it runs the notfound unit.

var defaultRoute = [socketUnit, ajaxUnit, eventSourceUnit,
                    routeUnit, staticUnit, notfoundUnit];

// Socket.io unit.
function socketUnit (server) {
  var io = server.io = require('socket.io').listen(server);
  // Client-side: <script src="/$socket.io/socket.io.js"></script>
  function ioConf() { io.set('resource', '/$socket.io'); }
  io.configure('development', ioConf);
  io.configure('production', ioConf);

  return function socketLayer (ask, next) {
    // Socket.io doesn't care about anything but /$socket.io now.
    if (ask.path.slice(1, 11) !== '$socket.io') next();
  };
}

// Ajax unit.
function ajaxUnit (server) {
  var ajax = server.ajax = new EventEmitter();

  return function ajaxLayer (ask, next) {
    if (ask.path[1] !== '$') return next();
    var action = ask.path.slice(2),
        res = ask.res;

    if (ajax.listeners(action).length <= 0) return next();

    res.setHeader('Content-Type', mime.json);

    // Handler for when we get a data request.
    var gotrequest = function (chunk) {

      if (chunk !== undefined) parsequery(ask.query, chunk.toString());

      // Launch the defined action.
      ajax.emit(action, ask.query, function ajaxEnd (data) {
        res.end(JSON.stringify(data || {}));
      }, ask);
    };
    if (ask.req.method === 'POST') ask.req.on ('data', gotrequest);
    else gotrequest();
  };
}

// EventSource unit.
//
// Note: great inspiration was taken from Remy Sharp's code.
function eventSourceUnit (server) {
  var sources = {};

  function Source () {
    this.conn = [];
    this.history = [];
    this.lastMsgId = 0;
  }

  Source.prototype.removeConn = function(res) {
    var i = this.conn.indexOf(res);
    if (i !== -1) {
      this.conn.splice(i, 1);
    }
  };

  Source.prototype.sendSSE = function (res, id, event, message) {
    var data = '';
    if (event !== null) {
      data += 'event:' + event + '\n';
    }

    // Blank id resets the id counter.
    if (id !== null) {
      data += 'id:' + id + '\n';
    } else {
      data += 'id\n';
    }

    if (message) {
      data += 'data:' + message.split('\n').join('\ndata') + '\n';
    }
    data += '\n';

    res.write(data);

    if (res.hasOwnProperty('xhr')) {
      clearTimeout(res.xhr);
      var self = this;
      res.xhr = setTimeout(function () {
        res.end();
        self.removeConn(res);
      }, 250);
    }
  };

  Source.prototype.emit = function (event, msg) {
    this.lastMsgId++;
    this.history.push({
      id: this.lastMsgId,
      event: event,
      msg: msg
    });

    for (var i = 0; i < this.conn.length; i++) {
      this.sendSSE(this.conn[i], this.lastMsgId, event, msg);
    }
  }

  Source.prototype.send = function (msg) {
    this.emit(null, JSON.stringify(msg));
  }

  function eventSource (channel) {
    return sources[channel] = new Source();
  }

  server.eventSource = eventSource;

  return function eventSourceLayer (ask, next) {
    if (ask.path[1] !== '$') return next();
    var action = ask.path.slice(2),
        res = ask.res,
        source = sources[action];
    if (!source || ask.req.headers.accept !== 'text/event-stream')
      return next();    // Don't bother if the client cannot handle it.

    // Remy Sharp's Polyfill support.
    if (ask.req.headers['x-requested-with'] == 'XMLHttpRequest') {
      res.xhr = null;
    }

    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');

    if (ask.req.headers['last-event-id']) {
      var id = parseInt(ask.req.headers['last-event-id']);
      for (var i = 0; i < source.history.length; i++)
        if (source.history[i].id > id)
          source.sendSSE(res, source.history[i].id,
              source.history[i].event, source.history[i].msg);
    } else res.write('id\n\n');      // Reset id.

    source.conn.push(res);

    // Every 15s, send a comment (avoids proxy dropping HTTP connection).
    var to = setInterval(function () {res.write(':\n');}, 15000);

    // This can only end in blood.
    ask.req.on('close', function () {
      source.removeConn(res);
      clearInterval(to);
    });
  };
}

// Static unit.
function staticUnit (server) {
  var documentRoot = server.documentRoot = process.cwd() + '/web';

  return function staticLayer (ask, next) {
    // We use `documentRoot` as the root wherein we seek files.
    var realpath = p.join(documentRoot, ask.path);
    fs.stat(realpath, function(err, stats) {
      if (err) return next();
      ask.mime(mime[p.extname(ask.path).slice(1)] || 'text/plain');

      if (stats.isDirectory()) {
        realpath = p.join(realpath, 'index.html');
        ask.mime(mime['html']);
      }

      // Connect the output of the file to the network!
      var raw = fs.createReadStream(realpath),
          enc = ask.req.headers['accept-encoding'] || '';

      // Compress when possible
      if (enc.match(/\bgzip\b/)) {
        ask.res.setHeader('content-encoding', 'gzip');
        raw.pipe(zlib.createGzip()).pipe(ask.res);
      } else if (enc.match(/\bdeflate\b/)) {
        ask.res.setHeader('content-encoding', 'deflate');
        raw.pipe(zlib.createDeflate()).pipe(ask.res);
      } else {
        raw.pipe(ask.res);
      }
    });
  };
}

// Template unit.
function routeUnit (server) {
  var templates = [];

  function route (paths, literalCall) {
    templates.push([RegExp(paths).source, literalCall]);
  }

  server.route = route;

  return function routeLayer (ask, next) {
    var platepaths;
    if ((platepaths = templates.filter (function(key) {
          return RegExp(key[0]).test (ask.path);
        })).length > 0) {
      catchpath(ask, platepaths);
    } else {
      next();
    }
  };
}

// Not Fount unit — in fact, mostly a copy&paste of the route unit.
function notfoundUnit (server) {
  var notfoundTemplates = [];

  function notfound (paths, literalCall) {
    notfoundTemplates.push([RegExp(paths).source, literalCall]);
  }

  server.notfound = notfound;

  return function notfoundLayer (ask) {
    var platepaths;
    ask.res.statusCode = 404;
    if ((platepaths = notfoundTemplates.filter (function(key) {
          return RegExp(key[0]).test (ask.path);
        })).length > 0) {
      catchpath(ask, platepaths);
    } else {
      ask.res.end('404\n');
    }
  };
}

// Route *and* not found units — see what I did there?

function catchpath (ask, platepaths) {
  var res = ask.res;

  if (platepaths.length > 1) {
    console.error ('More than one template path match', ask.path + ':');
    platepaths.forEach (function (path) {console.error ('-', path[0]);});
  }
  var pathmatch = ask.path.match (RegExp (platepaths[0][0]));

  // Template parameters (JSON-serializable).
  var params = platepaths[0][1](ask.query, pathmatch, function end (params) {
    if (!ask.res.getHeader('Content-Type'))   // Allow overriding.
      ask.mime(mime[p.extname(pathmatch[0]).slice(1)] || 'text/plain');

    var templatePath = p.join(ask.server.documentRoot, pathmatch[0]),
        reader = fs.createReadStream(templatePath);

    if (!(params && Object.keys(params).length)) {
      // No data was given. Same behaviour as static.
      var enc = ask.req.headers['accept-encoding'] || '';

      // Compress when possible
      if (enc.match(/\bgzip\b/)) {
        ask.res.setHeader('content-encoding', 'gzip');
        reader.pipe(zlib.createGzip()).pipe(ask.res);
      } else if (enc.match(/\bdeflate\b/)) {
        ask.res.setHeader('content-encoding', 'deflate');
        reader.pipe(zlib.createDeflate()).pipe(ask.res);
      } else {
        reader.pipe(ask.res);
      }
    } else {
      Plate.format(reader, ask.res, params);
    }
  }, ask);
}

// Internal start function.
//

function createServer () { return new Camp(); }

function createSecureServer (opts) { return new SecureCamp(opts); }

function startServer (settings) {
  var server;

  // Are we running https?
  if (settings.secure) { // Yep
    server = new SecureCamp ({
      key:  fs.readFileSync(settings.security.key),
      cert: fs.readFileSync(settings.security.cert),
      ca:   settings.security.ca.map(function(file) {
        try {
          var ca = fs.readFileSync(file);
          return ca;
        } catch (e) { console.error('CA file not found:', file); }
      })
    }).listen(settings.port);
  } else { // Nope
    server = new Camp().listen(settings.port);
  }

  return server;
}

// Each camp instance creates an HTTP / HTTPS server automatically.
//
function start (options) {

  // Settings.
  //
  // By settings I mean data that was set when starting the server, and that is
  // not meant to be changed thereafter.
  var settings = {
    port: 80,
    security: {}
  };

  options = options || {};

  for (var setting in options) {
    settings[setting] = options[setting];
  }

  // Populate security values with the corresponding files.
  if (options.secure) {
    settings.security.key = options.key || 'https.key';
    settings.security.cert = options.cert || 'https.crt';
    settings.security.ca = options.ca || [];
  }

  settings.port = settings.port || (settings.secure ? 443 : 80);

  return startServer(settings);
};

exports.start = start;
exports.createServer = createServer;
exports.createSecureServer = createSecureServer;
exports.Camp;
exports.SecureCamp;

exports.socketUnit;
exports.ajaxUnit;
exports.eventSourceUnit;
exports.routeUnit;
exports.staticUnit;
exports.notfoundUnit;

exports.Plate = Plate;
exports.mime = mime;
exports.binaries = binaries;
<commit_msg>gzip/deflate new even with templates!<commit_after>/* camp.js: server-side Ajax handler that wraps around Node.js.
 * Copyright © 2011 Thaddee Tyl, Jan Keromnes. All rights reserved.
 * Code covered by the LGPL license. */

"use strict";

var Plate = require ('./plate');

var EventEmitter = require ('events').EventEmitter,
    http = require('http'),
    https = require('https'),
    p = require('path'),
    fs = require('fs'),
    url = require('url'),
    qs = require('querystring'),
    zlib = require('zlib');

var mime = require('./mime.json'),
    binaries = [
      'pdf', 'ps', 'odt', 'ods', 'odp', 'xls', 'doc', 'ppt', 'dvi', 'ttf',
      'swf', 'rar', 'zip', 'tar', 'gz', 'ogg', 'mp3', 'mpeg', 'wav', 'wma',
      'gif', 'jpg', 'jpeg', 'png', 'svg', 'tiff', 'ico', 'mp4', 'ogv', 'mov',
      'webm', 'wmv'
];

// We'll need to parse the query (either POST or GET) as a literal.
function parsequery (query, strquery) {
  var items = strquery.split('&');
  for (var item in items) {
    // Each element of key=value is then again split along `=`.
    var elems = items[item].split('=');
    try {
      query[decodeURIComponent(elems[0])] =
        JSON.parse(decodeURIComponent(elems[1]));
    } catch (e) {
      console.log ('query:', JSON.stringify(query), e.toString());
    }
  }
  return query;
}

// Ask is a model of the client's request / response environment.
function Ask (server, req, res) {
  this.server = server;
  this.req = req;
  this.res = res;
  try {
    this.uri = url.parse(decodeURI(req.url), true);
  } catch (e) {     // Using `escape` should not kill the server.
    this.uri = url.parse(unescape(req.url), true);
  }
  this.path = this.uri.pathname;
  this.query = this.uri.query;
}

// Set the mime type of the response.
Ask.prototype.mime = function (type) {
  this.res.setHeader('Content-Type', type);
}

// Camp class is classy.
//
// Camp has a router function that returns the stack of functions to call, one
// after the other, in order to process the request.

function Camp() {
  http.Server.call(this);
  this.stack = [];
  for (var i = 0; i < defaultRoute.length; i++)
    this.stack.push(defaultRoute[i](this));
  this.on('request', listener.bind(this));
}
Camp.prototype = new http.Server();

function SecureCamp(opts) {
  https.Server.call(this, opts);
  this.stack = [];
  for (var i = 0; i < defaultRoute.length; i++)
    this.stack.push(defaultRoute[i](this));
  this.on('request', listener.bind(this));
}
// The following `requestCert` thing seems required by node.
SecureCamp.prototype = new https.Server({requestCert:null});

// Insert a listener after a listener named `listn`.

Camp.prototype.insertListener = SecureCamp.prototype.insertListener =
function addListenerBefore(listn, type, listener) {

  // this._events is an EventEmitter thing, a list of functions.

  if (this._events && this._events[type] && Array.isArray(this._events[type])) {
    var index = 0;
    for (var i = 0; i < this._events[type].length; i++) {
      if (this._events[type][i].name === listn) {
        index = i;
        break;
      }
    }

    // Insertion algorithm from <http://jsperf.com/insert-to-an-array>.
    var l = this._events[type],
        a = l.slice(0, index);
    a.push(listener);
    this._events[type] = a.concat(l.slice(index));

  } else {
    this.on(type, listener);
  }
  return this;
}

// Default request listener.

function listener (req, res) {
  var ask = new Ask(this, req, res);
  bubble(ask, 0);
}

// The bubble goes through each layer of the stack until it reaches the surface.
// The surface is a Server Error, btw.
function bubble (ask, layer) {
  ask.server.stack[layer](ask, function next() {
    if (ask.server.stack.length > layer + 1) bubble(ask, layer + 1);
    else {
      ask.res.statusCode = 500;
      ask.res.end('500\n');
    }
  });
}

// The default routing function:
//
// - if the request is of the form /$socket.io, it runs the socket.io unit.
// - if the request is of the form /$..., it runs the ajax / eventSource unit.
// - if the request is a registered template, it runs the template unit.
// - if the request isn't a registered route, it runs the static unit.
// - else, it runs the notfound unit.

var defaultRoute = [socketUnit, ajaxUnit, eventSourceUnit,
                    routeUnit, staticUnit, notfoundUnit];

// Socket.io unit.
function socketUnit (server) {
  var io = server.io = require('socket.io').listen(server);
  // Client-side: <script src="/$socket.io/socket.io.js"></script>
  function ioConf() { io.set('resource', '/$socket.io'); }
  io.configure('development', ioConf);
  io.configure('production', ioConf);

  return function socketLayer (ask, next) {
    // Socket.io doesn't care about anything but /$socket.io now.
    if (ask.path.slice(1, 11) !== '$socket.io') next();
  };
}

// Ajax unit.
function ajaxUnit (server) {
  var ajax = server.ajax = new EventEmitter();

  return function ajaxLayer (ask, next) {
    if (ask.path[1] !== '$') return next();
    var action = ask.path.slice(2),
        res = ask.res;

    if (ajax.listeners(action).length <= 0) return next();

    res.setHeader('Content-Type', mime.json);

    // Handler for when we get a data request.
    var gotrequest = function (chunk) {

      if (chunk !== undefined) parsequery(ask.query, chunk.toString());

      // Launch the defined action.
      ajax.emit(action, ask.query, function ajaxEnd (data) {
        res.end(JSON.stringify(data || {}));
      }, ask);
    };
    if (ask.req.method === 'POST') ask.req.on ('data', gotrequest);
    else gotrequest();
  };
}

// EventSource unit.
//
// Note: great inspiration was taken from Remy Sharp's code.
function eventSourceUnit (server) {
  var sources = {};

  function Source () {
    this.conn = [];
    this.history = [];
    this.lastMsgId = 0;
  }

  Source.prototype.removeConn = function(res) {
    var i = this.conn.indexOf(res);
    if (i !== -1) {
      this.conn.splice(i, 1);
    }
  };

  Source.prototype.sendSSE = function (res, id, event, message) {
    var data = '';
    if (event !== null) {
      data += 'event:' + event + '\n';
    }

    // Blank id resets the id counter.
    if (id !== null) {
      data += 'id:' + id + '\n';
    } else {
      data += 'id\n';
    }

    if (message) {
      data += 'data:' + message.split('\n').join('\ndata') + '\n';
    }
    data += '\n';

    res.write(data);

    if (res.hasOwnProperty('xhr')) {
      clearTimeout(res.xhr);
      var self = this;
      res.xhr = setTimeout(function () {
        res.end();
        self.removeConn(res);
      }, 250);
    }
  };

  Source.prototype.emit = function (event, msg) {
    this.lastMsgId++;
    this.history.push({
      id: this.lastMsgId,
      event: event,
      msg: msg
    });

    for (var i = 0; i < this.conn.length; i++) {
      this.sendSSE(this.conn[i], this.lastMsgId, event, msg);
    }
  }

  Source.prototype.send = function (msg) {
    this.emit(null, JSON.stringify(msg));
  }

  function eventSource (channel) {
    return sources[channel] = new Source();
  }

  server.eventSource = eventSource;

  return function eventSourceLayer (ask, next) {
    if (ask.path[1] !== '$') return next();
    var action = ask.path.slice(2),
        res = ask.res,
        source = sources[action];
    if (!source || ask.req.headers.accept !== 'text/event-stream')
      return next();    // Don't bother if the client cannot handle it.

    // Remy Sharp's Polyfill support.
    if (ask.req.headers['x-requested-with'] == 'XMLHttpRequest') {
      res.xhr = null;
    }

    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');

    if (ask.req.headers['last-event-id']) {
      var id = parseInt(ask.req.headers['last-event-id']);
      for (var i = 0; i < source.history.length; i++)
        if (source.history[i].id > id)
          source.sendSSE(res, source.history[i].id,
              source.history[i].event, source.history[i].msg);
    } else res.write('id\n\n');      // Reset id.

    source.conn.push(res);

    // Every 15s, send a comment (avoids proxy dropping HTTP connection).
    var to = setInterval(function () {res.write(':\n');}, 15000);

    // This can only end in blood.
    ask.req.on('close', function () {
      source.removeConn(res);
      clearInterval(to);
    });
  };
}

// Static unit.
function staticUnit (server) {
  var documentRoot = server.documentRoot = process.cwd() + '/web';

  return function staticLayer (ask, next) {
    // We use `documentRoot` as the root wherein we seek files.
    var realpath = p.join(documentRoot, ask.path);
    fs.stat(realpath, function(err, stats) {
      if (err) return next();
      ask.mime(mime[p.extname(ask.path).slice(1)] || 'text/plain');

      if (stats.isDirectory()) {
        realpath = p.join(realpath, 'index.html');
        ask.mime(mime['html']);
      }

      // Connect the output of the file to the network!
      var raw = fs.createReadStream(realpath),
          enc = ask.req.headers['accept-encoding'] || '';

      // Compress when possible
      if (enc.match(/\bgzip\b/)) {
        ask.res.setHeader('content-encoding', 'gzip');
        raw.pipe(zlib.createGzip()).pipe(ask.res);
      } else if (enc.match(/\bdeflate\b/)) {
        ask.res.setHeader('content-encoding', 'deflate');
        raw.pipe(zlib.createDeflate()).pipe(ask.res);
      } else {
        raw.pipe(ask.res);
      }
    });
  };
}

// Template unit.
function routeUnit (server) {
  var templates = [];

  function route (paths, literalCall) {
    templates.push([RegExp(paths).source, literalCall]);
  }

  server.route = route;

  return function routeLayer (ask, next) {
    var platepaths;
    if ((platepaths = templates.filter (function(key) {
          return RegExp(key[0]).test (ask.path);
        })).length > 0) {
      catchpath(ask, platepaths);
    } else {
      next();
    }
  };
}

// Not Fount unit — in fact, mostly a copy&paste of the route unit.
function notfoundUnit (server) {
  var notfoundTemplates = [];

  function notfound (paths, literalCall) {
    notfoundTemplates.push([RegExp(paths).source, literalCall]);
  }

  server.notfound = notfound;

  return function notfoundLayer (ask) {
    var platepaths;
    ask.res.statusCode = 404;
    if ((platepaths = notfoundTemplates.filter (function(key) {
          return RegExp(key[0]).test (ask.path);
        })).length > 0) {
      catchpath(ask, platepaths);
    } else {
      ask.res.end('404\n');
    }
  };
}

// Route *and* not found units — see what I did there?

function catchpath (ask, platepaths) {
  var res = ask.res;

  if (platepaths.length > 1) {
    console.error ('More than one template path match', ask.path + ':');
    platepaths.forEach (function (path) {console.error ('-', path[0]);});
  }
  var pathmatch = ask.path.match (RegExp (platepaths[0][0]));

  // Template parameters (JSON-serializable).
  var params = platepaths[0][1](ask.query, pathmatch, function end (params) {
    if (!ask.res.getHeader('Content-Type'))   // Allow overriding.
      ask.mime(mime[p.extname(pathmatch[0]).slice(1)] || 'text/plain');

    var templatePath = p.join(ask.server.documentRoot, pathmatch[0]),
        reader = fs.createReadStream(templatePath);

    if (!(params && Object.keys(params).length)) {
      // No data was given. Same behaviour as static.
      var enc = ask.req.headers['accept-encoding'] || '';

      // Compress when possible
      if (enc.match(/\bgzip\b/)) {
        ask.res.setHeader('content-encoding', 'gzip');
        reader.pipe(zlib.createGzip()).pipe(ask.res);
      } else if (enc.match(/\bdeflate\b/)) {
        ask.res.setHeader('content-encoding', 'deflate');
        reader.pipe(zlib.createDeflate()).pipe(ask.res);
      } else {
        reader.pipe(ask.res);
      }
    } else {
      var enc = ask.req.headers['accept-encoding'] || '',
          res = ask.res;

      // Compress when possible
      if (enc.match(/\bgzip\b/)) {
        res = zlib.createGzip();
        ask.res.setHeader('content-encoding', 'gzip');
        res.pipe(ask.res);
      } else if (enc.match(/\bdeflate\b/)) {
        res = zlib.createDeflate();
        ask.res.setHeader('content-encoding', 'deflate');
        res.pipe(ask.res);
      }

      Plate.format(reader, res, params);
    }
  }, ask);
}

// Internal start function.
//

function createServer () { return new Camp(); }

function createSecureServer (opts) { return new SecureCamp(opts); }

function startServer (settings) {
  var server;

  // Are we running https?
  if (settings.secure) { // Yep
    server = new SecureCamp ({
      key:  fs.readFileSync(settings.security.key),
      cert: fs.readFileSync(settings.security.cert),
      ca:   settings.security.ca.map(function(file) {
        try {
          var ca = fs.readFileSync(file);
          return ca;
        } catch (e) { console.error('CA file not found:', file); }
      })
    }).listen(settings.port);
  } else { // Nope
    server = new Camp().listen(settings.port);
  }

  return server;
}

// Each camp instance creates an HTTP / HTTPS server automatically.
//
function start (options) {

  // Settings.
  //
  // By settings I mean data that was set when starting the server, and that is
  // not meant to be changed thereafter.
  var settings = {
    port: 80,
    security: {}
  };

  options = options || {};

  for (var setting in options) {
    settings[setting] = options[setting];
  }

  // Populate security values with the corresponding files.
  if (options.secure) {
    settings.security.key = options.key || 'https.key';
    settings.security.cert = options.cert || 'https.crt';
    settings.security.ca = options.ca || [];
  }

  settings.port = settings.port || (settings.secure ? 443 : 80);

  return startServer(settings);
};

exports.start = start;
exports.createServer = createServer;
exports.createSecureServer = createSecureServer;
exports.Camp;
exports.SecureCamp;

exports.socketUnit;
exports.ajaxUnit;
exports.eventSourceUnit;
exports.routeUnit;
exports.staticUnit;
exports.notfoundUnit;

exports.Plate = Plate;
exports.mime = mime;
exports.binaries = binaries;
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_proce<commit_msg>Update character<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_proces<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Upda<commit_msg>Fast-forwarding changes<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updat<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add',<commit_msg>Update character<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', <|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    for (var counter = 0; counter < length; counter++)
    {
      var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
      var args = ['commit', outFile, '-m', message]
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/bin/git', args)
    }
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [time in seconds]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

process.on('exit', function () {
  var args = ['push']
  child_process.execFileSync('/usr/bin/git', args)
})

function randomIntFromInterval(min,max)
{
   return M<commit_msg>You feeling lucky punk?<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    for (var counter = 0; counter < length; counter++)
    {
      var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
      var args = ['commit', outFile, '-m', message]
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/bin/git', args)
    }
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [time in seconds]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

process.on('exit', function () {
  var args = ['push']
  child_process.execFileSync('/usr/bin/git', args)
})

function randomIntFromInterval(min,max)
{
   return Ma<|endoftext|>


<commit_before>'use strict';

// MODULES //

var getKeys = require( 'object-keys' ).shim();

// COPY ERROR //

/**
* FUNCTION: copy( error )
*	Copies an error.
*
* @param {Error|TypeError|SyntaxError|URIError|ReferenceError|RangeError|RangeError|EvalError} error - error to copy
* @returns {Error|TypeError|SyntaxError|URIError|ReferenceError|RangeError|RangeError|EvalError} error copy
*/
function copy( error ) {
	/* jshint newcap:false */
	var keys;
	var err;
	var i;
	if ( !( error instanceof Error ) ) {
		throw new TypeError( 'invalid input argument. Must provide an error object. Value: `' + error + '`.' );
	}
	// Create a new error and copy over standard error properties...
	err = new error.constructor( error.message );
	err.name = error.name;
	err.stack = error.stack;

	// Node.js specific (system errors)...
	if ( error.code ) {
		err.code = error.code;
	}
	if ( error.errno ) {
		err.errno = error.errno;
	}
	if ( error.syscall ) {
		err.syscall = error.syscall;
	}
	// Any enumerable properties...
	keys = getKeys( error );
	for ( i = 0; i < keys.length; i++ ) {
		err[ keys[ i ] ] = error[ keys[ i ] ];
	}
	return err;
} // end FUNCTION copy()

// EXPORTS //

module.exports = copy;
<commit_msg>Fix stack trace test<commit_after>'use strict';

// MODULES //

var getKeys = require( 'object-keys' ).shim();

// COPY ERROR //

/**
* FUNCTION: copy( error )
*	Copies an error.
*
* @param {Error|TypeError|SyntaxError|URIError|ReferenceError|RangeError|RangeError|EvalError} error - error to copy
* @returns {Error|TypeError|SyntaxError|URIError|ReferenceError|RangeError|RangeError|EvalError} error copy
*/
function copy( error ) {
	/* jshint newcap:false */
	var keys;
	var err;
	var i;
	if ( !( error instanceof Error ) ) {
		throw new TypeError( 'invalid input argument. Must provide an error object. Value: `' + error + '`.' );
	}
	// Create a new error and copy over standard error properties...
	err = new error.constructor( error.message );
	err.name = error.name;
	if ( error.stack ) {
		err.stack = error.stack;
	} else {
		delete err.stack;
	}
	// Node.js specific (system errors)...
	if ( error.code ) {
		err.code = error.code;
	}
	if ( error.errno ) {
		err.errno = error.errno;
	}
	if ( error.syscall ) {
		err.syscall = error.syscall;
	}
	// Any enumerable properties...
	keys = getKeys( error );
	for ( i = 0; i < keys.length; i++ ) {
		err[ keys[ i ] ] = error[ keys[ i ] ];
	}
	return err;
} // end FUNCTION copy()

// EXPORTS //

module.exports = copy;
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk<commit_msg>Logic error<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, functi<commit_msg>How many more of these can I make?<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, functio<|endoftext|>


<commit_before>/**

 Copyright 2015 Covistra Technologies Inc.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
var P = require('bluebird'),
    bunyan = require('bunyan'),
    Hapi = require('hapi'),
    bformat = require('bunyan-format'),
    Injector = require('./injector'),
    _ = require('lodash');

var formatOut = bformat({ outputMode: 'short' });

function CMBF() {
    this.hooks = {};
    this.injector = new Injector();
    this.log = bunyan.createLogger({name: 'core', level: 'debug'});

    if(process.env.NODE_ENV !== 'production') {
        this.log.warn("Enabling Bluebird long stack trace in development and samples mode");
        P.longStackTraces();
    }
}

CMBF.prototype.registerHook = function(key, hookHandler) {
    this.log.debug("Registering hook %s", key);
    this.hooks[key] = P.method(hookHandler);
};

/**
 * Generic hook calling helper. All hooks are promised-wrapped. DefaultImpl will be called
 * if no hook is present and will be passed to hooks for default implementation chaining.
 *
 * @param key
 * @param params
 * @param defaultImpl
 * @returns {*}
 */
CMBF.prototype.callHook = function(key, params, defaultImpl) {
    this.log.debug("Calling hook %s", key);

    if(arguments.length === 2 && _.isFunction(params)) {
        defaultImpl = params;
        params = {};
    }

    var hook = this.hooks[key];
    if(hook) {
        this.log.trace("Registered hook %s will be used", key);
        return P.method(hook).call(this, params, defaultImpl);
    }
    else if(defaultImpl) {
        this.log.trace("No registered hook %s was found but a default implementation was provided", key);
        return P.method(defaultImpl)(params);
    }
    else {
        this.log.trace("No hook found, let's continue");
        return P.resolve(params);
    }

};

CMBF.prototype.launch = P.method(function(pluginOpts) {
    var _this = this;
    this.log.info("Initiating the CMBF launch process");

    // Register all required dependencies
    return _this.callHook('inject-dependencies', { injector: this.injector}).then(function() {

        // Initializing the Hapi server
        var serverOpts = {
            cache: [{
                engine: require('catbox-memory')
            }],
            debug: {
                request: ['error', 'warning']
            }
        };

        // Configure the server
        return _this.callHook('configure-server', serverOpts).then(function(opts) {
            _this.log.trace("Server configuration will be", opts);
            var server = new Hapi.Server(opts);

            // Register early plugins (default load config)
            return _this.callHook('register-early-plugins', {server:server}, function() {
                _this.log.debug("Register Early Plugin: hapi-config, inert, vision");
                return P.join(
                    P.promisify(server.register, server)({register: require('hapi-config'), options: pluginOpts})
                );

            })

                // Register all connections
                .then(function() {

                    // Retrieve the computed configuration
                    var config = server.plugins['hapi-config'].CurrentConfiguration;

                    return _this.callHook('register-connections', {server:server, config:config}, function() {
                        _this.log.debug("Configuring server connections");

                        if(!config) {
                            throw new Error("Missing hapi-config plugin. Must be loaded in the register-early-plugin hook");
                        }

                        var connections = [];

                        var apiOpts = {
                            port: config.get('PORT'),
                            labels: ['api'],
                            router: {
                                stripTrailingSlash: true
                            },
                            routes: {
                                cors: {
                                    additionalHeaders: ['X-App-Key', 'X-Unsafe-Auth'],
                                    credentials: true
                                },
                                payload: {
                                    maxBytes: 1024 * 1024 * 1024 * 64
                                }
                            }
                        }, adminOpts;

                        // Serve admin through the same connection if no specific ADMIN_PORT is defined
                        if(config.get('ADMIN_PORT')) {
                            log.debug("Detected a separate ADMIN_PORT %d. Configure a separate server connection",config.get('ADMIN_PORT') );
                            adminOpts = {
                                port: config.get('ADMIN_PORT'),
                                labels: ['admin'],
                                router: {
                                    stripTrailingSlash: true
                                },
                                routes: {
                                    payload: {
                                        maxBytes: 1024 * 1024 * 1024 * 64
                                    }
                                }
                            };
                            connections.push(apiOpts);
                            connections.push(adminOpts);
                        }
                        else {
                            apiOpts.labels.push('admin')
                            connections.push(apiOpts);
                        }

                        return _this.callHook('configure-connections', {config:config, server:server, connections:connections}).then(function(result) {
                            _this.log.debug("%d connections will be configured for our server", result.connections.length);
                            return P.each(result.connections, function(connectionOpts){
                                server.connection(connectionOpts);
                            });

                        });

                    })

                        // Register security plugins (auth strategies)
                        .then(function() {

                            return _this.callHook('configure-security', {server:server, config:config}, function() {
                                _this.log.debug("Configure Security: Loading 3 auth strategies: hapi-auth-bearer-token, hapi-auth-cookie, hapi-auth-basic");

                                return P.join(
                                    P.promisify(server.register, server)({register: require('hapi-auth-bearer-token'), options: pluginOpts}),
                                    P.promisify(server.register,server)({register: require('hapi-auth-cookie'), options: pluginOpts}),
                                    P.promisify(server.register, server)({register: require('hapi-auth-basic'), options: pluginOpts})
                                );

                            });

                        })

                        // Configure the documentation (Swagger)
                        .then(function() {
                            _this.log.debug("Configuring API documentation plugin (Swagger)");

                            var swaggerOpts = {
                                basePath: config.get('server:prod:baseUrl'),
                                apiVersion: config.get('server:version'),
                                authorizations: {
                                    "bearer-access-token" : {
                                        type: "apiKey",
                                        passAs: 'header',
                                        keyName: 'Authorization'
                                    }
                                },
                                info: config.get('server:info')
                            };

                            return _this.callHook('configure-documentation', {server:server, config:config, swaggerOpts:swaggerOpts}).then(function(result) {
                                _this.log.debug("Configuring Documentation: Swagger plugin will be loaded with configuration", result.swaggerOpts);
                                return P.join(
                                    P.promisify(server.register, server)({register: require('inert'), options: pluginOpts}),
                                    P.promisify(server.register, server)({register: require('vision'), options: pluginOpts}),
                                    P.promisify(server.register, server)({register: require('hapi-swagger'), options: result.swaggerOpts})
                                );
                            });
                        })

                        // Register all plugins
                        .then(function() {
                            _this.log.debug("Loading all plugins");
                            return _this.callHook('register-plugins', {server:server, config:config}, function() {
                                _this.log.debug("Loading default foundation plugins: hapi-bunyan, covistra-system, covistra-mongodb, covistra-security, covistra-admin");

                                return P.join(
                                    P.promisify(server.register, server)({
                                        register: require('hapi-bunyan'),
                                        options: {
                                            logger: bunyan.createLogger(_.merge(config.get('server:log')||{}, { name: 'cmbf', stream: formatOut }))
                                        }
                                    }),
                                    P.promisify(server.register, server)({register: require('covistra-system'), options: pluginOpts}),
                                    P.promisify(server.register, server)({register: require('covistra-mongodb'), options: pluginOpts}),
                                    P.promisify(server.register, server)({register: require('covistra-security'), options: pluginOpts}),
                                    P.promisify(server.register, server)({register: require('covistra-admin'), options: pluginOpts})
                                );
                            });
                        })

                        // Register late plugins
                        .then(function() {
                            _this.log.debug("Registering late plugins");
                            return _this.callHook('register-late-plugins', {server:server, config:config});
                        });
                })

                // Launch the server
                .then(function() {
                    _this.log.debug("Preparing to start the server");
                    return _this.callHook('before-server-start', { server: server })

                        .then(function() {
                            _this.log.debug("Starting the server");
                            return P.promisify(server.start, server)();
                        })

                        .then(function() {
                            return _this.callHook('server-started', { server: server});
                        });

                })

                // Launch is complete
                .then(function() {
                    _this.log.debug("Server was successfully started", server.info);
                    _this.server = server;
                    server.method('getCmbf', function() { return _this }, {});
                    return _this;
                });

        });

    });

});

module.exports = CMBF;

<commit_msg>Make sure we create integration method earlier<commit_after>/**

 Copyright 2015 Covistra Technologies Inc.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
var P = require('bluebird'),
    bunyan = require('bunyan'),
    Hapi = require('hapi'),
    bformat = require('bunyan-format'),
    Injector = require('./injector'),
    _ = require('lodash');

var formatOut = bformat({ outputMode: 'short' });

function CMBF() {
    this.hooks = {};
    this.injector = new Injector();
    this.log = bunyan.createLogger({name: 'core', level: 'debug'});

    if(process.env.NODE_ENV !== 'production') {
        this.log.warn("Enabling Bluebird long stack trace in development and samples mode");
        P.longStackTraces();
    }
}

CMBF.prototype.registerHook = function(key, hookHandler) {
    this.log.debug("Registering hook %s", key);
    this.hooks[key] = P.method(hookHandler);
};

/**
 * Generic hook calling helper. All hooks are promised-wrapped. DefaultImpl will be called
 * if no hook is present and will be passed to hooks for default implementation chaining.
 *
 * @param key
 * @param params
 * @param defaultImpl
 * @returns {*}
 */
CMBF.prototype.callHook = function(key, params, defaultImpl) {
    this.log.debug("Calling hook %s", key);

    if(arguments.length === 2 && _.isFunction(params)) {
        defaultImpl = params;
        params = {};
    }

    var hook = this.hooks[key];
    if(hook) {
        this.log.trace("Registered hook %s will be used", key);
        return P.method(hook).call(this, params, defaultImpl);
    }
    else if(defaultImpl) {
        this.log.trace("No registered hook %s was found but a default implementation was provided", key);
        return P.method(defaultImpl)(params);
    }
    else {
        this.log.trace("No hook found, let's continue");
        return P.resolve(params);
    }

};

CMBF.prototype.launch = P.method(function(pluginOpts) {
    var _this = this;
    this.log.info("Initiating the CMBF launch process");

    // Register all required dependencies
    return _this.callHook('inject-dependencies', { injector: this.injector}).then(function() {

        // Initializing the Hapi server
        var serverOpts = {
            cache: [{
                engine: require('catbox-memory')
            }],
            debug: {
                request: ['error', 'warning']
            }
        };

        // Configure the server
        return _this.callHook('configure-server', serverOpts).then(function(opts) {
            _this.log.trace("Server configuration will be", opts);
            var server = new Hapi.Server(opts);

            _this.server = server;
            server.method('getCmbf', function() { return _this }, {});

            // Register early plugins (default load config)
            return _this.callHook('register-early-plugins', {server:server}, function() {
                _this.log.debug("Register Early Plugin: hapi-config, inert, vision");
                return P.join(
                    P.promisify(server.register, server)({register: require('hapi-config'), options: pluginOpts})
                );

            })

                // Register all connections
                .then(function() {

                    // Retrieve the computed configuration
                    var config = server.plugins['hapi-config'].CurrentConfiguration;

                    return _this.callHook('register-connections', {server:server, config:config}, function() {
                        _this.log.debug("Configuring server connections");

                        if(!config) {
                            throw new Error("Missing hapi-config plugin. Must be loaded in the register-early-plugin hook");
                        }

                        var connections = [];

                        var apiOpts = {
                            port: config.get('PORT'),
                            labels: ['api'],
                            router: {
                                stripTrailingSlash: true
                            },
                            routes: {
                                cors: {
                                    additionalHeaders: ['X-App-Key', 'X-Unsafe-Auth'],
                                    credentials: true
                                },
                                payload: {
                                    maxBytes: 1024 * 1024 * 1024 * 64
                                }
                            }
                        }, adminOpts;

                        // Serve admin through the same connection if no specific ADMIN_PORT is defined
                        if(config.get('ADMIN_PORT')) {
                            log.debug("Detected a separate ADMIN_PORT %d. Configure a separate server connection",config.get('ADMIN_PORT') );
                            adminOpts = {
                                port: config.get('ADMIN_PORT'),
                                labels: ['admin'],
                                router: {
                                    stripTrailingSlash: true
                                },
                                routes: {
                                    payload: {
                                        maxBytes: 1024 * 1024 * 1024 * 64
                                    }
                                }
                            };
                            connections.push(apiOpts);
                            connections.push(adminOpts);
                        }
                        else {
                            apiOpts.labels.push('admin')
                            connections.push(apiOpts);
                        }

                        return _this.callHook('configure-connections', {config:config, server:server, connections:connections}).then(function(result) {
                            _this.log.debug("%d connections will be configured for our server", result.connections.length);
                            return P.each(result.connections, function(connectionOpts){
                                server.connection(connectionOpts);
                            });

                        });

                    })

                        // Register security plugins (auth strategies)
                        .then(function() {

                            return _this.callHook('configure-security', {server:server, config:config}, function() {
                                _this.log.debug("Configure Security: Loading 3 auth strategies: hapi-auth-bearer-token, hapi-auth-cookie, hapi-auth-basic");

                                return P.join(
                                    P.promisify(server.register, server)({register: require('hapi-auth-bearer-token'), options: pluginOpts}),
                                    P.promisify(server.register,server)({register: require('hapi-auth-cookie'), options: pluginOpts}),
                                    P.promisify(server.register, server)({register: require('hapi-auth-basic'), options: pluginOpts})
                                );

                            });

                        })

                        // Configure the documentation (Swagger)
                        .then(function() {
                            _this.log.debug("Configuring API documentation plugin (Swagger)");

                            var swaggerOpts = {
                                basePath: config.get('server:prod:baseUrl'),
                                apiVersion: config.get('server:version'),
                                authorizations: {
                                    "bearer-access-token" : {
                                        type: "apiKey",
                                        passAs: 'header',
                                        keyName: 'Authorization'
                                    }
                                },
                                info: config.get('server:info')
                            };

                            return _this.callHook('configure-documentation', {server:server, config:config, swaggerOpts:swaggerOpts}).then(function(result) {
                                _this.log.debug("Configuring Documentation: Swagger plugin will be loaded with configuration", result.swaggerOpts);
                                return P.join(
                                    P.promisify(server.register, server)({register: require('inert'), options: pluginOpts}),
                                    P.promisify(server.register, server)({register: require('vision'), options: pluginOpts}),
                                    P.promisify(server.register, server)({register: require('hapi-swagger'), options: result.swaggerOpts})
                                );
                            });
                        })

                        // Register all plugins
                        .then(function() {
                            _this.log.debug("Loading all plugins");
                            return _this.callHook('register-plugins', {server:server, config:config}, function() {
                                _this.log.debug("Loading default foundation plugins: hapi-bunyan, covistra-system, covistra-mongodb, covistra-security, covistra-admin");

                                return P.join(
                                    P.promisify(server.register, server)({
                                        register: require('hapi-bunyan'),
                                        options: {
                                            logger: bunyan.createLogger(_.merge(config.get('server:log')||{}, { name: 'cmbf', stream: formatOut }))
                                        }
                                    }),
                                    P.promisify(server.register, server)({register: require('covistra-system'), options: pluginOpts}),
                                    P.promisify(server.register, server)({register: require('covistra-mongodb'), options: pluginOpts}),
                                    P.promisify(server.register, server)({register: require('covistra-security'), options: pluginOpts}),
                                    P.promisify(server.register, server)({register: require('covistra-admin'), options: pluginOpts})
                                );
                            });
                        })

                        // Register late plugins
                        .then(function() {
                            _this.log.debug("Registering late plugins");
                            return _this.callHook('register-late-plugins', {server:server, config:config});
                        });
                })

                // Launch the server
                .then(function() {
                    _this.log.debug("Preparing to start the server");
                    return _this.callHook('before-server-start', { server: server })

                        .then(function() {
                            _this.log.debug("Starting the server");
                            return P.promisify(server.start, server)();
                        })

                        .then(function() {
                            return _this.callHook('server-started', { server: server});
                        });

                })

                // Launch is complete
                .then(function() {
                    _this.log.debug("Server was successfully started", server.info);
                    return _this;
                });

        });

    });

});

module.exports = CMBF;

<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    for (var counter = 0; counter < length; counter++)
    {
      var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
      var args = ['commit', outFile, '-m', message]
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/bin/git', args<commit_msg>Updated the readme again<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    for (var counter = 0; counter < length; counter++)
    {
      var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
      var args = ['commit', outFile, '-m', message]
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/bin/git', args)<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    if (counter + step >= length) step = length - counter
    process.stdout.write("\033[2K Writing " + counter + "/" + length + " bytes: " + message + "\r");
    fs.writeSync(outFD, data.slice(counter, counter+step), 0, step)
    child_process.execFileSync('/Applications/Xcode.app/Contents/Developer/usr/bin/git', args)
    var timeout = randomIntFromInterval(0, max_sleep)
    counter = counter + step
    if (process.env.FAKETIME) {
      t_offset = t_offset + timeout;
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = timeout * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  } else {
    var args = ['push']
    child_process.execFileSync('git', args)
    console.info("Finished")
  }
}

function faketime(offset)
{
  process.env.FAKETIME = of<commit_msg>Updated the readme<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    if (counter + step >= length) step = length - counter
    process.stdout.write("\033[2K Writing " + counter + "/" + length + " bytes: " + message + "\r");
    fs.writeSync(outFD, data.slice(counter, counter+step), 0, step)
    child_process.execFileSync('/Applications/Xcode.app/Contents/Developer/usr/bin/git', args)
    var timeout = randomIntFromInterval(0, max_sleep)
    counter = counter + step
    if (process.env.FAKETIME) {
      t_offset = t_offset + timeout;
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = timeout * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  } else {
    var args = ['push']
    child_process.execFileSync('git', args)
    console.info("Finished")
  }
}

function faketime(offset)
{
  process.env.FAKETIME = off<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length =<commit_msg>AAAAAAAAAAARGH!<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = <|endoftext|>