<commit_before>var Server = require('../lib/server');
var utils = require('ssh2-streams').utils;

var semver = require('semver');

var fs = require('fs');
var crypto = require('crypto');
var path = require('path');
var join = path.join;
var assert = require('assert');
var spawn = require('child_process').spawn;

var t = -1;
var group = path.basename(__filename, '.js') + '/';
var fixturesdir = join(__dirname, 'fixtures');

var CLIENT_TIMEOUT = 5000;
var USER = 'nodejs';
var HOST_KEY_RSA = fs.readFileSync(join(fixturesdir, 'ssh_host_rsa_key'));
var HOST_KEY_DSA = fs.readFileSync(join(fixturesdir, 'ssh_host_dsa_key'));
var HOST_KEY_ECDSA = fs.readFileSync(join(fixturesdir, 'ssh_host_ecdsa_key'));
var CLIENT_KEY_RSA_PATH = join(fixturesdir, 'id_rsa');
var CLIENT_KEY_RSA = fs.readFileSync(CLIENT_KEY_RSA_PATH);
var CLIENT_KEY_RSA_PUB = utils.genPublicKey(utils.parseKey(CLIENT_KEY_RSA));
var CLIENT_KEY_DSA_PATH = join(fixturesdir, 'id_dsa');
var CLIENT_KEY_DSA = fs.readFileSync(CLIENT_KEY_DSA_PATH);
var CLIENT_KEY_DSA_PUB = utils.genPublicKey(utils.parseKey(CLIENT_KEY_DSA));
if (semver.gte(process.version, '5.2.0')) {
  var CLIENT_KEY_ECDSA_PATH = join(fixturesdir, 'id_ecdsa');
  var CLIENT_KEY_ECDSA = fs.readFileSync(CLIENT_KEY_ECDSA_PATH);
  var CLIENT_KEY_ECDSA_PUB = utils.genPublicKey(
    utils.parseKey(CLIENT_KEY_ECDSA)
  );
}
var DEBUG = false;

var tests = [
  { run: function() {
      var what = this.what;
      var server;

      server = setup(
        this,
        { privateKeyPath: CLIENT_KEY_RSA_PATH },
        { hostKeys: [HOST_KEY_RSA] }
      );

      server.on('connection', function(conn) {
        conn.on('authentication', function(ctx) {
          if (ctx.method === 'none')
            return ctx.reject();
          assert(ctx.method === 'publickey',
                 makeMsg(what, 'Unexpected auth method: ' + ctx.method));
          assert(ctx.username === USER,
                 makeMsg(what, 'Unexpected username: ' + ctx.username));
          assert(ctx.key.algo === 'ssh-rsa',
                 makeMsg(what, 'Unexpected key algo: ' + ctx.key.algo));
          assert.deepEqual(CLIENT_KEY_RSA_PUB.public,
                           ctx.key.data,
                           makeMsg(what, 'Public key mismatch'));
          if (ctx.signature) {
            var verifier = crypto.createVerify('RSA-SHA1');
            var pem = CLIENT_KEY_RSA_PUB.publicOrig;
            verifier.update(ctx.blob);
            assert(verifier.verify(pem, ctx.signature),
                   makeMsg(what, 'Could not verify PK signature'));
            ctx.accept();
          } else
            ctx.accept();
        }).on('ready', function() {
          conn.on('session', function(accept, reject) {
            var session = accept();
            if (session) {
              session.on('exec', function(accept, reject) {
                var stream = accept();
                if (stream) {
                  stream.exit(0);
                  stream.end();
                }
              }).on('pty', function(accept, reject) {
                accept && accept();
              });
            }
          });
        });
      });
    },
    what: 'Authenticate with an RSA key'
  },
  { run: function() {
      var what = this.what;
      var server;

      server = setup(
        this,
        { privateKeyPath: CLIENT_KEY_DSA_PATH },
        { hostKeys: [HOST_KEY_RSA] }
      );

      server.on('connection', function(conn) {
        conn.on('authentication', function(ctx) {
          if (ctx.method === 'none')
            return ctx.reject();
          assert(ctx.method === 'publickey',
                 makeMsg(what, 'Unexpected auth method: ' + ctx.method));
          assert(ctx.username === USER,
                 makeMsg(what, 'Unexpected username: ' + ctx.username));
          assert(ctx.key.algo === 'ssh-dss',
                 makeMsg(what, 'Unexpected key algo: ' + ctx.key.algo));
          assert.deepEqual(CLIENT_KEY_DSA_PUB.public,
                           ctx.key.data,
                           makeMsg(what, 'Public key mismatch'));
          if (ctx.signature) {
            var verifier = crypto.createVerify('DSA-SHA1');
            var pem = CLIENT_KEY_DSA_PUB.publicOrig;
            verifier.update(ctx.blob);
            assert(verifier.verify(pem, ctx.signature),
                   makeMsg(what, 'Could not verify PK signature'));
            ctx.accept();
          } else
            ctx.accept();
        }).on('ready', function() {
          conn.on('session', function(accept, reject) {
            var session = accept();
            if (session) {
              session.on('exec', function(accept, reject) {
                var stream = accept();
                if (stream) {
                  stream.exit(0);
                  stream.end();
                }
              }).on('pty', function(accept, reject) {
                accept && accept();
              });
            }
          });
        });
      });
    },
    what: 'Authenticate with a DSA key'
  },
  { run: function() {
      if (semver.lt(process.version, '5.2.0'))
        return next();
      var what = this.what;
      var server;

      server = setup(
        this,
        { privateKeyPath: CLIENT_KEY_ECDSA_PATH },
        { hostKeys: [HOST_KEY_RSA] }
      );

      server.on('connection', function(conn) {
        conn.on('authentication', function(ctx) {
          if (ctx.method === 'none')
            return ctx.reject();
          assert(ctx.method === 'publickey',
                 makeMsg(what, 'Unexpected auth method: ' + ctx.method));
          assert(ctx.username === USER,
                 makeMsg(what, 'Unexpected username: ' + ctx.username));
          assert(ctx.key.algo === 'ecdsa-sha2-nistp256',
                 makeMsg(what, 'Unexpected key algo: ' + ctx.key.algo));
          assert.deepEqual(CLIENT_KEY_ECDSA_PUB.public,
                           ctx.key.data,
                           makeMsg(what, 'Public key mismatch'));
          if (ctx.signature) {
            var verifier = crypto.createVerify('sha256');
            var pem = CLIENT_KEY_ECDSA_PUB.publicOrig;
            verifier.update(ctx.blob);
            assert(verifier.verify(pem, ctx.signature),
                   makeMsg(what, 'Could not verify PK signature'));
            ctx.accept();
          } else
            ctx.accept();
        }).on('ready', function() {
          conn.on('session', function(accept, reject) {
            var session = accept();
            if (session) {
              session.on('exec', function(accept, reject) {
                var stream = accept();
                if (stream) {
                  stream.exit(0);
                  stream.end();
                }
              }).on('pty', function(accept, reject) {
                accept && accept();
              });
            }
          });
        });
      });
    },
    what: 'Authenticate with a ECDSA key'
  },
  { run: function() {
      var server;

      server = setup(
        this,
        { privateKeyPath: CLIENT_KEY_RSA_PATH },
        { hostKeys: [HOST_KEY_DSA] }
      );

      server.on('connection', function(conn) {
        conn.on('authentication', function(ctx) {
          ctx.accept();
        }).on('ready', function() {
          conn.on('session', function(accept, reject) {
            var session = accept();
            if (session) {
              session.on('exec', function(accept, reject) {
                var stream = accept();
                if (stream) {
                  stream.exit(0);
                  stream.end();
                }
              }).on('pty', function(accept, reject) {
                accept && accept();
              });
            }
          });
        });
      });
    },
    what: 'Server with DSA host key'
  },
  { run: function() {
      if (semver.lt(process.version, '5.2.0'))
        return next();
      var server;

      server = setup(
        this,
        { privateKeyPath: CLIENT_KEY_RSA_PATH },
        { hostKeys: [HOST_KEY_ECDSA] }
      );

      server.on('connection', function(conn) {
        conn.on('authentication', function(ctx) {
          ctx.accept();
        }).on('ready', function() {
          conn.on('session', function(accept, reject) {
            var session = accept();
            if (session) {
              session.on('exec', function(accept, reject) {
                var stream = accept();
                if (stream) {
                  stream.exit(0);
                  stream.end();
                }
              }).on('pty', function(accept, reject) {
                accept && accept();
              });
            }
          });
        });
      });
    },
    what: 'Server with ECDSA host key'
  },
];

function setup(self, clientcfg, servercfg) {
  self.state = {
    serverReady: false,
    clientClose: false,
    serverClose: false
  };

  var client;
  var server = new Server(servercfg);

  server.on('error', onError)
        .on('connection', function(conn) {
          conn.on('error', onError)
              .on('ready', onReady);
          server.close();
        })
        .on('close', onClose);

  function onError(err) {
    var which = (arguments.length >= 3 ? 'client' : 'server');
    assert(false, makeMsg(self.what, 'Unexpected ' + which + ' error: ' + err));
  }
  function onReady() {
    assert(!self.state.serverReady,
           makeMsg(self.what, 'Received multiple ready events for server'));
    self.state.serverReady = true;
    self.onReady && self.onReady();
  }
  function onClose() {
    if (arguments.length >= 3) {
      assert(!self.state.clientClose,
             makeMsg(self.what, 'Received multiple close events for client'));
      self.state.clientClose = true;
    } else {
      assert(!self.state.serverClose,
             makeMsg(self.what, 'Received multiple close events for server'));
      self.state.serverClose = true;
    }
    if (self.state.clientClose && self.state.serverClose)
      next();
  }

  process.nextTick(function() {
    server.listen(0, 'localhost', function() {
      var cmd = 'ssh';
      var args = ['-o', 'UserKnownHostsFile=/dev/null',
                  '-o', 'StrictHostKeyChecking=no',
                  '-o', 'CheckHostIP=no',
                  '-o', 'ConnectTimeout=3',
                  '-o', 'GlobalKnownHostsFile=/dev/null',
                  '-o', 'GSSAPIAuthentication=no',
                  '-o', 'IdentitiesOnly=yes',
                  '-o', 'BatchMode=yes',
                  '-o', 'VerifyHostKeyDNS=no',
                  '-vvvvvv',
                  '-T',
                  '-o', 'KbdInteractiveAuthentication=no',
                  '-o', 'HostbasedAuthentication=no',
                  '-o', 'PasswordAuthentication=no',
                  '-o', 'PubkeyAuthentication=yes',
                  '-o', 'PreferredAuthentications=publickey'];
      if (clientcfg.privateKeyPath)
        args.push('-o', 'IdentityFile=' + clientcfg.privateKeyPath);
      args.push('-p', server.address().port.toString(),
                '-l', USER,
                'localhost',
                'uptime');

      client = spawn(cmd, args);
      if (DEBUG) {
        client.stdout.pipe(process.stdout);
        client.stderr.pipe(process.stderr);
      } else {
        client.stdout.resume();
        client.stderr.resume();
      }
      client.on('error', function(err) {
        onError(err, null, null);
      }).on('exit', function(code) {
        clearTimeout(client.timer);
        if (code !== 0)
          return onError(new Error('Non-zero exit code ' + code), null, null);
        onClose(null, null, null);
      });

      client.timer = setTimeout(function() {
        assert(false, makeMsg(self.what, 'Client timeout'));
      }, CLIENT_TIMEOUT);
    });
  });
  return server;
}

function next() {
  if (Array.isArray(process._events.exit))
    process._events.exit = process._events.exit[1];
  if (++t === tests.length)
    return;

  var v = tests[t];
  v.run.call(v);
}

function makeMsg(what, msg) {
  return '[' + group + what + ']: ' + msg;
}

process.once('uncaughtException', function(err) {
  if (t > -1 && !/(?:^|\n)AssertionError: /i.test(''+err))
    console.log(makeMsg(tests[t].what, 'Unexpected Exception:'));
  throw err;
});
process.once('exit', function() {
  assert(t === tests.length,
         makeMsg('_exit',
                 'Only finished ' + t + '/' + tests.length + ' tests'));
});

next();
<commit_msg>test: fix file permissions to avoid OpenSSH client issues<commit_after>var Server = require('../lib/server');
var utils = require('ssh2-streams').utils;

var semver = require('semver');

var fs = require('fs');
var crypto = require('crypto');
var path = require('path');
var join = path.join;
var assert = require('assert');
var spawn = require('child_process').spawn;

var t = -1;
var group = path.basename(__filename, '.js') + '/';
var fixturesdir = join(__dirname, 'fixtures');

var CLIENT_TIMEOUT = 5000;
var USER = 'nodejs';
var HOST_KEY_RSA = fs.readFileSync(join(fixturesdir, 'ssh_host_rsa_key'));
var HOST_KEY_DSA = fs.readFileSync(join(fixturesdir, 'ssh_host_dsa_key'));
var HOST_KEY_ECDSA = fs.readFileSync(join(fixturesdir, 'ssh_host_ecdsa_key'));
var CLIENT_KEY_RSA_PATH = join(fixturesdir, 'id_rsa');
var CLIENT_KEY_RSA = fs.readFileSync(CLIENT_KEY_RSA_PATH);
var CLIENT_KEY_RSA_PUB = utils.genPublicKey(utils.parseKey(CLIENT_KEY_RSA));
var CLIENT_KEY_DSA_PATH = join(fixturesdir, 'id_dsa');
var CLIENT_KEY_DSA = fs.readFileSync(CLIENT_KEY_DSA_PATH);
var CLIENT_KEY_DSA_PUB = utils.genPublicKey(utils.parseKey(CLIENT_KEY_DSA));
if (semver.gte(process.version, '5.2.0')) {
  var CLIENT_KEY_ECDSA_PATH = join(fixturesdir, 'id_ecdsa');
  var CLIENT_KEY_ECDSA = fs.readFileSync(CLIENT_KEY_ECDSA_PATH);
  var CLIENT_KEY_ECDSA_PUB = utils.genPublicKey(
    utils.parseKey(CLIENT_KEY_ECDSA)
  );
}
var DEBUG = false;

// Fix file modes to avoid OpenSSH client complaints about keys' permissions
fs.readdirSync(fixturesdir).forEach(function(file) {
  fs.chmodSync(join(fixturesdir, file), '0600');
});

var tests = [
  { run: function() {
      var what = this.what;
      var server;

      server = setup(
        this,
        { privateKeyPath: CLIENT_KEY_RSA_PATH },
        { hostKeys: [HOST_KEY_RSA] }
      );

      server.on('connection', function(conn) {
        conn.on('authentication', function(ctx) {
          if (ctx.method === 'none')
            return ctx.reject();
          assert(ctx.method === 'publickey',
                 makeMsg(what, 'Unexpected auth method: ' + ctx.method));
          assert(ctx.username === USER,
                 makeMsg(what, 'Unexpected username: ' + ctx.username));
          assert(ctx.key.algo === 'ssh-rsa',
                 makeMsg(what, 'Unexpected key algo: ' + ctx.key.algo));
          assert.deepEqual(CLIENT_KEY_RSA_PUB.public,
                           ctx.key.data,
                           makeMsg(what, 'Public key mismatch'));
          if (ctx.signature) {
            var verifier = crypto.createVerify('RSA-SHA1');
            var pem = CLIENT_KEY_RSA_PUB.publicOrig;
            verifier.update(ctx.blob);
            assert(verifier.verify(pem, ctx.signature),
                   makeMsg(what, 'Could not verify PK signature'));
            ctx.accept();
          } else
            ctx.accept();
        }).on('ready', function() {
          conn.on('session', function(accept, reject) {
            var session = accept();
            if (session) {
              session.on('exec', function(accept, reject) {
                var stream = accept();
                if (stream) {
                  stream.exit(0);
                  stream.end();
                }
              }).on('pty', function(accept, reject) {
                accept && accept();
              });
            }
          });
        });
      });
    },
    what: 'Authenticate with an RSA key'
  },
  { run: function() {
      var what = this.what;
      var server;

      server = setup(
        this,
        { privateKeyPath: CLIENT_KEY_DSA_PATH },
        { hostKeys: [HOST_KEY_RSA] }
      );

      server.on('connection', function(conn) {
        conn.on('authentication', function(ctx) {
          if (ctx.method === 'none')
            return ctx.reject();
          assert(ctx.method === 'publickey',
                 makeMsg(what, 'Unexpected auth method: ' + ctx.method));
          assert(ctx.username === USER,
                 makeMsg(what, 'Unexpected username: ' + ctx.username));
          assert(ctx.key.algo === 'ssh-dss',
                 makeMsg(what, 'Unexpected key algo: ' + ctx.key.algo));
          assert.deepEqual(CLIENT_KEY_DSA_PUB.public,
                           ctx.key.data,
                           makeMsg(what, 'Public key mismatch'));
          if (ctx.signature) {
            var verifier = crypto.createVerify('DSA-SHA1');
            var pem = CLIENT_KEY_DSA_PUB.publicOrig;
            verifier.update(ctx.blob);
            assert(verifier.verify(pem, ctx.signature),
                   makeMsg(what, 'Could not verify PK signature'));
            ctx.accept();
          } else
            ctx.accept();
        }).on('ready', function() {
          conn.on('session', function(accept, reject) {
            var session = accept();
            if (session) {
              session.on('exec', function(accept, reject) {
                var stream = accept();
                if (stream) {
                  stream.exit(0);
                  stream.end();
                }
              }).on('pty', function(accept, reject) {
                accept && accept();
              });
            }
          });
        });
      });
    },
    what: 'Authenticate with a DSA key'
  },
  { run: function() {
      if (semver.lt(process.version, '5.2.0'))
        return next();
      var what = this.what;
      var server;

      server = setup(
        this,
        { privateKeyPath: CLIENT_KEY_ECDSA_PATH },
        { hostKeys: [HOST_KEY_RSA] }
      );

      server.on('connection', function(conn) {
        conn.on('authentication', function(ctx) {
          if (ctx.method === 'none')
            return ctx.reject();
          assert(ctx.method === 'publickey',
                 makeMsg(what, 'Unexpected auth method: ' + ctx.method));
          assert(ctx.username === USER,
                 makeMsg(what, 'Unexpected username: ' + ctx.username));
          assert(ctx.key.algo === 'ecdsa-sha2-nistp256',
                 makeMsg(what, 'Unexpected key algo: ' + ctx.key.algo));
          assert.deepEqual(CLIENT_KEY_ECDSA_PUB.public,
                           ctx.key.data,
                           makeMsg(what, 'Public key mismatch'));
          if (ctx.signature) {
            var verifier = crypto.createVerify('sha256');
            var pem = CLIENT_KEY_ECDSA_PUB.publicOrig;
            verifier.update(ctx.blob);
            assert(verifier.verify(pem, ctx.signature),
                   makeMsg(what, 'Could not verify PK signature'));
            ctx.accept();
          } else
            ctx.accept();
        }).on('ready', function() {
          conn.on('session', function(accept, reject) {
            var session = accept();
            if (session) {
              session.on('exec', function(accept, reject) {
                var stream = accept();
                if (stream) {
                  stream.exit(0);
                  stream.end();
                }
              }).on('pty', function(accept, reject) {
                accept && accept();
              });
            }
          });
        });
      });
    },
    what: 'Authenticate with a ECDSA key'
  },
  { run: function() {
      var server;

      server = setup(
        this,
        { privateKeyPath: CLIENT_KEY_RSA_PATH },
        { hostKeys: [HOST_KEY_DSA] }
      );

      server.on('connection', function(conn) {
        conn.on('authentication', function(ctx) {
          ctx.accept();
        }).on('ready', function() {
          conn.on('session', function(accept, reject) {
            var session = accept();
            if (session) {
              session.on('exec', function(accept, reject) {
                var stream = accept();
                if (stream) {
                  stream.exit(0);
                  stream.end();
                }
              }).on('pty', function(accept, reject) {
                accept && accept();
              });
            }
          });
        });
      });
    },
    what: 'Server with DSA host key'
  },
  { run: function() {
      if (semver.lt(process.version, '5.2.0'))
        return next();
      var server;

      server = setup(
        this,
        { privateKeyPath: CLIENT_KEY_RSA_PATH },
        { hostKeys: [HOST_KEY_ECDSA] }
      );

      server.on('connection', function(conn) {
        conn.on('authentication', function(ctx) {
          ctx.accept();
        }).on('ready', function() {
          conn.on('session', function(accept, reject) {
            var session = accept();
            if (session) {
              session.on('exec', function(accept, reject) {
                var stream = accept();
                if (stream) {
                  stream.exit(0);
                  stream.end();
                }
              }).on('pty', function(accept, reject) {
                accept && accept();
              });
            }
          });
        });
      });
    },
    what: 'Server with ECDSA host key'
  },
];

function setup(self, clientcfg, servercfg) {
  self.state = {
    serverReady: false,
    clientClose: false,
    serverClose: false
  };

  var client;
  var server = new Server(servercfg);

  server.on('error', onError)
        .on('connection', function(conn) {
          conn.on('error', onError)
              .on('ready', onReady);
          server.close();
        })
        .on('close', onClose);

  function onError(err) {
    var which = (arguments.length >= 3 ? 'client' : 'server');
    assert(false, makeMsg(self.what, 'Unexpected ' + which + ' error: ' + err));
  }
  function onReady() {
    assert(!self.state.serverReady,
           makeMsg(self.what, 'Received multiple ready events for server'));
    self.state.serverReady = true;
    self.onReady && self.onReady();
  }
  function onClose() {
    if (arguments.length >= 3) {
      assert(!self.state.clientClose,
             makeMsg(self.what, 'Received multiple close events for client'));
      self.state.clientClose = true;
    } else {
      assert(!self.state.serverClose,
             makeMsg(self.what, 'Received multiple close events for server'));
      self.state.serverClose = true;
    }
    if (self.state.clientClose && self.state.serverClose)
      next();
  }

  process.nextTick(function() {
    server.listen(0, 'localhost', function() {
      var cmd = 'ssh';
      var args = ['-o', 'UserKnownHostsFile=/dev/null',
                  '-o', 'StrictHostKeyChecking=no',
                  '-o', 'CheckHostIP=no',
                  '-o', 'ConnectTimeout=3',
                  '-o', 'GlobalKnownHostsFile=/dev/null',
                  '-o', 'GSSAPIAuthentication=no',
                  '-o', 'IdentitiesOnly=yes',
                  '-o', 'BatchMode=yes',
                  '-o', 'VerifyHostKeyDNS=no',
                  '-vvvvvv',
                  '-T',
                  '-o', 'KbdInteractiveAuthentication=no',
                  '-o', 'HostbasedAuthentication=no',
                  '-o', 'PasswordAuthentication=no',
                  '-o', 'PubkeyAuthentication=yes',
                  '-o', 'PreferredAuthentications=publickey'];
      if (clientcfg.privateKeyPath)
        args.push('-o', 'IdentityFile=' + clientcfg.privateKeyPath);
      args.push('-p', server.address().port.toString(),
                '-l', USER,
                'localhost',
                'uptime');

      client = spawn(cmd, args);
      if (DEBUG) {
        client.stdout.pipe(process.stdout);
        client.stderr.pipe(process.stderr);
      } else {
        client.stdout.resume();
        client.stderr.resume();
      }
      client.on('error', function(err) {
        onError(err, null, null);
      }).on('exit', function(code) {
        clearTimeout(client.timer);
        if (code !== 0)
          return onError(new Error('Non-zero exit code ' + code), null, null);
        onClose(null, null, null);
      });

      client.timer = setTimeout(function() {
        assert(false, makeMsg(self.what, 'Client timeout'));
      }, CLIENT_TIMEOUT);
    });
  });
  return server;
}

function next() {
  if (Array.isArray(process._events.exit))
    process._events.exit = process._events.exit[1];
  if (++t === tests.length)
    return;

  var v = tests[t];
  v.run.call(v);
}

function makeMsg(what, msg) {
  return '[' + group + what + ']: ' + msg;
}

process.once('uncaughtException', function(err) {
  if (t > -1 && !/(?:^|\n)AssertionError: /i.test(''+err))
    console.log(makeMsg(tests[t].what, 'Unexpected Exception:'));
  throw err;
});
process.once('exit', function() {
  assert(t === tests.length,
         makeMsg('_exit',
                 'Only finished ' + t + '/' + tests.length + ' tests'));
});

next();
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

const co = require('co');
const commander = require('commander');
const dookie = require('../');
const fs = require('fs');
const yaml = require('js-yaml');

commander.
  usage('dookie (pull|push) --file <file> --db <database name>').
  option('-f, --file <file>', 'File to read/write from').
  option('-d, --db <database>', 'Database to read/write from').
  option('-u, --uri <uri>', 'MongoDB URI to use (mongodb://localhost:27017 by default)').
  parse(process.argv);

const cmd = process.argv[2];
if (!cmd || ['pull', 'push'].indexOf(cmd) === -1) {
  console.log('Must specify either pull (pull data from db into file) ' +
    'or push (push data into db from file).');
  process.exit(1);
}

if (!commander.file) {
  console.log('Must specify --file');
  process.exit(1);
}

if (!commander.db) {
  console.log('Must specify --db');
  process.exit(1);
}

if (cmd === 'pull') {
  const uri = commander.uri || `mongodb://localhost:27017/${commander.db}`;
  console.log(`Writing data from ${uri} to ${commander.file}`);
  co(function*() {
    const res = yield dookie.pull(uri);
    fs.writeFileSync(commander.file, JSON.stringify(res, null, '  '));
    process.exit(0);
  }).
  catch(function(error) {
    console.log('Error reading data:', error);
    process.exit(1);
  });
} else if (cmd === 'push') {
  console.log(`Writing data from ${commander.file} to ${commander.db}`);

  co(function*() {
    const uri = commander.uri || `mongodb://localhost:27017/${commander.db}`;
    const data = yaml.safeLoad(fs.readFileSync(commander.file));
    yield dookie.push(uri, data,
      commander.file);

    console.log('Success!');
    process.exit(0);
  }).catch(function(error) {
    console.log('Error writing data', error);
    process.exit(1);
  });
}
<commit_msg>feat(bin): support pushing json files<commit_after>#!/usr/bin/env node
'use strict';

const co = require('co');
const commander = require('commander');
const dookie = require('../');
const fs = require('fs');
const path = require('path');
const yaml = require('js-yaml');

commander.
  usage('dookie (pull|push) --file <file> --db <database name>').
  option('-f, --file <file>', 'File to read/write from').
  option('-d, --db <database>', 'Database to read/write from').
  option('-u, --uri <uri>', 'MongoDB URI to use (mongodb://localhost:27017 by default)').
  parse(process.argv);

const cmd = process.argv[2];
if (!cmd || ['pull', 'push'].indexOf(cmd) === -1) {
  console.log('Must specify either pull (pull data from db into file) ' +
    'or push (push data into db from file).');
  process.exit(1);
}

if (!commander.file) {
  console.log('Must specify --file');
  process.exit(1);
}

if (!commander.db) {
  console.log('Must specify --db');
  process.exit(1);
}

if (cmd === 'pull') {
  const uri = commander.uri || `mongodb://localhost:27017/${commander.db}`;
  console.log(`Writing data from ${uri} to ${commander.file}`);
  co(function*() {
    const res = yield dookie.pull(uri);
    fs.writeFileSync(commander.file, JSON.stringify(res, null, '  '));
    process.exit(0);
  }).
  catch(function(error) {
    console.log('Error reading data:', error);
    process.exit(1);
  });
} else if (cmd === 'push') {
  console.log(`Writing data from ${commander.file} to ${commander.db}`);

  co(function*() {
    const uri = commander.uri || `mongodb://localhost:27017/${commander.db}`;
    let data;
    if (path.extname(commander.file) === '.json') {
      data = JSON.parse(fs.readFileSync(commander.file));
    } else {
      data = yaml.safeLoad(fs.readFileSync(commander.file));
    }
    yield dookie.push(uri, data,
      commander.file);

    console.log('Success!');
    process.exit(0);
  }).catch(function(error) {
    console.log('Error writing data', error);
    process.exit(1);
  });
}
<|endoftext|>


<commit_before>var nodeunit = require('../lib/nodeunit');
var sandbox = require('../lib/utils').sandbox;
var testCase = nodeunit.testCase;

exports.testSimpleSandbox = function(test){
    var raw_jscode1 = sandbox('fixtures/raw_jscode1.js');
    test.equal(raw_jscode1.hello_world('foo'), '_foo_', 'evaluation ok');
    test.done();
};

exports.testSandboxContext = function(test){
    a_variable = 42; // should not be visible in the sandbox
    var raw_jscode2 = sandbox('fixtures/raw_jscode2.js');
    a_variable = 42; // again for the win
    test.equal(raw_jscode2.get_a_variable(), 'undefined', 'the variable should not be defined');
    test.done();
};

exports.testSandboxMultiple = function(test){
    var raw_jscode3 = sandbox(['fixtures/raw_jscode3.js','fixtures/raw_jscode3.js','fixtures/raw_jscode3.js']);
    test.equal(raw_jscode3.t, 3, 'two files loaded');
    test.done();
};
<commit_msg>update fixture paths for sandbox tests<commit_after>var nodeunit = require('../lib/nodeunit');
var sandbox = require('../lib/utils').sandbox;
var testCase = nodeunit.testCase;

exports.testSimpleSandbox = function(test){
    var raw_jscode1 = sandbox(__dirname + '/fixtures/raw_jscode1.js');
    test.equal(raw_jscode1.hello_world('foo'), '_foo_', 'evaluation ok');
    test.done();
};

exports.testSandboxContext = function(test){
    a_variable = 42; // should not be visible in the sandbox
    var raw_jscode2 = sandbox(__dirname + '/fixtures/raw_jscode2.js');
    a_variable = 42; // again for the win
    test.equal(
        raw_jscode2.get_a_variable(),
        'undefined',
        'the variable should not be defined'
    );
    test.done();
};

exports.testSandboxMultiple = function(test){
    var raw_jscode3 = sandbox([
        __dirname + '/fixtures/raw_jscode3.js',
        __dirname + '/fixtures/raw_jscode3.js',
        __dirname + '/fixtures/raw_jscode3.js'
    ]);
    test.equal(raw_jscode3.t, 3, 'two files loaded');
    test.done();
};
<|endoftext|>


<commit_before>/*jshint node:true */

var program = require('commander'),
    encode  = require('../parallelencoding');

program
  .version("0.0.1")
  .usage('[options] <input>')
  .option("-p, --parts <n>","Number of parts to encode in parallel [1].", 1)
  .option("-f, --format <type>","Output format (mkv/mp4/h264) [mkv]","mkv")
  .option("-t, --task <file>","Use a specific encoding profile.","encode.json")
  .parse(process.argv);

if(program.args[0]) {
  encode(program.args[0], program.parts, program.format);
}<commit_msg>Fleshing out the CLI some more.<commit_after>/*jshint node:true */

var program = require('commander'),
    encode  = require('../parallelencoding'),
    pkg     = require('../package.json');

program
  .version(pkg.version)
  .usage('[options] <input>')
  .option("-p, --parts <n>","Number of parts to encode in parallel [1].", 1)
  .option("-m, --merge","Merge parts to a single file on finish [false]")
  .option("-q, --qpfile <file>","The qpfile for the encode. (optional)")
  .option("-c, --tcfile <file>","The (VFR) timecode file for the encode. (optional)")
  .option("-t, --task <name>","The task to run from encode.json if present [default]","default")
  .option("-s, --settings <string>","The encoding settings as a string.")
  .option("-S, --setfile <file>","File to read encode settings from.");

program.on("--help", function() {
  console.log("  Encoding Settings:");
  console.log("");
  console.log("    You need to either specify --settings, --setfile,");
  console.log("    or have a valid encode.json in your working directory.");
  console.log("    encode.json overrides --settings and --setfile.");
  console.log("");
});

program.parse(process.argv);

if(program.args[0]) {
  encode(program.args[0], program);
}<|endoftext|>


<commit_before>var _,
    csv,
    download,
    downloads,
    destination,
    filename,
    fs,
    mongoose,
    processRats,
    processRescues,
    linkRatsAndRescues,
    Rat,
    ratSheet,
    Rescue,
    removeArchives,
    winston

// Node Modules
_ = require( 'underscore' )
csv = require( 'csv' )
download = require( 'download' )
fs = require( 'fs' )
mongoose = require( 'mongoose' )
winston = require( 'winston' )

// Mongoose Models
Rat = require( '../api/models/rat' )
Rescue = require( '../api/models/rescue' )

mongoose.Promise = global.Promise
mongoose.set( 'debug', false )

// Google Sheet URLs
spreadsheets = {
  rats: {
    workbookId: '1JoTrC3TmBNFkEtU6lWcGhOZkUaRr9YUY24kLA5LQnoc',
    sheetId: '445147052'
  },
  rescues: {
    workbookId: '1JoTrC3TmBNFkEtU6lWcGhOZkUaRr9YUY24kLA5LQnoc',
    sheetId: '1657880365'
  },
  rescueDrilledRats: {
    workbookId: '1_e0kJcMqjzoDfB2qRPYRIdR3naeEA19Y-ZzmYHo6yzE',
    sheetId: '72806282'
  },
  dispatchDrilledRats: {
    workbookId: '1_e0kJcMqjzoDfB2qRPYRIdR3naeEA19Y-ZzmYHo6yzE',
    sheetId: '84232353'
  },
  epicRescues: {
    workbookId: '1SUm4Ls-pHTDwmCobyrLFp1FGWv2_Dtbda99nXjEuo9M',
    sheetId: '498743399'
  }
}

// Config options
destinationFolder = 'data'

// Array to store our download promises in
downloads = []

mongoose.connect( 'mongodb://localhost/fuelrats' )

mongoose.set('debug', true)

processRats = function ( ratData, rescueDrills, dispatchDrills ) {
  winston.info( 'Processing rats' )

  return new Promise( function ( resolve, reject ) {
    var rats

    rats = []

    ratData.forEach( function ( ratDatum, index, ratData ) {
      var dispatchDrill, rat, rescueDrill

      rat = {
        archive: true,
        drilled: {
          dispatch: false,
          rescue: false
        },
        joined: new Date( ratDatum[0] ) || new Date,
        platform: 'pc',
        rescues: []
      }

      if ( dispatchDrill = _.findWhere( dispatchDrills, { 3: ratDatum[2], 4: 'Pass' } ) ) {
        rat.drilled.dispatch = true;
      }

      if ( rescueDrill = _.findWhere( rescueDrills, { 3: ratDatum[2], 4: 'Pass' } ) ) {
        rat.drilled.rescue = true
      }

      if ( ratDatum[1] === 'CMDR' || ratDatum[1] === 'GameTag' ) {
        rat.CMDRname = ratDatum[2].replace(/cmdr /i, '').replace(/\s\s+/g, ' ').trim()
      }

      if ( ratDatum[1] === 'GameTag' ) {
        rat.platform = 'xb'
      }

      if ( rat.CMDRname ) {
        rats.push( new Promise( function ( resolve, reject ) {
          Rat.find({
            CMDRname: rat.CMDRname,
            platform: rat.platform
          })
          .then( function ( rats ) {
            if ( !rats.length ) {
              new Rat( rat )
              .save()
              .then( resolve )
              .catch( reject )
            } else {
              resolve()
            }
          })
          .catch( reject )
        }))
      }
    })

    winston.info('Importing %d rats!', rats.length)

    Promise.all( rats )
    .then( resolve )
    .catch( reject )
  })
}

processRescues = function ( rescuesData ) {
  winston.info( 'Processing rescues' )

  return new Promise( function ( resolve, reject ) {
    var rescues

    rescues = []

    rescuesData.forEach( function ( rescueDatum, index, rescuesData ) {
      var rescue

      rescue = {
        client: {},
        archive: true,
        createdAt: new Date( rescueDatum[0] ),
        notes: rescueDatum[4].trim(),
        platform: 'pc',
        open: false,
        rats: [],
        name: null,
        firstLimpet: null,
        unidentifiedRats: [rescueDatum[1].replace(/cmdr /i, '').replace(/\s\s+/g, ' ').trim()],
        successful: rescueDatum[3].toLowerCase() === 'successful' ? true : false,
        system: rescueDatum[2].trim()
      }

       rescues.push(mongoose.models.Rat.findOneAndUpdate(
        {
            $text: {
                $search: rescueDatum[1].replace(/cmdr /i, '').replace(/\s\s+/g, ' ').trim(),
                $caseSensitive: false,
                $diacriticSensitive: false
            }
        },
        {
            $set: {
                CMDRname: rescueDatum[1].replace(/cmdr /i, '').replace(/\s\s+/g, ' ').trim(),
                archive: true,
                drilled: {
                  dispatch: false,
                  rescue: false
                },
                joined: new Date( rescueDatum[0] ) || new Date,
                rescues: []
            }
        },
        { upsert: true }
      ));

      rescues.push( new Rescue( rescue ).save() )
    })
    Promise.all( rescues )
    .then( resolve )
    .catch( reject )
  })
}

removeArchives = function removeArchives ( models ) {
  winston.info( 'Removing archives' )

  return new Promise( function ( resolve, reject ) {
    var promises

    promises = []

    models.forEach( function ( model, index, models ) {
      promises.push( model.remove( { archive: true } ) )
    })
    winston.info('Removing %d archived models!', promises.length)
    Promise.all( promises )
    .then( resolve )
    .catch( reject )
  })
}

// Download all of the spreadsheets
winston.info( 'Downloading spreadsheets' )
Object.keys( spreadsheets ).forEach( function ( name, index, names ) {
  var url, spreadsheet

  spreadsheet = spreadsheets[name]
  url = 'https://docs.google.com/spreadsheets/d/' + spreadsheet.workbookId + '/export?gid=' + spreadsheet.sheetId + '&format=csv'
  downloads.push( new Promise( function ( resolve, reject ) {
    download()
    .get( url )
    .dest( destinationFolder )
    .rename( name + '.csv' )
    .run( function ( error ) {
      if ( error ) {
        reject( error )
      } else {
        winston.info( 'Parsing spreadsheet:', name )
        csv.parse( fs.readFileSync( destinationFolder + '/' + name + '.csv' ), function ( error, data ) {
          if ( error ) {
            reject( error )
          } else {
            spreadsheets[name].data = data
            resolve()
          }
        })
      }
    })
  }))
})

Promise.all( downloads )
.then( function () {
  var dispatchDrills, promises, rats, removals, rescues, rescueDrills, epicRescueRats

  promises = []

  dispatchDrills = spreadsheets.dispatchDrilledRats.data
  rats = spreadsheets.rats.data
  rescues = spreadsheets.rescues.data
  rescueDrills = spreadsheets.rescueDrilledRats.data
  epicRescueRats = spreadsheets.epicRescues.data;

  rats.shift()
  rescues.shift()

  dispatchDrills.shift()
  rescueDrills.shift()

  epicRescueRats.shift();

  // Clear out the archives

  removeArchives( [ Rat, Rescue ] )
  .then( function () {
    var promises

    promises = []

    processRats( rats, rescueDrills, dispatchDrills )
    .then( function () {
      return processRescues( rescues )
    })
    .then( function () {
      Promise.all( promises )
      .then( function () {

            var promises

            promises = []

            promises.push( Rat.count({}) )
            promises.push( Rescue.count({}) )

            Promise.all( promises )
            .then( function ( results ) {
                var newRatCount, newRescuesCount, oldRatCount, oldRescuesCount

                newRatCount = rats.length
                newRescuesCount = rescues.length
                oldRatCount = results[0]
                oldRescuesCount = results[1]

                winston.info( 'Created', newRatCount, 'rats,', oldRatCount, 'total' )
                winston.info( 'Created', newRescuesCount, 'rescues,', oldRescuesCount, 'total' )

                mongoose.disconnect()

            })
            .catch( winston.error )

      })
      .catch( winston.error )
    })
    .catch( winston.error )
  })
  .catch( winston.error )
})
.catch( winston.error )
<commit_msg>Remove mongoose debug statement<commit_after>var _,
    csv,
    download,
    downloads,
    destination,
    filename,
    fs,
    mongoose,
    processRats,
    processRescues,
    linkRatsAndRescues,
    Rat,
    ratSheet,
    Rescue,
    removeArchives,
    winston

// Node Modules
_ = require( 'underscore' )
csv = require( 'csv' )
download = require( 'download' )
fs = require( 'fs' )
mongoose = require( 'mongoose' )
winston = require( 'winston' )

// Mongoose Models
Rat = require( '../api/models/rat' )
Rescue = require( '../api/models/rescue' )

mongoose.Promise = global.Promise
mongoose.set( 'debug', false )

// Google Sheet URLs
spreadsheets = {
  rats: {
    workbookId: '1JoTrC3TmBNFkEtU6lWcGhOZkUaRr9YUY24kLA5LQnoc',
    sheetId: '445147052'
  },
  rescues: {
    workbookId: '1JoTrC3TmBNFkEtU6lWcGhOZkUaRr9YUY24kLA5LQnoc',
    sheetId: '1657880365'
  },
  rescueDrilledRats: {
    workbookId: '1_e0kJcMqjzoDfB2qRPYRIdR3naeEA19Y-ZzmYHo6yzE',
    sheetId: '72806282'
  },
  dispatchDrilledRats: {
    workbookId: '1_e0kJcMqjzoDfB2qRPYRIdR3naeEA19Y-ZzmYHo6yzE',
    sheetId: '84232353'
  },
  epicRescues: {
    workbookId: '1SUm4Ls-pHTDwmCobyrLFp1FGWv2_Dtbda99nXjEuo9M',
    sheetId: '498743399'
  }
}

// Config options
destinationFolder = 'data'

// Array to store our download promises in
downloads = []

mongoose.connect( 'mongodb://localhost/fuelrats' )

processRats = function ( ratData, rescueDrills, dispatchDrills ) {
  winston.info( 'Processing rats' )

  return new Promise( function ( resolve, reject ) {
    var rats

    rats = []

    ratData.forEach( function ( ratDatum, index, ratData ) {
      var dispatchDrill, rat, rescueDrill

      rat = {
        archive: true,
        drilled: {
          dispatch: false,
          rescue: false
        },
        joined: new Date( ratDatum[0] ) || new Date,
        platform: 'pc',
        rescues: []
      }

      if ( dispatchDrill = _.findWhere( dispatchDrills, { 3: ratDatum[2], 4: 'Pass' } ) ) {
        rat.drilled.dispatch = true;
      }

      if ( rescueDrill = _.findWhere( rescueDrills, { 3: ratDatum[2], 4: 'Pass' } ) ) {
        rat.drilled.rescue = true
      }

      if ( ratDatum[1] === 'CMDR' || ratDatum[1] === 'GameTag' ) {
        rat.CMDRname = ratDatum[2].replace(/cmdr /i, '').replace(/\s\s+/g, ' ').trim()
      }

      if ( ratDatum[1] === 'GameTag' ) {
        rat.platform = 'xb'
      }

      if ( rat.CMDRname ) {
        rats.push( new Promise( function ( resolve, reject ) {
          Rat.find({
            CMDRname: rat.CMDRname,
            platform: rat.platform
          })
          .then( function ( rats ) {
            if ( !rats.length ) {
              new Rat( rat )
              .save()
              .then( resolve )
              .catch( reject )
            } else {
              resolve()
            }
          })
          .catch( reject )
        }))
      }
    })

    winston.info('Importing %d rats!', rats.length)

    Promise.all( rats )
    .then( resolve )
    .catch( reject )
  })
}

processRescues = function ( rescuesData ) {
  winston.info( 'Processing rescues' )

  return new Promise( function ( resolve, reject ) {
    var rescues

    rescues = []

    rescuesData.forEach( function ( rescueDatum, index, rescuesData ) {
      var rescue

      rescue = {
        client: {},
        archive: true,
        createdAt: new Date( rescueDatum[0] ),
        notes: rescueDatum[4].trim(),
        platform: 'pc',
        open: false,
        rats: [],
        name: null,
        firstLimpet: null,
        unidentifiedRats: [rescueDatum[1].replace(/cmdr /i, '').replace(/\s\s+/g, ' ').trim()],
        successful: rescueDatum[3].toLowerCase() === 'successful' ? true : false,
        system: rescueDatum[2].trim()
      }

       rescues.push(mongoose.models.Rat.findOneAndUpdate(
        {
            $text: {
                $search: rescueDatum[1].replace(/cmdr /i, '').replace(/\s\s+/g, ' ').trim(),
                $caseSensitive: false,
                $diacriticSensitive: false
            }
        },
        {
            $set: {
                CMDRname: rescueDatum[1].replace(/cmdr /i, '').replace(/\s\s+/g, ' ').trim(),
                archive: true,
                drilled: {
                  dispatch: false,
                  rescue: false
                },
                joined: new Date( rescueDatum[0] ) || new Date,
                rescues: []
            }
        },
        { upsert: true }
      ));

      rescues.push( new Rescue( rescue ).save() )
    })
    Promise.all( rescues )
    .then( resolve )
    .catch( reject )
  })
}

removeArchives = function removeArchives ( models ) {
  winston.info( 'Removing archives' )

  return new Promise( function ( resolve, reject ) {
    var promises

    promises = []

    models.forEach( function ( model, index, models ) {
      promises.push( model.remove( { archive: true } ) )
    })
    winston.info('Removing %d archived models!', promises.length)
    Promise.all( promises )
    .then( resolve )
    .catch( reject )
  })
}

// Download all of the spreadsheets
winston.info( 'Downloading spreadsheets' )
Object.keys( spreadsheets ).forEach( function ( name, index, names ) {
  var url, spreadsheet

  spreadsheet = spreadsheets[name]
  url = 'https://docs.google.com/spreadsheets/d/' + spreadsheet.workbookId + '/export?gid=' + spreadsheet.sheetId + '&format=csv'
  downloads.push( new Promise( function ( resolve, reject ) {
    download()
    .get( url )
    .dest( destinationFolder )
    .rename( name + '.csv' )
    .run( function ( error ) {
      if ( error ) {
        reject( error )
      } else {
        winston.info( 'Parsing spreadsheet:', name )
        csv.parse( fs.readFileSync( destinationFolder + '/' + name + '.csv' ), function ( error, data ) {
          if ( error ) {
            reject( error )
          } else {
            spreadsheets[name].data = data
            resolve()
          }
        })
      }
    })
  }))
})

Promise.all( downloads )
.then( function () {
  var dispatchDrills, promises, rats, removals, rescues, rescueDrills, epicRescueRats

  promises = []

  dispatchDrills = spreadsheets.dispatchDrilledRats.data
  rats = spreadsheets.rats.data
  rescues = spreadsheets.rescues.data
  rescueDrills = spreadsheets.rescueDrilledRats.data
  epicRescueRats = spreadsheets.epicRescues.data;

  rats.shift()
  rescues.shift()

  dispatchDrills.shift()
  rescueDrills.shift()

  epicRescueRats.shift();

  // Clear out the archives

  removeArchives( [ Rat, Rescue ] )
  .then( function () {
    var promises

    promises = []

    processRats( rats, rescueDrills, dispatchDrills )
    .then( function () {
      return processRescues( rescues )
    })
    .then( function () {
      Promise.all( promises )
      .then( function () {

            var promises

            promises = []

            promises.push( Rat.count({}) )
            promises.push( Rescue.count({}) )

            Promise.all( promises )
            .then( function ( results ) {
                var newRatCount, newRescuesCount, oldRatCount, oldRescuesCount

                newRatCount = rats.length
                newRescuesCount = rescues.length
                oldRatCount = results[0]
                oldRescuesCount = results[1]

                winston.info( 'Created', newRatCount, 'rats,', oldRatCount, 'total' )
                winston.info( 'Created', newRescuesCount, 'rescues,', oldRescuesCount, 'total' )

                mongoose.disconnect()

            })
            .catch( winston.error )

      })
      .catch( winston.error )
    })
    .catch( winston.error )
  })
  .catch( winston.error )
})
.catch( winston.error )
<|endoftext|>


<commit_before>"use strict";

var assert = require('assert');

var StringCalculator = function() {
  return {
    add: function(str) {
      if (str === '') {
        return 0;
      }

      if (-1 === str.indexOf(",")) {
        return str|0;
      }

      var nums = str.split(',');
      return (nums[0]|0) + (nums[1]|0);
    }
  };
};

suite('String calculator', function() {

  suite('creation', function() {
    test('can create', function() {
      assert(new StringCalculator());
    });
  });

  suite('#add', function() {

    var calc = new StringCalculator();

    test('can add', function() {
      assert(calc.add);
    });

    test('empty string returns 0', function() {
      assert.equal(0, calc.add(''));
    });

    test('single numbers return identity', function() {
      assert.equal(0, calc.add('0'));
      assert.equal(101, calc.add('101'));
    });

    test('multiple numbers', function() {
      assert.equal(2, calc.add('1,1'));
      assert.equal(1001, calc.add('999,2'));
    });
  });
});

// Learnings
// - use "mocha -u tdd <foo>"<commit_msg>improve test name<commit_after>"use strict";

var assert = require('assert');

var StringCalculator = function() {
  return {
    add: function(str) {
      if (str === '') {
        return 0;
      }

      if (-1 === str.indexOf(",")) {
        return str|0;
      }

      var nums = str.split(',');
      return (nums[0]|0) + (nums[1]|0);
    }
  };
};

suite('String calculator', function() {

  suite('creation', function() {
    test('can create', function() {
      assert(new StringCalculator());
    });
  });

  suite('#add', function() {

    var calc = new StringCalculator();

    test('can add', function() {
      assert(calc.add);
    });

    test('empty string returns 0', function() {
      assert.equal(0, calc.add(''));
    });

    test('single numbers return identity', function() {
      assert.equal(0, calc.add('0'));
      assert.equal(101, calc.add('101'));
    });

    test('two numbers', function() {
      assert.equal(2, calc.add('1,1'));
      assert.equal(1001, calc.add('999,2'));
    });
  });
});

// Learnings
// - use "mocha -u tdd <foo>"<|endoftext|>


<commit_before>#!/usr/bin/env node
const argv = require('argh').argv
const clog = require('jsome')
const slug = require('lodash.kebabcase')
const words = require('lodash.words')
const init = require('../')
const log = require('../lib/log')
const meta = require('../lib/meta')

// checks for help
// ///////////////////////////////////////////////////////////////////////////////
const noCommands = process.argv.length <= 2 && process.stdin.isTTY
const chk4help = (argv.argv !== undefined && argv.argv[0] === 'help') || argv.h || argv.help
const chkstate = argv.n || argv.new || argv.d || argv.dry

// usage
if (chk4help || noCommands) usage()

// version
if (argv.v || argv.version) vers()

// package name
if (argv.argv) var projName = makePkgName(false)
else if (chkstate) var projName = makePkgName(true)
else usage()

function usage () {
  console.log(function () {
  /*

  Usage: npinit <packageName> [options]
         npinit -n [options]
         npinit -d [options]

  Options:

    -h, --help          output usage information

    -v, --version       output the version number

    -d, --dry           dry run displaying metadata used for generation

    -n, --new           new private module. for use without a packageName. the default
                        packageName `testproj###` will be assigned. random number `###`
                        generated to avoid potential conflicts.

    -g, --github        new public module. a git repository will be
                        automactically initialized and pushed to gihub. a packageName
                        is required. [default mode is private module, no git repo]
                        running option -n or --new with -g or --github is equivalent to
                        option `-nr` or `--new --repo` initializing a new private
                        module with a git repository. packageName will not be required.
                        options --addRemote, --noRemote and --noPush are inactive in
                        this mode when `-ng` are run together.

    -r, --repo          initialize a git repository when generating a private module
                        [default is none]

    --addRemote         process will use the generic git command:

                          `git remote add origin https://github.com/username/repo.git`

                        username and repo will be automactically added. Leaving this
                        option off will use `hub` (https://github.com/github/hub)
                        to createthe remote repository. [default command `hub create`].
                        You will have to enter your github username and password
                        if NOT using the --noPush option.

    -R, --noRemote      do not create a remote repository on github. noRemote
                        assumes noPush and will override addRemote if both are present.
                        it will also override the default remote command `hub create`
                        if addRemote is not present when creating a public module
                        with flags -g or --github.

    -P, --noPush        do not push repository to github. use only with
                        flags -g or --github [default is push]

    -D, --noDeps        do not install default dependencies.
                        [defaults: `npm i mocha standard --save-dev`]

    --mods <string>     a list of node modules to install, i.e.,
                        `--mods "lodash moment"` or `--mods "lodash, moment"`.
                        this option is independent from no-dependencies option
                        -D or --noDeps.

  Overrides:

    --desc    <string>  description for package.json and github repository if using `hub`.
    --author  <string>  author name for project. [default reads from .npmrc or 'Your Name']
    --email   <string>  email for project. [default reads from .npmrc or 'your@email.com']
    --user    <string>  github username [default reads from .npmrc or 'githubName']
    --license <string>  license type for project. [default reads from .npmrc => ISC]
    --pkgv    <string>  semantic version for project [default reads from .npmrc => 1.0.0]

  */
  }.toString().split(/\n/).slice(2, -2).join('\n'))
  process.exit(0)
}

function vers () {
  process.stdout.write(require('../package.json').version + '\n')
  process.exit(0)
}

function makePkgName (choice) {
  switch (choice) {
    case false: return slug(argv.argv[0])
    case true: return 'testproj' + Math.floor(Math.random() * (1000 - 101) + 101)
  }
}

// default options
// ///////////////////////////////////////////////////////////////////////////////
var opts = {
  install: true,
  packages: ['standard', 'mocha'],
  git: false,
  files: {
    gitignore: false,
    index: true,
    license: false,
    package: true,
    readme: true,
    test: true,
    travis: false
  },
  meta: {
    date: new Date().toLocaleString(),
    year: new Date().getFullYear().toString(),
    packageName: projName,
    type: 'private',
    repo: 'none',
    remoteCmd: 'none',
    noPush: false,
    noRemote: false
  }
}

// option configuration
// ///////////////////////////////////////////////////////////////////////////////

// git repo initialization
if (argv.r || argv.repo) repo()

function repo () {
  opts.git = true
  opts.meta.repo = 'init'
  opts.files.gitignore = true
}

// check for private and public projects being created together
const pubpriv = (argv.g || argv.github) && (argv.n || argv.new)
const pub = (argv.g || argv.github)

// public repo
if (!pubpriv && pub) {
  opts.meta.type = 'public'
  opts.files.license = true
  opts.files.travis = true
  repo()
  chkRemote()
}

// private repo if options -g or --github and -n together
if (pubpriv && pub) repo()

function chkRemote () {
  if (argv.noRemote || argv.R) {
    opts.meta.noRemote = true
    opts.meta.noPush = true
    opts.meta.remoteCmd = 'no public repository'
  } else {
    opts.meta.noRemote = false
    opts.meta.noPush = argv.noPush || argv.P ? true : false
    opts.meta.remoteCmd = argv.addRemote ? 'addRemote' : 'hubCreate'
  }
}

// install dependencies
if (argv.noDeps || argv.D) opts.install = false
if (argv.mods) packages()

function packages () {
  opts.packages = opts.packages.concat(words(argv.mods))
  if (argv.noDeps || argv.D) {
    opts.install = true
    opts.packages = words(argv.mods)
  }
}

// description for package.json
const description = argv.desc || argv.description
if (description) opts.meta.description = description
else opts.meta.description = 'An awesome module being created'

// tags for package.json
// if (argv.tags) opts.meta.tags = argv.tags.split()
// else opts.meta.tags = ''

// get user information, display options & initialize project
// ///////////////////////////////////////////////////////////////////////////////

meta(opts, function (nwOpts) {
  log(nwOpts)
  if (argv.d || argv.dry) {
    process.stdout.write('\n')
    process.stdout.write('\x1b[36mOptions:\x1b[0m ')
    process.stdout.write('\n\n')
    clog(nwOpts)
  } else {
    init(nwOpts)
  }
})
<commit_msg>refactor<commit_after>#!/usr/bin/env node
const argv = require('argh').argv
const clog = require('jsome')
const slug = require('lodash.kebabcase')
const words = require('lodash.words')
const init = require('../')
const log = require('../lib/log')
const meta = require('../lib/meta')

// usage, version and projectName
// ///////////////////////////////////////////////////////////////////////////////
const noCommands = process.argv.length <= 2 && process.stdin.isTTY
const chk4help = (argv.argv !== undefined && argv.argv[0] === 'help') || argv.h || argv.help
const chkstate = argv.n || argv.new || argv.d || argv.dry

// usage
if (chk4help || noCommands) usage()

// version
if (argv.v || argv.version) vers()

// package name
if (argv.argv) var projName = makePkgName(false)
else if (chkstate) var projName = makePkgName(true)
else usage()

function usage () {
  console.log(function () {
  /*

  Usage: npinit <packageName> [options]
         npinit -n [options]
         npinit -d [options]

  Options:

    -h, --help          output usage information

    -v, --version       output the version number

    -d, --dry           dry run displaying metadata used for generation

    -n, --new           new private module. for use without a packageName. the default
                        packageName `testproj###` will be assigned. random number `###`
                        generated to avoid potential conflicts.

    -g, --github        new public module. a git repository will be
                        automactically initialized and pushed to gihub. a packageName
                        is required. [default mode is private module, no git repo]
                        running option -n or --new with -g or --github is equivalent to
                        option `-nr` or `--new --repo` initializing a new private
                        module with a git repository. packageName will not be required.
                        options --addRemote, --noRemote and --noPush are inactive in
                        this mode when `-ng` are run together.

    -r, --repo          initialize a git repository when generating a private module
                        [default is none]

    --addRemote         process will use the generic git command:

                          `git remote add origin https://github.com/username/repo.git`

                        username and repo will be automactically added. Leaving this
                        option off will use `hub` (https://github.com/github/hub)
                        to createthe remote repository. [default command `hub create`].
                        You will have to enter your github username and password
                        if NOT using the --noPush option.

    -R, --noRemote      do not create a remote repository on github. noRemote
                        assumes noPush and will override addRemote if both are present.
                        it will also override the default remote command `hub create`
                        if addRemote is not present when creating a public module
                        with flags -g or --github.

    -P, --noPush        do not push repository to github. use only with
                        flags -g or --github [default is push]

    -D, --noDeps        do not install default dependencies.
                        [defaults: `npm i mocha standard --save-dev`]

    --packs <string>    a list of node modules to install, i.e.,
                        `--packs "lodash moment"` or `--packs "lodash, moment"`.
                        this option is independent from no-dependencies option
                        -D or --noDeps. [npm i --save packages]

    --devpacks <string> a list of node dev modules to install, i.e.,
                        `--devpacks "tape istanbul"` or `--devpacks "tape, istanbul"`.
                        this option is independent from no-dependencies option
                        -D or --noDeps. [npm i --save-dev devpackages]

  Overrides:

    --desc    <string>  description for package.json and github repository if using `hub`.
    --author  <string>  author name for project. [default reads from .npmrc or 'Your Name']
    --email   <string>  email for project. [default reads from .npmrc or 'your@email.com']
    --user    <string>  github username [default reads from .npmrc or 'githubName']
    --license <string>  license type for project. [default reads from .npmrc => ISC]
    --pkgv    <string>  semantic version for project [default reads from .npmrc => 1.0.0]

  */
  }.toString().split(/\n/).slice(2, -2).join('\n'))
  process.exit(0)
}

function vers () {
  process.stdout.write(require('../package.json').version + '\n')
  process.exit(0)
}

function makePkgName (choice) {
  switch (choice) {
    case false: return slug(argv.argv[0])
    case true: return 'testproj' + Math.floor(Math.random() * (1000 - 101) + 101)
  }
}

// default options
// ///////////////////////////////////////////////////////////////////////////////
var opts = {
  install: true,
  devInstall: true,
  proInstall: false,
  devpackages: ['standard', 'mocha'],
  packages: [],
  git: false,
  files: {
    gitignore: false,
    index: true,
    license: false,
    package: true,
    readme: true,
    test: true,
    travis: false
  },
  meta: {
    date: new Date().toLocaleString(),
    year: new Date().getFullYear().toString(),
    packageName: projName,
    type: 'private',
    repo: 'none',
    remoteCmd: 'none',
    noPush: false,
    noRemote: false
  }
}

// git repository configuration
// ///////////////////////////////////////////////////////////////////////////////

// git repo initialization
if (argv.r || argv.repo) repo()

// configure private git repository
function repo () {
  opts.git = true
  opts.meta.repo = 'init'
  opts.files.gitignore = true
}

// check for private and public projects being created together
const pubpriv = (argv.g || argv.github) && (argv.n || argv.new)
const pub = (argv.g || argv.github)

// public repo
if (!pubpriv && pub) {
  opts.meta.type = 'public'
  opts.files.license = true
  opts.files.travis = true
  repo()
  chkRemote()
}

// private repo if options -g or --github and -n together
if (pubpriv && pub) repo()

// configure remote options
function chkRemote () {
  if (argv.noRemote || argv.R) {
    opts.meta.noRemote = true
    opts.meta.noPush = true
    opts.meta.remoteCmd = 'no public repository'
  } else {
    opts.meta.noRemote = false
    opts.meta.noPush = argv.noPush || argv.P ? true : false
    opts.meta.remoteCmd = argv.addRemote ? 'addRemote' : 'hubCreate'
  }
}

// install dependencies configuration
// ///////////////////////////////////////////////////////////////////////////////
// turn off default devDependencies
if (argv.noDeps || argv.D) {
  opts.install = false
  opts.devInstall = false
  opts.files.test = false
}
// check for user install dependencies
if (argv.devpacks) devpackages()
if (argv.packs) packages()

// configure user installed devDependencies
function devpackages () {
  opts.devpackages = opts.devpackages.concat(words(argv.devpacks))
  if (argv.noDeps || argv.D) {
    opts.devpackages = words(argv.devpacks)
    opts.install = true
    opts.devInstall = true
    opts.files.test = true
  }
}

// configure user installed dependencies
function packages () {
  opts.packages = words(argv.packs)
  opts.proInstall = true
  if (argv.noDeps || argv.D) {
    opts.install = true
  }
}

// misc overrides
// ///////////////////////////////////////////////////////////////////////////////
const description = argv.desc || argv.description
if (description) opts.meta.description = description
else opts.meta.description = 'An awesome module being created'

// tags for package.json
// if (argv.tags) opts.meta.tags = argv.tags.split()
// else opts.meta.tags = ''

// get user information, display options & initialize project
// ///////////////////////////////////////////////////////////////////////////////
meta(opts, function (nwOpts) {
  log(nwOpts)
  if (argv.d || argv.dry) {
    process.stdout.write('\n')
    process.stdout.write('\x1b[36mOptions:\x1b[0m ')
    process.stdout.write('\n\n')
    clog(nwOpts)
  } else {
    init(nwOpts)
  }
})
<|endoftext|>


<commit_before>#!/usr/bin/env node

/**
 * This file is the procKr cli.
 *
 * Usage examples:
 * $ procKr start
 * $ procKr add-target 4000 http://jsonplaceholder.typicode.com jsonplaceholder
 * $ procKr enable-target jsonplaceholder
 * $ procKr mock-target jsonplaceholder
 *
 * See README.md for more informations.
 */

'use strict';

var program   = require('commander');

var //fs        = require('fs'),
    program   = require('commander'),
    procKr    = require('../procKr'),
    log       = function () { console.log.apply(this, arguments); };

// @FIxME
// program.version(JSON.parse(fs.readFileSync('package.json')).version);
program.version('0.0.1');

program
  .command('start')
  .description('Start the daemon.')
  .action(procKr.start);

program
  .command('stop')
  .description('Stop procKr daemon.')
  .action(procKr.stop);

program
  .command('status')
  .description('Check procKr status.')
  .action(procKr.status);

program
  .command('hello')
  .description('Say hello to procKr to test websocket connexion.')
  .action(procKr.hello);

program
  .command('start-http')
  .description('Start the procKr http server.')
  .action(procKr.startHttp);

program
  .command('stop-http')
  .description('Stop the procKr http server.')
  .action(procKr.stopHttp);

program.parse(process.argv);

if (!program.args.length) {
  log( program.helpInformation() );
  process.exit();
}
<commit_msg>Fix jscs warn.<commit_after>#!/usr/bin/env node

/**
 * This file is the procKr cli.
 *
 * Usage examples:
 * $ procKr start
 * $ procKr add-target 4000 http://jsonplaceholder.typicode.com jsonplaceholder
 * $ procKr enable-target jsonplaceholder
 * $ procKr mock-target jsonplaceholder
 *
 * See README.md for more informations.
 */

'use strict';

var program   = require('commander');

var //fs        = require('fs'),
    program   = require('commander'),
    procKr    = require('../procKr'),
    log       = function () { console.log.apply(this, arguments); };

// @FIxME
// program.version(JSON.parse(fs.readFileSync('package.json')).version);
program.version('0.0.1');

program
  .command('start')
  .description('Start the daemon.')
  .action(procKr.start);

program
  .command('stop')
  .description('Stop procKr daemon.')
  .action(procKr.stop);

program
  .command('status')
  .description('Check procKr status.')
  .action(procKr.status);

program
  .command('hello')
  .description('Say hello to procKr to test websocket connexion.')
  .action(procKr.hello);

program
  .command('start-http')
  .description('Start the procKr http server.')
  .action(procKr.startHttp);

program
  .command('stop-http')
  .description('Stop the procKr http server.')
  .action(procKr.stopHttp);

program.parse(process.argv);

if (!program.args.length) {
  log(program.helpInformation());
  process.exit();
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

let path        = require('path');
let tryCatch    = require('try-catch');
let cliParse    = require('../lib/cli-parse');
let cwd         = process.cwd();
let argv        = process.argv;
let arg         = cliParse(argv.slice(2),  getInfo(cwd).scripts);

if (arg.name !== 'run') {
    console.log(arg.output);
} else if (arg.name === 'run') {
    if (arg.loud)
        console.log(arg.cmd);

    execute(arg.cmd);
}

function execute(cmd) {
    const spawnify = require('spawnify');

    const child = spawnify(cmd, {
        env: Object.assign(process.env, getEnv)
    });

    child.on('data', (data) => {
        process.stdout.write(data);
    });

    child.on('error', (error) => {
        process.stdout.write(error.message);
    });
}

function getEnv() {
    const env = require('../lib/env');
    const path = require('path');

    const config = getInfo(cwd).config;
    const assign = Object.assign;
    const PATH = process.env.PATH;
    const CWD = process.cwd();

    const envVars = assign(env.config(config), {
        PATH: env.path(PATH, path.delimiter, CWD, path.sep)
    });

    return envVars;
}

function getInfo(dir) {
    let info;
    let infoPath = path.join(dir, 'package.json');
    let error = tryCatch(() => {
        info = require(infoPath);
    });

    if (error) {
        console.error(error.message);
        process.exit(1);
    }

    return info;
}

<commit_msg>feature(redrun) preserve colors<commit_after>#!/usr/bin/env node

'use strict';

let path        = require('path');
let tryCatch    = require('try-catch');
let cliParse    = require('../lib/cli-parse');
let cwd         = process.cwd();
let argv        = process.argv;
let arg         = cliParse(argv.slice(2),  getInfo(cwd).scripts);

if (arg.name !== 'run') {
    console.log(arg.output);
} else if (arg.name === 'run') {
    if (arg.loud)
        console.log(arg.cmd);

    execute(arg.cmd);
}

function execute(cmd) {
    const spawnify = require('spawnify');

    const child = spawnify(cmd, {
        stdio: 'inherit',
        env: Object.assign(process.env, getEnv)
    });

    child.on('data', (data) => {
        process.stdout.write(data);
    });

    child.on('error', (error) => {
        process.stdout.write(error.message);
    });
}

function getEnv() {
    const env = require('../lib/env');
    const path = require('path');

    const config = getInfo(cwd).config;
    const assign = Object.assign;
    const PATH = process.env.PATH;
    const CWD = process.cwd();

    const envVars = assign(env.config(config), {
        PATH: env.path(PATH, path.delimiter, CWD, path.sep)
    });

    return envVars;
}

function getInfo(dir) {
    let info;
    let infoPath = path.join(dir, 'package.json');
    let error = tryCatch(() => {
        info = require(infoPath);
    });

    if (error) {
        console.error(error.message);
        process.exit(1);
    }

    return info;
}

<|endoftext|>


<commit_before>/**
 * Module dependencies
 */
var fs = require('fs');
var path = require('path');
var Logger = require('../lib/util/logger.js');
var cli = require('./_cli.js');

// CLI definitions

// $ nightwatch -c
// $ nightwatch --config
cli.command('config')
  .demand(true)
  .description('Path to configuration file')
  .alias('c')
  .defaults('./nightwatch.json');

// $ nightwatch -o
// $ nightwatch --output
cli.command('output')
  .description('Where to save the JUnit XML test reports.')
  .alias('o')
  .defaults('tests_output');

// $ nightwatch -e
// $ nightwatch --env saucelabs
cli.command('env')
  .description('Testing environment to use.')
  .alias('e')
  .defaults('default');

// $ nightwatch --verbose
cli.command('verbose')
  .description('Turns on selenium command logging during the session.');

// $ nightwatch -t
// $ nightwatch --test
cli.command('test')
  .description('Runs a single test.')
  .alias('t');

// $ nightwatch -g
// $ nightwatch --group
cli.command('group')
  .description('Runs a group of tests (i.e. a folder)')
  .alias('g');

// $ nightwatch -s
// $ nightwatch --skipgroup
cli.command('skipgroup')
  .description('Skips one or several (comma separated) group of tests.')
  .alias('s');

// $ nightwatch -f
// $ nightwatch --filter
cli.command('filter')
  .description('Specify a filter (glob expression) as the file name format to use when loading the files.')
  .defaults('')
  .alias('f');

// $ nightwatch -s
// $ nightwatch --skipgroup
cli.command('help')
  .description('Shows this help.')
  .alias('h');

// $ nightwatch --version
cli.command('version')
  .alias('v')
  .description('Shows version information.');

/**
 * Looks for pattern ${VAR_NAME} in settings
 * @param {Object} target
 */
function replaceEnvVariables(target) {
  for (var key in target) {
    switch(typeof target[key]) {
      case 'object':
        replaceEnvVariables(target[key]);
        break;
      case 'string':
        target[key] = target[key].replace(/\$\{(\w+)\}/g, function(match, varName) {
          return process.env[varName] || '${' + varName + '}';
        });
        break;
    }
  }
}

/**
 * Read the provided config json file; defaults to settings.json if one isn't provided
 * @param {Object} argv
 */
function readSettings(argv) {
  var settings;

  // use default settings.json file if we haven't received another value
  if (cli.command('config').isDefault(argv.c)) {
    var defaultValue = cli.command('config').defaults();
    var deprecatedValue = './settings.json';

    if (fs.existsSync(defaultValue)) {
      argv.c = path.join(path.resolve('./'), argv.c);
    } else if (fs.existsSync(deprecatedValue)) {
      argv.c = path.join(path.resolve('./'), deprecatedValue);
    } else {
      var defaultFile = path.join(__dirname, argv.c);
      if (fs.existsSync(defaultFile)) {
        argv.c = defaultFile;
      } else {
        argv.c = path.join(__dirname, deprecatedValue);
      }
    }
  } else {
    argv.c = path.resolve(argv.c);
  }

  // reading the settings file
  try {
    settings = require(argv.c);
    replaceEnvVariables(settings);
  } catch (ex) {
    Logger.error(ex);
    settings = {};
  }

  return settings;
}

/**
 * Reads globals from an external js or json file
 * @param {string} file
 * @returns {*}
 */
function readExternalGlobals(file) {
  try {
    var fullPath = path.resolve(file);
    if (fs.existsSync(fullPath)) {
      return require(fullPath);
    }
    throw new Error('External global file could not be located - using '+ file +'.');
  } catch (err) {
    err.message = 'Failed to load external global file: ' + err.message;
    throw err;
  }
}

function inheritFromDefaultEnv(test_settings) {
  var defaultEnv = settings.test_settings['default'] || {};
  for (var key in defaultEnv) {
    if (typeof test_settings[key] == 'undefined') {
      test_settings[key] = defaultEnv[key];
    }
  }
}

/**
 *
 * @param {Object} argv
 */
function parseTestSettings(argv) {
  // checking if the env passed is valid
  if (!settings.test_settings) {
    throw new Error('No testing environment specified.');
  }

  var envs = argv.e.split(',');
  for (var i = 0; i < envs.length; i++) {
    if (!(envs[i] in settings.test_settings)) {
      throw new Error('Invalid testing environment specified: ' + envs[i]);
    }
  }

  if (envs.length > 1) {
    setupClustering(envs);
    console.info('clustering mode');
    return false;
  }
  // picking the environment specific test settings
  var test_settings = settings.test_settings[argv.e];
  test_settings.custom_commands_path = settings.custom_commands_path || '';
  test_settings.custom_assertions_path = settings.custom_assertions_path || '';

  inheritFromDefaultEnv(test_settings);

  console.log('parseTest', test_settings)

  if (test_settings.selenium && typeof (test_settings.selenium) == 'object') {
    for (var prop in test_settings.selenium) {
      settings.selenium[prop] = test_settings.selenium[prop];
    }
  }
  if (typeof settings.globals == 'string' && settings.globals) {
    settings.globals_path = settings.globals_path;
  }
  if (typeof settings.globals_path == 'string' && settings.globals_path) {
    var globals = readExternalGlobals(settings.globals_path);
    if (globals && globals.hasOwnProperty(argv.e)) {
      test_settings.globals = globals[argv.e];
    }
  }

  if (argv.verbose) {
    test_settings.silent = false;
  }

  test_settings.output = test_settings.output || typeof test_settings.output === 'undefined';

  if (typeof argv.s == 'string') {
    test_settings.skipgroup = argv.s.split(',');
  }

  if (argv.f) {
    test_settings.filter = argv.f;
  }

  return test_settings;
}

function setupClustering(envs) {
  var execFile = require('child_process').execFile, child;
  for (var i = 0; i < envs.length; i++) {
    var cliArgs = ['-e', envs[i]];
    cliArgs.push('--disable_selenium');

    child = execFile(process.mainModule.filename, cliArgs, {
      cwd : process.cwd(),
      encoding: 'utf8'
    }, function (error, stdout, stderr) {
      //console.log('stdout: ' + stdout);
      //console.log('stderr: ' + stderr);
      if (error !== null) {
        console.log('exec error: ' + error);
      }
    });

    child.stderr.on('data', function (data) {
      process.stderr.write('['+ envs[i] +']' + ' ' + data);
    });
    child.stdout.on('data', function (data) {
      process.stdout.write('['+ envs[i] +']' + ' ' + data);
    });
  }
}

try {
  var argv = cli.init();
  if (argv.help) {
    cli.showHelp();
  } else if (argv.version) {
    var packageConfig = require(__dirname + '/../package.json');
    console.log(packageConfig.name + ' v' + packageConfig.version);
  } else {

    process.chdir(process.cwd());

    // the test runner
    var runner = require(__dirname + '/../lib/runner/run.js');

    var settings = readSettings(argv);

    // setting the output folder
    var output_folder = cli.command('output').isDefault(argv.o) &&
        settings.output_folder || argv.o;

    var test_settings = parseTestSettings(argv);
    if (!test_settings) {
      return;
    }

    // setting the path where the tests are located
    var testsource;
    if (typeof argv.t == 'string') {
      testsource =  (argv.t.indexOf(process.cwd()) === -1) ?
                      path.join(process.cwd(), argv.t) :
                      argv.t;
      if (testsource.substr(-3) != '.js') {
        testsource += '.js';
      }
      fs.statSync(testsource);
    } else if (typeof argv.g == 'string') {
      testsource = [argv.g];
    } else {
      testsource = settings.src_folders;
    }

    var errorHandler = function(err) {
      if (err) {
        if (err.message) {
          Logger.error(err.message);
        } else {
          Logger.error('There was an error while running the test.');
        }
      }
    };

    // running the tests
    if (settings.selenium && settings.selenium.start_process) {
      var selenium = require(__dirname + '/../lib/runner/selenium.js');
      selenium.startServer(settings, test_settings, function(error, child, error_out, exitcode) {
        if (error) {
          Logger.error('There was an error while starting the Selenium server:');
          console.log(error_out);
          process.exit(exitcode);
        }

        runner.run(testsource, test_settings, {
          output_folder : output_folder,
          src_folders : settings.src_folders
        }, function(err) {
          errorHandler(err);
          selenium.stopServer();
        });
      });
    } else {
      runner.run(testsource, test_settings, {
        output_folder : output_folder
      }, function(err) {
        errorHandler(err);
      });
    }
  }
} catch (ex) {
  Logger.error('There was an error while starting the test runner:\n');
  console.log(ex.stack);
}
<commit_msg>some refactoring<commit_after>/**
 * Module dependencies
 */
var fs = require('fs');
var path = require('path');
var Logger = require('../lib/util/logger.js');
var cli = require('./_cli.js');

// CLI definitions

// $ nightwatch -c
// $ nightwatch --config
cli.command('config')
  .demand(true)
  .description('Path to configuration file')
  .alias('c')
  .defaults('./nightwatch.json');

// $ nightwatch -o
// $ nightwatch --output
cli.command('output')
  .description('Where to save the JUnit XML test reports.')
  .alias('o')
  .defaults('tests_output');

// $ nightwatch -e
// $ nightwatch --env saucelabs
cli.command('env')
  .description('Testing environment to use.')
  .alias('e')
  .defaults('default');

// $ nightwatch --verbose
cli.command('verbose')
  .description('Turns on selenium command logging during the session.');

// $ nightwatch -t
// $ nightwatch --test
cli.command('test')
  .description('Runs a single test.')
  .alias('t');

// $ nightwatch -g
// $ nightwatch --group
cli.command('group')
  .description('Runs a group of tests (i.e. a folder)')
  .alias('g');

// $ nightwatch -s
// $ nightwatch --skipgroup
cli.command('skipgroup')
  .description('Skips one or several (comma separated) group of tests.')
  .alias('s');

// $ nightwatch -f
// $ nightwatch --filter
cli.command('filter')
  .description('Specify a filter (glob expression) as the file name format to use when loading the files.')
  .defaults('')
  .alias('f');

// $ nightwatch -s
// $ nightwatch --skipgroup
cli.command('help')
  .description('Shows this help.')
  .alias('h');

// $ nightwatch --version
cli.command('version')
  .alias('v')
  .description('Shows version information.');

/**
 * Looks for pattern ${VAR_NAME} in settings
 * @param {Object} target
 */
function replaceEnvVariables(target) {
  for (var key in target) {
    switch(typeof target[key]) {
      case 'object':
        replaceEnvVariables(target[key]);
        break;
      case 'string':
        target[key] = target[key].replace(/\$\{(\w+)\}/g, function(match, varName) {
          return process.env[varName] || '${' + varName + '}';
        });
        break;
    }
  }
}

/**
 * Read the provided config json file; defaults to settings.json if one isn't provided
 * @param {Object} argv
 */
function readSettings(argv) {
  var settings;

  // use default settings.json file if we haven't received another value
  if (cli.command('config').isDefault(argv.c)) {
    var defaultValue = cli.command('config').defaults();
    var deprecatedValue = './settings.json';

    if (fs.existsSync(defaultValue)) {
      argv.c = path.join(path.resolve('./'), argv.c);
    } else if (fs.existsSync(deprecatedValue)) {
      argv.c = path.join(path.resolve('./'), deprecatedValue);
    } else {
      var defaultFile = path.join(__dirname, argv.c);
      if (fs.existsSync(defaultFile)) {
        argv.c = defaultFile;
      } else {
        argv.c = path.join(__dirname, deprecatedValue);
      }
    }
  } else {
    argv.c = path.resolve(argv.c);
  }

  // reading the settings file
  try {
    settings = require(argv.c);
    replaceEnvVariables(settings);
  } catch (ex) {
    Logger.error(ex);
    settings = {};
  }

  return settings;
}

/**
 * Reads globals from an external js or json file
 * @param {string} file
 * @returns {*}
 */
function readExternalGlobals(file) {
  try {
    var fullPath = path.resolve(file);
    if (fs.existsSync(fullPath)) {
      return require(fullPath);
    }
    throw new Error('External global file could not be located - using '+ file +'.');
  } catch (err) {
    err.message = 'Failed to load external global file: ' + err.message;
    throw err;
  }
}

function inheritFromDefaultEnv(test_settings) {
  var defaultEnv = settings.test_settings['default'] || {};
  for (var key in defaultEnv) {
    if (typeof test_settings[key] == 'undefined') {
      test_settings[key] = defaultEnv[key];
    }
  }
}

/**
 *
 * @param {Object} argv
 */
function parseTestSettings(argv) {
  // checking if the env passed is valid
  if (!settings.test_settings) {
    throw new Error('No testing environment specified.');
  }

  var envs = argv.e.split(',');
  for (var i = 0; i < envs.length; i++) {
    if (!(envs[i] in settings.test_settings)) {
      throw new Error('Invalid testing environment specified: ' + envs[i]);
    }
  }

  if (envs.length > 1) {
    setupClustering(envs);
    console.info('clustering mode');
    return false;
  }
  // picking the environment specific test settings
  var test_settings = settings.test_settings[argv.e];
  test_settings.custom_commands_path = settings.custom_commands_path || '';
  test_settings.custom_assertions_path = settings.custom_assertions_path || '';

  inheritFromDefaultEnv(test_settings);

  console.log('parseTest', test_settings)

  if (test_settings.selenium && typeof (test_settings.selenium) == 'object') {
    for (var prop in test_settings.selenium) {
      settings.selenium[prop] = test_settings.selenium[prop];
    }
  }
  if (typeof settings.globals == 'string' && settings.globals) {
    settings.globals_path = settings.globals_path;
  }
  if (typeof settings.globals_path == 'string' && settings.globals_path) {
    var globals = readExternalGlobals(settings.globals_path);
    if (globals && globals.hasOwnProperty(argv.e)) {
      test_settings.globals = globals[argv.e];
    }
  }

  if (argv.verbose) {
    test_settings.silent = false;
  }

  test_settings.output = test_settings.output || typeof test_settings.output === 'undefined';

  if (typeof argv.s == 'string') {
    test_settings.skipgroup = argv.s.split(',');
  }

  if (argv.f) {
    test_settings.filter = argv.f;
  }

  return test_settings;
}

function setupClustering(envs) {
  var execFile = require('child_process').execFile, child;

  envs.forEach(function(item, index) {
    console.log(index, item);
    var cliArgs = ['-e', item];
    cliArgs.push('--disable_selenium');

    child = execFile(process.mainModule.filename, cliArgs, {
      cwd : process.cwd(),
      encoding: 'utf8'
    }, function (error, stdout, stderr) {
      if (error !== null) {
        console.log('exec error: ' + error);
      }
    });

    child.stderr.on('data', function (data) {
      process.stderr.write('['+ item +']' + ' ' + data);
    });
    child.stdout.on('data', function (data) {
      process.stdout.write('['+ item +']' + ' ' + data);
    });
    child.on('close', function (code) {
      console.log('child process exited with code ' + code);
    });
  });
}

try {
  var argv = cli.init();
  if (argv.help) {
    cli.showHelp();
  } else if (argv.version) {
    var packageConfig = require(__dirname + '/../package.json');
    console.log(packageConfig.name + ' v' + packageConfig.version);
  } else {

    process.chdir(process.cwd());

    // the test runner
    var runner = require(__dirname + '/../lib/runner/run.js');
    var settings = readSettings(argv);

    // setting the output folder
    var output_folder = cli.command('output').isDefault(argv.o) &&
        settings.output_folder || argv.o;

    var test_settings = parseTestSettings(argv);
    if (!test_settings) {
      return;
    }

    // setting the path where the tests are located
    var testsource;
    if (typeof argv.t == 'string') {
      testsource =  (argv.t.indexOf(process.cwd()) === -1) ?
                      path.join(process.cwd(), argv.t) :
                      argv.t;
      if (testsource.substr(-3) != '.js') {
        testsource += '.js';
      }
      fs.statSync(testsource);
    } else if (typeof argv.g == 'string') {
      testsource = [argv.g];
    } else {
      testsource = settings.src_folders;
    }

    var errorHandler = function(err) {
      if (err) {
        if (err.message) {
          Logger.error(err.message);
        } else {
          Logger.error('There was an error while running the test.');
        }
      }
    };

    // running the tests
    if (settings.selenium && settings.selenium.start_process) {
      var selenium = require(__dirname + '/../lib/runner/selenium.js');
      selenium.startServer(settings, test_settings, function(error, child, error_out, exitcode) {
        if (error) {
          Logger.error('There was an error while starting the Selenium server:');
          console.log(error_out);
          process.exit(exitcode);
        }

        runner.run(testsource, test_settings, {
          output_folder : output_folder,
          src_folders : settings.src_folders
        }, function(err) {
          errorHandler(err);
          selenium.stopServer();
        });
      });
    } else {
      runner.run(testsource, test_settings, {
        output_folder : output_folder
      }, function(err) {
        errorHandler(err);
      });
    }
  }
} catch (ex) {
  Logger.error('There was an error while starting the test runner:\n');
  console.log(ex.stack);
}
<|endoftext|>


<commit_before>import Events from "events";
import assert from "assert";
import { ReadableStream, TransformStream, WritableStream } from "../src/streams";
import connect from "../src/connect";

// consts
const
  broker = new Events,
  token = "suzanne",
  gen = c => c.enqueue(token),
  noop = (k, e, d) => e(k) && d();

suite("connect");

test("check allowed orders", () => {
  let testChain,

  // Keeps beaming token
  source = new ReadableStream({
    start: gen,
    pull: gen
  }),

  // passes token unscathed
  through = new TransformStream({
    transform: noop
  }),

  // Empty streams
  r1 = new ReadableStream,
  r2 = new ReadableStream,
  w1 = new WritableStream,
  w2 = new WritableStream;

  // Check chaining
  assert.doesNotThrow( () => {
    testChain = connect( source, w1 );
    testChain = connect( source, through, w1 );
    testChain = connect( through, source, w1 );
    testChain = connect( r1, r2, through, source, w1 );
  });

  assert.throws( () => {
    testChain = connect( w1, r1 );
  });
})

test("check flow order", done => {
  let marilyn,

  // Keeps beaming token
  source = new ReadableStream({
    start: gen,
    pull: gen
  }),

  // passes token unscathed
  through = new TransformStream({
    transform: noop
  }),

  // Emits chunks to broker
  sink = new WritableStream({
    write( chunk ) {
      broker.emit("chunk", chunk);
    }
  });

  // Chain
  marilyn = connect( source, through );

  // Set up listenener
  broker.on("chunk", chunk => {
    assert(chunk == token);

    // Clean up
    sink.close();
    source.cancel();
    done();
  });

  // pipe
  marilyn.pipeTo(sink);

});
<commit_msg>cancelled connect test for now<commit_after>// import Events from "events";
// import assert from "assert";
// import { ReadableStream, TransformStream, WritableStream } from "../src/streams";
// import connect from "../src/connect";
//
// // consts
// const
//   broker = new Events,
//   token = "suzanne",
//   gen = c => c.enqueue(token),
//   noop = (k, e, d) => e(k) && d();
//
// suite("connect");
//
// test("check allowed orders", () => {
//   let testChain,
//
//   // Keeps beaming token
//   source = new ReadableStream({
//     start: gen,
//     pull: gen
//   }),
//
//   // passes token unscathed
//   through = new TransformStream({
//     transform: noop
//   }),
//
//   // Empty streams
//   r1 = new ReadableStream,
//   r2 = new ReadableStream,
//   w1 = new WritableStream,
//   w2 = new WritableStream;
//
//   // Check chaining
//   assert.doesNotThrow( () => {
//     testChain = connect( source, w1 );
//     testChain = connect( source, through, w1 );
//     testChain = connect( through, source, w1 );
//     testChain = connect( r1, r2, through, source, w1 );
//   });
//
//   assert.throws( () => {
//     testChain = connect( w1, r1 );
//   });
// })
//
// test("check flow order", done => {
//   let marilyn,
//
//   // Keeps beaming token
//   source = new ReadableStream({
//     start: gen,
//     pull: gen
//   }),
//
//   // passes token unscathed
//   through = new TransformStream({
//     transform: noop
//   }),
//
//   // Emits chunks to broker
//   sink = new WritableStream({
//     write( chunk ) {
//       broker.emit("chunk", chunk);
//     }
//   });
//
//   // Chain
//   marilyn = connect( source, through );
//
//   // Set up listenener
//   broker.on("chunk", chunk => {
//     assert(chunk == token);
//
//     // Clean up
//     sink.close();
//     source.cancel();
//     done();
//   });
//
//   // pipe
//   marilyn.pipeTo(sink);
//
// });
<|endoftext|>


<commit_before>/**
 * Dependencies.
 */
var
	Message = require('../lib/Message'),
	expect = require('expect.js');

describe('creating messages', function () {

	it('message is created', function () {
		var
			message = new Message(),
			PRINTED =
				'From: Iñaki Baz Castillo <im:inaki.baz@eface2face.com>\r\n' +
				'To: Alicia <im:alicia@atlanta.com>\r\n' +
				'Subject: Urgent, read pliz pliz\r\n' +
				'\r\n' +
				'Content-Type: text/plain\r\n' +
				'Content-Length: 5\r\n' +
				'\r\n' +
				'HELLO';

		// Set message fields.

		message.from({
			name: 'Iñaki Baz Castillo',
			uri: 'im:inaki.baz@eface2face.com'
		});

		message.to({
			name: 'Alicia',
			uri: 'im:alicia@atlanta.com'
		});

		message.subject('Urgent, read pliz pliz');

		message.contentType({
			type: 'text',
			subtype: 'plain'
		});

		message.mimeHeader('Content-Length', '5');

		message.body('HELLO');

		// Verify field values.

		expect(message.from().name).to.be('Iñaki Baz Castillo');
		expect(message.from().uri).to.be('im:inaki.baz@eface2face.com');

		expect(message.to().name).to.be('Alicia');
		expect(message.to().uri).to.be('im:alicia@atlanta.com');

		expect(message.subject()).to.be('Urgent, read pliz pliz');

		expect(message.contentType()).to.eql({
			type: 'text',
			subtype: 'plain',
			value: 'text/plain'
		});

		// Verify printed message.

		expect(message.toString()).to.be(PRINTED);
	});

});
<commit_msg>Complete test_message.js.<commit_after>/**
 * Dependencies.
 */
var
	Message = require('../lib/Message'),
	expect = require('expect.js');

describe('creating messages', function () {

	it('message is created', function () {
		var
			message = new Message(),
			PRINTED =
				'From: Iñaki Baz Castillo <im:inaki.baz@eface2face.com>\r\n' +
				'To: Alicia <im:alicia@atlanta.com>\r\n' +
				'Subject: Urgent, read pliz pliz\r\n' +
				'\r\n' +
				'Content-Type: text/plain\r\n' +
				'Content-Length: 5\r\n' +
				'\r\n' +
				'HELLO';

		// Set message fields.

		message.from({
			name: 'Iñaki Baz Castillo',
			uri: 'im:inaki.baz@eface2face.com'
		});

		message.to({
			name: 'Alicia',
			uri: 'im:alicia@atlanta.com'
		});

		message.subject('Urgent, read pliz pliz');

		message.contentType({
			type: 'text',
			subtype: 'plain'
		});

		message.mimeHeader('Content-Length', '5');

		message.body('HELLO');

		// Verify field values.

		expect(message.from().name).to.be('Iñaki Baz Castillo');
		expect(message.from().uri).to.be('im:inaki.baz@eface2face.com');

		expect(message.to().name).to.be('Alicia');
		expect(message.to().uri).to.be('im:alicia@atlanta.com');

		expect(message.subject()).to.be('Urgent, read pliz pliz');

		expect(message.contentType()).to.eql({
			type: 'text',
			subtype: 'plain',
			value: 'text/plain'
		});

		expect(message.mimeHeader('Content-Length')).to.be('5');

		expect(message.body()).to.be('HELLO');

		// Verify printed message.

		expect(message.toString()).to.be(PRINTED);
	});

});
<|endoftext|>