<commit_before>#!/usr/bin/env node
require('shelljs/global');

var TEST_DIR = 'scripts';

var shouldLog = (process.argv[2] === 'log');
var log = [];

function writeLog(msg, link) {
  console.log(msg);
  if (link) {
    msg = msg.replace(']', '](' + link + ')');
  }
  log.push(msg);
}

cd(__dirname + '/' + TEST_DIR);
var prefix;
var shellJSWins = [];
ls().forEach(function (dir) {
  prefix = TEST_DIR + '/' + dir;
  writeLog('### [' + dir + ']', prefix)
  cd(dir)

  // Find the files
  var jsfile = ls('*.js')[0];
  var shfile = ls('*.sh')[0];

  if (!jsfile || !shfile) {
    console.error('Could not find your files. Please use proper extensions.');
    return;
  }

  // execute it
  var start_time,
      end_time,
      shell_time,
      shell_output,
      js_time,
      js_output;

  config.silent = true;

  start_time = new Date().getTime();
  js_output = exec('node ' + jsfile).output;
  end_time = new Date().getTime();
  js_time = end_time - start_time;
  writeLog(' - [ShellJS] took `' + js_time + '` milliseconds', prefix + '/' + jsfile);

  start_time = new Date().getTime();
  shell_output = exec('bash ' + shfile).output;
  end_time = new Date().getTime();
  shell_time = end_time - start_time;
  writeLog(' - [Bash] took `' + shell_time + '` milliseconds', prefix + '/' + shfile);

  if (shell_time < js_time) {
    writeLog('Bash was `' + (js_time/shell_time).toFixed(3) + '` times faster than ShellJS');
  } else {
    writeLog('ShellJS was `' + (shell_time/js_time).toFixed(3) + '` times faster than Bash');
    shellJSWins.push(dir);
  }

  if (shell_output !== js_output)
    writeLog('Output differs');

  // Clean up
  echo('=======================');
  echo();
  config.silent = false;
  cd('..')
});

if (shouldLog) {
  cd(__dirname);
  var text = '### ShellJS performance wins\n\n';
  text += shellJSWins.map(x => ' - [' + x + '](' + TEST_DIR + '/' + x + ')').join('\n');
  text += '\n\n' + log.join('\n\n');

  // Wipe out the old results
  cat('README.md').replace(/## Results(.|\n)*/, '## Results').to('README.md');

  // Append new docs to README
  sed('-i', /## Results/, '## Results\n\n' + text, 'README.md');
}
<commit_msg>Print system information after tests<commit_after>#!/usr/bin/env node
require('shelljs/global');

var TEST_DIR = 'scripts';

var shouldLog = (process.argv[2] === 'log');
var log = [];

function writeLog(msg, link) {
  console.log(msg);
  if (link) {
    msg = msg.replace(']', '](' + link + ')');
  }
  log.push(msg);
}

function printSystemInfo() {
  var os = require('os');
  var cpus = os.cpus();
  var spawn = require('child_process').spawn;
  console.log('System Information:');
  console.log(os.type(), os.release(), os.arch());
  console.log('Node.js ' + process.versions.node);
  console.log('V8 ' + process.versions.v8);
  console.log(cpus[0].model + ' × ' + cpus.length);
  console.log();
  console.log('Shell Information:');
  spawn('sh', ['-c', '${SHELL} --version'], { stdio: 'inherit' });
}

cd(__dirname + '/' + TEST_DIR);
var prefix;
var shellJSWins = [];
ls().forEach(function (dir) {
  prefix = TEST_DIR + '/' + dir;
  writeLog('### [' + dir + ']', prefix)
  cd(dir)

  // Find the files
  var jsfile = ls('*.js')[0];
  var shfile = ls('*.sh')[0];

  if (!jsfile || !shfile) {
    console.error('Could not find your files. Please use proper extensions.');
    return;
  }

  // execute it
  var start_time,
      end_time,
      shell_time,
      shell_output,
      js_time,
      js_output;

  config.silent = true;

  start_time = new Date().getTime();
  js_output = exec('node ' + jsfile).output;
  end_time = new Date().getTime();
  js_time = end_time - start_time;
  writeLog(' - [ShellJS] took `' + js_time + '` milliseconds', prefix + '/' + jsfile);

  start_time = new Date().getTime();
  shell_output = exec('bash ' + shfile).output;
  end_time = new Date().getTime();
  shell_time = end_time - start_time;
  writeLog(' - [Bash] took `' + shell_time + '` milliseconds', prefix + '/' + shfile);

  if (shell_time < js_time) {
    writeLog('Bash was `' + (js_time/shell_time).toFixed(3) + '` times faster than ShellJS');
  } else {
    writeLog('ShellJS was `' + (shell_time/js_time).toFixed(3) + '` times faster than Bash');
    shellJSWins.push(dir);
  }

  if (shell_output !== js_output)
    writeLog('Output differs');

  // Clean up
  echo('=======================');
  echo();
  config.silent = false;
  cd('..')
});

if (shouldLog) {
  cd(__dirname);
  var text = '### ShellJS performance wins\n\n';
  text += shellJSWins.map(x => ' - [' + x + '](' + TEST_DIR + '/' + x + ')').join('\n');
  text += '\n\n' + log.join('\n\n');

  // Wipe out the old results
  cat('README.md').replace(/## Results(.|\n)*/, '## Results').to('README.md');

  // Append new docs to README
  sed('-i', /## Results/, '## Results\n\n' + text, 'README.md');
}
printSystemInfo();
<|endoftext|>


<commit_before>const path = require("path"),
    haro = require(path.join(__dirname, "lib", "haro.es6")),
    precise = require("precise"),
    nth = 15000,
    data = [];

let indexes;

let i = -1;

while (++i < nth) {
    data.push({id: i, name: "abba " + i});
}

function second () {
    const timer = precise().start(),
        store = haro(null, {key: "id", index: ["name"]}),
        deferreds = [];

    deferreds.push(store.override(data, "records"));
    deferreds.push(store.override(indexes, "indexes"));

    Promise.all(deferreds).then(function () {
	    let i = -1,
		    nth = 5;

        timer.stop();
        console.log("time to override data: " + (timer.diff() / 1000000) + "ms");
	    console.log("testing time to 'search(regex, index)' on overridden data for a record (first one is cold):");

	    while (++i < nth) {
		    (function () {
			    const timer2 = precise().start();
			    const record = store.search(/abba 12345/, "name");
			    timer2.stop();
			    console.log((timer2.diff() / 1000000) + "ms");

			    if (!record) {
				    console.log("Couldn't find record");
                }
		    }());
	    }
    });
}

function first () {
	const timer = precise().start(),
        store = haro(null, {key: "id", index: ["name"]});

    store.batch(data, "set").then(function () {
        timer.stop();
        console.log("time to batch insert data: " + (timer.diff() / 1000000) + "ms");
        console.log("datastore record count: " + store.total);
        console.log("name indexes: " + store.indexes.get("name").size);
    }).then(function () {
        let i = -1,
            nth = 5;

        console.log("testing time to 'find()' a record (first one is cold):");
        indexes = store.dump("indexes");

        while (++i < nth) {
            (function () {
                const timer2 = precise().start();
				const record = store.find({name: "abba 12345"});
                timer2.stop();
                console.log((timer2.diff() / 1000000) + "ms");

	            if (!record) {
		            console.log("Couldn't find record");
	            }
            }());
        }
    }).then(function () {
        let i = -1,
            nth = 5;

        console.log("testing time to 'search(regex, index)' for a record (first one is cold):");

        while (++i < nth) {
            (function () {
                const timer2 = precise().start();
                const record = store.search(/abba 12345/, "name");
                timer2.stop();
                console.log((timer2.diff() / 1000000) + "ms");

	            if (!record) {
		            console.log("Couldn't find record");
	            }
            }());
        }

        second();
    });
}

first();

<commit_msg>Random record change<commit_after>const path = require("path"),
    haro = require(path.join(__dirname, "lib", "haro.es6")),
    precise = require("precise"),
    nth = 15000,
    data = [];

let indexes;

let i = -1;

while (++i < nth) {
    data.push({id: i, name: "abba " + i});
}

function second () {
    const timer = precise().start(),
        store = haro(null, {key: "id", index: ["name"]}),
        deferreds = [];

    deferreds.push(store.override(data, "records"));
    deferreds.push(store.override(indexes, "indexes"));

    Promise.all(deferreds).then(function () {
	    let i = -1,
		    nth = 5;

        timer.stop();
        console.log("time to override data: " + (timer.diff() / 1000000) + "ms");
	    console.log("testing time to 'search(regex, index)' on overridden data for a record (first one is cold):");

	    while (++i < nth) {
		    (function () {
			    const timer2 = precise().start();
			    const record = store.search(/abba 2342/, "name");
			    timer2.stop();
			    console.log((timer2.diff() / 1000000) + "ms");

			    if (!record) {
				    console.log("Couldn't find record");
                }
		    }());
	    }
    });
}

function first () {
	const timer = precise().start(),
        store = haro(null, {key: "id", index: ["name"]});

    store.batch(data, "set").then(function () {
        timer.stop();
        console.log("time to batch insert data: " + (timer.diff() / 1000000) + "ms");
        console.log("datastore record count: " + store.total);
        console.log("name indexes: " + store.indexes.get("name").size);
    }).then(function () {
        let i = -1,
            nth = 5;

        console.log("testing time to 'find()' a record (first one is cold):");
        indexes = store.dump("indexes");

        while (++i < nth) {
            (function () {
                const timer2 = precise().start();
				const record = store.find({name: "abba 12345"});
                timer2.stop();
                console.log((timer2.diff() / 1000000) + "ms");

	            if (!record) {
		            console.log("Couldn't find record");
	            }
            }());
        }
    }).then(function () {
        let i = -1,
            nth = 5;

        console.log("testing time to 'search(regex, index)' for a record (first one is cold):");

        while (++i < nth) {
            (function () {
                const timer2 = precise().start();
                const record = store.search(/abba 12345/, "name");
                timer2.stop();
                console.log((timer2.diff() / 1000000) + "ms");

	            if (!record) {
		            console.log("Couldn't find record");
	            }
            }());
        }

        second();
    });
}

first();

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012, Joyent, Inc. All rights reserved.
 */

var assert = require('assert');
var Logger = require('bunyan');
var restify = require('restify');
var uuid = require('node-uuid');

function genServers(numServers, serverRam, numVmsPerServer, vmRam) {
    var numRacks = numServers / 24;
    var servers = [];

    for (var i = 0; i !== numServers; i++) {
        var server = {
            uuid: uuid(),
            setup: true,
            reserved: false,
            status: 'running',
            memory_total_bytes: serverRam * 1024 * 1024,
            memory_available_bytes: (serverRam - 8 * 1024) * 1024 * 1024,
            'Zpool Size in GiB': 3600,
            rack_identifier: 'ams-' + i % numRacks,
            sysinfo: {
                'Network Interfaces': {
                    e1000g0: {
                        'Link Status': 'up',
                        'NIC Names': [ 'external' ]
                    },
                    e1000g1: {
                       'Link Status': 'up',
                       'NIC Names': [ 'admin' ]
                    }
                }
            },
            vms: {}
        };

        for (var j = 0; j !== numVmsPerServer; j++) {
            var vm = {
                uuid: uuid(),
                owner_uuid: '98c9f65b-ad6d-4819-bb27-5d00dd54de29',
                // owner_uuid: uuid(),
                quota: 15,
                max_physical_memory: vmRam,
                zone_state: 'running',
                state: 'running',
                last_modified: '2012-12-19T05:26:05.000Z'
            };

            server.vms[vm.uuid] = vm;
        }

        servers.push(server);
    }

    return servers;
}

function bench(name, numServers, serverRam, numVmsPerServer, vmRam, callback) {
    var client = restify.createStringClient({
        url: 'http://localhost:8080',
        version: '*',
        retryOptions: { retry: 0 },
        contentType: 'application/json',
        accept: 'application/json'
    });

    var servers = genServers(numServers, serverRam, numVmsPerServer, vmRam);
    // var data = { servers: servers, vm: { ram: vmRam, owner_uuid: uuid() } };
    var data = { servers: servers,
                 vm: { ram: vmRam,
                       owner_uuid: '98c9f65b-ad6d-4819-bb27-5d00dd54de29' } };
    var json = JSON.stringify(data);

    var start = new Date();

    client.post('/allocation', json, function (err, req, res, body) {
        console.log(name, 'time:', (new Date() - start) / 1000);

//        assert.ifError(err);
//        assert.equal(res.statusCode, 200);
//        assert.ok(body);

//        var server = JSON.parse(body);
//        console.dir(server.uuid);

        if (callback)
            callback();
    });
}

bench('current', 300, 80 * 1024, 25, 2048, function () {
    bench('high', 40 * 25, 128 * 1024, 192, 512, function () {
        bench('ridiculous', 40 * 25, 128 * 1024, 768, 128);
    });
});
<commit_msg>DAPI-97 - bench.js wasn't terminating due to restify 2.* keep-alive.<commit_after>/*
 * Copyright (c) 2012, Joyent, Inc. All rights reserved.
 */

var assert = require('assert');
var Logger = require('bunyan');
var restify = require('restify');
var uuid = require('node-uuid');

function genServers(numServers, serverRam, numVmsPerServer, vmRam) {
    var numRacks = numServers / 24;
    var servers = [];

    for (var i = 0; i !== numServers; i++) {
        var server = {
            uuid: uuid(),
            setup: true,
            reserved: false,
            status: 'running',
            memory_total_bytes: serverRam * 1024 * 1024,
            memory_available_bytes: (serverRam - 8 * 1024) * 1024 * 1024,
            'Zpool Size in GiB': 3600,
            rack_identifier: 'ams-' + i % numRacks,
            sysinfo: {
                'Network Interfaces': {
                    e1000g0: {
                        'Link Status': 'up',
                        'NIC Names': [ 'external' ]
                    },
                    e1000g1: {
                       'Link Status': 'up',
                       'NIC Names': [ 'admin' ]
                    }
                }
            },
            vms: {}
        };

        for (var j = 0; j !== numVmsPerServer; j++) {
            var vm = {
                uuid: uuid(),
                owner_uuid: '98c9f65b-ad6d-4819-bb27-5d00dd54de29',
                // owner_uuid: uuid(),
                quota: 15,
                max_physical_memory: vmRam,
                zone_state: 'running',
                state: 'running',
                last_modified: '2012-12-19T05:26:05.000Z'
            };

            server.vms[vm.uuid] = vm;
        }

        servers.push(server);
    }

    return servers;
}

function bench(name, numServers, serverRam, numVmsPerServer, vmRam, callback) {
    var client = restify.createStringClient({
        agent: false,
        url: 'http://localhost:8080',
        version: '*',
        retryOptions: { retry: 0 },
        contentType: 'application/json',
        accept: 'application/json'
    });

    var servers = genServers(numServers, serverRam, numVmsPerServer, vmRam);
    // var data = { servers: servers, vm: { ram: vmRam, owner_uuid: uuid() } };
    var data = { servers: servers,
                 vm: { ram: vmRam,
                       owner_uuid: '98c9f65b-ad6d-4819-bb27-5d00dd54de29' } };
    var json = JSON.stringify(data);

    var start = new Date();

    client.post('/allocation', json, function (err, req, res, body) {
        console.log(name, 'time:', (new Date() - start) / 1000);

//        assert.ifError(err);
//        assert.equal(res.statusCode, 200);
//        assert.ok(body);

//        var server = JSON.parse(body);
//        console.dir(server.uuid);

        if (callback)
            callback();
    });
}

bench('current', 300, 80 * 1024, 25, 2048, function () {
    bench('high', 40 * 25, 128 * 1024, 192, 512, function () {
        bench('ridiculous', 40 * 25, 128 * 1024, 768, 128);
    });
});
<|endoftext|>


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

var spawn = require('child_process').spawn;
var path = require('path');
var _ = require('lodash');
var Liftoff = require('liftoff');
var parsePhoneNumber = require('../lib/parsePhoneNumber').parsePhoneNumber;
var cleanArgs = process.argv.map(function (item) {
  return (item || '').toLowerCase();
});

function getUserHome() {
  return process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
}

var globalConfigFileName = '.skypeitrc';
var debug = cleanArgs.indexOf('--debug') >= 0 || cleanArgs.indexOf('--verbose') >= 0;

var dlog = function () {
  if(debug) {
    console.log.apply(null, arguments);
  }
};

var getVersion = function () {
  return require('../package.json').version;
};

var printHelpMessage = function() {

  dlog("printing help...");

  var helpFile = path.join(__dirname, 'help.md');
  var output = require('msee').parseFile(helpFile);

  var version = getVersion();
  output = output.replace('{{version}}', version);

  // Some spacing formatting cleanup
  output = output.replace(/ /g, ' ');
  console.log(output);
};

var Skypeit = new Liftoff({
  processTitle: 'SkypeIt',
  moduleName: 'skypeit',
  configName: globalConfigFileName,
  extensions:{
    '': null
  }
});

var argv = require('minimist')(process.argv.slice(2));

var invoke = function (env) {

  dlog('Environment is:', env);
  dlog('Cli options are:', argv);
  dlog('Liftoff config is:', this);

  if(argv.help) {
    printHelpMessage();
    return;
  }

  if(argv.version) {
    console.log(getVersion());
    return;
  }

  var globalConfigPath = path.join(getUserHome(), globalConfigFileName);
  var localConfigPath = path.join(env.configBase, globalConfigFileName);
  dlog('globalConfigPath:', globalConfigPath);
  dlog('localConfigPath:', localConfigPath);
  var config = require('../lib/config.js')(debug, globalConfigPath, localConfigPath);

  if(argv.sampleConfig) {
    console.log(config.sampleConfig());
    return;
  }

  if(argv.completion) {

    if(argv.completion === true) {
      console.log(config.listAlias.join('\n'));
      return;
    }

    require('../lib/completion')(argv.completion);
    return;
  }

  var aliasNumber;
  var alias = argv._[0];
  var result;
  dlog("config.alias: ", config.alias);
  if(alias && config.alias[alias]) {
    dlog('found alias for: ' + alias);
    var aliasValue = config.alias[alias];
    dlog('alias:', aliasValue);
    aliasNumber = aliasValue.number;
    result = parsePhoneNumber(aliasNumber.split(' '), debug);
  } else {
    dlog('no alias found');
    result = parsePhoneNumber(argv._, debug);
  }

  if(!result) {
    printHelpMessage();
    var chalk = require('chalk');
    console.log(chalk.red("invalid input... Consider using the --debug parameter to help diagnose issues."));
    return;
  }

  dlog('process.argv:', process.argv);
  dlog('debug:', debug);
  dlog('parsePhoneNumber result: ', result);

  var appleScriptArgs = [ path.join(__dirname, './skypeItAppleScript.scpt'), result.num, result.ext];

  var appleScriptCmd = 'osascript';

  dlog(appleScriptCmd + ' ' + appleScriptArgs.join(' '));

  if(debug) {
    var cmd = spawn(appleScriptCmd, appleScriptArgs);

    cmd.stdout.on('data', function (data) {
      console.log('stdout: ' + data);
    });

    cmd.stderr.on('data', function (data) {
      console.error('stderr: ' + data);
    });

    cmd.on('close', function (code) {
      console.log('child process exited with code ' + code);
    });
  } else {
    var cmd = spawn(appleScriptCmd, appleScriptArgs, {
      detached: true,
      stdio: ['ignore', 'ignore', 'ignore']
    });
    cmd.unref();
  }

};
Skypeit.launch({
  cwd: argv.cwd,
  configPath: argv.myappfile,
  require: argv.require,
  completion: argv.completion
}, invoke);
<commit_msg>only look for local file is the env.configBase exists. Should fix #3<commit_after>#!/usr/bin/env node
'use strict';

var spawn = require('child_process').spawn;
var path = require('path');
var _ = require('lodash');
var Liftoff = require('liftoff');
var parsePhoneNumber = require('../lib/parsePhoneNumber').parsePhoneNumber;
var cleanArgs = process.argv.map(function (item) {
  return (item || '').toLowerCase();
});

function getUserHome() {
  return process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
}

var skypeitrcName = '.skypeitrc';
var debug = cleanArgs.indexOf('--debug') >= 0 || cleanArgs.indexOf('--verbose') >= 0;

var dlog = function () {
  if(debug) {
    console.log.apply(null, arguments);
  }
};

var getVersion = function () {
  return require('../package.json').version;
};

var printHelpMessage = function() {

  dlog("printing help...");

  var helpFile = path.join(__dirname, 'help.md');
  var output = require('msee').parseFile(helpFile);

  var version = getVersion();
  output = output.replace('{{version}}', version);

  // Some spacing formatting cleanup
  output = output.replace(/ /g, ' ');
  console.log(output);
};

var Skypeit = new Liftoff({
  processTitle: 'SkypeIt',
  moduleName: 'skypeit',
  configName: skypeitrcName,
  extensions:{
    '': null
  }
});

var argv = require('minimist')(process.argv.slice(2));

var invoke = function (env) {

  dlog('Environment is:', env);
  dlog('Cli options are:', argv);
  dlog('Liftoff config is:', this);

  if(argv.help) {
    printHelpMessage();
    return;
  }

  if(argv.version) {
    console.log(getVersion());
    return;
  }

  var globalConfigPath = path.join(getUserHome(), skypeitrcName);
  var localConfigPath = env.configBase && path.join(env.configBase, skypeitrcName);
  dlog('globalConfigPath:', globalConfigPath);
  dlog('localConfigPath:', localConfigPath);
  var config = require('../lib/config.js')(debug, globalConfigPath, localConfigPath);

  if(argv.sampleConfig) {
    console.log(config.sampleConfig());
    return;
  }

  if(argv.completion) {

    if(argv.completion === true) {
      console.log(config.listAlias.join('\n'));
      return;
    }

    require('../lib/completion')(argv.completion);
    return;
  }

  var aliasNumber;
  var alias = argv._[0];
  var result;
  dlog("config.alias: ", config.alias);
  if(alias && config.alias[alias]) {
    dlog('found alias for: ' + alias);
    var aliasValue = config.alias[alias];
    dlog('alias:', aliasValue);
    aliasNumber = aliasValue.number;
    result = parsePhoneNumber(aliasNumber.split(' '), debug);
  } else {
    dlog('no alias found');
    result = parsePhoneNumber(argv._, debug);
  }

  if(!result) {
    printHelpMessage();
    var chalk = require('chalk');
    console.log(chalk.red("invalid input... Consider using the --debug parameter to help diagnose issues."));
    return;
  }

  dlog('process.argv:', process.argv);
  dlog('debug:', debug);
  dlog('parsePhoneNumber result: ', result);

  var appleScriptArgs = [ path.join(__dirname, './skypeItAppleScript.scpt'), result.num, result.ext];

  var appleScriptCmd = 'osascript';

  dlog(appleScriptCmd + ' ' + appleScriptArgs.join(' '));

  if(debug) {
    var cmd = spawn(appleScriptCmd, appleScriptArgs);

    cmd.stdout.on('data', function (data) {
      console.log('stdout: ' + data);
    });

    cmd.stderr.on('data', function (data) {
      console.error('stderr: ' + data);
    });

    cmd.on('close', function (code) {
      console.log('child process exited with code ' + code);
    });
  } else {
    var cmd = spawn(appleScriptCmd, appleScriptArgs, {
      detached: true,
      stdio: ['ignore', 'ignore', 'ignore']
    });
    cmd.unref();
  }

};
Skypeit.launch({
  cwd: argv.cwd,
  configPath: argv.myappfile,
  require: argv.require,
  completion: argv.completion
}, invoke);
<|endoftext|>


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

const util = require('util');
const exec = require('child_process').execSync;
const fs = require('fs');
const path = require('path');

const dirs = [
  //Flux
  './app',
  './app/actions',
  './app/constants',
  './app/components',
  './app/dispatcher',
  './app/stores',
  './app/utils',

  //Build
  './public',
  './public/css',
  './public/img',
  './public/js',

  //Jest
  './__tests__'
]

const npms = [
  //Babel
  'npm install --save-dev babel-cli',
  'npm install --save-dev babel-preset-es2015',
  'npm install --save-dev babel-preset-react',

  //React.js
  'npm install --save react',
  'npm install --save react-dom',
  'npm install --save-dev react-addons-css-transition-group',
  'npm install --save-dev react-addons-test-utils',
  'npm install --save-dev react-addons-perf',

  //Flux
  'npm install --save flux',

  //Immutable.js
  'npm install --save immutable',

  //Jest
  'npm install --save-dev jest-cli',
  'npm install --save-dev babel-jest',
  'npm install --save-dev babel-polyfill',

  //WebPack
  'npm install --save-dev webpack',
  'npm install --save-dev webpack-dev-server',
  'npm install --save-dev babel-loader',

  //ESLint
  'npm install --save-dev eslint',
  'npm install --save-dev eslint-plugin-import',
  'npm install --save-dev eslint-plugin-react',
  'npm install --save-dev eslint-plugin-jsx-a11y',
  'npm install --save-dev eslint-config-airbnb'
]

const npms_plus = [
  'npm install --save react-tap-event-plugin',
  'npm install --save material-ui',
  'npm install --save react-router',
  'npm install --save axios'
]

const repository = {
  "type":"git",
  "url":"https://example.com"
};

const jest = {
  "unmockedModulePathPatterns": [
    "<rootDir>/node_modules/react",
    "<rootDir>/node_modules/react-dom",
    "<rootDir>/node_modules/react-addons-test-utils"
  ]
};

const scripts = {
  "start": "webpack-dev-server -d --progress --colors --display-error-details",
  "build": "NODE_ENV=production node_modules/.bin/webpack -p --progress --colors",
  "test": "jest",
  "lint": "eslint app/**"
};

const eslint = {
    "extends": "airbnb",
    "plugins": [
        "react"
    ]
}

const webpackConfig =
`const webpack = require('webpack');

const config = {
  devtool: "inline-source-map",
  entry:  __dirname + "/app/App.js",
  output: {
    path: __dirname + "/public",
    filename: "bundle.js"
  },
  module: {
    loaders: [{
      test: /\.jsx?$/,
      exclude: /node_modules/,
      loader: "babel",
      query: {
        presets: ["es2015","react"]
      }
    }]
  },
  devServer: {
    contentBase: "./public",
    colors: true,
    historyApiFallback: true,
    inline: true
  },
}

if (process.env.NODE_ENV === 'production') {
  config.devtool = false;
  config.plugins = [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin({comments: false}),
    new webpack.DefinePlugin({
      'process.env': {NODE_ENV: JSON.stringify('production')}
    })
  ];
};

module.exports = config;
`;

const indexHTML =
`<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="styles.css">

`;

const appJS =
`import React, { Component } from 'react';
import { render } from 'react-dom';
import { Container } from 'flux/utils';
import Sample from './components/Sample';

class App extends Component {
  static getStores() {
    return [];
  }

  static calculateState() {
    return null;
  }

  componentDidMount() {
  }

  render() {
    return (
      <Sample title="World" />
    );
  }
}

const AppContainer = Container.create(App);
render(<AppContainer />, document.getElementById('root'));
`;

const appDispatcherJS =
`import { Dispatcher } from 'flux';

class AppDispatcher extends Dispatcher {
  dispatch(action = {}) {
    super.dispatch(action);
  }
}

export default new AppDispatcher();
`;

const appConstantsJS =
`export const ActionTypes = {
  TYPE_001: 'type-001',
  TYPE_002: 'type-002',
};
`;

const componentSample =
`import React from 'react';

const Sample = (props) => (

Hello

{props.title}

);

Sample.propTypes = {
  title: React.PropTypes.string.isRequired,
};

export default Sample;
`;

const containerSample =
`import React from 'react';

const Sample = (props) => (

Hello

{props.title}

);

Sample.propTypes = {
  title: React.PropTypes.string.isRequired,
};

export default Sample;
`;

const sampleTest =
`jest.unmock('../app/components/Sample');

import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import Sample from '../app/components/Sample'

describe('<Sample />', () => {
  it('displays "Hello World"', () => {
    const app = TestUtils.renderIntoDocument(

        <Sample title="World" />

    );
    const appNode = ReactDOM.findDOMNode(app);
    expect(appNode.textContent).toEqual('HelloWorld');
  });
});
`;

main();

function main() {
  console.log('*** starter-react-flux ***');
  const args = process.argv;
  switch (args.length) {
    case 3:
      if (args[2] == 'init') {
        setupReact();
        setupReactPlus();
        showComplete();
      } else if (args[2] == 'init-basic'){
        setupReact();
        showUsage();
      }
      break;
    case 4:
      if (args[2] == 'generate' && args[3] == 'test') {
        generateComponentTestFiles();
        showComplete();
      } else {
        showUsage();
      }
      break;
    case 5:
      if (args[2] == 'generate' && args[3] == 'store') {
        generateStoreFile(args[4]);
        showComplete();
      } else if (args[2] == 'generate' && args[3] == 'action') {
        generateActionFile(args[4]);
        showComplete();
      } else {
        showUsage();
      }
      break;
    default:
      showUsage();
      break;
  }
}

function showUsage() {
  console.log('Usage:');
  console.log('starter-react-flux init                             : Setup a React/Flux project.');
  console.log('starter-react-flux init-basic                       : Setup a React/Flux project which is limited for Facebook libraries');
  console.log('starter-react-flux generate test                    : Generate tests of components.');
  console.log('starter-react-flux generate store  [Store]          : Generate the Store. ');
  console.log('starter-react-flux generate action [ActionCreators] : Generate the ActionCreators.');
  process.exit(-1);
}

function showComplete() {
  console.log('Completed!');
}

function setupReact(arg) {
  createDirectories(dirs);
  exec('npm init -y', puts);
  fixJSON('package.json', 'description', 'React template.');
  fixJSON('package.json', 'repository', repository);
  fixJSON('package.json', 'jest', jest);
  fixJSON('package.json', 'scripts', scripts);
  createJSON('.eslintrc', eslint);
  createJSON('.babelrc', {"presets":["react", "es2015"]});
  createFile('./public/index.html', indexHTML);
  createFile('./public/css/style.css', '');
  createFile('webpack.config.js', webpackConfig);
  createFile('./app/App.js', appJS);
  createFile('./app/dispatcher/AppDispatcher.js', appDispatcherJS);
  createFile('./app/constants/AppConstants.js', appConstantsJS);
  createFile('./app/components/Sample.js', componentSample);
  createFile('./__tests__/Sample-test.js', sampleTest);
  npmInstall(npms);
}

function setupReactPlus() {
  npmInstall(npms_plus);
}

function generateComponentTestFiles() {
  const basePath = './app/components/';
  const components = getFileNames(basePath);
  for (const i in components) {
    const component = path.parse(components[i]).name;
    const testFile = './__tests__/' + component + '-test.js';
    createFile(testFile, generateComponentTestCode(component));
  }
}

function generateComponentTestCode(module) {
  const testCode =
`jest.unmock('../app/components/${module}');

import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import ${module} from '../app/components/${module}'

describe('<${module} />', () => {
  it('', () => {
    const renderer = TestUtils.createRenderer();
    renderer.render(
      <${module} />
    );
    const dom = renderer.getRenderOutput();
    //expect(dom.props.//PROPS_NAME).toEqual('//TEXT');
  });
});
`
  return testCode;
}

function generateStoreFile(name) {

const code =
`import { ReduceStore } from 'flux/utils';
import { ActionTypes } from '../constants/AppConstants';
import AppDispatcher from '../dispatcher/AppDispatcher';
import Immutable from 'immutable';

class ${name} extends ReduceStore {
  getInitialState() {
    return [];
  }

  reduce(state, action) {
    switch (action.type) {
      case ActionTypes.TYPE_001:
        return state;
      default:
        return state;
    }
  }
}

export default new ${name}(AppDispatcher);
`;

  createFile(`./app/stores/${name}.js`, code);
}

function generateActionFile(name) {

const code =
`import AppDispatcher from '../dispatcher/AppDispatcher';
import { ActionTypes } from '../constants/AppConstants';

const ${name}ActionCreators = {

  action001(arg1) {
    //
    // Do something and pass the result to the data in the dispatch.
    //
    AppDispatcher.dispatch({
      type: ActionTypes.TYPE_001,
      data: 'RESULT OF YOUT ACTION',
    });
  },

  action002(arg1) {
    AppDispatcher.dispatch({
      type: ActionTypes.TYPE_002,
      data: 'RESULT OF YOUT ACTION',
    });
  },

};

export default ${name}ActionCreators;
`;

  createFile(`./app/actions/${name}ActionCreators.js`, code);
}

function getFileNames(dir) {
  if (fs.existsSync(dir)) {
    return fs.readdirSync(dir);
  }
  return [];
}

function createDirectories(dirs) {
  dirs.map(function(dir) {
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir);
      console.log('Create:', dir);
    }
  })
}

function npmInstall(npms) {
  npms.map(command => {
    console.log(command);
    exec(command, puts);
  });
}

function puts(error, stdout, stderr) {
  util.puts(stdout);
  util.puts(stderr);
  util.puts(error);
}

function createFile(file, content) {
  if (!fs.existsSync(file)) {
    fs.writeFileSync(file, content);
    console.log('Create:', file);
  }
}

function createJSON(file, json) {
  if (!fs.existsSync(file)) {
    fs.writeFileSync(file, JSON.stringify(json, null, "  "));
    console.log('Create:', file);
  }
}

function fixJSON(file, key, value) {
  var json = JSON.parse(fs.readFileSync(file));
  json[key] = value;
  fs.writeFileSync(file, JSON.stringify(json, null, "  "));
  console.log('Fix:', file, 'Key:', key);
}

<commit_msg>bug fix<commit_after>#!/usr/bin/env node

const util = require('util');
const exec = require('child_process').execSync;
const fs = require('fs');
const path = require('path');

const dirs = [
  //Flux
  './app',
  './app/actions',
  './app/constants',
  './app/components',
  './app/dispatcher',
  './app/stores',
  './app/utils',

  //Build
  './public',
  './public/css',
  './public/img',
  './public/js',

  //Jest
  './__tests__'
]

const npms = [
  //Babel
  'npm install --save-dev babel-cli',
  'npm install --save-dev babel-preset-es2015',
  'npm install --save-dev babel-preset-react',

  //React.js
  'npm install --save react',
  'npm install --save react-dom',
  'npm install --save-dev react-addons-css-transition-group',
  'npm install --save-dev react-addons-test-utils',
  'npm install --save-dev react-addons-perf',

  //Flux
  'npm install --save flux',

  //Immutable.js
  'npm install --save immutable',

  //Jest
  'npm install --save-dev jest-cli',
  'npm install --save-dev babel-jest',
  'npm install --save-dev babel-polyfill',

  //WebPack
  'npm install --save-dev webpack',
  'npm install --save-dev webpack-dev-server',
  'npm install --save-dev babel-loader',

  //ESLint
  'npm install --save-dev eslint',
  'npm install --save-dev eslint-plugin-import',
  'npm install --save-dev eslint-plugin-react',
  'npm install --save-dev eslint-plugin-jsx-a11y',
  'npm install --save-dev eslint-config-airbnb'
]

const npms_plus = [
  'npm install --save react-tap-event-plugin',
  'npm install --save material-ui',
  'npm install --save react-router',
  'npm install --save axios'
]

const repository = {
  "type":"git",
  "url":"https://example.com"
};

const jest = {
  "unmockedModulePathPatterns": [
    "<rootDir>/node_modules/react",
    "<rootDir>/node_modules/react-dom",
    "<rootDir>/node_modules/react-addons-test-utils"
  ]
};

const scripts = {
  "start": "webpack-dev-server -d --progress --colors --display-error-details",
  "build": "NODE_ENV=production node_modules/.bin/webpack -p --progress --colors --display-error-details",
  "test": "jest",
  "lint": "eslint app/**"
};

const eslint = {
    "extends": "airbnb",
    "plugins": [
        "react"
    ]
}

const webpackConfig =
`const webpack = require('webpack');

const config = {
  devtool: "inline-source-map",
  entry:  __dirname + "/app/App.js",
  output: {
    path: "./public/js/",
    publicPath: "/js/",
    filename: "bundle.js"
  },
  module: {
    loaders: [{
      test: /\.jsx?$/,
      exclude: /node_modules/,
      loader: "babel",
      query: {
        presets: ["es2015","react"]
      }
    }]
  },
  devServer: {
    contentBase: "./public",
    colors: true,
    historyApiFallback: true,
    inline: true
  },
}

if (process.env.NODE_ENV === 'production') {
  config.devtool = false;
  config.plugins = [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin({comments: false}),
    new webpack.DefinePlugin({
      'process.env': {NODE_ENV: JSON.stringify('production')}
    })
  ];
};

module.exports = config;
`;

const indexHTML =
`<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="./css/style.css">

`;

const appJS =
`import React, { Component } from 'react';
import { render } from 'react-dom';
import { Container } from 'flux/utils';
import Sample from './components/Sample';

class App extends Component {
  static getStores() {
    return [];
  }

  static calculateState() {
    return null;
  }

  componentDidMount() {
  }

  render() {
    return (
      <Sample title="World" />
    );
  }
}

const AppContainer = Container.create(App);
render(<AppContainer />, document.getElementById('root'));
`;

const appDispatcherJS =
`import { Dispatcher } from 'flux';

class AppDispatcher extends Dispatcher {
  dispatch(action = {}) {
    super.dispatch(action);
  }
}

export default new AppDispatcher();
`;

const appConstantsJS =
`export const ActionTypes = {
  TYPE_001: 'type-001',
  TYPE_002: 'type-002',
};
`;

const componentSample =
`import React from 'react';

const Sample = (props) => (

Hello

{props.title}

);

Sample.propTypes = {
  title: React.PropTypes.string.isRequired,
};

export default Sample;
`;

const containerSample =
`import React from 'react';

const Sample = (props) => (

Hello

{props.title}

);

Sample.propTypes = {
  title: React.PropTypes.string.isRequired,
};

export default Sample;
`;

const sampleTest =
`jest.unmock('../app/components/Sample');

import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import Sample from '../app/components/Sample'

describe('<Sample />', () => {
  it('displays "Hello World"', () => {
    const app = TestUtils.renderIntoDocument(

        <Sample title="World" />

    );
    const appNode = ReactDOM.findDOMNode(app);
    expect(appNode.textContent).toEqual('HelloWorld');
  });
});
`;

main();

function main() {
  console.log('*** starter-react-flux ***');
  const args = process.argv;
  switch (args.length) {
    case 3:
      if (args[2] == 'init') {
        setupReact();
        setupReactPlus();
        showComplete();
      } else if (args[2] == 'init-basic'){
        setupReact();
        showUsage();
      }
      break;
    case 4:
      if (args[2] == 'generate' && args[3] == 'test') {
        generateComponentTestFiles();
        showComplete();
      } else {
        showUsage();
      }
      break;
    case 5:
      if (args[2] == 'generate' && args[3] == 'store') {
        generateStoreFile(args[4]);
        showComplete();
      } else if (args[2] == 'generate' && args[3] == 'action') {
        generateActionFile(args[4]);
        showComplete();
      } else {
        showUsage();
      }
      break;
    default:
      showUsage();
      break;
  }
}

function showUsage() {
  console.log('Usage:');
  console.log('starter-react-flux init                             : Setup a React/Flux project.');
  console.log('starter-react-flux init-basic                       : Setup a React/Flux project which is limited for Facebook libraries');
  console.log('starter-react-flux generate test                    : Generate tests of components.');
  console.log('starter-react-flux generate store  [Store]          : Generate the Store. ');
  console.log('starter-react-flux generate action [ActionCreators] : Generate the ActionCreators.');
  process.exit(-1);
}

function showComplete() {
  console.log('Completed!');
}

function setupReact(arg) {
  createDirectories(dirs);
  exec('npm init -y', puts);
  fixJSON('package.json', 'description', 'React template.');
  fixJSON('package.json', 'repository', repository);
  fixJSON('package.json', 'jest', jest);
  fixJSON('package.json', 'scripts', scripts);
  createJSON('.eslintrc', eslint);
  createJSON('.babelrc', {"presets":["react", "es2015"]});
  createFile('./public/index.html', indexHTML);
  createFile('./public/css/style.css', '');
  createFile('webpack.config.js', webpackConfig);
  createFile('./app/App.js', appJS);
  createFile('./app/dispatcher/AppDispatcher.js', appDispatcherJS);
  createFile('./app/constants/AppConstants.js', appConstantsJS);
  createFile('./app/components/Sample.js', componentSample);
  createFile('./__tests__/Sample-test.js', sampleTest);
  npmInstall(npms);
}

function setupReactPlus() {
  npmInstall(npms_plus);
}

function generateComponentTestFiles() {
  const basePath = './app/components/';
  const components = getFileNames(basePath);
  for (const i in components) {
    const component = path.parse(components[i]).name;
    const testFile = './__tests__/' + component + '-test.js';
    createFile(testFile, generateComponentTestCode(component));
  }
}

function generateComponentTestCode(module) {
  const testCode =
`jest.unmock('../app/components/${module}');

import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import ${module} from '../app/components/${module}'

describe('<${module} />', () => {
  it('', () => {
    const renderer = TestUtils.createRenderer();
    renderer.render(
      <${module} />
    );
    const dom = renderer.getRenderOutput();
    //expect(dom.props.//PROPS_NAME).toEqual('//TEXT');
  });
});
`
  return testCode;
}

function generateStoreFile(name) {

const code =
`import { ReduceStore } from 'flux/utils';
import { ActionTypes } from '../constants/AppConstants';
import AppDispatcher from '../dispatcher/AppDispatcher';
import Immutable from 'immutable';

class ${name} extends ReduceStore {
  getInitialState() {
    return [];
  }

  reduce(state, action) {
    switch (action.type) {
      case ActionTypes.TYPE_001:
        return state;
      default:
        return state;
    }
  }
}

export default new ${name}(AppDispatcher);
`;

  createFile(`./app/stores/${name}.js`, code);
}

function generateActionFile(name) {

const code =
`import AppDispatcher from '../dispatcher/AppDispatcher';
import { ActionTypes } from '../constants/AppConstants';

const ${name}ActionCreators = {

  action001(arg1) {
    //
    // Do something and pass the result to the data in the dispatch.
    //
    AppDispatcher.dispatch({
      type: ActionTypes.TYPE_001,
      data: 'RESULT OF YOUT ACTION',
    });
  },

  action002(arg1) {
    AppDispatcher.dispatch({
      type: ActionTypes.TYPE_002,
      data: 'RESULT OF YOUT ACTION',
    });
  },

};

export default ${name}ActionCreators;
`;

  createFile(`./app/actions/${name}ActionCreators.js`, code);
}

function getFileNames(dir) {
  if (fs.existsSync(dir)) {
    return fs.readdirSync(dir);
  }
  return [];
}

function createDirectories(dirs) {
  dirs.map(function(dir) {
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir);
      console.log('Create:', dir);
    }
  })
}

function npmInstall(npms) {
  npms.map(command => {
    console.log(command);
    exec(command, puts);
  });
}

function puts(error, stdout, stderr) {
  util.puts(stdout);
  util.puts(stderr);
  util.puts(error);
}

function createFile(file, content) {
  if (!fs.existsSync(file)) {
    fs.writeFileSync(file, content);
    console.log('Create:', file);
  }
}

function createJSON(file, json) {
  if (!fs.existsSync(file)) {
    fs.writeFileSync(file, JSON.stringify(json, null, "  "));
    console.log('Create:', file);
  }
}

function fixJSON(file, key, value) {
  var json = JSON.parse(fs.readFileSync(file));
  json[key] = value;
  fs.writeFileSync(file, JSON.stringify(json, null, "  "));
  console.log('Fix:', file, 'Key:', key);
}

<|endoftext|>


<commit_before>#!/usr/bin/env

const meow = require('meow');
const SharpBot = require('..');

const envPaths = require('env-paths');
const paths = envPaths('SharpBot', { suffix: '' });

const wait = ms => new Promise(_ => setTimeout(_, ms));

const start = (config = {}) => {
    let bot = new SharpBot(config);

    bot.once('sharpbot-shutdown', async reboot => {
        if (reboot) {
            console.log('Process has exited. Rebooting... (3 seconds)');
            await wait(3000);
            start();
        } else {
            console.log('Bot has exited cleanly.');
        }
    });

    bot.start();
};

const cli = meow(
    `
    Usage
      $ sharpbot

    Options
      --configDir, -c <folder>
        What folder to use for storing the config files.

      --dataDir, -d <folder>
        What folder to use for storing the data files.

      --token, -t <token>
        What user token to use.

      --prefix, -p <prefix>
        What prefix to use.

      --debug, -D
        Debug SharpBot and report the results.

      --config, -C
        Run the SharpBot configuration wizard.
`,
    {
        configDir: {
            alias: 'c',
            type: 'string'
        },
        dataDir: {
            alias: 'd',
            type: 'string'
        },
        token: {
            alias: 't',
            type: 'string'
        },
        prefix: {
            alias: 'p',
            type: 'string'
        },
        debug: {
            alias: 'D',
            type: 'boolean'
        },
        config: {
            alias: 'C',
            type: 'boolean'
        }
    }
);

global.settings = {
    dataFolder: cli.flags.dataDir || paths.data,
    configsFolder: cli.flags.configDir || paths.config
};

const main = () => {
    if (cli.flags.debug) {
        return require('../src/scripts/debug');
    } else if (cli.flags.config) {
        return require('../src/scripts/configure');
    } else {
        let { token: botToken, prefix } = cli.flags;

        start({ botToken, prefix });
    }
};

main();
<commit_msg>Made launcher executable<commit_after>#!/usr/bin/env

const meow = require('meow');
const SharpBot = require('..');

const envPaths = require('env-paths');
const paths = envPaths('SharpBot', { suffix: '' });

const wait = ms => new Promise(_ => setTimeout(_, ms));

const start = (config = {}) => {
    let bot = new SharpBot(config);

    bot.once('sharpbot-shutdown', async reboot => {
        if (reboot) {
            console.log('Process has exited. Rebooting... (3 seconds)');
            await wait(3000);
            start();
        } else {
            console.log('Bot has exited cleanly.');
        }
    });

    bot.start();
};

const cli = meow(
    `
    Usage
      $ sharpbot

    Options
      --configDir, -c <folder>
        What folder to use for storing the config files.

      --dataDir, -d <folder>
        What folder to use for storing the data files.

      --token, -t <token>
        What user token to use.

      --prefix, -p <prefix>
        What prefix to use.

      --debug, -D
        Debug SharpBot and report the results.

      --config, -C
        Run the SharpBot configuration wizard.
`,
    {
        configDir: {
            alias: 'c',
            type: 'string'
        },
        dataDir: {
            alias: 'd',
            type: 'string'
        },
        token: {
            alias: 't',
            type: 'string'
        },
        prefix: {
            alias: 'p',
            type: 'string'
        },
        debug: {
            alias: 'D',
            type: 'boolean'
        },
        config: {
            alias: 'C',
            type: 'boolean'
        }
    }
);

global.settings = {
    dataFolder: cli.flags.dataDir || paths.data,
    configsFolder: cli.flags.configDir || paths.config
};

const main = () => {
    if (cli.flags.debug) {
        return require('../src/scripts/debug');
    } else if (cli.flags.config) {
        return require('../src/scripts/configure');
    } else {
        let { token: botToken, prefix } = cli.flags;

        start({ botToken, prefix });
    }
};

main();
<|endoftext|>


<commit_before>#!/usr/bin/env node
var program = require('commander'),
  pkg = require('../package.json'),
  cwd = process.cwd(),
  fs = require('fs'),
  os = require('os'),
  async = require('async'),
  ncp = require('ncp').ncp,
  colors = require('colors');

program
  .version(pkg.version)
  .usage('[command] <parameters ...>')
  .option('-v, --verbose', ' be verbose')
;

program
  .command('create')
  .description('Create basic application structure in current directory')
  .action(function () {
    console.log('Creating you Kabam project!'.green);
    console.log('Enter values required and press ' + 'Enter'.green);
    //checking if directory is empty
    var dir = fs.readdirSync(process.cwd());
    if (dir.length === 0) {
      async.series({
        'projectName': function (cb) {
          program.prompt('What is the name of your project? Default is "my-kabam-project": ', function (name) {
            cb(null, name);
          });
        },
        'hostUrl': function (cb) {
          program.prompt('What is the hostname of your server? Default is "http://' + os.hostname() + '/": ', function (name) {
            cb(null, name);
          });
        },
        'mongoUrl': function (cb) {
          program.prompt('What is the mongoUrl of your project? Default is "mongo://localhost/kabam_dev" or it can be extracted from environment values: ', function (name) {
            cb(null, name);
          });
        },
        'redisUrl': function (cb) {
          program.prompt('What is the redis url of your project? Default is "redis://localhost:6379" or it can be extracted from environment values: ', function (name) {
            cb(null, name);
          });
        },
        'gitHubName': function (cb) {
          program.prompt('What is your github username?: ', function (name) {
            cb(null, name);
          });
        }
      }, function (err, input) {
                async.parallel({
          'createConfigJson':function(cb){
            var config = {
              'emailConfig': 'myemail@gmail.com:myLoooongPassword',
              "passport": {
              "GITHUB_CLIENT_ID": "--insert-github-client-id-here--",
                "GITHUB_CLIENT_SECRET": "--insert-github-client-secret-here--",
                "TWITTER_CONSUMER_KEY": "--insert-twitter-consumer-key-here--",
                "TWITTER_CONSUMER_SECRET": "--insert-twitter-consumer-secret-here--",
                "FACEBOOK_APP_ID": "--insert-facebook-app-id-here--",
                "FACEBOOK_APP_SECRET": "--insert-facebook-app-secret-here--"
            },
              "spine": {
              'domains': ['urgentTasks']
            }};

            if(input.hostUrl){
              config.hostUrl = input.hostUrl;
            } else {
              config.hostUrl = os.hostname();
            }

            if(input.mongoUrl){
              config.mongoUrl = input.mongoUrl;
            } else {
              config.mongoUrl = 'mongo://localhost/kabam_dev';
            }

            if(input.redisUrl){
              config.redisUrl = input.redisUrl;
            } else {
              config.redisUrl = 'redis://localhost:6379';
            }

            fs.writeFile(process.cwd()+'/config.json',JSON.stringify(config, null, 2),cb);
          },
          'createPackagejson':function(cb){
            var
              projectName = (input.projectName)?(input.projectName):'my-kabam-project',
              gitHubName = (input.gitHubName)?(input.gitHubName):'johgdoe',
              packageJson = {
              "name": projectName,
              "version": "0.0.1",
              "description": "My Kabam project",
              "main": "index.js",
              "engines": {
                "node": "0.10.x",
                "npm": "1.3.x"
              },
              "scripts": {
                "start": "node index.js"
              },
              "bin":{
                "kabam":"bin/kabam.js"
              },
              "repository": {
                "type": "git",
                "url": "git://github.com/"+gitHubName+"/"+projectName+".git"
              },
              "keywords": [],
              "author": (input.gitHubName)?(input.gitHubName):'johgdoe',
              "license": "MIT",
              "contributors": [
                {
                  "name": gitHubName,
                  "url": "https://github.com/"+gitHubName
                }
              ],
              "dependencies": {
                "async": "*",
                "commander":"1.3.2",
                "ncp":"*",
                "colors":"*",
                "kabam": "git+https://github.com/mykabam/kabam.git"
              },
              "devDependencies": {},
              "bugs": {
                "url": "https://github.com/"+gitHubName+"/"+projectName+"/issues"
              }
            };
            fs.writeFile(process.cwd()+'/package.json',JSON.stringify(packageJson, null, 2),cb);
          },
          'moveFiles':function(cb){
            ncp(__dirname+'/../skel', process.cwd(), {'clobber':true}, cb);
          }
        },function(err,actionsDone){
          if(err) throw err;
          console.log('Project created!'.green);
          process.exit(0);
        });

      });
    } else {
      console.error('This directory is not empty! Unable to process'.red);
      process.exit(1);
    }
  });

program
  .command('publishAssets')
  .description('Publish modules templates, css, javascripts and images')
  .action(function () {
    console.log('Publishing...');
    process.exit(0);
  });

program
  .command('procfile')
  .description('create Procfile for Foreman or nodeForeman')
  .action(function () {
    if (packageJson.scripts && packageJson.scripts.start) {
      var startCommand = packageJson.scripts.start;
//      console.log('We found command to start this application  - '+startCommand);

      var procFileText = 'web: ' + startCommand + '\n';
      fs.exists(cwd + '/Procfile', function (isExists) {
        if (isExists) {
          console.error('We already have Procfile created!'.red);
          process.exit(1);
        } else {
//          console.log('Trying to write');
//          console.log(procFileText);
//          console.log(cwd+'/Procfile');

          fs.writeFile(cwd + '/Procfile', procFileText, function (err) {
            if (err) {
              throw err;
            }
            console.log('Procfile created successfully! You can edit it if you want.'.green);
            process.exit(0);
          });
        }
      });

    } else {
      console.error('We need this project to be run by `npm start`'.red);
      process.exit(1);
    }
  });

program.on('--help', function () {
  console.log(' Examples');
  console.log((' $ kabam create').bold);
  console.log((' $ kabam procfile').bold);
});

console.log(('Kabam-Cli version ' + pkg.version).bold.yellow.redBG);
program.parse(process.argv);

if (process.argv.length === 2) {
  program.outputHelp();
}

<commit_msg>[fix] small fixes in console program<commit_after>#!/usr/bin/env node
var program = require('commander'),
  pkg = require('../package.json'),
  cwd = process.cwd(),
  fs = require('fs'),
  os = require('os'),
  async = require('async'),
  ncp = require('ncp').ncp,
  colors = require('colors');

program
  .version(pkg.version)
  .usage('[command] <parameters ...>')
  .option('-v, --verbose', ' be verbose')
;

program
  .command('create')
  .description('Create basic application structure in current directory')
  .action(function () {
    console.log('Creating you Kabam project!'.green);
    console.log('Enter values required and press ' + 'Enter'.green);
    //checking if directory is empty
    var dir = fs.readdirSync(process.cwd());
    if (dir.length === 0) {
      async.series({
        'projectName': function (cb) {
          program.prompt('What is the name of your project? Default is "my-kabam-project": ', function (name) {
            cb(null, name);
          });
        },
        'hostUrl': function (cb) {
          program.prompt('What is the hostname of your server? Default is "' +(''+ os.hostname()+'').green+ '": ', function (name) {
            cb(null, name);
          });
        },
        'mongoUrl': function (cb) {
          program.prompt('What is the mongoUrl of your project? Default is "mongo://localhost/kabam_dev" or it can be extracted from environment values: ', function (name) {
            cb(null, name);
          });
        },
        'redisUrl': function (cb) {
          program.prompt('What is the redis url of your project? Default is "redis://localhost:6379" or it can be extracted from environment values: ', function (name) {
            cb(null, name);
          });
        },
        'gitHubName': function (cb) {
          program.prompt('What is your github username?: ', function (name) {
            cb(null, name);
          });
        }
      }, function (err, input) {
                async.parallel({
          'createConfigJson':function(cb){
            var config = {
              'emailConfig': 'myemail@gmail.com:myLoooongPassword',
              "passport": {
              "GITHUB_CLIENT_ID": "--insert-github-client-id-here--",
                "GITHUB_CLIENT_SECRET": "--insert-github-client-secret-here--",
                "TWITTER_CONSUMER_KEY": "--insert-twitter-consumer-key-here--",
                "TWITTER_CONSUMER_SECRET": "--insert-twitter-consumer-secret-here--",
                "FACEBOOK_APP_ID": "--insert-facebook-app-id-here--",
                "FACEBOOK_APP_SECRET": "--insert-facebook-app-secret-here--"
            },
              "spine": {
              'domains': ['urgentTasks']
            }};

            if(input.hostUrl){
              config.hostUrl = input.hostUrl;
            } else {
              config.hostUrl = os.hostname();
            }

            if(input.mongoUrl){
              config.mongoUrl = input.mongoUrl;
            } else {
              config.mongoUrl = 'mongo://localhost/kabam_dev';
            }

            if(input.redisUrl){
              config.redisUrl = input.redisUrl;
            } else {
              config.redisUrl = 'redis://localhost:6379';
            }

            fs.writeFile(process.cwd()+'/config.json',JSON.stringify(config, null, 2),cb);
          },
          'createPackagejson':function(cb){
            var
              projectName = (input.projectName)?(input.projectName):'my-kabam-project',
              gitHubName = (input.gitHubName)?(input.gitHubName):'johgdoe',
              packageJson = {
              "name": projectName,
              "version": "0.0.1",
              "description": "My Kabam project",
              "main": "index.js",
              "engines": {
                "node": "0.10.x",
                "npm": "1.3.x"
              },
              "scripts": {
                "start": "node index.js"
              },
              "bin":{
                "kabam":"bin/kabam.js"
              },
              "repository": {
                "type": "git",
                "url": "git://github.com/"+gitHubName+"/"+projectName+".git"
              },
              "keywords": [],
              "author": gitHubName,
              "license": "MIT",
              "contributors": [
                {
                  "name": gitHubName,
                  "url": "https://github.com/"+gitHubName
                }
              ],
              "dependencies": {
                "async": "*",
                "commander":"1.3.2",
                "ncp":"*",
                "colors":"*",
                "kabam": "git+https://github.com/mykabam/kabam.git"
              },
              "devDependencies": {},
              "bugs": {
                "url": "https://github.com/"+gitHubName+"/"+projectName+"/issues"
              }
            };
            fs.writeFile(process.cwd()+'/package.json',JSON.stringify(packageJson, null, 2),cb);
          },
          'moveFiles':function(cb){
            ncp(__dirname+'/../skel', process.cwd(), {'clobber':true}, cb);
          }
        },function(err,actionsDone){
          if(err) throw err;
          console.log('Project created!'.green);
          process.exit(0);
        });

      });
    } else {
      console.error('This directory is not empty! Unable to process'.red);
      process.exit(1);
    }
  });

program
  .command('publishAssets')
  .description('Publish modules templates, css, javascripts and images')
  .action(function () {
    console.log('Publishing...');
    process.exit(0);
  });

program
  .command('procfile')
  .description('create Procfile for Foreman or nodeForeman')
  .action(function () {
    if (packageJson.scripts && packageJson.scripts.start) {
      var startCommand = packageJson.scripts.start;
//      console.log('We found command to start this application  - '+startCommand);

      var procFileText = 'web: ' + startCommand + '\n';
      fs.exists(cwd + '/Procfile', function (isExists) {
        if (isExists) {
          console.error('We already have Procfile created!'.red);
          process.exit(1);
        } else {
//          console.log('Trying to write');
//          console.log(procFileText);
//          console.log(cwd+'/Procfile');

          fs.writeFile(cwd + '/Procfile', procFileText, function (err) {
            if (err) {
              throw err;
            }
            console.log('Procfile created successfully! You can edit it if you want.'.green);
            process.exit(0);
          });
        }
      });

    } else {
      console.error('We need this project to be run by `npm start`'.red);
      process.exit(1);
    }
  });

program.on('--help', function () {
  console.log(' Examples');
  console.log((' $ kabam create').bold);
  console.log((' $ kabam procfile').bold);
});

console.log(('Kabam-Cli version ' + pkg.version).bold.yellow.redBG);
program.parse(process.argv);

if (process.argv.length === 2) {
  program.outputHelp();
}

<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 *  WSO2 Inc. licenses this file to you under the Apache License,
 *  Version 2.0 (the "License"); you may not use this file except
 *  in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.w   See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 *
 */

var resources = function (page, meta) {
    return {
        js:['flowchart/jsPlumb-2.0.7.js','libs/jquery.form.min.js','publisher-utils.js','create_asset.js','jquery-ui.js',
            'jquery-file-upload/alertify.js','jquery-file-upload/bootstrap-filestyle.js','jquery.cookie.js','common/option_text.js',
            "tinymce/tinymce.min.js",'tags/tags-init-create-asset.js','notify.min.js','messages.js',
            'jquery-file-upload/jquery.iframe-transport.js','jquery-file-upload/jquery.fileupload.js',
            'jquery-file-upload/vendor/jquery.ui.widget.js','create-asset-functions.js','flowchart/create-flowchart.js',
            'auto-complete-tags/bootstrap-tokenfield.min.js'
        ],

        css:['flowchart/jsPlumb-defaults.css','flowchart/jsPlumb-demo.css','bootstrap-select.min.css',
            'alertify.css','default.css','datepick/smoothness.datepick.css','grid.css',
            'select2.min.css','jquery-ui.css','flowchart/flowchart.css','font-awesome.css',
            'auto-complete-tags/bootstrap-tokenfield.min.css',
            'auto-complete-tags/tokenfield-typehead.min.css'],
        code: ['publisher.assets.hbs']
    };
};

<commit_msg>Removed empty lines in create_asset.js file<commit_after>/*
 *  Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 *  WSO2 Inc. licenses this file to you under the Apache License,
 *  Version 2.0 (the "License"); you may not use this file except
 *  in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.w   See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 *
 */

var resources = function (page, meta) {
    return {
        js:['flowchart/jsPlumb-2.0.7.js','libs/jquery.form.min.js','publisher-utils.js','create_asset.js','jquery-ui.js',
            'jquery-file-upload/alertify.js','jquery-file-upload/bootstrap-filestyle.js','jquery.cookie.js','common/option_text.js',
            "tinymce/tinymce.min.js",'tags/tags-init-create-asset.js','notify.min.js','messages.js',
            'jquery-file-upload/jquery.iframe-transport.js','jquery-file-upload/jquery.fileupload.js',
            'jquery-file-upload/vendor/jquery.ui.widget.js','create-asset-functions.js','flowchart/create-flowchart.js',
            'auto-complete-tags/bootstrap-tokenfield.min.js'
        ],
        css:['flowchart/jsPlumb-defaults.css','flowchart/jsPlumb-demo.css','bootstrap-select.min.css',
            'alertify.css','default.css','datepick/smoothness.datepick.css','grid.css',
            'select2.min.css','jquery-ui.css','flowchart/flowchart.css','font-awesome.css',
            'auto-complete-tags/bootstrap-tokenfield.min.css',
            'auto-complete-tags/tokenfield-typehead.min.css'],
        code: ['publisher.assets.hbs']
    };
};

<|endoftext|>


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

"use strict";

var fs = require ("fs");
var readLine = require ("readline");
var argp = require ("argp");
var statusBar = require ("status-bar");
var ntftp = require ("../lib");

var client;
var rl;
var timer;
var read;
var write;

//The main parser is not cached
argp.createParser ()
    .readPackage (__dirname + "/../package.json")
    .usages (["ntftp [options] <host>[:<port>]"])
    .allowUndefinedArguments ()
    .on ("argument", function (argv, argument, ignore){
      if (argv.server) this.fail ("Too many arguments");
      argument = argument.split (":");
      argv.server = {
        address: argument[0],
        port: argument[1]
      };
      ignore ();
    })
    .on ("end", function (argv){
      if (!argv.server) this.fail ("Missing server address");
      createClient (argv);
    })
    .footer ("By default this client sends some known option extensions " +
            "trying to achieve the best performance. If the remote server " +
            "doesn't support option extensions, it automatically fallbacks " +
            "to a pure RFC 1350 compliant TFTP client implementation.")
    .body ()
        .text ("Once ntftp is running, it shows a prompt and recognizes the " +
            "following commands:")
        .text ("> get <remote> [<local>]", "  ")
        .text ("Gets a file from the remote server.", "    ")
        .text ("\n> put <local> [<remote>]", "  ")
        .text ("Puts a file to the remote server.", "    ")
        .text ("\nTo quit the program press ctrl-c two times.")

        .text ("\nExample:")
        .text ("$ ntftp localhost -w 4 --blksize 256", "  ")
        .text ("> get remote_file", "  ")
        .text ("> get --md5sum 1234 remote_file local_file", "  ")
        .text ("> put path/to/local_file remote_file", "  ")

        .text ("\nArguments:")
        .columns ("  <host>[:<port>]", "The address and port of the remote " +
            "server, eg.\n$ ntftp localhost:1234. Default port is 69")

        .text ("\nOptions:")
        .option ({ short: "b", long: "blksize", metavar: "SIZE",
            type: Number, description: "Sets the blksize option extension. " +
            "Valid range: [8, 65464]. Default is 1468, the size before IP " +
            "fragmentation in Ethernet environments"})
        .option ({ short: "r", long: "retries", metavar: "NUM",
            type: Number, description: "Number of retries before finishing " +
            "the transfer of the file due to an unresponsive server or a " +
            "massive packet loss"})
        .option ({ short: "t", long: "timeout", metavar: "MILLISECONDS",
            type: Number, description: "Sets the timeout option extension. " +
            "Default is 3000ms"})
        .option ({ short: "w", long: "windowsize", metavar: "SIZE",
            type: Number, description: "Sets the windowsize option " +
            "extension. Valid range: [1, 65535]. Default is 64"})

        .help ()
        .argv ();

function notifyError (str){
  console.error ("Error: " + str);
  rl.prompt ();
};

var again = function (){
  timer = setTimeout (function (){
    timer = null;
  }, 3000);

  console.log ("\n(^C again to quit)");
  rl.line = "";
  rl.prompt ();
};

function createCommandParser (){
  //Don't produce errors when undefined arguments and options are
  //introduced, they are simply omitted
  return argp.createParser ()
      .main ()
          .allowUndefinedArguments ()
          .allowUndefinedOptions ()
          .on ("end", function (){
            notifyError ("Invalid command");
          })
          .on ("error", function (error){
            notifyError (error.message);
          })
      .command ("get", { trailing: { min: 1, max: 2 } })
          .allowUndefinedArguments ()
          .allowUndefinedOptions ()
          .on ("end", get)
          .on ("error", function (error){
            notifyError (error.message);
          })
      .command ("put", { trailing: { min: 1, max: 2 } })
          .allowUndefinedArguments ()
          .allowUndefinedOptions ()
          .on ("end", put)
          .on ("error", function (error){
            notifyError (error.message);
          });
};

function createClient (argv){
  var parser = createCommandParser ();

  //Default values are not checked in the cli layer. If they are not valid they
  //are set to their default values silently
  client = ntftp.createClient ({
    hostname: argv.server.address,
    port: argv.server.port,
    blockSize: argv.blksize,
    retries: argv.retries,
    timeout: argv.timeout,
    windowSize: argv.windowsize
  });

  var completions = ["get ", "put "];

  //Start prompt
  rl = readLine.createInterface ({
    input: process.stdin,
    output: process.stdout,
    completer: function (line){
      var hits = completions.filter (function (command){
        return command.indexOf (line) === 0;
      });
      return [hits.length ? hits : [], line];
    }
  });
  rl.on ("line", function (line){
    if (!line) return rl.prompt ();
    parser.argv (line.split (" ").filter (function (word){
      return word;
    }));
  });
  rl.on ("SIGINT", function (){
    if (timer) process.exit ();

    //Abort the current transfer
    if (read){
      read.gs.abort ();
    }else if (write){

    }else{
      again ();
    }
  });
  rl.prompt ();
};

function formatFilename (filename){
  //80 - 59
  var filenameMaxLength = 21;
  if (filename.length > filenameMaxLength){
    filename = filename.slice (0, filenameMaxLength - 3) + "...";
  }else{
    var remaining = filenameMaxLength - filename.length;
    while (remaining--){
      filename += " ";
    }
  }
  return filename;
};

function get (argv){
  clearTimeout (timer);
  timer = null;

  try{
    client._checkRemote (argv.get[0]);
  }catch (e){
    return notifyError (e.message);
  }

  var local = argv.get[1] || argv.get[0];

  //Check if local is a dir and prevent from starting a request
  fs.stat (local, function (error, stats){
    if (error){
      if (error.code !== "ENOENT") return notifyError (error.message);
    }else if (stats.isDirectory ()){
      return notifyError ("The local file is a directory");
    }

    read = {};
    read.local = local;

    read.ws = fs.createWriteStream (read.local)
        .on ("error", function (error){
          bar.clearInterval ();
          console.log ();
          read.gs.on ("abort", function (){
            read = null;
            fs.unlink (local, function (){
              notifyError (error.message);
            });
          });
          read.gs.abort ();
        })
        .on ("finish", function (){
          read = null;
          console.log ();
          rl.prompt ();
        });

    var bar;
    var filename = formatFilename (argv.get[0]);
    var extensions = true;

    read.gs = client.createGetStream (argv.get[0]);
    read.gs
        .on ("error", function (error){
          bar.clearInterval ();
          console.log ();
          read.ws.on ("close", function (){
            fs.unlink (read.local, function (){
              read = null;
              notifyError (error.message);
            });
          });
          read.ws.destroy ();
        })
        .on ("abort", function (){
          bar.clearInterval ();
          read.ws.on ("close", function (){
            var local = read.local;
            read = null;
            fs.unlink (local, again);
          });
          read.ws.destroy ();
        })
        .on ("no-extensions", function (){
          process.stdout.write ("no extensions");
        })
        .on ("size", function (size){
          bar = statusBar.create ({
            total: size,
            frequency: 200,
            write: function (){
              process.stdout.write (filename + " " + this.stats.size + " " +
                  this.stats.speed + " " + this.stats.eta + " [" +
                  this.stats.progress + "] " + this.stats.percentage);
              process.stdout.cursorTo (0);
            }
          });
          this.pipe (bar);
        })
        .pipe (read.ws);
  });
};

function put (argv){
  clearTimeout (timer);
  timer = null;

  write = {};

};<commit_msg>added shell support when the server doesn't support extensions<commit_after>#!/usr/bin/env node

"use strict";

var fs = require ("fs");
var readLine = require ("readline");
var argp = require ("argp");
var statusBar = require ("status-bar");
var ntftp = require ("../lib");

var client;
var rl;
var timer;
var read;
var write;

//The main parser is not cached
argp.createParser ()
    .readPackage (__dirname + "/../package.json")
    .usages (["ntftp [options] <host>[:<port>]"])
    .allowUndefinedArguments ()
    .on ("argument", function (argv, argument, ignore){
      if (argv.server) this.fail ("Too many arguments");
      argument = argument.split (":");
      argv.server = {
        address: argument[0],
        port: argument[1]
      };
      ignore ();
    })
    .on ("end", function (argv){
      if (!argv.server) this.fail ("Missing server address");
      createClient (argv);
    })
    .footer ("By default this client sends some known option extensions " +
            "trying to achieve the best performance. If the remote server " +
            "doesn't support option extensions, it automatically fallbacks " +
            "to a pure RFC 1350 compliant TFTP client implementation.")
    .body ()
        .text ("Once ntftp is running, it shows a prompt and recognizes the " +
            "following commands:")
        .text ("> get <remote> [<local>]", "  ")
        .text ("Gets a file from the remote server.", "    ")
        .text ("\n> put <local> [<remote>]", "  ")
        .text ("Puts a file to the remote server.", "    ")
        .text ("\nTo quit the program press ctrl-c two times.")

        .text ("\nExample:")
        .text ("$ ntftp localhost -w 4 --blksize 256", "  ")
        .text ("> get remote_file", "  ")
        .text ("> get --md5sum 1234 remote_file local_file", "  ")
        .text ("> put path/to/local_file remote_file", "  ")

        .text ("\nArguments:")
        .columns ("  <host>[:<port>]", "The address and port of the remote " +
            "server, eg.\n$ ntftp localhost:1234. Default port is 69")

        .text ("\nOptions:")
        .option ({ short: "b", long: "blksize", metavar: "SIZE",
            type: Number, description: "Sets the blksize option extension. " +
            "Valid range: [8, 65464]. Default is 1468, the size before IP " +
            "fragmentation in Ethernet environments"})
        .option ({ short: "r", long: "retries", metavar: "NUM",
            type: Number, description: "Number of retries before finishing " +
            "the transfer of the file due to an unresponsive server or a " +
            "massive packet loss"})
        .option ({ short: "t", long: "timeout", metavar: "MILLISECONDS",
            type: Number, description: "Sets the timeout option extension. " +
            "Default is 3000ms"})
        .option ({ short: "w", long: "windowsize", metavar: "SIZE",
            type: Number, description: "Sets the windowsize option " +
            "extension. Valid range: [1, 65535]. Default is 64"})

        .help ()
        .argv ();

function notifyError (str){
  console.error ("Error: " + str);
  rl.prompt ();
};

var again = function (){
  timer = setTimeout (function (){
    timer = null;
  }, 3000);

  console.log ("\n(^C again to quit)");
  rl.line = "";
  rl.prompt ();
};

function createCommandParser (){
  //Don't produce errors when undefined arguments and options are
  //introduced, they are simply omitted
  return argp.createParser ()
      .main ()
          .allowUndefinedArguments ()
          .allowUndefinedOptions ()
          .on ("end", function (){
            notifyError ("Invalid command");
          })
          .on ("error", function (error){
            notifyError (error.message);
          })
      .command ("get", { trailing: { min: 1, max: 2 } })
          .allowUndefinedArguments ()
          .allowUndefinedOptions ()
          .on ("end", get)
          .on ("error", function (error){
            notifyError (error.message);
          })
      .command ("put", { trailing: { min: 1, max: 2 } })
          .allowUndefinedArguments ()
          .allowUndefinedOptions ()
          .on ("end", put)
          .on ("error", function (error){
            notifyError (error.message);
          });
};

function createClient (argv){
  var parser = createCommandParser ();

  //Default values are not checked in the cli layer. If they are not valid they
  //are set to their default values silently
  client = ntftp.createClient ({
    hostname: argv.server.address,
    port: argv.server.port,
    blockSize: argv.blksize,
    retries: argv.retries,
    timeout: argv.timeout,
    windowSize: argv.windowsize
  });

  var completions = ["get ", "put "];

  //Start prompt
  rl = readLine.createInterface ({
    input: process.stdin,
    output: process.stdout,
    completer: function (line){
      var hits = completions.filter (function (command){
        return command.indexOf (line) === 0;
      });
      return [hits.length ? hits : [], line];
    }
  });
  rl.on ("line", function (line){
    if (!line) return rl.prompt ();
    parser.argv (line.split (" ").filter (function (word){
      return word;
    }));
  });
  rl.on ("SIGINT", function (){
    if (timer) process.exit ();

    //Abort the current transfer
    if (read){
      read.gs.abort ();
    }else if (write){

    }else{
      again ();
    }
  });
  rl.prompt ();
};

function formatFilename (filename){
  //80 - 59
  var filenameMaxLength = 21;
  if (filename.length > filenameMaxLength){
    filename = filename.slice (0, filenameMaxLength - 3) + "...";
  }else{
    var remaining = filenameMaxLength - filename.length;
    while (remaining--){
      filename += " ";
    }
  }
  return filename;
};

function get (argv){
  clearTimeout (timer);
  timer = null;

  try{
    client._checkRemote (argv.get[0]);
  }catch (e){
    return notifyError (e.message);
  }

  var local = argv.get[1] || argv.get[0];

  //Check if local is a dir and prevent from starting a request
  fs.stat (local, function (error, stats){
    if (error){
      if (error.code !== "ENOENT") return notifyError (error.message);
    }else if (stats.isDirectory ()){
      return notifyError ("The local file is a directory");
    }

    read = {};
    read.local = local;

    read.ws = fs.createWriteStream (read.local)
        .on ("error", function (error){
          if (bar) bar.clearInterval ();
          clearInterval (noExtensionsTimer);

          console.log ();

          read.gs.on ("abort", function (){
            read = null;
            fs.unlink (local, function (){
              notifyError (error.message);
            });
          });
          read.gs.abort ();
        })
        .on ("finish", function (){
          read = null;
          clearInterval (noExtensionsTimer);
          console.log ();
          rl.prompt ();
        });

    var bar;
    var filename = formatFilename (argv.get[0]);
    var noExtensionsTimer = null;

    read.gs = client.createGetStream (argv.get[0]);
    read.gs
        .on ("error", function (error){
          if (bar) bar.clearInterval ();
          clearInterval (noExtensionsTimer);

          console.log ();

          read.ws.on ("close", function (){
            fs.unlink (read.local, function (){
              read = null;
              notifyError (error.message);
            });
          });
          read.ws.destroy ();
        })
        .on ("abort", function (){
          if (bar) bar.clearInterval ();
          clearInterval (noExtensionsTimer);

          read.ws.on ("close", function (){
            var local = read.local;
            read = null;
            fs.unlink (local, again);
          });
          read.ws.destroy ();
        })
        .on ("no-extensions", function (){
          var dots = "...";
          var i = 1;
          noExtensionsTimer = setInterval (function (){
            i = i%4;
            process.stdout.clearLine ();
            process.stdout.cursorTo (0);
            process.stdout.write (dots.slice (0, i++));
          }, 200);
        })
        .on ("size", function (size){
          bar = statusBar.create ({
            total: size,
            frequency: 200,
            write: function (){
              process.stdout.write (filename + " " + this.stats.size + " " +
                  this.stats.speed + " " + this.stats.eta + " [" +
                  this.stats.progress + "] " + this.stats.percentage);
              process.stdout.cursorTo (0);
            }
          });
          this.pipe (bar);
        })
        .pipe (read.ws);
  });
};

function put (argv){
  clearTimeout (timer);
  timer = null;

  write = {};

};<|endoftext|>


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

/**
 * Module dependencies
 */

var _ = require('@sailshq/lodash');
var program = require('./private/patched-commander');
var sailsPackageJson = require('../package.json');
var NOOP = function() {};

program
  .version(sailsPackageJson.version, '-v, --version');

//
// Normalize version argument, i.e.
//
// $ sails -v
// $ sails -V
// $ sails --version
// $ sails version
//

// make `-v` option case-insensitive
process.argv = _.map(process.argv, function(arg) {
  return (arg === '-V') ? '-v' : arg;
});

// $ sails version (--version synonym)
program
  .command('version')
  .description('')
  .action(program.versionInformation);

program
  .unknownOption = NOOP;
program.usage('[command]');

// $ sails lift
var cmd;
cmd = program.command('lift');
cmd.option('--prod', 'Lift in "production" environment.');
cmd.option('--staging', 'Lift in "staging" environment.');
cmd.option('--port [port]', 'Listen on the specified port (defaults to 1337).');
cmd.option('--silent', 'Set log level to "silent".');
cmd.option('--verbose', 'Set log level to "verbose".');
cmd.option('--silly', 'Set log level to "silly".');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.alias('l');
cmd.action(require('./sails-lift'));

// $ sails new <appname>
cmd = program.command('new [path_to_new_app]');
// cmd.option('--dry');
cmd.option('--no-front-end', 'Don\'t generate "assets", "views" or "task" folders.');
cmd.option('--fast', 'Don\'t install node modules after generating app.');
cmd.usage('[path_to_new_app]');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.action(require('./sails-new'));

// $ sails generate <module>
cmd = program.command('generate');
// cmd.option('--dry');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.usage('[something]');
cmd.action(require('./sails-generate'));

// $ sails upgrade
cmd = program.command('upgrade');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.action(require('./sails-upgrade'));

// $ sails migrate
cmd = program.command('migrate');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.action(require('./sails-migrate'));

// $ sails console
cmd = program.command('console');
cmd.option('--silent', 'Set log level to "silent".');
cmd.option('--verbose', 'Set log level to "verbose".');
cmd.option('--silly', 'Set log level to "silly".');
cmd.option('--dontLift', 'Start console session without lifting an HTTP server.');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.alias('c');
cmd.action(require('./sails-console'));

// $ sails www
// Compile `assets` directory into a standalone `www` folder.
cmd = program.command('www');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.action(require('./sails-www'));

// $ sails debug
cmd = program.command('debug');
cmd.unknownOption = NOOP;
cmd.description('(for Node v5 and below)');
cmd.action(require('./sails-debug'));

// $ sails inspect
cmd = program.command('inspect');
cmd.unknownOption = NOOP;
cmd.description('(for Node v6 and above)');
cmd.action(require('./sails-inspect'));

// $ sails run
cmd = program.command('run');
cmd.usage('[name-of-script]');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.action(require('./sails-run'));

// $ sails test
cmd = program.command('test');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.action(function(){
  require('./sails-run')('test', _.last(arguments));
});

// $ sails lint
cmd = program.command('lint');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.action(function(){
  require('./sails-run')('lint', _.last(arguments));
});

// - - - - - - - - - - - - - - - - - - - - - - - - - - -
// $ sails deploy
cmd = program.command('deploy');
// cmd.option('--dry');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.usage('');
cmd.action(require('./sails-deploy'));
// FUTURE: ^^ Consider simplifying this into a script.
// - - - - - - - - - - - - - - - - - - - - - - - - - - -

// $ sails debug-console
cmd = program.command('debug-console');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.alias('dc');
cmd.action(require('./sails-debug-console'));

//
// Normalize help argument, i.e.
//
// $ sails --help
// $ sails help
// $ sails
// $ sails <unrecognized_cmd>
//

// $ sails help (--help synonym)
cmd = program.command('help [command]');
cmd.description('');
cmd.action(function(){
  if (program.args.length > 1 && _.isString(program.args[0])) {
    var helpCmd = _.find(program.commands, {_name: program.args[0]});
    if (helpCmd) {
      helpCmd.help();
      return;
    }
  }
  program.help();
});

// $ sails <unrecognized_cmd>
// Output Sails help when an unrecognized command is used.
program
  .command('*')
  .action(function(cmd){
    console.log('\n  ** Unrecognized command:', cmd, '**');
    program.help();
  });

// Don't balk at unknown options
program.unknownOption = NOOP;

// $ sails
//
program.parse(process.argv);
var NO_COMMAND_SPECIFIED = program.args.length === 0;
if (NO_COMMAND_SPECIFIED) {
  program.help();
}
<commit_msg>fix: change typo --no-front-end to --no-frontend in CLI flag help output<commit_after>#!/usr/bin/env node

/**
 * Module dependencies
 */

var _ = require('@sailshq/lodash');
var program = require('./private/patched-commander');
var sailsPackageJson = require('../package.json');
var NOOP = function() {};

program
  .version(sailsPackageJson.version, '-v, --version');

//
// Normalize version argument, i.e.
//
// $ sails -v
// $ sails -V
// $ sails --version
// $ sails version
//

// make `-v` option case-insensitive
process.argv = _.map(process.argv, function(arg) {
  return (arg === '-V') ? '-v' : arg;
});

// $ sails version (--version synonym)
program
  .command('version')
  .description('')
  .action(program.versionInformation);

program
  .unknownOption = NOOP;
program.usage('[command]');

// $ sails lift
var cmd;
cmd = program.command('lift');
cmd.option('--prod', 'Lift in "production" environment.');
cmd.option('--staging', 'Lift in "staging" environment.');
cmd.option('--port [port]', 'Listen on the specified port (defaults to 1337).');
cmd.option('--silent', 'Set log level to "silent".');
cmd.option('--verbose', 'Set log level to "verbose".');
cmd.option('--silly', 'Set log level to "silly".');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.alias('l');
cmd.action(require('./sails-lift'));

// $ sails new <appname>
cmd = program.command('new [path_to_new_app]');
// cmd.option('--dry');
cmd.option('--no-frontend', 'Don\'t generate "assets", "views" or "task" folders.');
cmd.option('--fast', 'Don\'t install node modules after generating app.');
cmd.usage('[path_to_new_app]');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.action(require('./sails-new'));

// $ sails generate <module>
cmd = program.command('generate');
// cmd.option('--dry');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.usage('[something]');
cmd.action(require('./sails-generate'));

// $ sails upgrade
cmd = program.command('upgrade');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.action(require('./sails-upgrade'));

// $ sails migrate
cmd = program.command('migrate');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.action(require('./sails-migrate'));

// $ sails console
cmd = program.command('console');
cmd.option('--silent', 'Set log level to "silent".');
cmd.option('--verbose', 'Set log level to "verbose".');
cmd.option('--silly', 'Set log level to "silly".');
cmd.option('--dontLift', 'Start console session without lifting an HTTP server.');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.alias('c');
cmd.action(require('./sails-console'));

// $ sails www
// Compile `assets` directory into a standalone `www` folder.
cmd = program.command('www');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.action(require('./sails-www'));

// $ sails debug
cmd = program.command('debug');
cmd.unknownOption = NOOP;
cmd.description('(for Node v5 and below)');
cmd.action(require('./sails-debug'));

// $ sails inspect
cmd = program.command('inspect');
cmd.unknownOption = NOOP;
cmd.description('(for Node v6 and above)');
cmd.action(require('./sails-inspect'));

// $ sails run
cmd = program.command('run');
cmd.usage('[name-of-script]');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.action(require('./sails-run'));

// $ sails test
cmd = program.command('test');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.action(function(){
  require('./sails-run')('test', _.last(arguments));
});

// $ sails lint
cmd = program.command('lint');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.action(function(){
  require('./sails-run')('lint', _.last(arguments));
});

// - - - - - - - - - - - - - - - - - - - - - - - - - - -
// $ sails deploy
cmd = program.command('deploy');
// cmd.option('--dry');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.usage('');
cmd.action(require('./sails-deploy'));
// FUTURE: ^^ Consider simplifying this into a script.
// - - - - - - - - - - - - - - - - - - - - - - - - - - -

// $ sails debug-console
cmd = program.command('debug-console');
cmd.unknownOption = NOOP;
cmd.description('');
cmd.alias('dc');
cmd.action(require('./sails-debug-console'));

//
// Normalize help argument, i.e.
//
// $ sails --help
// $ sails help
// $ sails
// $ sails <unrecognized_cmd>
//

// $ sails help (--help synonym)
cmd = program.command('help [command]');
cmd.description('');
cmd.action(function(){
  if (program.args.length > 1 && _.isString(program.args[0])) {
    var helpCmd = _.find(program.commands, {_name: program.args[0]});
    if (helpCmd) {
      helpCmd.help();
      return;
    }
  }
  program.help();
});

// $ sails <unrecognized_cmd>
// Output Sails help when an unrecognized command is used.
program
  .command('*')
  .action(function(cmd){
    console.log('\n  ** Unrecognized command:', cmd, '**');
    program.help();
  });

// Don't balk at unknown options
program.unknownOption = NOOP;

// $ sails
//
program.parse(process.argv);
var NO_COMMAND_SPECIFIED = program.args.length === 0;
if (NO_COMMAND_SPECIFIED) {
  program.help();
}
<|endoftext|>