<commit_before>'use strict';

const util = require('util');
const Peer = require('./peer');

const MAX_PEERS = 8;

function Swarm (config) {
  this.name = 'Swarm';
  this.config = Object.assign({
    peers: []
  }, config);

  this.nodes = {};
  this.peers = {};
  this.self = null;
}

util.inherits(Swarm, require('./vector'));

Swarm.prototype.broadcast = function broadcast (msg) {
  this.self.broadcast(msg);
};

Swarm.prototype.start = function () {
  let swarm = this;

  // create a peer for one's own $self
  swarm.self = new Peer(swarm.config.peer);

  swarm.self.on('info', function (msg) {
    swarm.emit('info', msg);
  });

  // TODO: consider renaming this to JOIN
  swarm.self.on('peer', function (peer) {
    swarm._registerPeer(peer);
  });

  swarm.self.on('connections:open', function (connection) {
    swarm.emit('connections:open', connection);
  });

  swarm.self.on('connections:close', function (connection) {
    swarm.emit('connections:close', connection);
    swarm._fillPeerSlots();
  });

  swarm.self.on('collections:post', function (message) {
    swarm.emit('collections:post', message);
  });

  swarm.self.on('ready', function (info) {
    swarm.log(`swarm is ready (${info.id})`);
    swarm.emit('ready');
    swarm._fillPeerSlots();
  });

  return swarm.self.start();
};

Swarm.prototype.connect = function (address) {
  this.log(`connecting to: ${address}`);

  try {
    this.self._connect(address);
  } catch (E) {
    console.log('Error connecting:', E);
  }
};

Swarm.prototype._broadcastTypedMessage = function broadcast (type, msg) {
  if (!type) return new Error('Message type must be supplied.');
  this.self._broadcastTypedMessage(type, msg);
};

Swarm.prototype._registerPeer = function registerPeer (peer) {
  let swarm = this;
  if (!swarm.peers[peer.id]) swarm.peers[peer.id] = peer;
  swarm.emit('peer', peer);
};

Swarm.prototype._scheduleReconnect = function scheduleReconnect (peer) {
  let swarm = this;
  this.log('schedule reconnect:', peer);

  // TODO: store timers globally (ConnectionManager?)
  // TODO: exponential backoff for reconnections
  // starts at 60s timer
  if (swarm.peers[peer.id]) {
    if (swarm.peers[peer.id].timer) return true;
    swarm.peers[peer.id].timer = setTimeout(function () {
      clearTimeout(swarm.peers[peer.id].timer);
      swarm.connect(peer);
    }, 60000);
  }
};

Swarm.prototype._fillPeerSlots = function findPeers () {
  let swarm = this;
  let slots = MAX_PEERS - Object.keys(this.nodes).length;
  let peers = Object.keys(this.peers).map(function (id) {
    swarm.log('checking:', swarm.peers[id]);
    return swarm.peers[id].address;
  });
  let candidates = swarm.config.peers.filter(function (address) {
    return !peers.includes(address);
  });

  if (slots) {
    // TODO: use `slots` from above
    for (let i = 0; (i < candidates.length && i < slots); i++) {
      swarm._scheduleReconnect(candidates[i]);
    }
  }
};

module.exports = Swarm;
<commit_msg>Add Swarm<commit_after>'use strict';

const Peer = require('./peer');
const Scribe = require('./scribe');

const MAX_PEERS = 16;

class Swarm extends Scribe {
  constructor (config) {
    super(config);

    this.name = 'Swarm';
    this.config = Object.assign({
      peers: []
    }, config);

    this.nodes = {};
    this.peers = {};

    return this;
  }

  broadcast (msg) {
    this.self.broadcast(msg);
  }

  connect (address) {
    this.log(`connecting to: ${address}`);

    try {
      this.self._connect(address);
    } catch (E) {
      console.log('Error connecting:', E);
    }
  }

  trust (source) {
    super.trust(source);
  }

  _broadcastTypedMessage (type, msg) {
    if (!type) return new Error('Message type must be supplied.');
    this.self._broadcastTypedMessage(type, msg);
  }

  _registerPeer (peer) {
    let swarm = this;
    if (!swarm.peers[peer.id]) swarm.peers[peer.id] = peer;
    swarm.emit('peer', peer);
  }

  _scheduleReconnect (peer) {
    let swarm = this;
    this.log('schedule reconnect:', peer);

    // TODO: store timers globally (ConnectionManager?)
    // TODO: exponential backoff for reconnections
    // starts at 60s timer
    if (swarm.peers[peer.id]) {
      if (swarm.peers[peer.id].timer) return true;
      swarm.peers[peer.id].timer = setTimeout(function () {
        clearTimeout(swarm.peers[peer.id].timer);
        swarm.connect(peer);
      }, 60000);
    }
  }

  _fillPeerSlots () {
    let swarm = this;
    let slots = MAX_PEERS - Object.keys(this.nodes).length;
    let peers = Object.keys(this.peers).map(function (id) {
      swarm.log('checking:', swarm.peers[id]);
      return swarm.peers[id].address;
    });
    let candidates = swarm.config.peers.filter(function (address) {
      return !peers.includes(address);
    });

    if (slots) {
      // TODO: use `slots` from above
      for (let i = 0; (i < candidates.length && i < slots); i++) {
        swarm._scheduleReconnect(candidates[i]);
      }
    }
  }

  async start () {
    await super.start();

    let swarm = this;

    // create a peer for one's own $self
    swarm.self = new Peer(swarm.config.peer);

    swarm.self.on('info', function (msg) {
      swarm.emit('info', msg);
    });

    // TODO: consider renaming this to JOIN
    swarm.self.on('peer', function (peer) {
      swarm._registerPeer(peer);
    });

    swarm.self.on('connections:open', function (connection) {
      swarm.emit('connections:open', connection);
    });

    swarm.self.on('connections:close', function (connection) {
      swarm.emit('connections:close', connection);
      swarm._fillPeerSlots();
    });

    swarm.self.on('collections:post', function (message) {
      swarm.emit('collections:post', message);
    });

    swarm.self.on('ready', function (info) {
      swarm.log(`swarm is ready (${info.id})`);
      swarm.emit('ready');
      swarm._fillPeerSlots();
    });

    return swarm.self.start();
  }
}

module.exports = Swarm;
<|endoftext|>


<commit_before>"use strict";

var _ = require('underscore'),
    async = require('async'),
    path = require('path'),
    fs = require('fs'),
    wrench = require('wrench');

_.mixin(require('./helpers'));

function fileSuffix(fname, suff){
    return path.join(path.dirname(fname), path.basename(fname, path.extname(fname)) + suff + path.extname(fname));
}

module.exports = {

    read: function(done) {
        var t = this;
        _.each(this.files, function(f) {
            f.content = fs.readFileSync(f.src, 'utf8');
        });
        done();
    },

    filter: function(regex, done) {
        this.files = _.filter(this.files, function(f) {
            return _.isFunction(regex) ? regex(f) : regex.test(f.src);
        });
        done();
    },

    compress: function(options, done) {

        if(_.isFunction(options)) {
            done = options;
        }

        var files = _.map(this.files, function(f) {
            var dest = fileSuffix(f.dest, '.min');
            var content = path.extname(f.src)==='.js' ? _.compressjs(f.content):
                            (path.extname(f.src)==='.css' ? _.compresscss(f.content):
                                f.content);
            return {
                src: f.src,
                content: content,
                dest: dest
            };
        });
        this.write(files, done);

    },

    write: function(files, done) {
        if(_.isFunction(files)) {
            done = files;
            files = this.files;
        }
        var t = this;
        _.each(files, function(f) {
            var dest = path.join(t.config.dest, f.dest)
            wrench.mkdirSyncRecursive(path.dirname(dest));
            fs.writeFileSync(dest, f.content);
        });
        done();
    },
    // takes a bunch of files, creates a meta hash with it, and writes it to `<target>`.json
    meta: function(files, target, done){
        var meta = {}, t = this;
        if(_.isFunction(target)){
            done = target;
            target = files;
            files = this.files;
        }
        _.each(files, function(f){
            meta[path.relative(t.config.src, f)] = f.dest;
        });
        t.write([{
            content: JSON.stringify(meta),
            dest:  target +'.json'
        }], done);
    },
    // takes a bunch of files, generates hashed file names, writes to them
    hashify: function(done) {

        var files = _.map(this.files, function(f) {
            var dest = fileSuffix(f.dest, '.' +  _.hashify(f.content));
            return {
                src: f.src,
                content: f.content,
                dest: dest
            };
        });
        this.write(files, done);

    },

    wait: function(time, done) {
        setTimeout(done, time);
    },

    log: function(msg, done) {
        console.log(msg);
        done();
    },

    concat: function(dest, done) {
        this.write([{
            content: _(this.files).pluck('content').join('/n'),
            dest: dest
        }], done);
    },

    templates: function(options, callback) {
        var dest = 'templates.js'; // this has to be rewritten.
        // basic logic is so -
        // find the longest common substring in all files tarting from start
        // excluding that bit, construct template name by stripping / and ., and replacing with - (or _)
        // write it to that common dir, unless passed in options

        // for now, just read all ejs templates
        done();

    },

    analyze: function(options, callback) {
        // just a yui analyze for now, I guess
    },

    cdnify: function(options, callback) {
        // config options -
        // cdnbase
        done();
    },

    watch: function(onChange, done) {
        // setup handler on `this.files` that run everytime a file in the list changes
        done();
    },

    cmd: function(cmd, done) {
        require('child_process').exec(cmd, done);
    },

    clean: function(done) {
        // wipe out dest? what about versioned?
        if(this.config.src !== this.config.dest){
            this.cmd('rm -rf ' + this.config.dest, done);
        }
        else{
            done();
        }
    }
};
<commit_msg>let compress pass on content<commit_after>"use strict";

var _ = require('underscore'),
    async = require('async'),
    path = require('path'),
    fs = require('fs'),
    wrench = require('wrench');

_.mixin(require('./helpers'));

function fileSuffix(fname, suff){
    return path.join(path.dirname(fname), path.basename(fname, path.extname(fname)) + suff + path.extname(fname));
}

module.exports = {

    read: function(done) {
        var t = this;
        _.each(this.files, function(f) {
            f.content = fs.readFileSync(f.src, 'utf8');
        });
        done();
    },

    filter: function(regex, done) {
        this.files = _.filter(this.files, function(f) {
            return _.isFunction(regex) ? regex(f) : regex.test(f.src);
        });
        done();
    },

    compress: function(options, done) {

        if(_.isFunction(options)) {
            done = options;
        }

        var files = _.map(this.files, function(f) {
            var dest = fileSuffix(f.dest, '.min');
            var content = path.extname(f.src)==='.js' ? _.compressjs(f.content):
                            (path.extname(f.src)==='.css' ? _.compresscss(f.content):
                                f.content);
            // set on 'f' to pass on
            f.content = content;
            return {
                src: f.src,
                content: content,
                dest: dest
            };
        });
        this.write(files, done);

    },

    write: function(files, done) {
        if(_.isFunction(files)) {
            done = files;
            files = this.files;
        }
        var t = this;
        _.each(files, function(f) {
            var dest = path.join(t.config.dest, f.dest)
            wrench.mkdirSyncRecursive(path.dirname(dest));
            fs.writeFileSync(dest, f.content);
        });
        done();
    },
    // takes a bunch of files, creates a meta hash with it, and writes it to `<target>`.json
    meta: function(files, target, done){
        var meta = {}, t = this;
        if(_.isFunction(target)){
            done = target;
            target = files;
            files = this.files;
        }
        _.each(files, function(f){
            meta[path.relative(t.config.src, f)] = f.dest;
        });
        t.write([{
            content: JSON.stringify(meta),
            dest:  target +'.json'
        }], done);
    },
    // takes a bunch of files, generates hashed file names, writes to them
    hashify: function(done) {

        var files = _.map(this.files, function(f) {
            var dest = fileSuffix(f.dest, '.' +  _.hashify(f.content));
            return {
                src: f.src,
                content: f.content,
                dest: dest
            };
        });
        this.write(files, done);

    },

    wait: function(time, done) {
        setTimeout(done, time);
    },

    log: function(msg, done) {
        console.log(msg);
        done();
    },

    concat: function(dest, done) {
        this.write([{
            content: _(this.files).pluck('content').join('/n'),
            dest: dest
        }], done);
    },

    templates: function(options, callback) {
        var dest = 'templates.js'; // this has to be rewritten.
        // basic logic is so -
        // find the longest common substring in all files tarting from start
        // excluding that bit, construct template name by stripping / and ., and replacing with - (or _)
        // write it to that common dir, unless passed in options

        // for now, just read all ejs templates
        done();

    },

    analyze: function(options, callback) {
        // just a yui analyze for now, I guess
    },

    cdnify: function(options, callback) {
        // config options -
        // cdnbase
        done();
    },

    watch: function(onChange, done) {
        // setup handler on `this.files` that run everytime a file in the list changes
        done();
    },

    cmd: function(cmd, done) {
        require('child_process').exec(cmd, done);
    },

    clean: function(done) {
        // wipe out dest? what about versioned?
        if(this.config.src !== this.config.dest){
            this.cmd('rm -rf ' + this.config.dest, done);
        }
        else{
            done();
        }
    }
};
<|endoftext|>


<commit_before>/*

Copyright (c) 2012 Nicolas Clerc <kernicpanel@nclerc.fr>

This file is part of realTeam.

realTeam is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

realTeam is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with realTeam.  If not, see <http://www.gnu.org/licenses/>.

*/

console.log("»»»»»timer load««««««");
var timer ={},
  mongoose = require('mongoose');
var eventsManager = server.eventsManager;

// var TeamMember = mongoose.model('TeamMember');
var User = mongoose.model('User');
var Issue = mongoose.model('Issue');

timer.init = function() {
  timer.events();
};

timer.events = function() {

  eventsManager.on('timer::getCurrentIssues', function(callback){
    timer.getCurrentIssues( function(err, issues) {
      callback(err, issues);
    });
  });

  eventsManager.on('timer::start', function(login, issueId, callback){
    timer.checkStart(login, issueId, function(err, data) {
      callback(err, data);
    });
  });

  eventsManager.on('timer::pause', function(login, callback){
    timer.pause(login, function(err, data) {
      callback(err, data);
    });
  });

  eventsManager.on('timer::stop', function(login, callback){
    timer.stop(login, function(err, data) {
      callback(err, data);
    });
  });

  eventsManager.on('timer::addtime', function(login, issue, callback){
    console.log("addtime", issue);
    timer.addtime(login, issue, function(err, data) {
      callback(err, data);
    });
  });
};

timer.getUserFromId = function getUserFromId ( id, callback ) {
  User.findOne( {id: id}, function (err, user) {
    callback(err, user);
  });
};

timer.getUserFromLogin = function getUserFromLogin ( login, callback ) {
  console.log(" login : ", login);
  User.findOne( {login: login}, function (err, user) {
    callback(err, user);
  });
};

timer.getCurrentIssues = function( callback ) {
  // var stream = User
  //   .find({})
  //   .where('currentIssue.id').gt(0)
  //   .select('login currentIssue')
  //   .stream();

  // stream.on('data', function (data) {
  //   var currentIssue = {
  //     login: data.login,
  //     currentIssue: {
  //       timeCounter: data.currentIssue.pendingDuration + (new Date() - data.currentIssue.startedAt),
  //       issueId: data.currentIssue.issueId,
  //       issueName: data.currentIssue.issueName,
  //       issueUrl: data.currentIssue.issueUrl,
  //       issueStatus: data.currentIssue.issueStatus,
  //       startedAt: data.currentIssue.startedAt,
  //       paused: data.currentIssue.paused,
  //       pendingDuration: data.currentIssue.pendingDuration,
  //       pendingTimeCounter: data.currentIssue.pendingDuration + (new Date() - data.currentIssue.startedAt)
  //     }
  //   };
  //   // eventsManager.emit('log', data);
  //   eventsManager.emit('timer::getCurrentIssues::response', currentIssue);
  // });

  // stream.on('error', function (err) {
  //   // handle the error
  // });

  // stream.on('close', function () {
  //   // the stream is closed
  // });

  var query = User
    .find({})
    .where('currentIssue.id').gt(0)
    .select('login currentIssue')
    .exec(function (err, issues) {
      callback(err, issues);
    });

};

timer.checkStart = function(login, issueId, callback) {
  timer.getUserFromLogin( login, function( err, user ){
    if (!!user.currentIssue.id) {
      timer.stop(login, function(){
        timer.start(login, issueId, callback)
      });
    }
    else {
      timer.start(login, issueId, callback);
    }
  });
};

timer.start = function(login, issueId, callback) {
  console.log("timer start login : ", login);
  Issue.findOne({ id: issueId  }, function (err, issue) {
    timer.getUserFromLogin( login, function( err, user ){
      user.startIssue( issue, function( err, issue ) {
        var currentIssue = {
          login: login,
          timeCounter: issue.pendingDuration + (new Date() - issue.startedAt),
          issueId: issue.issueId,
          issueName: issue.issueName,
          issueUrl: issue.issueUrl,
          issueStatus: issue.issueStatus,
          startedAt: issue.startedAt,
          paused: issue.paused,
          pendingDuration: issue.pendingDuration
        };
        callback( err, currentIssue );
      });
    });
  });
};

timer.pause = function(login, callback) {
  timer.getUserFromLogin( login, function( err, user ){
    user.pauseIssue( function( err, issue ) {
      eventsManager.emit('timer::pauseCurrentIssue', user.login);
      var currentIssue = {
        login: login,
        timeCounter: issue.pendingDuration + (new Date() - issue.startedAt),
        issueId: issue.issueId,
        issueName: issue.issueName,
        issueUrl: issue.issueUrl,
        issueStatus: issue.issueStatus,
        startedAt: issue.startedAt,
        paused: issue.paused,
        pendingDuration: issue.pendingDuration,
        pendingTimeCounter: issue.pendingDuration + (new Date() - issue.startedAt)
      };
      callback( err, currentIssue );
    });
  });
};

timer.stop = function(login, callback) {
  console.log("timen stop login : ", login);
  timer.getUserFromLogin( login, function( err, user ){
    user.stopIssue( function( err, currentIssue ) {
      eventsManager.emit('timer::stopCurrentIssue', login);

      callback(err, currentIssue);
      // if (currentIssue.id) {
      //   timer.addtime(login, currentIssue.id, currentIssue.pendingDuration / 1000 / 60 / 60, null, callback );
      // }
    });
  });
};

timer.addtime = function addtime (login, issue, callback) {
  var issueId = issue.id;
  var issueHours = issue.hours !== '' ? parseInt(issue.hours, 10) : 0;
  var issueMinutes = issue.minutes !== '' ? parseInt(issue.minutes, 10) / 60 : 0;
  var hours = issueHours + issueMinutes;
  var comments = issue.message || '';
  var params = {
    time_entry:{
      issue_id: issueId,
      hours: hours,
      comments: comments
    }
  };

  // eventsManager.emit('log', login);
  eventsManager.emit('log', params);

  /*
   *var userRest = server.users[login].redmineRest;
   *userRest.request('POST', '/time_entries.json', params, function(err, data) {
   *  console.log("data response : ", data);
   *  callback( err, data );
   *});
   */
    callback();
};

module.exports = timer;
<commit_msg>activate redmine timeentry post<commit_after>/*

Copyright (c) 2012 Nicolas Clerc <kernicpanel@nclerc.fr>

This file is part of realTeam.

realTeam is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

realTeam is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with realTeam.  If not, see <http://www.gnu.org/licenses/>.

*/

console.log("»»»»»timer load««««««");
var timer ={},
  mongoose = require('mongoose');
var eventsManager = server.eventsManager;

// var TeamMember = mongoose.model('TeamMember');
var User = mongoose.model('User');
var Issue = mongoose.model('Issue');

timer.init = function() {
  timer.events();
};

timer.events = function() {

  eventsManager.on('timer::getCurrentIssues', function(callback){
    timer.getCurrentIssues( function(err, issues) {
      callback(err, issues);
    });
  });

  eventsManager.on('timer::start', function(login, issueId, callback){
    timer.checkStart(login, issueId, function(err, data) {
      callback(err, data);
    });
  });

  eventsManager.on('timer::pause', function(login, callback){
    timer.pause(login, function(err, data) {
      callback(err, data);
    });
  });

  eventsManager.on('timer::stop', function(login, callback){
    timer.stop(login, function(err, data) {
      callback(err, data);
    });
  });

  eventsManager.on('timer::addtime', function(login, issue, callback){
    console.log("addtime", issue);
    timer.addtime(login, issue, function(err, data) {
      callback(err, data);
    });
  });
};

timer.getUserFromId = function getUserFromId ( id, callback ) {
  User.findOne( {id: id}, function (err, user) {
    callback(err, user);
  });
};

timer.getUserFromLogin = function getUserFromLogin ( login, callback ) {
  console.log(" login : ", login);
  User.findOne( {login: login}, function (err, user) {
    callback(err, user);
  });
};

timer.getCurrentIssues = function( callback ) {
  // var stream = User
  //   .find({})
  //   .where('currentIssue.id').gt(0)
  //   .select('login currentIssue')
  //   .stream();

  // stream.on('data', function (data) {
  //   var currentIssue = {
  //     login: data.login,
  //     currentIssue: {
  //       timeCounter: data.currentIssue.pendingDuration + (new Date() - data.currentIssue.startedAt),
  //       issueId: data.currentIssue.issueId,
  //       issueName: data.currentIssue.issueName,
  //       issueUrl: data.currentIssue.issueUrl,
  //       issueStatus: data.currentIssue.issueStatus,
  //       startedAt: data.currentIssue.startedAt,
  //       paused: data.currentIssue.paused,
  //       pendingDuration: data.currentIssue.pendingDuration,
  //       pendingTimeCounter: data.currentIssue.pendingDuration + (new Date() - data.currentIssue.startedAt)
  //     }
  //   };
  //   // eventsManager.emit('log', data);
  //   eventsManager.emit('timer::getCurrentIssues::response', currentIssue);
  // });

  // stream.on('error', function (err) {
  //   // handle the error
  // });

  // stream.on('close', function () {
  //   // the stream is closed
  // });

  var query = User
    .find({})
    .where('currentIssue.id').gt(0)
    .select('login currentIssue')
    .exec(function (err, issues) {
      callback(err, issues);
    });

};

timer.checkStart = function(login, issueId, callback) {
  timer.getUserFromLogin( login, function( err, user ){
    if (!!user.currentIssue.id) {
      timer.stop(login, function(){
        timer.start(login, issueId, callback)
      });
    }
    else {
      timer.start(login, issueId, callback);
    }
  });
};

timer.start = function(login, issueId, callback) {
  console.log("timer start login : ", login);
  Issue.findOne({ id: issueId  }, function (err, issue) {
    timer.getUserFromLogin( login, function( err, user ){
      user.startIssue( issue, function( err, issue ) {
        var currentIssue = {
          login: login,
          timeCounter: issue.pendingDuration + (new Date() - issue.startedAt),
          issueId: issue.issueId,
          issueName: issue.issueName,
          issueUrl: issue.issueUrl,
          issueStatus: issue.issueStatus,
          startedAt: issue.startedAt,
          paused: issue.paused,
          pendingDuration: issue.pendingDuration
        };
        callback( err, currentIssue );
      });
    });
  });
};

timer.pause = function(login, callback) {
  timer.getUserFromLogin( login, function( err, user ){
    user.pauseIssue( function( err, issue ) {
      eventsManager.emit('timer::pauseCurrentIssue', user.login);
      var currentIssue = {
        login: login,
        timeCounter: issue.pendingDuration + (new Date() - issue.startedAt),
        issueId: issue.issueId,
        issueName: issue.issueName,
        issueUrl: issue.issueUrl,
        issueStatus: issue.issueStatus,
        startedAt: issue.startedAt,
        paused: issue.paused,
        pendingDuration: issue.pendingDuration,
        pendingTimeCounter: issue.pendingDuration + (new Date() - issue.startedAt)
      };
      callback( err, currentIssue );
    });
  });
};

timer.stop = function(login, callback) {
  console.log("timen stop login : ", login);
  timer.getUserFromLogin( login, function( err, user ){
    user.stopIssue( function( err, currentIssue ) {
      eventsManager.emit('timer::stopCurrentIssue', login);

      callback(err, currentIssue);
      // if (currentIssue.id) {
      //   timer.addtime(login, currentIssue.id, currentIssue.pendingDuration / 1000 / 60 / 60, null, callback );
      // }
    });
  });
};

timer.addtime = function addtime (login, issue, callback) {
  var issueId = issue.id;
  var issueHours = issue.hours !== '' ? parseInt(issue.hours, 10) : 0;
  var issueMinutes = issue.minutes !== '' ? parseInt(issue.minutes, 10) / 60 : 0;
  var hours = issueHours + issueMinutes;
  var comments = issue.message || '';
  var params = {
    time_entry:{
      issue_id: issueId,
      hours: hours,
      comments: comments
    }
  };

  // eventsManager.emit('log', login);
  eventsManager.emit('log', params);

  var userRest = server.users[login].redmineRest;
  userRest.request('POST', '/time_entries.json', params, function(err, data) {
    console.log("data response : ", data);
    callback( err, data );
  });
    callback();
};

module.exports = timer;
<|endoftext|>


<commit_before>"use strict";
let validator = require('validator');
module.exports = {
  string: function(value) {
    return typeof value === 'string';
  },
  number: function(value) {
    return typeof value === 'number' && !isNaN(value);
  },
  uuid: function(value) {
    if (!module.exports.string(value)) {
      return false;
    }
    return validator.isUUID(value, 4);
  },
  email: function(value) {
    if (!module.exports.string(value)) {
      return false;
    }
    return validator.isEmail(value);
  },
  fqdn: function(value) {
    if (!module.exports.string(value)) {
      return false;
    }
    return validator.isFQDN(value);
  },
  rfqdn: function(value) {
    if (!module.exports.string(value)) {
      return false;
    }
    return validator.isFQDN(value.split('.').reverse().join('.'));
  },
  iso8601: function(value) {
    if (!module.exports.string(value)) {
      return false;
    }
    return validator.isISO8601(value);
  },
  boolean: function(value) {
    return typeof value === 'boolean';
  },
  custom: function() {
    return true;
  },
  e164: function(value) {
    let pattern = /^\+[1-9]\d{1,14}$/;
    return pattern.test(value);
  },
  allBoolean: function(value) {
    return ((value === true) || (value === false) || (value === 'all'));
  },
};
<commit_msg>add object and any types<commit_after>"use strict";
let validator = require('validator');
module.exports = {
  string: function(value) {
    return typeof value === 'string';
  },
  number: function(value) {
    return typeof value === 'number' && !isNaN(value);
  },
  uuid: function(value) {
    if (!module.exports.string(value)) {
      return false;
    }
    return validator.isUUID(value, 4);
  },
  email: function(value) {
    if (!module.exports.string(value)) {
      return false;
    }
    return validator.isEmail(value);
  },
  fqdn: function(value) {
    if (!module.exports.string(value)) {
      return false;
    }
    return validator.isFQDN(value);
  },
  rfqdn: function(value) {
    if (!module.exports.string(value)) {
      return false;
    }
    return validator.isFQDN(value.split('.').reverse().join('.'));
  },
  iso8601: function(value) {
    if (!module.exports.string(value)) {
      return false;
    }
    return validator.isISO8601(value);
  },
  boolean: function(value) {
    return typeof value === 'boolean';
  },
  custom: function() {
    return true;
  },
  e164: function(value) {
    let pattern = /^\+[1-9]\d{1,14}$/;
    return pattern.test(value);
  },
  allBoolean: function(value) {
    return ((value === true) || (value === false) || (value === 'all'));
  },
  object: function(value) {
    return typeof value === 'object';
  },
  any: function(value) {
    return true;
  }
};
<|endoftext|>


<commit_before>var utils = exports

utils.segmentIsHeader = function(segment) {
  if (segment.hasOwnProperty('SegmentType')) {
    return utils.segmentTypeIsHeader(segment.SegmentType)
  }
  return false
}

utils.segmentTypeIsHeader = function(type) {
  return type === 'MSH'
}
<commit_msg>Update for change in the way a Segment is stored<commit_after>var utils = exports

utils.segmentIsHeader = function(segment) {
  if (segment) {
    return segment.parsed.SegmentType === 'MSH'
  }
  return false
}

utils.segmentTypeIsHeader = function(type) {
  return type === 'MSH'
}
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */

var fs = require('fs')
  , path = require('path')
  , join = path.join
  , debug = require('debug')('mocha:watch');

/**
 * Ignored directories.
 */

var ignore = ['node_modules', '.git'];

/**
 * Escape special characters in the given string of html.
 *
 * @param  {String} html
 * @return {String}
 * @api private
 */

exports.escape = function(html){
  return String(html)
    .replace(/&/g, '&')
    .replace(/"/g, '"')
    .replace(/</g, '<')
    .replace(/>/g, '>');
};

/**
 * Array#forEach (<=IE8)
 *
 * @param {Array} array
 * @param {Function} fn
 * @param {Object} scope
 * @api private
 */

exports.forEach = function(arr, fn, scope){
  for (var i = 0, l = arr.length; i < l; i++)
    fn.call(scope, arr[i], i);
};

/**
 * Array#map (<=IE8)
 *
 * @param {Array} array
 * @param {Function} fn
 * @param {Object} scope
 * @api private
 */

exports.map = function(arr, fn, scope){
  var result = [];
  for (var i = 0, l = arr.length; i < l; i++)
    result.push(fn.call(scope, arr[i], i));
  return result;
};

/**
 * Array#indexOf (<=IE8)
 *
 * @parma {Array} arr
 * @param {Object} obj to find index of
 * @param {Number} start
 * @api private
 */

exports.indexOf = function(arr, obj, start){
  for (var i = start || 0, l = arr.length; i < l; i++) {
    if (arr[i] === obj)
      return i;
  }
  return -1;
};

/**
 * Array#reduce (<=IE8)
 *
 * @param {Array} array
 * @param {Function} fn
 * @param {Object} initial value
 * @api private
 */

exports.reduce = function(arr, fn, val){
  var rval = val;

  for (var i = 0, l = arr.length; i < l; i++) {
    rval = fn(rval, arr[i], i, arr);
  }

  return rval;
};

/**
 * Array#filter (<=IE8)
 *
 * @param {Array} array
 * @param {Function} fn
 * @api private
 */

exports.filter = function(arr, fn){
  var ret = [];

  for (var i = 0, l = arr.length; i < l; i++) {
    var val = arr[i];
    if (fn(val, i, arr)) ret.push(val);
  }

  return ret;
};

/**
 * Object.keys (<=IE8)
 *
 * @param {Object} obj
 * @return {Array} keys
 * @api private
 */

exports.keys = Object.keys || function(obj) {
  var keys = []
    , has = Object.prototype.hasOwnProperty // for `window` on <=IE8

  for (var key in obj) {
    if (has.call(obj, key)) {
      keys.push(key);
    }
  }

  return keys;
};

/**
 * Watch the given `files` for changes
 * and invoke `fn(file)` on modification.
 *
 * @param {Array} files
 * @param {Function} fn
 * @api private
 */

exports.watch = function(files, fn){
  var options = { interval: 100 };
  files.forEach(function(file){
    debug('file %s', file);
    fs.watchFile(file, options, function(curr, prev){
      if (prev.mtime < curr.mtime) fn(file);
    });
  });
};

/**
 * Ignored files.
 */

function ignored(path){
  return !~ignore.indexOf(path);
}

/**
 * Lookup files in the given `dir`.
 *
 * @return {Array}
 * @api private
 */

exports.files = function(dir, ext, ret){
  ret = ret || [];
  ext = ext || ['js'];

  var re = new RegExp('\\.(' + ext.join('|') + ')$');

  fs.readdirSync(dir)
  .filter(ignored)
  .forEach(function(path){
    path = join(dir, path);
    if (fs.statSync(path).isDirectory()) {
      exports.files(path, ext, ret);
    } else if (path.match(re)) {
      ret.push(path);
    }
  });

  return ret;
};

/**
 * Compute a slug from the given `str`.
 *
 * @param {String} str
 * @return {String}
 * @api private
 */

exports.slug = function(str){
  return str
    .toLowerCase()
    .replace(/ +/g, '-')
    .replace(/[^-\w]/g, '');
};

/**
 * Strip the function definition from `str`,
 * and re-indent for pre whitespace.
 */

exports.clean = function(str) {
  str = str
    .replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, '')
    .replace(/^function *\(.*\) *{|\(.*\) *=> *{?/, '')
    .replace(/\s+\}$/, '');

  var spaces = str.match(/^\n?( *)/)[1].length
    , tabs = str.match(/^\n?(\t*)/)[1].length
    , re = new RegExp('^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs ? tabs : spaces) + '}', 'gm');

  str = str.replace(re, '');

  return exports.trim(str);
};

/**
 * Escape regular expression characters in `str`.
 *
 * @param {String} str
 * @return {String}
 * @api private
 */

exports.escapeRegexp = function(str){
  return str.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&");
};

/**
 * Trim the given `str`.
 *
 * @param {String} str
 * @return {String}
 * @api private
 */

exports.trim = function(str){
  return str.replace(/^\s+|\s+$/g, '');
};

/**
 * Parse the given `qs`.
 *
 * @param {String} qs
 * @return {Object}
 * @api private
 */

exports.parseQuery = function(qs){
  return exports.reduce(qs.replace('?', '').split('&'), function(obj, pair){
    var i = pair.indexOf('=')
      , key = pair.slice(0, i)
      , val = pair.slice(++i);

    obj[key] = decodeURIComponent(val);
    return obj;
  }, {});
};

/**
 * Highlight the given string of `js`.
 *
 * @param {String} js
 * @return {String}
 * @api private
 */

function highlight(js) {
  return js
    .replace(/</g, '<')
    .replace(/>/g, '>')
    .replace(/\/\/(.*)/gm, '//$1')
    .replace(/('.*?')/gm, '$1')
    .replace(/(\d+\.\d+)/gm, '$1')
    .replace(/(\d+)/gm, '$1')
    .replace(/\bnew[ \t]+(\w+)/gm, 'new $1')
    .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '$1')
}

/**
 * Highlight the contents of tag `name`.
 *
 * @param {String} name
 * @api private
 */

exports.highlightTags = function(name) {
  var code = document.getElementsByTagName(name);
  for (var i = 0, len = code.length; i < len; ++i) {
    code[i].innerHTML = highlight(code[i].innerHTML);
  }
};

/**
 * Stringify `obj`.
 *
 * @param {Object} obj
 * @return {String}
 * @api private
 */

exports.stringify = function(obj) {
  if (obj instanceof RegExp) return obj.toString();
  return JSON.stringify(exports.canonicalize(obj), null, 2);
}

/**
 * Return a new object that has the keys in sorted order.
 * @param {Object} obj
 * @return {Object}
 * @api private
 */

exports.canonicalize = function(obj, stack) {
   stack = stack || [];

   if (exports.indexOf(stack, obj) !== -1) return '[Circular]';

   var canonicalizedObj;

   if ({}.toString.call(obj) === '[object Array]') {
     stack.push(obj);
     canonicalizedObj = exports.map(obj, function(item) {
       return exports.canonicalize(item, stack);
     });
     stack.pop();
   } else if (typeof obj === 'object' && obj !== null) {
     stack.push(obj);
     canonicalizedObj = {};
     exports.forEach(exports.keys(obj).sort(), function(key) {
       canonicalizedObj[key] = exports.canonicalize(obj[key], stack);
     });
     stack.pop();
   } else {
     canonicalizedObj = obj;
   }

   return canonicalizedObj;
 }
<commit_msg>Strip commas from the JSON.stringify output before diffing<commit_after>/**
 * Module dependencies.
 */

var fs = require('fs')
  , path = require('path')
  , join = path.join
  , debug = require('debug')('mocha:watch');

/**
 * Ignored directories.
 */

var ignore = ['node_modules', '.git'];

/**
 * Escape special characters in the given string of html.
 *
 * @param  {String} html
 * @return {String}
 * @api private
 */

exports.escape = function(html){
  return String(html)
    .replace(/&/g, '&')
    .replace(/"/g, '"')
    .replace(/</g, '<')
    .replace(/>/g, '>');
};

/**
 * Array#forEach (<=IE8)
 *
 * @param {Array} array
 * @param {Function} fn
 * @param {Object} scope
 * @api private
 */

exports.forEach = function(arr, fn, scope){
  for (var i = 0, l = arr.length; i < l; i++)
    fn.call(scope, arr[i], i);
};

/**
 * Array#map (<=IE8)
 *
 * @param {Array} array
 * @param {Function} fn
 * @param {Object} scope
 * @api private
 */

exports.map = function(arr, fn, scope){
  var result = [];
  for (var i = 0, l = arr.length; i < l; i++)
    result.push(fn.call(scope, arr[i], i));
  return result;
};

/**
 * Array#indexOf (<=IE8)
 *
 * @parma {Array} arr
 * @param {Object} obj to find index of
 * @param {Number} start
 * @api private
 */

exports.indexOf = function(arr, obj, start){
  for (var i = start || 0, l = arr.length; i < l; i++) {
    if (arr[i] === obj)
      return i;
  }
  return -1;
};

/**
 * Array#reduce (<=IE8)
 *
 * @param {Array} array
 * @param {Function} fn
 * @param {Object} initial value
 * @api private
 */

exports.reduce = function(arr, fn, val){
  var rval = val;

  for (var i = 0, l = arr.length; i < l; i++) {
    rval = fn(rval, arr[i], i, arr);
  }

  return rval;
};

/**
 * Array#filter (<=IE8)
 *
 * @param {Array} array
 * @param {Function} fn
 * @api private
 */

exports.filter = function(arr, fn){
  var ret = [];

  for (var i = 0, l = arr.length; i < l; i++) {
    var val = arr[i];
    if (fn(val, i, arr)) ret.push(val);
  }

  return ret;
};

/**
 * Object.keys (<=IE8)
 *
 * @param {Object} obj
 * @return {Array} keys
 * @api private
 */

exports.keys = Object.keys || function(obj) {
  var keys = []
    , has = Object.prototype.hasOwnProperty // for `window` on <=IE8

  for (var key in obj) {
    if (has.call(obj, key)) {
      keys.push(key);
    }
  }

  return keys;
};

/**
 * Watch the given `files` for changes
 * and invoke `fn(file)` on modification.
 *
 * @param {Array} files
 * @param {Function} fn
 * @api private
 */

exports.watch = function(files, fn){
  var options = { interval: 100 };
  files.forEach(function(file){
    debug('file %s', file);
    fs.watchFile(file, options, function(curr, prev){
      if (prev.mtime < curr.mtime) fn(file);
    });
  });
};

/**
 * Ignored files.
 */

function ignored(path){
  return !~ignore.indexOf(path);
}

/**
 * Lookup files in the given `dir`.
 *
 * @return {Array}
 * @api private
 */

exports.files = function(dir, ext, ret){
  ret = ret || [];
  ext = ext || ['js'];

  var re = new RegExp('\\.(' + ext.join('|') + ')$');

  fs.readdirSync(dir)
  .filter(ignored)
  .forEach(function(path){
    path = join(dir, path);
    if (fs.statSync(path).isDirectory()) {
      exports.files(path, ext, ret);
    } else if (path.match(re)) {
      ret.push(path);
    }
  });

  return ret;
};

/**
 * Compute a slug from the given `str`.
 *
 * @param {String} str
 * @return {String}
 * @api private
 */

exports.slug = function(str){
  return str
    .toLowerCase()
    .replace(/ +/g, '-')
    .replace(/[^-\w]/g, '');
};

/**
 * Strip the function definition from `str`,
 * and re-indent for pre whitespace.
 */

exports.clean = function(str) {
  str = str
    .replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, '')
    .replace(/^function *\(.*\) *{|\(.*\) *=> *{?/, '')
    .replace(/\s+\}$/, '');

  var spaces = str.match(/^\n?( *)/)[1].length
    , tabs = str.match(/^\n?(\t*)/)[1].length
    , re = new RegExp('^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs ? tabs : spaces) + '}', 'gm');

  str = str.replace(re, '');

  return exports.trim(str);
};

/**
 * Escape regular expression characters in `str`.
 *
 * @param {String} str
 * @return {String}
 * @api private
 */

exports.escapeRegexp = function(str){
  return str.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&");
};

/**
 * Trim the given `str`.
 *
 * @param {String} str
 * @return {String}
 * @api private
 */

exports.trim = function(str){
  return str.replace(/^\s+|\s+$/g, '');
};

/**
 * Parse the given `qs`.
 *
 * @param {String} qs
 * @return {Object}
 * @api private
 */

exports.parseQuery = function(qs){
  return exports.reduce(qs.replace('?', '').split('&'), function(obj, pair){
    var i = pair.indexOf('=')
      , key = pair.slice(0, i)
      , val = pair.slice(++i);

    obj[key] = decodeURIComponent(val);
    return obj;
  }, {});
};

/**
 * Highlight the given string of `js`.
 *
 * @param {String} js
 * @return {String}
 * @api private
 */

function highlight(js) {
  return js
    .replace(/</g, '<')
    .replace(/>/g, '>')
    .replace(/\/\/(.*)/gm, '//$1')
    .replace(/('.*?')/gm, '$1')
    .replace(/(\d+\.\d+)/gm, '$1')
    .replace(/(\d+)/gm, '$1')
    .replace(/\bnew[ \t]+(\w+)/gm, 'new $1')
    .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '$1')
}

/**
 * Highlight the contents of tag `name`.
 *
 * @param {String} name
 * @api private
 */

exports.highlightTags = function(name) {
  var code = document.getElementsByTagName(name);
  for (var i = 0, len = code.length; i < len; ++i) {
    code[i].innerHTML = highlight(code[i].innerHTML);
  }
};

/**
 * Stringify `obj`.
 *
 * @param {Object} obj
 * @return {String}
 * @api private
 */

exports.stringify = function(obj) {
  if (obj instanceof RegExp) return obj.toString();
  return JSON.stringify(exports.canonicalize(obj), null, 2).replace(/,(\n|$)/g, '$1');
}

/**
 * Return a new object that has the keys in sorted order.
 * @param {Object} obj
 * @return {Object}
 * @api private
 */

exports.canonicalize = function(obj, stack) {
   stack = stack || [];

   if (exports.indexOf(stack, obj) !== -1) return '[Circular]';

   var canonicalizedObj;

   if ({}.toString.call(obj) === '[object Array]') {
     stack.push(obj);
     canonicalizedObj = exports.map(obj, function(item) {
       return exports.canonicalize(item, stack);
     });
     stack.pop();
   } else if (typeof obj === 'object' && obj !== null) {
     stack.push(obj);
     canonicalizedObj = {};
     exports.forEach(exports.keys(obj).sort(), function(key) {
       canonicalizedObj[key] = exports.canonicalize(obj[key], stack);
     });
     stack.pop();
   } else {
     canonicalizedObj = obj;
   }

   return canonicalizedObj;
 }
<|endoftext|>


<commit_before>'use strict'

require('./typedefs')

const path = require('path')
const versiony = require('versiony')
const Promise = require('promise')
const cpExec = require('child_process').exec
const exec = Promise.denodeify(cpExec)

const utils = {

  /**
   * Make sure scope is one of 'patch', 'minor', 'major' (or their aliases)
   *
   * @param {String} scope - the scope to check
   * @param {String} prNumber - the # of the PR
   * @param {String} prUrl - the url of the PR
   * @returns {String} the validated scope
   * @throws Error if scope is invalid
   */
  getValidatedScope (scope, prNumber, prUrl) {
    switch (scope) {
      case 'fix': // fallthrough
      case 'patch':
        return 'patch'

      case 'feature':  // fallthrough
      case 'minor':
        return 'minor'

      case 'breaking': // fallthrough
      case 'major':
        return 'major'

      default:
        throw new Error(`Invalid version-bump scope [${scope}] found for PR #${prNumber} (${prUrl})`)
    }
  },

  /**
   * If we are in a PR build, just grab the sha from env, if not
   * take a look at the git history (one before the merge we're handling) and find that PR
   * @returns {String} the sha of the current commit
   */
  getSha () {
    if (process.env.TRAVIS_PULL_REQUEST && (process.env.TRAVIS_PULL_REQUEST !== 'false')) {
      console.log(`Using TRAVIS_COMMIT [${process.env.TRAVIS_COMMIT}] for sha`)
      return Promise.resolve(process.env.TRAVIS_COMMIT)
    }

    return exec('git log -1 --skip=1 --format="%H"').then((stdout) => {
      const sha = stdout.replace('\n', '')
      console.log(`Using [${sha}] for sha`)
      return sha
    })
  },

  /**
   * Extract the scope string ('patch', 'minor', 'major') from the PR object
   * @param {PullRequest} pr - the PR object
   * @returns {String} the scope of the PR (from the pr description)
   * @throws Error if there is not a single, valid scope in the PR description
   */
  getScopeForPr (pr) {
    const matches = pr.description.match(/#[A-Za-z]+#/g)

    if (!matches) {
      throw new Error(`No version-bump scope found for PR #${pr.number} (${pr.url})`)
    }

    if (matches.length > 1) {
      throw new Error(`Too many version-bump scopes found for PR #${pr.number} (${pr.url})`)
    }

    const scope = matches[0].replace(/#/g, '').toLowerCase()
    return utils.getValidatedScope(scope, pr.number, pr.url)
  },

  /**
   * Bump the version in package.json with the given scope
   * @param {String} scope - the scope of the version bump (major, minor, patch)
   */
  bumpVersion (scope) {
    switch (scope) {
      case 'patch':
        versiony
          .patch()
          .with('package.json')
          .end()
        break

      case 'minor':
        versiony
          .minor()
          .patch(0)
          .with('package.json')
          .end()
        break

      case 'major':
        versiony
          .major()
          .minor(0)
          .patch(0)
          .with('package.json')
          .end()
        break
    }
  },

  /**
   * Bump the version in package.json with the given scope
   * @returns {Promise} - a promise resolved with the results of the git commands
   */
  commitChanges () {
    // TODO: make this more configurable
    const buildNumber = process.env.TRAVIS_BUILD_NUMBER

    return exec('git config --global user.email "builds@travis-ci.com"')
      .then(() => {
        return exec('git config --global user.name "Travis CI"')
      })
      .then(() => {
        // TODO: make this more configurable? (what's being bumped that is)
        return exec(`git add package.json`)
      })
      .then(() => {
        return exec(`git commit -m "Automated version bump from CI build ${buildNumber}"`)
      })
      .then(() => {
        const name = require(path.join(process.cwd(), 'package.json')).name
        return exec(`git tag v${name} -a -m "Generated tag from CI build ${buildNumber}"`)
      })
  }
}

module.exports = utils
<commit_msg>Fixed format of tag name<commit_after>'use strict'

require('./typedefs')

const path = require('path')
const versiony = require('versiony')
const Promise = require('promise')
const cpExec = require('child_process').exec
const exec = Promise.denodeify(cpExec)

const utils = {

  /**
   * Make sure scope is one of 'patch', 'minor', 'major' (or their aliases)
   *
   * @param {String} scope - the scope to check
   * @param {String} prNumber - the # of the PR
   * @param {String} prUrl - the url of the PR
   * @returns {String} the validated scope
   * @throws Error if scope is invalid
   */
  getValidatedScope (scope, prNumber, prUrl) {
    switch (scope) {
      case 'fix': // fallthrough
      case 'patch':
        return 'patch'

      case 'feature':  // fallthrough
      case 'minor':
        return 'minor'

      case 'breaking': // fallthrough
      case 'major':
        return 'major'

      default:
        throw new Error(`Invalid version-bump scope [${scope}] found for PR #${prNumber} (${prUrl})`)
    }
  },

  /**
   * If we are in a PR build, just grab the sha from env, if not
   * take a look at the git history (one before the merge we're handling) and find that PR
   * @returns {String} the sha of the current commit
   */
  getSha () {
    if (process.env.TRAVIS_PULL_REQUEST && (process.env.TRAVIS_PULL_REQUEST !== 'false')) {
      console.log(`Using TRAVIS_COMMIT [${process.env.TRAVIS_COMMIT}] for sha`)
      return Promise.resolve(process.env.TRAVIS_COMMIT)
    }

    return exec('git log -1 --skip=1 --format="%H"').then((stdout) => {
      const sha = stdout.replace('\n', '')
      console.log(`Using [${sha}] for sha`)
      return sha
    })
  },

  /**
   * Extract the scope string ('patch', 'minor', 'major') from the PR object
   * @param {PullRequest} pr - the PR object
   * @returns {String} the scope of the PR (from the pr description)
   * @throws Error if there is not a single, valid scope in the PR description
   */
  getScopeForPr (pr) {
    const matches = pr.description.match(/#[A-Za-z]+#/g)

    if (!matches) {
      throw new Error(`No version-bump scope found for PR #${pr.number} (${pr.url})`)
    }

    if (matches.length > 1) {
      throw new Error(`Too many version-bump scopes found for PR #${pr.number} (${pr.url})`)
    }

    const scope = matches[0].replace(/#/g, '').toLowerCase()
    return utils.getValidatedScope(scope, pr.number, pr.url)
  },

  /**
   * Bump the version in package.json with the given scope
   * @param {String} scope - the scope of the version bump (major, minor, patch)
   */
  bumpVersion (scope) {
    switch (scope) {
      case 'patch':
        versiony
          .patch()
          .with('package.json')
          .end()
        break

      case 'minor':
        versiony
          .minor()
          .patch(0)
          .with('package.json')
          .end()
        break

      case 'major':
        versiony
          .major()
          .minor(0)
          .patch(0)
          .with('package.json')
          .end()
        break
    }
  },

  /**
   * Bump the version in package.json with the given scope
   * @returns {Promise} - a promise resolved with the results of the git commands
   */
  commitChanges () {
    // TODO: make this more configurable
    const buildNumber = process.env.TRAVIS_BUILD_NUMBER

    return exec('git config --global user.email "builds@travis-ci.com"')
      .then(() => {
        return exec('git config --global user.name "Travis CI"')
      })
      .then(() => {
        // TODO: make this more configurable? (what's being bumped that is)
        return exec(`git add package.json`)
      })
      .then(() => {
        return exec(`git commit -m "Automated version bump from CI build ${buildNumber}"`)
      })
      .then(() => {
        const name = require(path.join(process.cwd(), 'package.json')).version
        return exec(`git tag v${name} -a -m "Generated tag from CI build ${buildNumber}"`)
      })
  }
}

module.exports = utils
<|endoftext|>


<commit_before>
/**
 * Optionally format generated XML
 */
exports.format = function(src) {
  return require('js-prettify').html(src, {
    indent_size: 2,
    indent_inner_html: true
  }).replace(/(\r\n|\n\r|\n|\r){2,}/g, '\n');
};
<commit_msg>Remove extra space from utils.js<commit_after>/**
 * Optionally format generated XML
 */
exports.format = function(src) {
  return require('js-prettify').html(src, {
    indent_size: 2,
    indent_inner_html: true
  }).replace(/(\r\n|\n\r|\n|\r){2,}/g, '\n');
};
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var fs = require('fs')
  , cssom = require('cssom')
  , jsdom = require('jsdom')

/**
 * Returns an array of the selectors.
 *
 * @license Sizzle CSS Selector Engine - MIT
 * @param {String} selectorText from cssom
 * @api public
 */

exports.extract = function extract (selectorText) {
  var attr = 0
    , sels = []
    , sel = ''

  for (var i = 0, l = selectorText.length; i < l; i++) {
    var c = selectorText.charAt(i);

    if (attr) {
      if (']' == c || ')' == c) attr--;
      sel += c;
    } else {
      if (',' == c) {
        sels.push(sel);
        sel = '';
      } else {
        if ('[' == c || '(' == c) attr++;
        if (sel.length || (c != ',' && c != ' ')) sel += c;
      }
    }
  }

  if (sel.length) sels.push(sel);

  return sels;
}

/**
 * Returns a parse tree for a CSS source.
 * If it encounters multiple selectors separated by a comma, it splits the
 * tree.
 *
 * @param {String} css source
 * @api public
 */

exports.parseCSS = function (css) {
  var rules = cssom.parse(css).cssRules || []
    , ret = []

  for (var i = 0, l = rules.length; i < l; i++) {
    var rule = rules[i]
      , selectors = exports.extract(rule.selectorText)

    for (var ii = 0, ll = selectors.length; ii < ll; ii++) {
      ret.push([selectors[ii], rule.style]);
    }
  }

  return ret;
}

/**
 * Returns a JSDom jQuery object
 *
 * api public
 */

exports.jsdom = function (html) {
  return jsdom.html(html, null, {
    features: {
        QuerySelector: ['1.0']
      , FetchExternalResources: false
      , ProcessExternalResources: false
      , MutationEvents: false
    }
  });
};

/**
 * Converts to array
 *
 * @api public
 */

exports.toArray = function (arr) {
  var ret = [];

  for (var i = 0, l = arr.length; i < l; i++)
    ret.push(arr[i]);

  return ret;
};

/**
 * Compares two specificity vectors, returning the winning one.
 *
 * @param {Array} vector a
 * @param {Array} vector b
 * @return {Array}
 * @api public
 */

exports.compare = function (a, b) {
  for (var i = 0; i < 4; i++) {
    if (a[i] === b[i]) continue;
    if (a[i] > b[i]) return a;
    return b;
  }

  return b;
}
<commit_msg>Fixed presence of \n in selectors.<commit_after>
/**
 * Module dependencies.
 */

var fs = require('fs')
  , cssom = require('cssom')
  , jsdom = require('jsdom')

/**
 * Returns an array of the selectors.
 *
 * @license Sizzle CSS Selector Engine - MIT
 * @param {String} selectorText from cssom
 * @api public
 */

exports.extract = function extract (selectorText) {
  var attr = 0
    , sels = []
    , sel = ''

  for (var i = 0, l = selectorText.length; i < l; i++) {
    var c = selectorText.charAt(i);

    if (attr) {
      if (']' == c || ')' == c) attr--;
      sel += c;
    } else {
      if (',' == c) {
        sels.push(sel);
        sel = '';
      } else {
        if ('[' == c || '(' == c) attr++;
        if (sel.length || (c != ',' && c != '\n' && c != ' ')) sel += c;
      }
    }
  }

  if (sel.length) sels.push(sel);

  return sels;
}

/**
 * Returns a parse tree for a CSS source.
 * If it encounters multiple selectors separated by a comma, it splits the
 * tree.
 *
 * @param {String} css source
 * @api public
 */

exports.parseCSS = function (css) {
  var rules = cssom.parse(css).cssRules || []
    , ret = []

  for (var i = 0, l = rules.length; i < l; i++) {
    var rule = rules[i]
      , selectors = exports.extract(rule.selectorText)

    for (var ii = 0, ll = selectors.length; ii < ll; ii++) {
      ret.push([selectors[ii], rule.style]);
    }
  }

  return ret;
}

/**
 * Returns a JSDom jQuery object
 *
 * api public
 */

exports.jsdom = function (html) {
  return jsdom.html(html, null, {
    features: {
        QuerySelector: ['1.0']
      , FetchExternalResources: false
      , ProcessExternalResources: false
      , MutationEvents: false
    }
  });
};

/**
 * Converts to array
 *
 * @api public
 */

exports.toArray = function (arr) {
  var ret = [];

  for (var i = 0, l = arr.length; i < l; i++)
    ret.push(arr[i]);

  return ret;
};

/**
 * Compares two specificity vectors, returning the winning one.
 *
 * @param {Array} vector a
 * @param {Array} vector b
 * @return {Array}
 * @api public
 */

exports.compare = function (a, b) {
  for (var i = 0; i < 4; i++) {
    if (a[i] === b[i]) continue;
    if (a[i] > b[i]) return a;
    return b;
  }

  return b;
}
<|endoftext|>


<commit_before>/*jshint esversion:6, node:true*/
'use strict';

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

module.exports.normalizePort = normalizePort;

function getPort(){
    return normalizePort(process.env.PORT || process.env.NODE_APP_PORT || '3000');
}

module.exports.getPort = getPort;
<commit_msg>lib: utils clean up, this closes issue #3<commit_after>/*jshint esversion:6, node:true*/
'use strict';

/**
 * Normalize a port into a number, string, or false.
 */
function normalizePort(val, def) {
    var port = parseInt(val, 10);

    // named pipe
    if (isNaN(port)) return val;

    // port number
    if (port >= 0) return port;

    return false;
}

module.exports.normalizePort = normalizePort;

function getPort(port=3000){
    return normalizePort(process.env.PORT || process.env.NODE_APP_PORT || port);
}

module.exports.getPort = getPort;
<|endoftext|>


<commit_before>
(function (module) {
	'use strict';

	var _key_iterator = Symbol.iterator;

	module.exports = {
		dialog: dialog,
		notice: notice,
		info: notice('info'),
		warn: notice('warning'),
		error: notice('error'),
		chainFunction: chainFunction,
		isIterable: isIterable,
		repeat: repeat,
		some: some,
		forOf: forOf,
		makeSubProperty: makeSubProperty,
		ternary: ternary,
		makeDefaultProperty: makeDefaultProperty,
		deepJoin: deepJoin,
		tryCatch: tryCatch,
		tryCatchOf: tryCatchOf,
		throwError: throwError,
		createMerelyObject: createMerelyObject,
		clearChildren: clearChildren
	};

	function dialog(title) {
		return (message) =>
			setTimeout(alert.bind(null, message, title));
	}

	function notice(type) {
		return (message, detail) =>
			atom.notifications.add(type, message, {detail: detail});
	}

	function chainFunction(fna, fnb) {
		return (arg) => new chainFunction.Return(fna(arg), fnb(arg));
	}

	chainFunction.array = (fnlist) => {
		var fn = () => chainFunction.NOT_AN_ELEMENT;
		for (let fne of fnlist) {
			ensure(fne);
			fn = chainFunction(fn, fne);
		}
		function ensure(fn) {
			if (typeof fn !== 'function') {
				let error = new TypeError(`An element of parameter 'fnlist' is not a function: ${typeof fn} ${tryConvert.forString(fn)}`);
				error.details = {element: fn, array: fnlist};
				throw error;
			}
		}
		return fn;
	}

	chainFunction.Return = class Return extends Array {

		constructor(a, b) {
			if (a instanceof Return) {
				a.push(b);
				return a;
			} else {
				super();
				this.push(a);
				this.push(b);
			}
		}

		push(element) {
			return element === chainFunction.NOT_AN_ELEMENT ? this.length : super.push(element);
		}

	}

	chainFunction.NOT_AN_ELEMENT = Symbol('NOT_AN_ELEMENT');

	function isIterable(object) {
		return typeof object === 'object' && typeof object[_key_iterator] === 'function';
	}

	function tryConvert(value, type) {
		return tryCatch(() => type(value), (error) => error);
	}

	tryConvert.forString = (value) => tryConvert(value, String);

	tryConvert.forNumber = (value) => tryConvert(value, Number);

	function repeat(action) {
		return new repeat.Return(action);
	}

	repeat.Return = class {

		constructor(action) {
			if (typeof action !== 'function') {
				throw new TypeError(`Parameter 'action' must be a function`)
			}
			this.action = action.bind(null);
		}

		until(isstop) {
			do {
				this.action();
			} while (!isstop());
		}

		times(count) {
			while (count) {
				action(count);
				--count;
			}
		}

	};

	function some(iterable, element, check) {
		for (let el of iterable) {
			if (check(element, el)) {
				return true;
			}
		}
		return false;
	}

	some.equal = (values, value) =>
		some(values, value, some.equal.check);

	some.equal.check = (a, b) => a === b;

	some.equal.typeof = (types, value) =>
		some.equal(types, typeof value);

	some.equiv = (iterable, element, get) =>
		some(iterable, element, equiv.checkOf(get));

	some.equiv.checkOf = (get) =>
		(a, b) => a === get(b);

	some.equiv.forType = (iterable, element, types) =>
		some.equiv(iterable, element, some.equiv.forType.get);

	some.equiv.forType.get = (value) => typeof value;

	function forOf(iterable, callback) {

		var isiter = isIterable(iterable);
		var isfunc = typeof callback === 'function';

		if (isiter && isfunc) {
			return forOf.for.both(iterable, callback);
		}

		if (isiter) {
			return forOf.for.iterable(iterable);
		}

		if (isfunc) {
			return forOf.for.callback(callback);
		}

		throw new TypeError(`Invalid type of arguments.`);

	}

	forOf.gen = function * (iterable, generator) {
		for (let element of iterable) {
			yield * generator(element, iterable);
		}
	}

	forOf.gen.fromCallback = function * (iterable, callback) {
		yield * forOf.gen(iterable, forOf.gen.create(callback));
	}

	forOf.gen.create = (callback) =>
		function * (element, iterable) {
			yield callback(element, iterable);
		}

	forOf.for = (iterable, callback) => {
		for (let element of iterable) {
			callback(element, iterable);
		}
	}

	forOf.for.both = (iterable, callback) =>
		forOf.for.bind(null, iterable, callback);

	forOf.for.iterable = (iterable) =>
		(callback) => forOf.for(iterable, callback);

	forOf.for.callback = (callback) =>
		(iterable) => forOf.for(iterable, callback);

	function makeSubProperty(object, pname, subpname, subval) {
		var sub = object[pname];
		if (some.typeof(['object', 'function'], sub)) {
			sub[subpname] = subval;
		} else {
			object[pname] = {[subpname]: subval};
		}
	}

	function ternary(is, iftrue, iffalse) {
		return (is() ? iftrue : iffalse)();
	}

	ternary.if = (is, act, val) =>
		ternary(is, act, () => val);

	ternary.unless = (is, act, val) =>
		ternary(is, () => val, act);

	ternary.ternary = (is, valiftrue, valiffalse) =>
		ternary(is, () => valiftrue, () => valiffalse);

	ternary.correct = (val, iswrong, getright) =>
		ternary(() => iswrong(val()), getright, val);

	ternary.correct.typeof = (val, wrongtypes, getright) =>
		ternary.correct(val, some.equal.typeof.bind(null, wrongtypes), getright);

	ternary.correct.valof = (val, wrongs, getright) =>
		ternary.correct(val, some.equal.bind(null, wrongs), getright);

	function makeDefaultProperty(object, pname, iswrong, right) {
		if (iswrong(object[pname])) {
			object[pname] = right;
		}
	}

	makeDefaultProperty.typeof = (object, pname, wrongtypes, right) =>
		makeDefaultProperty(object, pname, some.equal.typeof.bind(null, wrongtypes), right);

	makeDefaultProperty.belongs = (object, pname, wrongs, right) =>
		makeDefaultProperty(object, pname, some.equal.bind(null, wrongs), right);

	function deepJoin(array, separator) {
		return array.map((element) => element instanceof Array ? deepJoin(element, separator) : element).join(separator);
	}

	deepJoin.fromAny = (val, sep) => deepJoin([val], sep);

	function tryCatch(callback, onerror, onsuccess, param) {

		var result;

		try {
			result = callback(param)
		} catch (error) {
			return typeof onerror === 'function' && onerror(error, param);
		}

		typeof onsuccess === 'function' && onsuccess(result, param);

		return result;

	}

	tryCatch.of = tryCatchOf;

	function tryCatchOf(callback, onerror, onsuccess) {

		if (typeof callback !== 'function') {
			throw new TypeError(`Parameter 'callback' must be a function.`);
		}

		return (param) =>
			tryCatch(callback, onerror, onsuccess, param);

	}

	tryCatchOf.setTimeout = (callback, timeout) => {
		setTimeout((param) => tryCatch(callback, result.onerror, result.onsuccess, param), timeout);
		var result = new tryCatchOf.setTimeout.Return();
		return result;
	};

	tryCatchOf.setTimeout.Return = class {

		constructor() {
			var res = this;
			res.then = (handle) => (res.onsuccess = handle, res);
			res.catch = (handle) => (res.onerror = handle, res);
		}

		onsuccess() {}

		onerror(error) {
			throw error;
		}

	};

	function throwError(error) {
		throw error;
	}

	function createMerelyObject() {
		return new MerelyObject();
	}

	class MerelyObject {

		constructor() {
			this.object = Object.create(null);
		}

		assign(object) {
			Object.assign(this.object, object);
			return this;
		}

		defineProperty(pname, desc) {
			Object.defineProperty(this.object, pname, desc);
			return this;
		}

		makeData(pname, value, writable, enumerable, configurable) {
			this.defineProperty(pname, {
				value: value,
				writable: writable,
				enumerable: enumerable,
				configurable: configurable
			});
			return this;
		}

		makeAccessor(pname, get, set, enumerable, configurable) {
			this.defineProperty({
				get: get,
				set: set,
				enumerable: enumerable,
				configurable: configurable
			});
			return this;
		}

		newFrozen() {
			return Object.freeze(this.createChild());
		}

		createChild() {
			return Object.create(this.object);
		}

		createClass() {
			base.prototype = this.createChild();
			return class extends base {};
			function base() {}
		}

	}

	createMerelyObject.MerelyObject = MerelyObject;

	function clearChildren(element) {
		for ( ; ; ) {
			let child = element.lastChild;
			if (child) {
				child.remove();
			} else {
				break;
			}
		}
	}

})(module);
<commit_msg>update utils.js<commit_after>
(function (module) {
	'use strict';

	var _key_iterator = Symbol.iterator;

	module.exports = {
		dialog: dialog,
		notice: notice,
		info: notice('info'),
		warn: notice('warning'),
		error: notice('error'),
		chainFunction: chainFunction,
		isIterable: isIterable,
		repeat: repeat,
		some: some,
		forOf: forOf,
		makeSubProperty: makeSubProperty,
		ternary: ternary,
		makeDefaultProperty: makeDefaultProperty,
		deepJoin: deepJoin,
		tryCatch: tryCatch,
		tryCatchOf: tryCatchOf,
		throwError: throwError,
		createMerelyObject: createMerelyObject,
		clearChildren: clearChildren
	};

	function dialog(title) {
		return (message) =>
			setTimeout(alert.bind(null, message, title));
	}

	function notice(type) {
		return (message, detail) =>
			atom.notifications.add(type, message, {detail: detail});
	}

	function chainFunction(fna, fnb) {
		return (...arg) => new chainFunction.Return(fna(...arg), fnb(...arg));
	}

	chainFunction.array = (fnlist) => {
		var fn = () => chainFunction.NOT_AN_ELEMENT;
		for (let fne of fnlist) {
			ensure(fne);
			fn = chainFunction(fn, fne);
		}
		function ensure(fn) {
			if (typeof fn !== 'function') {
				let error = new TypeError(`An element of parameter 'fnlist' is not a function: ${typeof fn} ${tryConvert.forString(fn)}`);
				error.details = {element: fn, array: fnlist};
				throw error;
			}
		}
		return fn;
	}

	chainFunction.Return = class Return extends Array {

		constructor(a, b) {
			if (a instanceof Return) {
				a.push(b);
				return a;
			} else {
				super();
				this.push(a, b);
			}
		}

		push(...args) {
			return super.push(...this.filter((val) => val !== chainFunction.NOT_AN_ELEMENT));
		}

	}

	chainFunction.NOT_AN_ELEMENT = Symbol('NOT_AN_ELEMENT');

	function isIterable(object) {
		return typeof object === 'object' && typeof object[_key_iterator] === 'function';
	}

	function tryConvert(value, type) {
		return tryCatch(() => type(value), (error) => error);
	}

	tryConvert.forString = (value) => tryConvert(value, String);

	tryConvert.forNumber = (value) => tryConvert(value, Number);

	function repeat(action) {
		return new repeat.Return(action);
	}

	repeat.Return = class {

		constructor(action) {
			if (typeof action !== 'function') {
				throw new TypeError(`Parameter 'action' must be a function`)
			}
			this.action = action.bind(null);
		}

		until(isstop) {
			do {
				this.action();
			} while (!isstop());
		}

		times(count) {
			while (count) {
				action(count);
				--count;
			}
		}

	};

	function some(iterable, element, check) {
		for (let el of iterable) {
			if (check(element, el)) {
				return true;
			}
		}
		return false;
	}

	some.equal = (values, value) =>
		some(values, value, some.equal.check);

	some.equal.check = (a, b) => a === b;

	some.equal.typeof = (types, value) =>
		some.equal(types, typeof value);

	some.equiv = (iterable, element, get) =>
		some(iterable, element, equiv.checkOf(get));

	some.equiv.checkOf = (get) =>
		(a, b) => a === get(b);

	some.equiv.forType = (iterable, element, types) =>
		some.equiv(iterable, element, some.equiv.forType.get);

	some.equiv.forType.get = (value) => typeof value;

	function forOf(iterable, callback) {

		var isiter = isIterable(iterable);
		var isfunc = typeof callback === 'function';

		if (isiter && isfunc) {
			return forOf.for.both(iterable, callback);
		}

		if (isiter) {
			return forOf.for.iterable(iterable);
		}

		if (isfunc) {
			return forOf.for.callback(callback);
		}

		throw new TypeError(`Invalid type of arguments.`);

	}

	forOf.gen = function * (iterable, generator) {
		for (let element of iterable) {
			yield * generator(element, iterable);
		}
	}

	forOf.gen.fromCallback = function * (iterable, callback) {
		yield * forOf.gen(iterable, forOf.gen.create(callback));
	}

	forOf.gen.create = (callback) =>
		function * (element, iterable) {
			yield callback(element, iterable);
		}

	forOf.for = (iterable, callback) => {
		for (let element of iterable) {
			callback(element, iterable);
		}
	}

	forOf.for.both = (iterable, callback) =>
		forOf.for.bind(null, iterable, callback);

	forOf.for.iterable = (iterable) =>
		(callback) => forOf.for(iterable, callback);

	forOf.for.callback = (callback) =>
		(iterable) => forOf.for(iterable, callback);

	function makeSubProperty(object, pname, subpname, subval) {
		var sub = object[pname];
		if (some.typeof(['object', 'function'], sub)) {
			sub[subpname] = subval;
		} else {
			object[pname] = {[subpname]: subval};
		}
	}

	function ternary(is, iftrue, iffalse) {
		return (is() ? iftrue : iffalse)();
	}

	ternary.if = (is, act, val) =>
		ternary(is, act, () => val);

	ternary.unless = (is, act, val) =>
		ternary(is, () => val, act);

	ternary.ternary = (is, valiftrue, valiffalse) =>
		ternary(is, () => valiftrue, () => valiffalse);

	ternary.correct = (val, iswrong, getright) =>
		ternary(() => iswrong(val()), getright, val);

	ternary.correct.typeof = (val, wrongtypes, getright) =>
		ternary.correct(val, some.equal.typeof.bind(null, wrongtypes), getright);

	ternary.correct.valof = (val, wrongs, getright) =>
		ternary.correct(val, some.equal.bind(null, wrongs), getright);

	function makeDefaultProperty(object, pname, iswrong, right) {
		if (iswrong(object[pname])) {
			object[pname] = right;
		}
	}

	makeDefaultProperty.typeof = (object, pname, wrongtypes, right) =>
		makeDefaultProperty(object, pname, some.equal.typeof.bind(null, wrongtypes), right);

	makeDefaultProperty.belongs = (object, pname, wrongs, right) =>
		makeDefaultProperty(object, pname, some.equal.bind(null, wrongs), right);

	function deepJoin(array, separator) {
		return array.map((element) => element instanceof Array ? deepJoin(element, separator) : element).join(separator);
	}

	deepJoin.fromAny = (val, sep) => deepJoin([val], sep);

	function tryCatch(callback, onerror, onsuccess, ...args) {

		var result;

		try {
			result = callback(...args)
		} catch (error) {
			return typeof onerror === 'function' && onerror(error, ...args);
		}

		typeof onsuccess === 'function' && onsuccess(result, ...args);

		return result;

	}

	tryCatch.of = tryCatchOf;

	function tryCatchOf(callback, onerror, onsuccess) {

		if (typeof callback !== 'function') {
			throw new TypeError(`Parameter 'callback' must be a function.`);
		}

		return (...args) =>
			tryCatch(callback, onerror, onsuccess, ...args);

	}

	tryCatchOf.setTimeout = (callback, timeout) => {
		setTimeout((param) => tryCatch(callback, result.onerror, result.onsuccess, param), timeout);
		var result = new tryCatchOf.setTimeout.Return();
		return result;
	};

	tryCatchOf.setTimeout.Return = class {

		constructor() {
			var res = this;
			res.then = (handle) => (res.onsuccess = handle, res);
			res.catch = (handle) => (res.onerror = handle, res);
		}

		onsuccess() {}

		onerror(error) {
			throw error;
		}

	};

	function throwError(error) {
		throw error;
	}

	function createMerelyObject() {
		return new MerelyObject();
	}

	class MerelyObject {

		constructor() {
			this.object = Object.create(null);
		}

		assign(object) {
			Object.assign(this.object, object);
			return this;
		}

		defineProperty(pname, desc) {
			Object.defineProperty(this.object, pname, desc);
			return this;
		}

		makeData(pname, value, writable, enumerable, configurable) {
			this.defineProperty(pname, {
				value: value,
				writable: writable,
				enumerable: enumerable,
				configurable: configurable
			});
			return this;
		}

		makeAccessor(pname, get, set, enumerable, configurable) {
			this.defineProperty({
				get: get,
				set: set,
				enumerable: enumerable,
				configurable: configurable
			});
			return this;
		}

		newFrozen() {
			return Object.freeze(this.createChild());
		}

		createChild() {
			return Object.create(this.object);
		}

		createClass() {
			base.prototype = this.createChild();
			return class extends base {};
			function base() {}
		}

	}

	createMerelyObject.MerelyObject = MerelyObject;

	function clearChildren(element) {
		for ( ; ; ) {
			let child = element.lastChild;
			if (child) {
				child.remove();
			} else {
				break;
			}
		}
	}

})(module);
<|endoftext|>


<commit_before>'use strict';
/**
 * utils
 *
 * @author Chen Liang [code@chen.technology]
 */

/*!
 * Module dependencies.
 */
var Promise = require('bluebird/js/main/promise')();

Promise.prototype.getTaskId = function () {
  return this.taskId;
};

Promise.prototype.setTaskId = function (taskId) {
  this.taskId = taskId;
};

var stringifyError = function (err) {
  var plainObject = {};
  Object.getOwnPropertyNames(err).forEach(function (key) {
    plainObject[key] = err[key];
  });
  return plainObject;
};

module.exports = {
  Promise: Promise,
  stringifyError: stringifyError
};
<commit_msg>[utils] added LocalStack (LIFO)<commit_after>'use strict';
/**
 * utils
 *
 * @author Chen Liang [code@chen.technology]
 */

/*!
 * Module dependencies.
 */
var Promise = require('bluebird/js/main/promise')();

Promise.prototype.getTaskId = function () {
  return this.taskId;
};

Promise.prototype.setTaskId = function (taskId) {
  this.taskId = taskId;
};

var stringifyError = function (err) {
  var plainObject = {};
  Object.getOwnPropertyNames(err).forEach(function (key) {
    plainObject[key] = err[key];
  });
  return plainObject;
};

var LocalStack = function () {
  this.stack = [];
};

LocalStack.prototype.push = function () {
  return this.stack.push.apply(this.stack, arguments);
};

LocalStack.prototype.pop = function (k) {
  var stackLength = this.stack.length;
  var l = k ? Math.min(k, stackLength) : 0;
  return l ? this.stack.splice(stackLength - l, stackLength).reverse() : this.stack.pop();
};

LocalStack.prototype.top = function (k) {
  var l = k ? (+k ? Math.abs(k) : 0) : 0;
  var stack = this.stack;
  var hpos = stack.length - l - 1;
  return stack[hpos];
};

LocalStack.prototype.tail = function (k) {
  var stack = this.stack;
  var l = k ? (+k ? Math.abs(k) : 0) : 0;
  return stack[l];
};

LocalStack.prototype.size = function () {
  return this.stack.length;
};

LocalStack.prototype.indexOf = function (el, from) {
  var stack = this.stack;
  var r = stack.indexOf(el);
  var len = stack.length - 1;
  var f = len - (+from || 0);
  return ~r ? (r <= f ? len - r : -1) : -1;
};

LocalStack.prototype.flush = function (evict) {
  var stack = this.stack;
  var slen = stack.length;
  var empty = evict === undefined || evict === true;
  return empty ? (stack.length = 0) || slen : 0;
};

module.exports = {
  Promise: Promise,
  stringifyError: stringifyError,
  LocalStack: LocalStack
};
<|endoftext|>


<commit_before>var error = require('./error');

exports.flatten = function() {
  return _.flatten(arguments);
};

exports.argsToArray = function(args) {
  return Array.prototype.slice.call(args, 0);
};

exports.numbers = function() {
  var possibleNumbers = this.flatten(arguments);
  return possibleNumbers.filter(function(el) {
    return typeof el === 'number';
  });
};

exports.cleanFloat = function(number) {
  var power = 1e14;
  return Math.round(number * power) / power;
};

exports.parseBool = function(bool) {
  if (typeof bool === 'boolean') {
    return bool;
  }

  if (bool instanceof Error) {
    return bool;
  }

  if (typeof bool === 'number') {
    if (bool === 0) {
      return false;
    } else {
      return true;
    }
  }

  if (typeof bool === 'string') {
    var up = bool.toUpperCase();
    if (up === 'TRUE') {
      return true;
    }

    if (up === 'FALSE') {
      return false;
    }
  }

  if (bool instanceof Date && !isNaN(bool)) {
    return true;
  }

  return error.value;
};

exports.parseNumber = function(string) {
  if (string === undefined || string === '') {
    return error.value;
  }
  if (!isNaN(string)) {
    return parseFloat(string);
  }
  return error.value;
};

exports.parseNumberArray = function(arr) {
  var len;
  if (!arr || (len = arr.length) === 0) {
    return error.value;
  }
  var parsed;
  while (len--) {
    parsed = exports.parseNumber(arr[len]);
    if (parsed === error.value) {
      return parsed;
    }
    arr[len] = parsed;
  }
  return arr;
};

exports.parseMatrix = function(matrix) {
  var n;
  if (!matrix || (n = matrix.length) === 0) {
    return error.value;
  }
  var pnarr;
  for (var i = 0; i < matrix.length; i++) {
    pnarr = exports.parseNumberArray(matrix[i]);
    matrix[i] = pnarr;
    if (pnarr instanceof Error) {
      return pnarr;
    }
  }
  return matrix;
};

var d1900 = new Date(1900, 0, 1);
exports.parseDate = function(date) {
  if (!isNaN(date)) {
    if (date instanceof Date) {
      return new Date(date);
    }
    var d = parseInt(date, 10);
    if (d < 0) {
      return error.num;
    }
    if (d <= 60) {
      return new Date(d1900.getTime() + (d - 1) * 86400000);
    }
    return new Date(d1900.getTime() + (d - 2) * 86400000);
  }
  if (typeof date === 'string') {
    date = new Date(date);
    if (!isNaN(date)) {
      return date;
    }
  }
  return error.value;
};

exports.parseDateArray = function(arr) {
  var len = arr.length;
  var parsed;
  while (len--) {
    parsed = this.parseDate(arr[len]);
    if (parsed === error.value) {
      return parsed;
    }
    arr[len] = parsed;
  }
  return arr;
};

exports.anyIsError = function() {
  var n = arguments.length;
  while (n--) {
    if (arguments[n] instanceof Error) {
      return true;
    }
  }
  return false;
};

exports.arrayValuesToNumbers = function(arr) {
  var n = arr.length;
  var el;
  while (n--) {
    el = arr[n];
    if (typeof el === 'number') {
      continue;
    }
    if (el === true) {
      arr[n] = 1;
      continue;
    }
    if (el === false) {
      arr[n] = 0;
      continue;
    }
    if (typeof el === 'string') {
      var number = this.parseNumber(el);
      if (number instanceof Error) {
        arr[n] = 0;
      } else {
        arr[n] = number;
      }
    }
  }
  return arr;
};<commit_msg>Refactoring<commit_after>var error = require('./error');

exports.flatten = function() {
  return _.flatten(arguments);
};

exports.argsToArray = function(args) {
  return Array.prototype.slice.call(args, 0);
};

exports.numbers = function() {
  var possibleNumbers = this.flatten(arguments);
  return possibleNumbers.filter(function(el) {
    return typeof el === 'number';
  });
};

exports.cleanFloat = function(number) {
  var power = 1e14;
  return Math.round(number * power) / power;
};

exports.parseBool = function(bool) {
  if (typeof bool === 'boolean') {
    return bool;
  }

  if (bool instanceof Error) {
    return bool;
  }

  if (typeof bool === 'number') {
    return bool === 0;
  }

  if (typeof bool === 'string') {
    var up = bool.toUpperCase();
    if (up === 'TRUE') {
      return true;
    }

    if (up === 'FALSE') {
      return false;
    }
  }

  if (bool instanceof Date && !isNaN(bool)) {
    return true;
  }

  return error.value;
};

exports.parseNumber = function(string) {
  if (string === undefined || string === '') {
    return error.value;
  }
  if (!isNaN(string)) {
    return parseFloat(string);
  }
  return error.value;
};

exports.parseNumberArray = function(arr) {
  var len;
  if (!arr || (len = arr.length) === 0) {
    return error.value;
  }
  var parsed;
  while (len--) {
    parsed = exports.parseNumber(arr[len]);
    if (parsed === error.value) {
      return parsed;
    }
    arr[len] = parsed;
  }
  return arr;
};

exports.parseMatrix = function(matrix) {
  var n;
  if (!matrix || (n = matrix.length) === 0) {
    return error.value;
  }
  var pnarr;
  for (var i = 0; i < matrix.length; i++) {
    pnarr = exports.parseNumberArray(matrix[i]);
    matrix[i] = pnarr;
    if (pnarr instanceof Error) {
      return pnarr;
    }
  }
  return matrix;
};

var d1900 = new Date(1900, 0, 1);
exports.parseDate = function(date) {
  if (!isNaN(date)) {
    if (date instanceof Date) {
      return new Date(date);
    }
    var d = parseInt(date, 10);
    if (d < 0) {
      return error.num;
    }
    if (d <= 60) {
      return new Date(d1900.getTime() + (d - 1) * 86400000);
    }
    return new Date(d1900.getTime() + (d - 2) * 86400000);
  }
  if (typeof date === 'string') {
    date = new Date(date);
    if (!isNaN(date)) {
      return date;
    }
  }
  return error.value;
};

exports.parseDateArray = function(arr) {
  var len = arr.length;
  var parsed;
  while (len--) {
    parsed = this.parseDate(arr[len]);
    if (parsed === error.value) {
      return parsed;
    }
    arr[len] = parsed;
  }
  return arr;
};

exports.anyIsError = function() {
  var n = arguments.length;
  while (n--) {
    if (arguments[n] instanceof Error) {
      return true;
    }
  }
  return false;
};

exports.arrayValuesToNumbers = function(arr) {
  var n = arr.length;
  var el;
  while (n--) {
    el = arr[n];
    if (typeof el === 'number') {
      continue;
    }
    if (el === true) {
      arr[n] = 1;
      continue;
    }
    if (el === false) {
      arr[n] = 0;
      continue;
    }
    if (typeof el === 'string') {
      var number = this.parseNumber(el);
      if (number instanceof Error) {
        arr[n] = 0;
      } else {
        arr[n] = number;
      }
    }
  }
  return arr;
};<|endoftext|>


<commit_before>/* eslint-disable no-proto */
var canSetPrototype = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array);
var greedyIntervalPacker = require('greedy-interval-packer');

var setPrototypeOf = Object.setPrototypeOf || function setPrototypeOf(obj, proto) {
    obj.__proto__ = proto;
    return obj;
};
/* eslint-enable no-proto */

var utils = module.exports = {
    objectIs: Object.is || function (a, b) {
        // Polyfill from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
        if (a === 0 && b === 0) {
            return 1 / a === 1 / b;
        }
        if (a !== a) {
            return b !== b;
        }
        return a === b;
    },

    isArray: function (ar) {
        return Object.prototype.toString.call(ar) === '[object Array]';
    },

    isRegExp: function (re) {
        return (Object.prototype.toString.call(re) === '[object RegExp]');
    },

    isError: function (err) {
        return typeof err === 'object' && (Object.prototype.toString.call(err) === '[object Error]' || err instanceof Error);
    },

    extend: function (target) {
        for (var i = 1; i < arguments.length; i += 1) {
            var source = arguments[i];
            if (source) {
                Object.keys(source).forEach(function (key) {
                    target[key] = source[key];
                });
            }
        }
        return target;
    },

    findFirst: function (arr, predicate, thisObj) {
        var scope = thisObj || null;
        for (var i = 0 ; i < arr.length ; i += 1) {
            if (predicate.call(scope, arr[i], i, arr)) {
                return arr[i];
            }
        }
        return null;
    },

    leftPad: function (str, width, ch) {
        ch = ch || ' ';
        while (str.length < width) {
            str = ch + str;
        }
        return str;
    },

    escapeRegExpMetaChars: function (str) {
        return str.replace(/[[\]{}()*+?.\\^$|]/g, '\\$&');
    },

    escapeChar: function (ch) {
        if (ch === '\t') {
            return '\\t';
        } else if (ch === '\r') {
            return '\\r';
        } else {
            var charCode = ch.charCodeAt(0);
            var hexChars = charCode.toString(16).toUpperCase();
            if (charCode < 256) {
                return '\\x' + utils.leftPad(hexChars, 2, '0');
            } else {
                return '\\u' + utils.leftPad(hexChars, 4, '0');
            }
        }
    },

    getFunctionName: function (f) {
        if (typeof f.name === 'string') {
            return f.name;
        }
        var matchFunctionName = Function.prototype.toString.call(f).match(/function ([^\(]+)/);
        if (matchFunctionName) {
            return matchFunctionName[1];
        }

        if (f === Object) {
            return 'Object';
        }
        if (f === Function) {
            return 'Function';
        }
        return '';
    },

    wrapConstructorNameAroundOutput: function (output, obj) {
        var constructor = obj.constructor;
        var constructorName = constructor && constructor !== Object && utils.getFunctionName(constructor);
        if (constructorName && constructorName !== 'Object') {
            return output.clone().text(constructorName + '(').append(output).text(')');
        } else {
            return output;
        }
    },

    setPrototypeOfOrExtend: canSetPrototype ? setPrototypeOf : function extend(target, source) {
        for (var prop in source) {
            if (source.hasOwnProperty(prop)) {
                target[prop] = source[prop];
            }
        }
        return target;
    },

    uniqueStringsAndSymbols: function () { // [filterFn], item1, item2...
        var filterFn;
        if (typeof arguments[0] === 'function') {
            filterFn = arguments[0];
        }
        var index = {};
        var uniqueStringsAndSymbols = [];

        function visit(item) {
            if (Array.isArray(item)) {
                item.forEach(visit);
            } else if (!Object.prototype.hasOwnProperty.call(index, item) && (!filterFn || filterFn(item))) {
                index[item] = true;
                uniqueStringsAndSymbols.push(item);
            }
        }

        for (var i = filterFn ? 1 : 0 ; i < arguments.length ; i += 1) {
            visit(arguments[i]);
        }
        return uniqueStringsAndSymbols;
    },

    uniqueNonNumericalStringsAndSymbols: function () { // ...
        return utils.uniqueStringsAndSymbols(function (stringOrSymbol) {
            return typeof stringOrSymbol === 'symbol' || !utils.numericalRegExp.test(stringOrSymbol);
        }, Array.prototype.slice.call(arguments));
    },

    numericalRegExp: /^(?:0|[1-9][0-9]*)$/,

    packArrows: function (changes) {
        var moveSourceAndTargetByActualIndex = {};
        changes.forEach(function (diffItem, index) {
            if (diffItem.type === 'moveSource') {
                diffItem.changeIndex = index;
                (moveSourceAndTargetByActualIndex[diffItem.actualIndex] = moveSourceAndTargetByActualIndex[diffItem.actualIndex] || {}).source = diffItem;
            } else if (diffItem.type === 'moveTarget') {
                diffItem.changeIndex = index;
                (moveSourceAndTargetByActualIndex[diffItem.actualIndex] = moveSourceAndTargetByActualIndex[diffItem.actualIndex] || {}).target = diffItem;
            }
        });
        var moveIndices = Object.keys(moveSourceAndTargetByActualIndex);
        if (moveIndices.length > 0) {
            var arrowSpecs = [];
            moveIndices.sort(function (a, b) {
                // Order by distance between change indices descending
                return Math.abs(moveSourceAndTargetByActualIndex[b].source.changeIndex - moveSourceAndTargetByActualIndex[b].target.changeIndex) - Math.abs(moveSourceAndTargetByActualIndex[a].source.changeIndex - moveSourceAndTargetByActualIndex[a].target.changeIndex);
            }).forEach(function (actualIndex, i, keys) {
                var moveSourceAndMoveTarget = moveSourceAndTargetByActualIndex[actualIndex];
                var firstChangeIndex = Math.min(moveSourceAndMoveTarget.source.changeIndex, moveSourceAndMoveTarget.target.changeIndex);
                var lastChangeIndex = Math.max(moveSourceAndMoveTarget.source.changeIndex, moveSourceAndMoveTarget.target.changeIndex);

                arrowSpecs.push({
                    start: firstChangeIndex,
                    end: lastChangeIndex,
                    direction: moveSourceAndMoveTarget.source.changeIndex < moveSourceAndMoveTarget.target.changeIndex ? 'down' : 'up'
                });
            });

            var packing = greedyIntervalPacker(arrowSpecs);
            while (packing.length > 3) {
                // The arrow packing takes up too many lanes. Turn the moveSource/moveTarget items into inserts and removes
                packing.shift().forEach(function (entry) {
                    changes[entry.direction === 'up' ? entry.start : entry.end].type = 'insert';
                    changes[entry.direction === 'up' ? entry.end : entry.start].type = 'remove';
                });
            }
            return packing;
        }
    }
};
<commit_msg>Simplify utils.findFirst, reclaiming a bit of the lost performance :)<commit_after>/* eslint-disable no-proto */
var canSetPrototype = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array);
var greedyIntervalPacker = require('greedy-interval-packer');

var setPrototypeOf = Object.setPrototypeOf || function setPrototypeOf(obj, proto) {
    obj.__proto__ = proto;
    return obj;
};
/* eslint-enable no-proto */

var utils = module.exports = {
    objectIs: Object.is || function (a, b) {
        // Polyfill from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
        if (a === 0 && b === 0) {
            return 1 / a === 1 / b;
        }
        if (a !== a) {
            return b !== b;
        }
        return a === b;
    },

    isArray: function (ar) {
        return Object.prototype.toString.call(ar) === '[object Array]';
    },

    isRegExp: function (re) {
        return (Object.prototype.toString.call(re) === '[object RegExp]');
    },

    isError: function (err) {
        return typeof err === 'object' && (Object.prototype.toString.call(err) === '[object Error]' || err instanceof Error);
    },

    extend: function (target) {
        for (var i = 1; i < arguments.length; i += 1) {
            var source = arguments[i];
            if (source) {
                Object.keys(source).forEach(function (key) {
                    target[key] = source[key];
                });
            }
        }
        return target;
    },

    findFirst: function (arr, predicate) {
        for (var i = 0 ; i < arr.length ; i += 1) {
            if (predicate(arr[i])) {
                return arr[i];
            }
        }
        return null;
    },

    leftPad: function (str, width, ch) {
        ch = ch || ' ';
        while (str.length < width) {
            str = ch + str;
        }
        return str;
    },

    escapeRegExpMetaChars: function (str) {
        return str.replace(/[[\]{}()*+?.\\^$|]/g, '\\$&');
    },

    escapeChar: function (ch) {
        if (ch === '\t') {
            return '\\t';
        } else if (ch === '\r') {
            return '\\r';
        } else {
            var charCode = ch.charCodeAt(0);
            var hexChars = charCode.toString(16).toUpperCase();
            if (charCode < 256) {
                return '\\x' + utils.leftPad(hexChars, 2, '0');
            } else {
                return '\\u' + utils.leftPad(hexChars, 4, '0');
            }
        }
    },

    getFunctionName: function (f) {
        if (typeof f.name === 'string') {
            return f.name;
        }
        var matchFunctionName = Function.prototype.toString.call(f).match(/function ([^\(]+)/);
        if (matchFunctionName) {
            return matchFunctionName[1];
        }

        if (f === Object) {
            return 'Object';
        }
        if (f === Function) {
            return 'Function';
        }
        return '';
    },

    wrapConstructorNameAroundOutput: function (output, obj) {
        var constructor = obj.constructor;
        var constructorName = constructor && constructor !== Object && utils.getFunctionName(constructor);
        if (constructorName && constructorName !== 'Object') {
            return output.clone().text(constructorName + '(').append(output).text(')');
        } else {
            return output;
        }
    },

    setPrototypeOfOrExtend: canSetPrototype ? setPrototypeOf : function extend(target, source) {
        for (var prop in source) {
            if (source.hasOwnProperty(prop)) {
                target[prop] = source[prop];
            }
        }
        return target;
    },

    uniqueStringsAndSymbols: function () { // [filterFn], item1, item2...
        var filterFn;
        if (typeof arguments[0] === 'function') {
            filterFn = arguments[0];
        }
        var index = {};
        var uniqueStringsAndSymbols = [];

        function visit(item) {
            if (Array.isArray(item)) {
                item.forEach(visit);
            } else if (!Object.prototype.hasOwnProperty.call(index, item) && (!filterFn || filterFn(item))) {
                index[item] = true;
                uniqueStringsAndSymbols.push(item);
            }
        }

        for (var i = filterFn ? 1 : 0 ; i < arguments.length ; i += 1) {
            visit(arguments[i]);
        }
        return uniqueStringsAndSymbols;
    },

    uniqueNonNumericalStringsAndSymbols: function () { // ...
        return utils.uniqueStringsAndSymbols(function (stringOrSymbol) {
            return typeof stringOrSymbol === 'symbol' || !utils.numericalRegExp.test(stringOrSymbol);
        }, Array.prototype.slice.call(arguments));
    },

    numericalRegExp: /^(?:0|[1-9][0-9]*)$/,

    packArrows: function (changes) {
        var moveSourceAndTargetByActualIndex = {};
        changes.forEach(function (diffItem, index) {
            if (diffItem.type === 'moveSource') {
                diffItem.changeIndex = index;
                (moveSourceAndTargetByActualIndex[diffItem.actualIndex] = moveSourceAndTargetByActualIndex[diffItem.actualIndex] || {}).source = diffItem;
            } else if (diffItem.type === 'moveTarget') {
                diffItem.changeIndex = index;
                (moveSourceAndTargetByActualIndex[diffItem.actualIndex] = moveSourceAndTargetByActualIndex[diffItem.actualIndex] || {}).target = diffItem;
            }
        });
        var moveIndices = Object.keys(moveSourceAndTargetByActualIndex);
        if (moveIndices.length > 0) {
            var arrowSpecs = [];
            moveIndices.sort(function (a, b) {
                // Order by distance between change indices descending
                return Math.abs(moveSourceAndTargetByActualIndex[b].source.changeIndex - moveSourceAndTargetByActualIndex[b].target.changeIndex) - Math.abs(moveSourceAndTargetByActualIndex[a].source.changeIndex - moveSourceAndTargetByActualIndex[a].target.changeIndex);
            }).forEach(function (actualIndex, i, keys) {
                var moveSourceAndMoveTarget = moveSourceAndTargetByActualIndex[actualIndex];
                var firstChangeIndex = Math.min(moveSourceAndMoveTarget.source.changeIndex, moveSourceAndMoveTarget.target.changeIndex);
                var lastChangeIndex = Math.max(moveSourceAndMoveTarget.source.changeIndex, moveSourceAndMoveTarget.target.changeIndex);

                arrowSpecs.push({
                    start: firstChangeIndex,
                    end: lastChangeIndex,
                    direction: moveSourceAndMoveTarget.source.changeIndex < moveSourceAndMoveTarget.target.changeIndex ? 'down' : 'up'
                });
            });

            var packing = greedyIntervalPacker(arrowSpecs);
            while (packing.length > 3) {
                // The arrow packing takes up too many lanes. Turn the moveSource/moveTarget items into inserts and removes
                packing.shift().forEach(function (entry) {
                    changes[entry.direction === 'up' ? entry.start : entry.end].type = 'insert';
                    changes[entry.direction === 'up' ? entry.end : entry.start].type = 'remove';
                });
            }
            return packing;
        }
    }
};
<|endoftext|>