<commit_before><commit_msg>Add CLI to `cli.js`<commit_after>#!/usr/bin/env node
'use strict';

/*
 * Dependencies.
 */

var stemmer,
    pack;

pack = require('./package.json');
stemmer = require('./');

/*
 * Detect if a value is expected to be piped in.
 */

var expextPipeIn;

expextPipeIn = !process.stdin.isTTY;

/*
 * Arguments.
 */

var argv;

argv = process.argv.slice(2);

/*
 * Command.
 */

var command;

command = Object.keys(pack.bin)[0];

/**
 * Get the distance for a word.
 *
 * @param {Array.<string>} values
 * @return {string}
 */
function stems(values) {
    return values.map(stemmer).join(' ');
}

/**
 * Help.
 *
 * @return {string}
 */
function help() {
    return [
        '',
        'Usage: ' + command + ' [options] <words...>',
        '',
        pack.description,
        '',
        'Options:',
        '',
        '  -h, --help           output usage information',
        '  -v, --version        output version number',
        '',
        'Usage:',
        '',
        '# output stems',
        '$ ' + command + ' considerations',
        '# ' + stems(['considerations']),
        '',
        '# output stems from stdin',
        '$ echo "detestable vileness" | ' + command,
        '# ' + stems(['detestable', 'vileness']),
        ''
    ].join('\n  ') + '\n';
}

/**
 * Get the edit distance for a list containing one word.
 *
 * @param {Array.<string>} values
 */
function getStems(values) {
    if (values.length) {
        console.log(stems(values));
    } else {
        process.stderr.write(help());
        process.exit(1);
    }
}

/*
 * Program.
 */

if (
    argv.indexOf('--help') !== -1 ||
    argv.indexOf('-h') !== -1
) {
    console.log(help());
} else if (
    argv.indexOf('--version') !== -1 ||
    argv.indexOf('-v') !== -1
) {
    console.log(pack.version);
} else if (argv.length) {
    getStems(argv.join(' ').split(/\s+/g));
} else if (!expextPipeIn) {
    getStems([]);
} else {
    process.stdin.resume();
    process.stdin.setEncoding('utf8');
    process.stdin.on('data', function (data) {
        getStems(data.trim().split(/\s+/g));
    });
}
<|endoftext|>


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

'use strict';
const childProcess = require('child_process');
const isCi = require('is-ci');

function run(args, isCi) {
	const script = isCi ? args[0] : args[1];

	if (script) {
		return childProcess.spawn(
      process.env.npm_execpath || 'npm',
      ['run', script],
			{
				detached: true,
				stdio: 'inherit'
			}
    );
	}
}

module.exports = run;

if (require.main === module) {
	const proc = run(process.argv.slice(2), isCi);
	if (proc) {
		proc.on('exit', process.exit);
	}
}
<commit_msg>Use npm.cmd for windows<commit_after>#!/usr/bin/env node

'use strict';
const childProcess = require('child_process');
const isCi = require('is-ci');
const isWindows = process.platform === 'win32';
const npmExec = isWindows ? 'npm.cmd' : 'npm'

function run(args, isCi) {
	const script = isCi ? args[0] : args[1];

	if (script) {
		return childProcess.spawn(
			npmExec,
			['run', script],
			{
				detached: !isWindows,
				stdio: 'inherit'
			}
		);
	}
}

module.exports = run;

if (require.main === module) {
	const proc = run(process.argv.slice(2), isCi);
	if (proc) {
		proc.on('exit', process.exit);
	}
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
var path = require('path');
var Config = require('./index.js');

var parser = require('nomnom');
var log_levels = ['silly', 'debug', 'info', 'warn', 'critical'];
var log_level = 4;

parser.script('jetconfig');

parser.option('version', {
        flag: true,
        help: "Print version and exit",
        callback: function () { console.log(require('./package').version); }
    })
    .option('noInherit', {
        flag: true,
        help: "Prevent configuration inheritance",
        abbr: 'n',
        full: 'no-inherit',
    })
    .option('verbose', {
        abbr: 'v',
        help: "Increase verbosity, can be used multiple times",
        flag: true,
        callback: function () {
            if (log_level > 0) log_level -= 1;
        }
    });

var cmd = function cmd (func) {
    var handler = function handler (params) {
        var opts = {};
        var conf;
        var result;

        opts.logLevel = log_levels[log_level];
        opts.prefix = params.prefix;
        opts.inherit = !params.noInherit;

        conf = new Config(opts);
        result = func(conf, params);
        if (result !== undefined) console.log(JSON.stringify(result, null, 2));
    };
    return handler;
};

parser.command('dump')
    .help("Dump the current etcd configuration")
    .option('prefix', {
        position: 1,
        help: 'Etcd namespace (default: config/)',
        default: 'config/',
        required: true
    })
    .callback(cmd(function (conf) {
        return conf.dump();
    }));

parser.command('list')
    .help("List all available etcd configurations")
    .option('prefix', {
        position: 1,
        help: 'Etcd namespace (default: /)',
        default: '/',
        required: true
    })
    .callback(cmd(function (conf) {
        return conf.list(undefined, {dirOnly: false});
    }));

parser.command('clear')
    .help("Clear the current etcd configuration")
    .option('prefix', {
        position: 1,
        help: 'Etcd namespace',
        required: true
    })
    .callback(cmd(function (conf) {
        conf.allowClear = true;
        conf.clear();
    }));

parser.command('load')
    .help("Load a configuration from a file")
    .option('prefix', {
        position: 1,
        help: 'Etcd namespace',
        required: true
    })
    .option('file', {
        position: 2,
        help: 'Filename to load',
        required: true,
    })
    .callback(cmd(function (conf, params) {
        var filename = path.resolve(params.file);
        var new_conf;
        try {
            new_conf = require(filename);
        } catch (err) {
            if (String(err).match(/Cannot find module/)) {
                console.log("No such file:", params.file);
            }
            else {
                console.log('' + err);
            }
            return process.exit(1);
        }
        conf.log.silly("Read config", new_conf);
        conf.load(new_conf, {cacheOnly: false});
    }));

parser.command('get')
    .help("Get a configuration key")
    .option('prefix', {
        position: 1,
        help: 'Etcd namespace',
        required: true
    })
    .option('key', {
        position: 2,
        help: 'Configuration key',
        required: true
    })
    .callback(cmd(function (conf, params) {
        var value = conf.get(params.key, params.value);
        if (value === undefined) process.exit(1);
        return value;
    }));

parser.command('set')
    .help("Set a configuration key to a value")
    .option('prefix', {
        position: 1,
        help: 'Etcd namespace',
        required: true
    })
    .option('key', {
        position: 2,
        help: 'Configuration key',
        required: true
    })
    .option('value', {
        position: 3,
        help: 'Configuration value',
        required: true
    })
    .callback(cmd(function (conf, params) {
        conf.set(params.key, params.value);
    }));

parser.parse();
<commit_msg>Make jetconfig always reflect the script name.<commit_after>#!/usr/bin/env node
var path = require('path');
var Config = require('./index.js');

var parser = require('nomnom');
var log_levels = ['silly', 'debug', 'info', 'warn', 'critical'];
var log_level = 4;

parser.script(path.basename(process.argv[1]));

parser.option('version', {
        flag: true,
        help: "Print version and exit",
        callback: function () { console.log(require('./package').version); }
    })
    .option('noInherit', {
        flag: true,
        help: "Prevent configuration inheritance",
        abbr: 'n',
        full: 'no-inherit',
    })
    .option('verbose', {
        abbr: 'v',
        help: "Increase verbosity, can be used multiple times",
        flag: true,
        callback: function () {
            if (log_level > 0) log_level -= 1;
        }
    });

var cmd = function cmd (func) {
    var handler = function handler (params) {
        var opts = {};
        var conf;
        var result;

        opts.logLevel = log_levels[log_level];
        opts.prefix = params.prefix;
        opts.inherit = !params.noInherit;

        conf = new Config(opts);
        result = func(conf, params);
        if (result !== undefined) console.log(JSON.stringify(result, null, 2));
    };
    return handler;
};

parser.command('dump')
    .help("Dump the current etcd configuration")
    .option('prefix', {
        position: 1,
        help: 'Etcd namespace (default: config/)',
        default: 'config/',
        required: true
    })
    .callback(cmd(function (conf) {
        return conf.dump();
    }));

parser.command('list')
    .help("List all available etcd configurations")
    .option('prefix', {
        position: 1,
        help: 'Etcd namespace (default: /)',
        default: '/',
        required: true
    })
    .callback(cmd(function (conf) {
        return conf.list(undefined, {dirOnly: false});
    }));

parser.command('clear')
    .help("Clear the current etcd configuration")
    .option('prefix', {
        position: 1,
        help: 'Etcd namespace',
        required: true
    })
    .callback(cmd(function (conf) {
        conf.allowClear = true;
        conf.clear();
    }));

parser.command('load')
    .help("Load a configuration from a file")
    .option('prefix', {
        position: 1,
        help: 'Etcd namespace',
        required: true
    })
    .option('file', {
        position: 2,
        help: 'Filename to load',
        required: true,
    })
    .callback(cmd(function (conf, params) {
        var filename = path.resolve(params.file);
        var new_conf;
        try {
            new_conf = require(filename);
        } catch (err) {
            if (String(err).match(/Cannot find module/)) {
                console.log("No such file:", params.file);
            }
            else {
                console.log('' + err);
            }
            return process.exit(1);
        }
        conf.log.silly("Read config", new_conf);
        conf.load(new_conf, {cacheOnly: false});
    }));

parser.command('get')
    .help("Get a configuration key")
    .option('prefix', {
        position: 1,
        help: 'Etcd namespace',
        required: true
    })
    .option('key', {
        position: 2,
        help: 'Configuration key',
        required: true
    })
    .callback(cmd(function (conf, params) {
        var value = conf.get(params.key, params.value);
        if (value === undefined) process.exit(1);
        return value;
    }));

parser.command('set')
    .help("Set a configuration key to a value")
    .option('prefix', {
        position: 1,
        help: 'Etcd namespace',
        required: true
    })
    .option('key', {
        position: 2,
        help: 'Configuration key',
        required: true
    })
    .option('value', {
        position: 3,
        help: 'Configuration value',
        required: true
    })
    .callback(cmd(function (conf, params) {
        conf.set(params.key, params.value);
    }));

parser.parse();
<|endoftext|>


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

try {
    require('cli-config').run({
        dirname: __dirname,
        clone: true,
        cli: {
            boolean: {
                'v': 'verbose',
                't': 'localTunnel'
            },
            string: {
                'n': 'appName',
                'd': 'appDomain'
            },
            // map options into commands
            alias: {
                '--version': 'version'
            }
        },
        cmdTree: require('./lib')
    });
} catch (ex) {
    console.error(ex);
    process.exit(1);
}
<commit_msg>Now supports .stlive.config files in current and ancestor directories (implemented in cli-config 0.3.2). Cleaned up cli-config.run() options.<commit_after>#!/usr/bin/env node

try {
    require('cli-config').run({
        dirname: __dirname,
        clone: true,        // Clones default.config to '~/.stlive.config'
        ancestors: true,    // Search curr and ancestor dirs for '.stlive.config' files
        cmdTree: require('./lib')
    });
} catch (ex) {
    console.error(ex);
    process.exit(1);
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
/**
 * html-minifier CLI tool
 *
 * The MIT License (MIT)
 *
 *  Copyright (c) 2014-2016 Zoltan Frombach
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy of
 *  this software and associated documentation files (the "Software"), to deal in
 *  the Software without restriction, including without limitation the rights to
 *  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 *  the Software, and to permit persons to whom the Software is furnished to do so,
 *  subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in all
 *  copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 *  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 *  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 *  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 *  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

'use strict';

var cli = require('cli');
var concat = require('concat-stream');
var changeCase = require('change-case');
var path = require('path');
var fs = require('fs');
var appName = require('./package.json').name;
var appVersion = require('./package.json').version;
var minify = require('.').minify;
var HTMLLint = require('./src/htmllint').HTMLLint;
var minifyOptions = {};
var input = null;
var output = null;

cli.width = 100;
cli.option_width = 40;
cli.setApp(appName, appVersion);

var usage = appName + ' [OPTIONS] [FILE(s)]\n\n';
usage += '  If no input files are specified then STDIN will be used for input.\n';
usage += '  If more than one input file is specified then those will be concatenated and minified together.\n\n';
usage += '  When you specify a config file with the --config-file option (see sample-cli-config-file.conf for format)\n';
usage += '    you can still override some of its contents by providing individual command line options, too.\n\n';
usage += '  When you want to provide an array of strings for --ignore-custom-comments or --process-scripts options\n';
usage += '    on the command line you must escape those such as --ignore-custom-comments "[\\"string1\\",\\"string1\\"]"\n';

cli.setUsage(usage);

var mainOptions = {
  caseSensitive: [[false, 'Treat attributes in case sensitive manner (useful for SVG; e.g. viewBox)']],
  collapseBooleanAttributes: [[false, 'Omit attribute values from boolean attributes']],
  collapseInlineTagWhitespace: [[false, 'Collapse white space around inline tag']],
  collapseWhitespace: [[false, 'Collapse white space that contributes to text nodes in a document tree.']],
  conservativeCollapse: [[false, 'Always collapse to 1 space (never remove it entirely)']],
  customAttrAssign: [[false, 'Arrays of regex\'es that allow to support custom attribute assign expressions (e.g. \'

\')', 'string'], 'json-regex'],
  customAttrCollapse: [[false, 'Regex that specifies custom attribute to strip newlines from (e.g. /ng\-class/)', 'string'], 'string-regex'],
  customAttrSurround: [[false, 'Arrays of regex\'es that allow to support custom attribute surround expressions (e.g. <input {{#if value}}checked="checked"{{/if}}>)', 'string'], 'json-regex'],
  customEventAttributes: [[false, 'Arrays of regex\'es that allow to support custom event attributes for minifyJS (e.g. ng-click)', 'string'], 'json-regex'],
  html5: [[false, 'Parse input according to HTML5 specifications']],
  ignoreCustomComments: [[false, 'Array of regex\'es that allow to ignore certain comments, when matched', 'string'], 'json-regex'],
  ignoreCustomFragments: [[false, 'Array of regex\'es that allow to ignore certain fragments, when matched (e.g. <?php ... ?>, {{ ... }})', 'string'], 'json-regex'],
  includeAutoGeneratedTags: [[false, 'Insert tags generated by HTML parser'], true],
  keepClosingSlash: [[false, 'Keep the trailing slash on singleton elements']],
  lint: [[false, 'Toggle linting']],
  maxLineLength: [[false, 'Max line length', 'number'], true],
  minifyCSS: [[false, 'Minify CSS in style elements and style attributes (uses clean-css)']],
  minifyJS: [[false, 'Minify Javascript in script elements and on* attributes (uses UglifyJS)']],
  minifyURLs: [[false, 'Minify URLs in various attributes (uses relateurl)', 'string'], 'site-url'],
  preserveLineBreaks: [[false, 'Always collapse to 1 line break (never remove it entirely) when whitespace between tags include a line break.']],
  preventAttributesEscaping: [[false, 'Prevents the escaping of the values of attributes.']],
  processConditionalComments: [[false, 'Process contents of conditional comments through minifier']],
  processScripts: [[false, 'Array of strings corresponding to types of script elements to process through minifier (e.g. "text/ng-template", "text/x-handlebars-template", etc.)', 'string'], 'json'],
  quoteCharacter: [[false, 'Type of quote to use for attribute values (\' or ")', 'string'], true],
  removeAttributeQuotes: [[false, 'Remove quotes around attributes when possible.']],
  removeCDATASectionsFromCDATA: [[false, 'Remove CDATA sections from script and style elements']],
  removeComments: [[false, 'Strip HTML comments']],
  removeCommentsFromCDATA: [[false, 'Strip HTML comments from scripts and styles']],
  removeEmptyAttributes: [[false, 'Remove all attributes with whitespace-only values']],
  removeEmptyElements: [[false, 'Remove all elements with empty contents']],
  removeOptionalTags: [[false, 'Remove unrequired tags']],
  removeRedundantAttributes: [[false, 'Remove attributes when value matches default.']],
  removeScriptTypeAttributes: [[false, 'Remove type="text/javascript" from script tags. Other type attribute values are left intact.']],
  removeStyleLinkTypeAttributes: [[false, 'Remove type="text/css" from style and link tags. Other type attribute values are left intact.']],
  removeTagWhitespace: [[false, 'Remove space between attributes whenever possible.']],
  useShortDoctype: [[false, 'Replaces the doctype with the short (HTML5) doctype']]
};

var cliOptions = {
  version: ['v', 'Version information'],
  output: ['o', 'Specify output file (if not specified STDOUT will be used for output)', 'file'],
  'config-file': ['c', 'Use config file', 'file'],
  'input-dir': [false, 'Specify an input directory', 'dir'],
  'output-dir': [false, 'Specify an output directory', 'dir']
};

var mainOptionKeys = Object.keys(mainOptions);
mainOptionKeys.forEach(function(key) {
  cliOptions[changeCase.paramCase(key)] = mainOptions[key][0];
});

cli.parse(cliOptions);

cli.main(function(args, options) {

  function stringToRegExp(value) {
    // JSON does not support regexes, so, e.g., JSON.parse() will not create
    // a RegExp from the JSON value `[ "/matchString/" ]`, which is
    // technically just an array containing a string that begins and end with
    // a forward slash. To get a RegExp from a JSON string, it must be
    // constructed explicitly in JavaScript.
    //
    // The likelihood of actually wanting to match text that is enclosed in
    // forward slashes is probably quite rare, so if forward slashes were
    // included in an argument that requires a regex, the user most likely
    // thought they were part of the syntax for specifying a regex.
    //
    // In the unlikely case that forward slashes are indeed desired in the
    // search string, the user would need to enclose the expression in a
    // second set of slashes:
    //
    //    --customAttrSrround "[\"//matchString//\"]"
    //
    if (value) {
      var stripSlashes = /^\/(.*)\/$/.exec(value);
      if (stripSlashes) {
        value = stripSlashes[1];
      }
      return new RegExp(value);
    }
  }

  function parseJSONOption(value, regexArray) {
    if (value !== null) {
      var jsonArray;
      try {
        jsonArray = JSON.parse(value);
        if (regexArray) {
          jsonArray = jsonArray.map(function (regexString) {
            return stringToRegExp(regexString);
          });
        }
      }
      catch (e) {
        cli.fatal('Could not parse JSON value \'' + value + '\'');
      }
      if (jsonArray instanceof Array) {
        return jsonArray;
      }
      else {
        return [value];
      }
    }
  }

  function runMinify(original, output) {
    var status = 0;
    var minified = null;
    try {
      minified = minify(original, minifyOptions);
    }
    catch (e) {
      status = 3;
      cli.error('Minification error');
      process.stderr.write((e.stack || e).toString());
    }

    if (minifyOptions.lint) {
      minifyOptions.lint.populate();
    }

    if (minified !== null) {
      // Write the output
      try {
        // eslint-disable-next-line eqeqeq
        if (output != null) {
          fs.writeFileSync(path.resolve(output), minified);
        }
        else {
          process.stdout.write(minified);
        }
      }
      catch (e) {
        status = 4;
        console.log(output);
        cli.error('Cannot write to output');
      }
    }

    return status;
  }

  function createDirectory(path) {
    try {
      fs.mkdirSync(path);
    }
    catch (e) {
      if (e.code !== 'EEXIST') {
        cli.fatal('Can not create directory ' + path);
        return 3;
      }
    }
    return 0;
  }

  function processDirectory(inputDir, outputDir) {
    var fileList = fs.readdirSync(inputDir);
    var status = createDirectory(outputDir);

    for (var i = 0; status === 0 && i < fileList.length; i++) {
      var fileName = fileList[i];
      var inputFilePath = inputDir + '/' + fileName;
      var outputFilePath = outputDir + '/' + fileName;

      var stat = fs.statSync(inputFilePath);
      if (stat.isDirectory()) {
        status = processDirectory(inputFilePath, outputFilePath);
      }
      else {
        var originalContent = fs.readFileSync(inputFilePath, 'utf8');
        status = runMinify(originalContent, outputFilePath);
      }
    }

    return status;
  }

  if (options.version) {
    cli.output(appName + ' v' + appVersion);
    cli.exit(0);
  }

  if (options['config-file']) {
    var fileOptions;
    var fileOptionsPath = path.resolve(options['config-file']);
    try {
      fileOptions = fs.readFileSync(fileOptionsPath, { encoding: 'utf8' });
    }
    catch (e) {
      cli.fatal('The specified config file doesn’t exist or is unreadable:\n' + fileOptionsPath);
    }
    try {
      fileOptions = JSON.parse(fileOptions);
    }
    catch (je) {
      try {
        fileOptions = require(fileOptionsPath);
      }
      catch (ne) {
        cli.fatal('Cannot read the specified config file. \nAs JSON: ' + je.message + '\nAs module: ' + ne.message);
      }
    }

    if (fileOptions && typeof fileOptions === 'object') {
      minifyOptions = fileOptions;
    }
  }
  mainOptionKeys.forEach(function(key) {
    var paramKey = changeCase.paramCase(key);
    var value = options[paramKey];
    if (value !== null) {
      switch (mainOptions[key][1]) {
        case 'json':
          minifyOptions[key] = parseJSONOption(value);
          break;
        case 'json-regex':
          minifyOptions[key] = parseJSONOption(value, true);
          break;
        case 'string-regex':
          minifyOptions[key] = stringToRegExp(value);
          break;
        case 'site-url':
          minifyOptions[key] = { site: value };
          break;
        case true:
          minifyOptions[key] = value;
          break;
        default:
          minifyOptions[key] = true;
      }
    }
  });

  if (minifyOptions.lint === true) {
    minifyOptions.lint = new HTMLLint();
  }

  if (args.length) {
    input = args;
  }

  if (options['input-dir'] || options['output-dir']) {
    var inputDir = options['input-dir'];
    var outputDir = options['output-dir'];

    if (!inputDir) {
      cli.error('The option output-dir needs to be used with the option input-dir. If you are working with a single file, use -o.');
      cli.exit(2);
    }

    try {
      fs.statSync(inputDir);
    }
    catch (e) {
      cli.error('The input directory does not exist');
      cli.exit(2);
    }

    if (!outputDir) {
      cli.error('You need to specify where to write the output files with the option --output-dir');
      cli.exit(2);
    }

    try {
      cli.exit(processDirectory(inputDir, outputDir));
    }
    catch (e) {
      cli.error('Error while processing input files');
      cli.error(e);
      cli.exit(3);
    }
  }

  if (options.output) {
    output = options.output;
  }

  if (input !== null) { // Minifying one or more files specified on the CMD line

    var original = '';

    input.forEach(function(afile) {
      try {
        original += fs.readFileSync(afile, 'utf8');
      }
      catch (e) {
        cli.error('Cannot read file ' + afile);
        cli.exit(2);
      }
    });

    cli.exit(runMinify(original, output));

  }
  else { // Minifying input coming from STDIN
    process.stdin.pipe(concat({ encoding: 'string' }, function(content) {
      runMinify(content, output);
    }));
  }
});
<commit_msg>clean up null/undefined usages add missing cli.ext()<commit_after>#!/usr/bin/env node
/**
 * html-minifier CLI tool
 *
 * The MIT License (MIT)
 *
 *  Copyright (c) 2014-2016 Zoltan Frombach
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy of
 *  this software and associated documentation files (the "Software"), to deal in
 *  the Software without restriction, including without limitation the rights to
 *  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 *  the Software, and to permit persons to whom the Software is furnished to do so,
 *  subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in all
 *  copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 *  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 *  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 *  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 *  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

'use strict';

var cli = require('cli');
var concat = require('concat-stream');
var changeCase = require('change-case');
var path = require('path');
var fs = require('fs');
var appName = require('./package.json').name;
var appVersion = require('./package.json').version;
var minify = require('.').minify;
var HTMLLint = require('./src/htmllint').HTMLLint;
var minifyOptions = {};
var output;

cli.width = 100;
cli.option_width = 40;
cli.setApp(appName, appVersion);

var usage = appName + ' [OPTIONS] [FILE(s)]\n\n';
usage += '  If no input files are specified then STDIN will be used for input.\n';
usage += '  If more than one input file is specified then those will be concatenated and minified together.\n\n';
usage += '  When you specify a config file with the --config-file option (see sample-cli-config-file.conf for format)\n';
usage += '    you can still override some of its contents by providing individual command line options, too.\n\n';
usage += '  When you want to provide an array of strings for --ignore-custom-comments or --process-scripts options\n';
usage += '    on the command line you must escape those such as --ignore-custom-comments "[\\"string1\\",\\"string1\\"]"\n';

cli.setUsage(usage);

var mainOptions = {
  caseSensitive: [[false, 'Treat attributes in case sensitive manner (useful for SVG; e.g. viewBox)']],
  collapseBooleanAttributes: [[false, 'Omit attribute values from boolean attributes']],
  collapseInlineTagWhitespace: [[false, 'Collapse white space around inline tag']],
  collapseWhitespace: [[false, 'Collapse white space that contributes to text nodes in a document tree.']],
  conservativeCollapse: [[false, 'Always collapse to 1 space (never remove it entirely)']],
  customAttrAssign: [[false, 'Arrays of regex\'es that allow to support custom attribute assign expressions (e.g. \'

\')', 'string'], 'json-regex'],
  customAttrCollapse: [[false, 'Regex that specifies custom attribute to strip newlines from (e.g. /ng\-class/)', 'string'], 'string-regex'],
  customAttrSurround: [[false, 'Arrays of regex\'es that allow to support custom attribute surround expressions (e.g. <input {{#if value}}checked="checked"{{/if}}>)', 'string'], 'json-regex'],
  customEventAttributes: [[false, 'Arrays of regex\'es that allow to support custom event attributes for minifyJS (e.g. ng-click)', 'string'], 'json-regex'],
  html5: [[false, 'Parse input according to HTML5 specifications']],
  ignoreCustomComments: [[false, 'Array of regex\'es that allow to ignore certain comments, when matched', 'string'], 'json-regex'],
  ignoreCustomFragments: [[false, 'Array of regex\'es that allow to ignore certain fragments, when matched (e.g. <?php ... ?>, {{ ... }})', 'string'], 'json-regex'],
  includeAutoGeneratedTags: [[false, 'Insert tags generated by HTML parser'], true],
  keepClosingSlash: [[false, 'Keep the trailing slash on singleton elements']],
  lint: [[false, 'Toggle linting']],
  maxLineLength: [[false, 'Max line length', 'number'], true],
  minifyCSS: [[false, 'Minify CSS in style elements and style attributes (uses clean-css)']],
  minifyJS: [[false, 'Minify Javascript in script elements and on* attributes (uses UglifyJS)']],
  minifyURLs: [[false, 'Minify URLs in various attributes (uses relateurl)', 'string'], 'site-url'],
  preserveLineBreaks: [[false, 'Always collapse to 1 line break (never remove it entirely) when whitespace between tags include a line break.']],
  preventAttributesEscaping: [[false, 'Prevents the escaping of the values of attributes.']],
  processConditionalComments: [[false, 'Process contents of conditional comments through minifier']],
  processScripts: [[false, 'Array of strings corresponding to types of script elements to process through minifier (e.g. "text/ng-template", "text/x-handlebars-template", etc.)', 'string'], 'json'],
  quoteCharacter: [[false, 'Type of quote to use for attribute values (\' or ")', 'string'], true],
  removeAttributeQuotes: [[false, 'Remove quotes around attributes when possible.']],
  removeCDATASectionsFromCDATA: [[false, 'Remove CDATA sections from script and style elements']],
  removeComments: [[false, 'Strip HTML comments']],
  removeCommentsFromCDATA: [[false, 'Strip HTML comments from scripts and styles']],
  removeEmptyAttributes: [[false, 'Remove all attributes with whitespace-only values']],
  removeEmptyElements: [[false, 'Remove all elements with empty contents']],
  removeOptionalTags: [[false, 'Remove unrequired tags']],
  removeRedundantAttributes: [[false, 'Remove attributes when value matches default.']],
  removeScriptTypeAttributes: [[false, 'Remove type="text/javascript" from script tags. Other type attribute values are left intact.']],
  removeStyleLinkTypeAttributes: [[false, 'Remove type="text/css" from style and link tags. Other type attribute values are left intact.']],
  removeTagWhitespace: [[false, 'Remove space between attributes whenever possible.']],
  useShortDoctype: [[false, 'Replaces the doctype with the short (HTML5) doctype']]
};

var cliOptions = {
  version: ['v', 'Version information'],
  output: ['o', 'Specify output file (if not specified STDOUT will be used for output)', 'file'],
  'config-file': ['c', 'Use config file', 'file'],
  'input-dir': [false, 'Specify an input directory', 'dir'],
  'output-dir': [false, 'Specify an output directory', 'dir']
};

var mainOptionKeys = Object.keys(mainOptions);
mainOptionKeys.forEach(function(key) {
  cliOptions[changeCase.paramCase(key)] = mainOptions[key][0];
});

cli.parse(cliOptions);

cli.main(function(args, options) {

  function stringToRegExp(value) {
    // JSON does not support regexes, so, e.g., JSON.parse() will not create
    // a RegExp from the JSON value `[ "/matchString/" ]`, which is
    // technically just an array containing a string that begins and end with
    // a forward slash. To get a RegExp from a JSON string, it must be
    // constructed explicitly in JavaScript.
    //
    // The likelihood of actually wanting to match text that is enclosed in
    // forward slashes is probably quite rare, so if forward slashes were
    // included in an argument that requires a regex, the user most likely
    // thought they were part of the syntax for specifying a regex.
    //
    // In the unlikely case that forward slashes are indeed desired in the
    // search string, the user would need to enclose the expression in a
    // second set of slashes:
    //
    //    --customAttrSrround "[\"//matchString//\"]"
    //
    if (value) {
      var stripSlashes = /^\/(.*)\/$/.exec(value);
      if (stripSlashes) {
        value = stripSlashes[1];
      }
      return new RegExp(value);
    }
  }

  function parseJSONOption(value, regexArray) {
    if (value !== null) {
      var jsonArray;
      try {
        jsonArray = JSON.parse(value);
        if (regexArray) {
          jsonArray = jsonArray.map(function (regexString) {
            return stringToRegExp(regexString);
          });
        }
      }
      catch (e) {
        cli.fatal('Could not parse JSON value \'' + value + '\'');
      }
      if (jsonArray instanceof Array) {
        return jsonArray;
      }
      else {
        return [value];
      }
    }
  }

  function runMinify(original, output) {
    var status = 0;
    var minified = null;
    try {
      minified = minify(original, minifyOptions);
    }
    catch (e) {
      status = 3;
      cli.error('Minification error');
      process.stderr.write((e.stack || e).toString());
    }

    if (minifyOptions.lint) {
      minifyOptions.lint.populate();
    }

    if (minified !== null) {
      // Write the output
      if (output) {
        try {
          fs.writeFileSync(path.resolve(output), minified);
        }
        catch (e) {
          status = 4;
          cli.error('Cannot write to ' + output);
        }
      }
      else {
        process.stdout.write(minified);
      }
    }

    return status;
  }

  function createDirectory(path) {
    try {
      fs.mkdirSync(path);
    }
    catch (e) {
      if (e.code !== 'EEXIST') {
        cli.fatal('Can not create directory ' + path);
        return 3;
      }
    }
    return 0;
  }

  function processDirectory(inputDir, outputDir) {
    var fileList = fs.readdirSync(inputDir);
    var status = createDirectory(outputDir);

    for (var i = 0; status === 0 && i < fileList.length; i++) {
      var fileName = fileList[i];
      var inputFilePath = inputDir + '/' + fileName;
      var outputFilePath = outputDir + '/' + fileName;

      var stat = fs.statSync(inputFilePath);
      if (stat.isDirectory()) {
        status = processDirectory(inputFilePath, outputFilePath);
      }
      else {
        var originalContent = fs.readFileSync(inputFilePath, 'utf8');
        status = runMinify(originalContent, outputFilePath);
      }
    }

    return status;
  }

  if (options.version) {
    cli.output(appName + ' v' + appVersion);
    cli.exit(0);
  }

  if (options['config-file']) {
    var fileOptions;
    var fileOptionsPath = path.resolve(options['config-file']);
    try {
      fileOptions = fs.readFileSync(fileOptionsPath, { encoding: 'utf8' });
    }
    catch (e) {
      cli.fatal('The specified config file doesn’t exist or is unreadable:\n' + fileOptionsPath);
    }
    try {
      fileOptions = JSON.parse(fileOptions);
    }
    catch (je) {
      try {
        fileOptions = require(fileOptionsPath);
      }
      catch (ne) {
        cli.fatal('Cannot read the specified config file. \nAs JSON: ' + je.message + '\nAs module: ' + ne.message);
      }
    }

    if (fileOptions && typeof fileOptions === 'object') {
      minifyOptions = fileOptions;
    }
  }
  mainOptionKeys.forEach(function(key) {
    var paramKey = changeCase.paramCase(key);
    var value = options[paramKey];
    if (value !== null) {
      switch (mainOptions[key][1]) {
        case 'json':
          minifyOptions[key] = parseJSONOption(value);
          break;
        case 'json-regex':
          minifyOptions[key] = parseJSONOption(value, true);
          break;
        case 'string-regex':
          minifyOptions[key] = stringToRegExp(value);
          break;
        case 'site-url':
          minifyOptions[key] = { site: value };
          break;
        case true:
          minifyOptions[key] = value;
          break;
        default:
          minifyOptions[key] = true;
      }
    }
  });

  if (minifyOptions.lint === true) {
    minifyOptions.lint = new HTMLLint();
  }

  if (options['input-dir'] || options['output-dir']) {
    var inputDir = options['input-dir'];
    var outputDir = options['output-dir'];

    if (!inputDir) {
      cli.error('The option output-dir needs to be used with the option input-dir. If you are working with a single file, use -o.');
      cli.exit(2);
    }

    try {
      fs.statSync(inputDir);
    }
    catch (e) {
      cli.error('The input directory does not exist');
      cli.exit(2);
    }

    if (!outputDir) {
      cli.error('You need to specify where to write the output files with the option --output-dir');
      cli.exit(2);
    }

    try {
      cli.exit(processDirectory(inputDir, outputDir));
    }
    catch (e) {
      cli.error('Error while processing input files');
      cli.error(e);
      cli.exit(3);
    }
  }

  if (options.output) {
    output = options.output;
  }

  if (args.length) { // Minifying one or more files specified on the CMD line
    var original = '';

    args.forEach(function(afile) {
      try {
        original += fs.readFileSync(afile, 'utf8');
      }
      catch (e) {
        cli.error('Cannot read file ' + afile);
        cli.exit(2);
      }
    });

    cli.exit(runMinify(original, output));
  }
  else { // Minifying input coming from STDIN
    process.stdin.pipe(concat({ encoding: 'string' }, function(content) {
      cli.exit(runMinify(content, output));
    }));
  }
});
<|endoftext|>


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

const Promise = require("bluebird")
const reporter = require("./lib/reporter")
const utils = require("./lib/utils")
const cli = require("./lib/cli")
const pkg = require("./package")
const co = Promise.coroutine

co(function* () {
	// get command options
	const o = cli.options()
	const t = o._.length ? o._ : ["default"]

	if (o.help) {
		return cli.help()
	}

	if (o.version) {
		return cli.version(pkg)
	}

	const fly = yield cli.spawn(o.pwd)
	reporter.call(fly)

	if (!fly.file) {
		return fly.emit("flyfile_not_found")
	}

	if (o.list) {
		return cli.list(fly.tasks, o.list === "bare")
	}

	fly.init()
	// announce start
	fly.emit("fly_run", fly.file)
	// run `tasks` in `mode`
	fly[o.mode](t)
})().catch(e => {
	if (e.type === "cli") {
		utils.error(`CLI Error!\t${e.message}`)
	} else {
		utils.trace(e)
	}
})
<commit_msg>fix 'pwd' typo<commit_after>#!/usr/bin/env node
"use strict"

const Promise = require("bluebird")
const reporter = require("./lib/reporter")
const utils = require("./lib/utils")
const cli = require("./lib/cli")
const pkg = require("./package")
const co = Promise.coroutine

co(function* () {
	// get command options
	const o = cli.options()
	const t = o._.length ? o._ : ["default"]

	if (o.help) {
		return cli.help()
	}

	if (o.version) {
		return cli.version(pkg)
	}

	const fly = yield cli.spawn(o.cwd)
	reporter.call(fly)

	if (!fly.file) {
		return fly.emit("flyfile_not_found")
	}

	if (o.list) {
		return cli.list(fly.tasks, o.list === "bare")
	}

	fly.init()
	// announce start
	fly.emit("fly_run", fly.file)
	// run `tasks` in `mode`
	fly[o.mode](t)
})().catch(e => {
	if (e.type === "cli") {
		utils.error(`CLI Error!\t${e.message}`)
	} else {
		utils.trace(e)
	}
})
<|endoftext|>


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

var argv = process.argv;
argv.shift();

var file_path = __dirname;
var current_path = process.cwd();

var apie = require('./index')

apie(current_path + '/routes');

<commit_msg>lazycommmit, please ignore<commit_after>#!/usr/bin/env node

var argv = process.argv;
argv.shift();

var file_path = __dirname;
var current_path = process.cwd();

var apie = require('./index')

apie(current_path + '/routes');

<|endoftext|>


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

var path = require('path');
var opts = require('./cli/args');
var async = require('async');
var prompts = require('./cli/prompts');
var partial = require('lodash/function/partial');
var backends = require('./backends');
var mapValues = require('lodash/object/mapValues');
var steps = {
    getTables: require('./steps/table-list'),
    tableToObject: require('./steps/table-to-object'),
    findReferences: require('./steps/find-references'),
    generateTypes: require('./steps/generate-types'),
    outputData: require('./steps/output-data'),

    collect: {
        tableStructure: require('./steps/table-structure'),
        tableComments: require('./steps/table-comment')
    }
};

// Command vs requirements
opts.command = (opts._ || [])[0];
opts.user =
    opts.backend !== 'mysql' &&
    opts.user === 'root' ?
        process.env.USER || 'root' :
        opts.user;

// Force recast to throw away whitespace information
opts.reuseWhitespace = false;

var commands = ['app'];
if (!opts.command || !opts.command.length) {
    opts.command = 'app';
}

if (commands.indexOf(opts.command) === -1) {
    return bail(new Error('Invalid command. Valid commands: ' + commands.join(', ')));
}

if (opts.command === 'app' && !opts.outputDir) {
    return bail(new Error('You need to provide an output directory (--output-dir=<path>) to generate an application'));
}

// Do we support the given backend?
var backend = backends(opts.backend);
if (!backend) {
    return bail(new Error('Database backend "' + opts.backend + '" not supported'));
}

// Instantiate the adapter for the given backend
var adapter = backend(opts, function(err) {
    bailOnError(err);

    getTables();
});

function getTables() {
    // Collect a list of available tables
    steps.getTables(adapter, opts, function(err, tableNames) {
        bailOnError(err);

        // If we're in interactive mode, prompt the user to select from the list of available tables
        if (opts.interactive) {
            return prompts.tableSelection(tableNames, onTablesSelected);
        }

        // Use the found tables (or a filtered set if --table is used)
        return onTablesSelected(tableNames);
    });
}

// When tables have been selected, fetch data for those tables
function onTablesSelected(tables) {
    // Assign partialed functions to make the code slightly more readable
    steps.collect = mapValues(steps.collect, function(method) {
        return partial(method, adapter, { tables: tables });
    });

    // Collect the data in parallel
    async.parallel(steps.collect, onTableDataCollected);
}

// When table data has been collected, build an object representation of them
function onTableDataCollected(err, data) {
    bailOnError(err);
    adapter.close();

    var tableName, models = {}, model;
    for (tableName in data.tableStructure) {
        model = steps.tableToObject({
            name: tableName,
            columns: data.tableStructure[tableName],
            comment: data.tableComments[tableName]
        }, opts);

        models[model.name] = model;
    }

    data.models = steps.findReferences(models);
    data.types = steps.generateTypes(data, opts);

    steps.outputData(data, opts, onDataOutput);
}

// When the data has been written to stdout/files
function onDataOutput() {
    if (!opts.outputDir) {
        return;
    }

    var dir = path.resolve(opts.outputDir);
    console.log('Demo app generated in ' + dir + '. To run:');
    console.log('cd ' + dir);
    console.log('npm install');
    console.log('npm start');
    console.log();
    console.log('Then point your browser at http://localhost:3000');
}

function bail(err) {
    console.error(err.message ? err.message : err.toString());
    process.exit(1);
}

function bailOnError(err) {
    if (err) {
        return bail(err);
    }
}
<commit_msg>Use the one-to-many relationship functionality<commit_after>#!/usr/bin/env node
'use strict';

var path = require('path');
var opts = require('./cli/args');
var async = require('async');
var prompts = require('./cli/prompts');
var partial = require('lodash/function/partial');
var backends = require('./backends');
var mapValues = require('lodash/object/mapValues');
var steps = {
    getTables: require('./steps/table-list'),
    tableToObject: require('./steps/table-to-object'),
    findReferences: require('./steps/find-references'),
    findOneToManyReferences: require('./steps/find-one-to-many-rels'),
    generateTypes: require('./steps/generate-types'),
    outputData: require('./steps/output-data'),

    collect: {
        tableStructure: require('./steps/table-structure'),
        tableComments: require('./steps/table-comment')
    }
};

// Command vs requirements
opts.command = (opts._ || [])[0];
opts.user =
    opts.backend !== 'mysql' &&
    opts.user === 'root' ?
        process.env.USER || 'root' :
        opts.user;

// Force recast to throw away whitespace information
opts.reuseWhitespace = false;

var commands = ['app'];
if (!opts.command || !opts.command.length) {
    opts.command = 'app';
}

if (commands.indexOf(opts.command) === -1) {
    return bail(new Error('Invalid command. Valid commands: ' + commands.join(', ')));
}

if (opts.command === 'app' && !opts.outputDir) {
    return bail(new Error('You need to provide an output directory (--output-dir=<path>) to generate an application'));
}

// Do we support the given backend?
var backend = backends(opts.backend);
if (!backend) {
    return bail(new Error('Database backend "' + opts.backend + '" not supported'));
}

// Instantiate the adapter for the given backend
var adapter = backend(opts, function(err) {
    bailOnError(err);

    getTables();
});

function getTables() {
    // Collect a list of available tables
    steps.getTables(adapter, opts, function(err, tableNames) {
        bailOnError(err);

        // If we're in interactive mode, prompt the user to select from the list of available tables
        if (opts.interactive) {
            return prompts.tableSelection(tableNames, onTablesSelected);
        }

        // Use the found tables (or a filtered set if --table is used)
        return onTablesSelected(tableNames);
    });
}

// When tables have been selected, fetch data for those tables
function onTablesSelected(tables) {
    // Assign partialed functions to make the code slightly more readable
    steps.collect = mapValues(steps.collect, function(method) {
        return partial(method, adapter, { tables: tables });
    });

    // Collect the data in parallel
    async.parallel(steps.collect, onTableDataCollected);
}

// When table data has been collected, build an object representation of them
function onTableDataCollected(err, data) {
    bailOnError(err);

    var tableName, models = {}, model;
    for (tableName in data.tableStructure) {
        model = steps.tableToObject({
            name: tableName,
            columns: data.tableStructure[tableName],
            comment: data.tableComments[tableName]
        }, opts);

        models[model.name] = model;
    }

    data.models = steps.findReferences(models);

    // Note: This mutates the models - sorry. PRs are welcome.
    steps.findOneToManyReferences(adapter, data.models, function(refErr) {
        if (refErr) {
            throw refErr;
        }

        data.types = steps.generateTypes(data, opts);

        adapter.close();
        steps.outputData(data, opts, onDataOutput);
    });
}

// When the data has been written to stdout/files
function onDataOutput() {
    if (!opts.outputDir) {
        return;
    }

    var dir = path.resolve(opts.outputDir);
    console.log('Demo app generated in ' + dir + '. To run:');
    console.log('cd ' + dir);
    console.log('npm install');
    console.log('npm start');
    console.log();
    console.log('Then point your browser at http://localhost:3000');
}

function bail(err) {
    console.error(err.message ? err.message : err.toString());
    process.exit(1);
}

function bailOnError(err) {
    if (err) {
        return bail(err);
    }
}
<|endoftext|>


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

'use strict';

/* dependencies */

const fs = require('fs');
const http = require('follow-redirects').http;
const mkdirp = require('mkdirp');
const md5 = require('md5');
// const Parse = require('jsonparse');
const request = require('request');
const boxen = require('boxen');
const cheerio = require('cheerio');
const colors = require('colors');

colors.setTheme({
	directory: ['cyan', 'bold']
});

colors.setTheme({
	description: ['green', 'bold']
});

colors.setTheme({
	info: ['cyan', 'bold']
});

colors.setTheme({
	status: ['green', 'bold']
});

colors.setTheme({
	normal: ['red', 'bold']
});

colors.setTheme({
	error: ['red', 'bold']
});

const argv = require('yargs')
	.usage('\n Usage : $0 -u [email@id] -n [file name]'.info)
	.demand(['u', 'n'])
	.describe('u', '❱'.status + ' Email-Id of any gravatar user')
	.describe('n', '❱'.status + ' Name of Image')
	.argv;

const localFold = argv.n;

// hashing and storing the email
const hashEmail = md5(argv.u);

// passed
const usedAs = hashEmail;

// defining directories
// is the directory where the image will be saved
const saveImage = './Gravatar/';

// because I want to
const removeSlash = saveImage.replace('./', '');

// used where the directory is shown to the user
const forSaved = removeSlash.replace('/', '');

// finding username based on email address
// will show the user's data only if the gravatar user name of a person is starting chars of his email before '@'
function removeString(emailAddress) {
	// removing everything after '@', basic strategy used by gravtar for username
	return emailAddress.replace(/\@.*/, '');
}

// removing the google.plus text from the url
// the below function was used to parse url of googlePlus to show 'id', but since, while scrapping, if the id isn't found
// the code breaks. Disabling it to show complete url instead.
/*
function removeURL(urlAddress) {
		return urlAddress.replace(/\D/g,'');
}
*/

// stored argument
const replacedString = removeString(argv.u);

mkdirp(removeSlash, err => {
	if (err) {
		console.error(boxen('  Failed to create the directory   ').error);
	} else { /* referred to another mkdirp */ }
});

// loading lightweight page to check internet connection and creating directory based on the same process.
request('http://rishigiri.com/gravatar/', (error, response) => {
	if (!error && response.statusCode === 200) {
		console.log('\n\t ❱ Internet Connection    :    '.directory + '✔'.status);
		// another with same name
		mkdirp(removeSlash, err => {
			if (err) {
				console.log(boxen('  Failed to create the directory   ').error);
			} else {
				setTimeout(() => {
					console.log('\n\t ❱ Directory Created      :    '.directory + '✔'.status);
				}, 1000);
			}
		});
	} else {
		// console when statusCode !== 200 or no internet connection
		console.log('\n');
		console.log(boxen('  ERROR : Please check your internet connection  ').error);
		console.log('\n');
		// stop the whole process
		process.exit(1);
	}
});

console.log('\n  Fetching'.status, replacedString.toString().info, '\'s'.info,
	'gravatar data.'.status);
// requesting for image with hashed email address which was previously stored in 'usedAs'

request
	.get('http://1.gravatar.com/avatar/' + usedAs)

.on('response', response => {
	// checking for the type of remote image.
	const storeType = response.headers['content-type'];

	// initially the result comes like image/.gif
	// thus removing the 'image/' part
	const parseType = storeType.toString().replace('image/', '');

	// stored the possible extension in typeArray
	const typeArray = ['png', 'jpeg', 'gif'];

	// checking if the remote image is png
	if (response.statusCode === 200 && typeArray[0] === parseType) {
		// will save the image in the default defined directory
		const imageFile = fs.createWriteStream(removeSlash + argv.n + '.png');

		// started downloading image
		http.get('http://1.gravatar.com/avatar/' + usedAs + '?size=400px',
			res => {
				res.pipe(imageFile);
				setTimeout(() => {
					console.log('\n\t ❱ Image Saved In         :    '.directory +
						forSaved.toString().status + ' ❱ ' + localFold.toString().status +
						'.png\n'.status);
				}, 2000);
			}).on('error', err => {
				console.log(err);
			});
		// Parsing the HTML content for getting user's data.
		setTimeout(() => {
			function getProfile() {
				request('http://en.gravatar.com/' + replacedString, (error, response,
					html) => {
					if (!error && response.statusCode === 200) {
						// loading the whole HTML
						const $ = cheerio.load(html);
						return {
							// returning the datas
							name: console.log(' Name      :    '.info + $('h2.fn').text().toString()
								.description, '\n') || null,

							//
							place: console.log(' Location  :    '.info + $('p.location').text()
								.toString()
								.description, '\n') || null,

							bio: console.log(' Bio       :    '.info + $('p.description').text()
									.trim().replace('
', '').toString().description, '\n') ||
								null,

							twitter: console.log(' Twitter   :    '.info + $(
									'a.accounts_twitter')
								.text()
								.toString().description, '\n'
							) || null,

							facebook: console.log(' Facebook  :    '.info + $(
										'a.accounts_facebook').text()
									.toString().description,
									'\n') ||
								null,

							wordpress: console.log(' Wordpress  :   '.info + $(
										'a.accounts_wordpress').text().toString().description,
									'\n') ||
								null,

							// error parsing the data if url not found | better to remove
							// color not provided
							googlePlus: console.log(' Google +  :    '.info + $(
									'a.accounts_google').attr('href'),
								'\n') || null,

							linkedIn: console.log(' LinkedIn  :    '.info + $(
									'a.accounts_linkedin').attr('href'),
								'\n') || null
						};
					}
				});
			}
			getProfile();
		}, 5000);
	} else {
		/* something to be done | but no need */
	}
	// checking if the remote image if jpg/jpeg
	if (response.statusCode === 200 && typeArray[1] === parseType) {
		const imageFile = fs.createWriteStream(removeSlash + argv.n + '.jpeg');
		http.get('http://1.gravatar.com/avatar/' + usedAs + '?size=400px',
			res => {
				res.pipe(imageFile);
				setTimeout(() => {
					console.log('\n\t ❱ Image Saved In         :    '.directory +
						forSaved.toString().status + ' ❱ ' + localFold.toString().status +
						'.jpeg\n'.status);
				}, 2000);
			}).on('error', err => {
				console.log(err);
			});
		// Parsing the HTML content for getting user's data.
		setTimeout(() => {
			function getProfile() {
				request('http://en.gravatar.com/' + replacedString, (error, response,
					html) => {
					if (!error && response.statusCode === 200) {
						// loading the whole HTML
						const $ = cheerio.load(html);
						return {
							// returning the datas
							name: console.log(' Name      :    '.info + $('h2.fn').text().toString()
								.description, '\n') || null,

							place: console.log(' Location  :    '.info + $('p.location').text()
								.toString()
								.description, '\n') || null,

							bio: console.log(' Bio       :    '.info + $('p.description').text()
									.trim().replace('
', '').toString().description, '\n') ||
								null,
							// twitter name would be fine | instead URL
							twitter: console.log(' Twitter   :    '.info + $(
									'a.accounts_twitter')
								.text()
								.toString().description, '\n'
							) || null,

							facebook: console.log(' Facebook  :    '.info + $(
										'a.accounts_facebook').text()
									.toString().description,
									'\n') ||
								null,
							wordpress: console.log(' Wordpress  :   '.info + $(
										'a.accounts_wordpress').text().toString().description,
									'\n') ||
								null,

							googlePlus: console.log(' Google +  :    '.info + $(
									'a.accounts_google').attr('href') || 'true',
								'\n') || null,

							linkedIn: console.log(' LinkedIn  :    '.info + $(
									'a.accounts_linkedin').attr('href'),
								'\n') || null
						};
					}
				});
			}
			getProfile();
		}, 5000);
	} else {
		/* do something */
	}
});
// to be continued ... [ Maths examination on 14th of March]
<commit_msg>spaces<commit_after>#!/usr/bin/env node

'use strict';

/* dependencies */

const fs = require('fs');
const http = require('follow-redirects').http;
const mkdirp = require('mkdirp');
const md5 = require('md5');
// const Parse = require('jsonparse');
const request = require('request');
const boxen = require('boxen');
const cheerio = require('cheerio');
const colors = require('colors');

colors.setTheme({
	directory: ['cyan', 'bold']
});

colors.setTheme({
	description: ['green', 'bold']
});

colors.setTheme({
	info: ['cyan', 'bold']
});

colors.setTheme({
	status: ['green', 'bold']
});

colors.setTheme({
	normal: ['red', 'bold']
});

colors.setTheme({
	error: ['red', 'bold']
});

const argv = require('yargs')
	.usage('\n Usage : $0 -u [email@id] -n [file name]'.info)
	.demand(['u', 'n'])
	.describe('u', '❱'.status + ' Email-Id of any gravatar user')
	.describe('n', '❱'.status + ' Name of Image')
	.argv;

const localFold = argv.n;

// hashing and storing the email
const hashEmail = md5(argv.u);

// passed
const usedAs = hashEmail;

// defining directories
// is the directory where the image will be saved
const saveImage = './Gravatar/';

// because I want to
const removeSlash = saveImage.replace('./', '');

// used where the directory is shown to the user
const forSaved = removeSlash.replace('/', '');

// finding username based on email address
// will show the user's data only if the gravatar user name of a person is starting chars of his email before '@'
function removeString(emailAddress) {
	// removing everything after '@', basic strategy used by gravtar for username
	return emailAddress.replace(/\@.*/, '');
}

// removing the google.plus text from the url
// the below function was used to parse url of googlePlus to show 'id', but since, while scrapping, if the id isn't found
// the code breaks. Disabling it to show complete url instead.
/*
function removeURL(urlAddress) {
		return urlAddress.replace(/\D/g,'');
}
*/

// stored argument
const replacedString = removeString(argv.u);

mkdirp(removeSlash, err => {
	if (err) {
		console.error(boxen('  Failed to create the directory   ').error);
	} else { /* referred to another mkdirp */ }
});

// loading lightweight page to check internet connection and creating directory based on the same process.
request('http://rishigiri.com/gravatar/', (error, response) => {
	if (!error && response.statusCode === 200) {
		console.log('\n\t ❱ Internet Connection    :    '.directory + '✔'.status);
		// another with same name
		mkdirp(removeSlash, err => {
			if (err) {
				console.log(boxen('  Failed to create the directory   ').error);
			} else {
				setTimeout(() => {
					console.log('\n\t ❱ Directory Created      :    '.directory + '✔'.status);
				}, 1000);
			}
		});
	} else {
		// console when statusCode !== 200 or no internet connection
		console.log('\n');
		console.log(boxen('  ERROR : Please check your internet connection  ').error);
		console.log('\n');
		// stop the whole process
		process.exit(1);
	}
});

console.log('\n  Fetching'.status, replacedString.toString().info, '\'s'.info,
	'gravatar data.'.status);
// requesting for image with hashed email address which was previously stored in 'usedAs'

request
	.get('http://1.gravatar.com/avatar/' + usedAs)

.on('response', response => {
	// checking for the type of remote image.
	const storeType = response.headers['content-type'];

	// initially the result comes like image/.gif
	// thus removing the 'image/' part
	const parseType = storeType.toString().replace('image/', '');

	// stored the possible extension in typeArray
	const typeArray = ['png', 'jpeg', 'gif'];

	// checking if the remote image is png
	if (response.statusCode === 200 && typeArray[0] === parseType) {
		// will save the image in the default defined directory
		const imageFile = fs.createWriteStream(removeSlash + argv.n + '.png');

		// started downloading image
		http.get('http://1.gravatar.com/avatar/' + usedAs + '?size=400px',
			res => {
				res.pipe(imageFile);
				setTimeout(() => {
					console.log('\n\t ❱ Image Saved In         :    '.directory +
						forSaved.toString().status + ' ❱ ' + localFold.toString().status +
						'.png\n'.status);
				}, 2000);
			}).on('error', err => {
				console.log(err);
			});
		// Parsing the HTML content for getting user's data.
		setTimeout(() => {
			function getProfile() {
				request('http://en.gravatar.com/' + replacedString, (error, response,
					html) => {
					if (!error && response.statusCode === 200) {
						// loading the whole HTML
						const $ = cheerio.load(html);
						return {
							// returning the datas
							name: console.log(' Name       :    '.info + $('h2.fn').text().toString()
								.description, '\n') || null,

							//
							place: console.log(' Location   :    '.info + $('p.location').text()
								.toString()
								.description, '\n') || null,

							bio: console.log(' Bio        :    '.info + $('p.description').text()
									.trim().replace('
', '').toString().description, '\n') ||
								null,

							twitter: console.log(' Twitter    :    '.info + $(
									'a.accounts_twitter')
								.text()
								.toString().description, '\n'
							) || null,

							facebook: console.log(' Facebook   :    '.info + $(
										'a.accounts_facebook').text()
									.toString().description,
									'\n') ||
								null,

							wordpress: console.log(' Wordpress   :   '.info + $(
										'a.accounts_wordpress').text().toString().description,
									'\n') ||
								null,

							// error parsing the data if url not found | better to remove
							// color not provided
							googlePlus: console.log(' Google +   :    '.info + $(
									'a.accounts_google').attr('href'),
								'\n') || null,

							linkedIn: console.log(' LinkedIn   :    '.info + $(
									'a.accounts_linkedin').attr('href'),
								'\n') || null
						};
					}
				});
			}
			getProfile();
		}, 5000);
	} else {
		/* something to be done | but no need */
	}
	// checking if the remote image if jpg/jpeg
	if (response.statusCode === 200 && typeArray[1] === parseType) {
		const imageFile = fs.createWriteStream(removeSlash + argv.n + '.jpeg');
		http.get('http://1.gravatar.com/avatar/' + usedAs + '?size=400px',
			res => {
				res.pipe(imageFile);
				setTimeout(() => {
					console.log('\n\t ❱ Image Saved In         :    '.directory +
						forSaved.toString().status + ' ❱ ' + localFold.toString().status +
						'.jpeg\n'.status);
				}, 2000);
			}).on('error', err => {
				console.log(err);
			});
		// Parsing the HTML content for getting user's data.
		setTimeout(() => {
			function getProfile() {
				request('http://en.gravatar.com/' + replacedString, (error, response,
					html) => {
					if (!error && response.statusCode === 200) {
						// loading the whole HTML
						const $ = cheerio.load(html);
						return {
							// returning the datas
							name: console.log(' Name       :    '.info + $('h2.fn').text().toString()
								.description, '\n') || null,

							place: console.log(' Location   :    '.info + $('p.location').text()
								.toString()
								.description, '\n') || null,

							bio: console.log(' Bio        :    '.info + $('p.description').text()
									.trim().replace('
', '').toString().description, '\n') ||
								null,
							// twitter name would be fine | instead URL
							twitter: console.log(' Twitter    :    '.info + $(
									'a.accounts_twitter')
								.text()
								.toString().description, '\n'
							) || null,

							facebook: console.log(' Facebook   :    '.info + $(
										'a.accounts_facebook').text()
									.toString().description,
									'\n') ||
								null,
							wordpress: console.log(' Wordpress   :   '.info + $(
										'a.accounts_wordpress').text().toString().description,
									'\n') ||
								null,

							googlePlus: console.log(' Google +   :    '.info + $(
									'a.accounts_google').attr('href') || 'true',
								'\n') || null,

							linkedIn: console.log(' LinkedIn   :    '.info + $(
									'a.accounts_linkedin').attr('href'),
								'\n') || null
						};
					}
				});
			}
			getProfile();
		}, 5000);
	} else {
		/* do something */
	}
});
// to be continued ... [ Maths examination on 14th of March]
<|endoftext|>


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

var amok = require('./');
var async = require('async');

var fs = require('fs');
var path = require('path');
var repl = require('repl');
var util = require('util');

var bole = require('bole');
var bistre = require('bistre');

function program(callback, data) {
  var cmd = require('commander');
  var pkg = require('./package.json');

  cmd.usage('[options] <script | url>');
  cmd.version(pkg.version);

  cmd.option('--host <HOST>', 'specify http host', 'localhost');
  cmd.option('--port <PORT>', 'specify http port', 9966);

  cmd.option('--debugger-host <HOST>', 'specify debugger host', 'localhost');
  cmd.option('--debugger-port <PORT>', 'specify debugger port', 9222);

  cmd.option('-i, --interactive', 'enable interactive mode');
  cmd.option('-w, --watch <GLOB>', 'specify watch pattern', process.cwd());

  cmd.option('--client <CMD>', 'specify the client to spawn');
  cmd.option('--compiler <CMD>', 'specify the compiler to spawn');

  cmd.option('-v, --verbose', 'enable verbose logging mode');

  cmd.parse(process.argv);
  cmd.cwd = process.cwd();

  if (cmd.args.length < 1) {
    cmd.help();
  }

  var scripts = cmd.args.filter(function(arg) {
    return arg.match(/[^\\/]+$/);
  });

  var url = cmd.args.filter(function(arg) {
    return arg.match(/^(http|https):\/\//);
  }).pop();

  cmd.scripts = scripts.reduce(function(object, value, key) {
    object[value] = path.resolve(value);
    return object;
  }, {});

  cmd.url = url;

  var transform = bistre.createStream();
  transform.pipe(process.stdout);

  bole.output({
    level: cmd.verbose ? 'info' : 'error',
    stream: transform
  });

  callback(null, cmd);
}

function compiler(callback, data) {
  var log = bole('compile');

  if (data.program.compiler === undefined) {
    log.info('skip');
    return callback(null, null);
  }

  log.info('spawn');

  var compiler = amok.compile(data.program, function(error, stdout, stderr) {
    if (error) {
      return callback(error);
    }

    log.info('ok', { pid: compiler.pid });

    data.program.scripts = {
      'bundle.js': compiler.output,
    };

    callback(null, compiler);
  });

  compiler.stdout.on('data', function(data) {
    log.info(data.toString());
  });

  compiler.stderr.on('data', function(data) {
    log.error(data.toString());
  });
}

function watcher(callback, data) {
  var log = bole('watch');

  log.info('start');
  var watcher = amok.watch(data.program, function() {
    log.info('ok');

    callback(null, watcher);
  });

  var emit = function(event, filename) {
    filename = path.relative(process.cwd(), filename);

    var source = 'if (typeof(window) !== \'undefined\') {'
               + '  var e = new CustomEvent(\''+ event + '\','
               + '    { detail: \'' + filename +'\' });'
               + ''
               + '  window.dispatchEvent(e);'
               + '}';
               + ''
               + 'if (typeof(process) !== \'undefined\') {'
               + '  process.emit(\'' + event + '\', \'' + filename + '\');'
               + '}';

    data.bugger.evaluate(source, function(error, result) {
      if (error) {
        log.error(error);
      }
    });
  };

  watcher.on('add', function(filename) {
    log.info('add', { filename: filename });
    emit('add', filename);
  });

  watcher.on('unlink', function(filename) {
    log.info('remove', { filename: filename });
    emit('remove', filename);
  });

  watcher.on('change', function(filename) {
    log.info('change', { filename: filename });
    emit('change', filename);

    var script = Object.keys(data.program.scripts).filter(function(key) {
      return data.program.scripts[key] === filename;
    }).pop();

    if (script == undefined) {
      var scripts = data.bugger._scripts.map(function(obj) {
        return path.basename(obj.url);
      });

      script = scripts.filter(function(basename) {
        return path.resolve(basename) == filename;
      })[0];
    }

    if (script) {
      log.info('re-compile', { filename: filename });

      fs.readFile(filename, 'utf-8', function(error, contents) {
        if (error) {
          log.error(error);
        }

        data.bugger.source(script, contents, function(error) {
          if (error) {
            return log.error(error);
          }

          log.info('ok');
          emit('source', filename);
        });
      });
    }
  });

  watcher.on('error', function(error) {
    log.error(error);
    process.exit(error.errno);
  });
}

function server(callback, data) {
  var log = bole('http');

  if (data.program.url) {
    log.info('skip');
    return callback(null, null);
  }

  log.info('starting');

  var server = amok.serve(data.program, function() {
    var address = server.address();
    log.info('listening', { host: address.address, port: address.port });

    data.program.url = util.format('http://%s:%d', options.host, options.port);
    callback(null, server);
  });

  server.on('request', function(request, response) {
    log.info(request);
  });

  server.on('error', function(error) {
    log.error(error);
    process.exit(error.errno);
  });
}

function client(callback, data) {
  var log = bole('client');

  if (data.program.client === undefined) {
    log('skip');
    return callback(null, null);
  }

  log.info('spawn');
  var client = amok.open(data.program, function(error, stdout, stderr) {
    if (error) {
      return callback(error);
    }

    log.info('ok', { pid: client.pid });
    callback(null, client);
  });

  client.on('error', function(error) {
    log.error(error);
    process.exit(error.errno);
  });

  client.stdout.on('data', function(data) {
    log.info(data.toString());
  });

  client.stderr.on('data', function(data) {
    log.warn(data.toString());
  });
}

function bugger(callback, data) {
  var log = bole('debugger');

  log.info('connect');

  var bugger = amok.debug(data.program, function(error, target) {
    if (error) {
      return callback(error);
    }

    callback(null, bugger);
  });

  bugger.on('attach', function(target) {
    log.info('attach', { url: target.url, title: target.title });
  });

  bugger.on('detatch', function() {
    log.warn('detatch');
  });

  bugger.on('error', function(error) {
    log.error(error);
    process.exit(error.errno);
  });

  bugger.console.on('data', function(message) {
    if (message.parameters) {
      var parameters = message.parameters.map(function(parameter) {
        return parameter.value;
      });

      if (console[message.level]) {
        console[message.level].apply(console, parameters);
      }
    }
  });
}

function prompt(callback, data) {
  if (data.program.interactive === undefined) {
    return callback(null, null);
  }

  var options = {
    prompt: '> ',
    input: process.stdin,
    output: process.stdout,
    writer: function(result) {
      if (result.value) {
        return util.inspect(result.value, {
          colors: true,
        });
      } else if (result.objectId) {
        return util.format('[class %s]\n%s', result.className, result.description);
      }
    },

    eval: function(cmd, context, filename, write) {
      data.bugger.evaluate(data.program, function(error, result) {
        write(error, result);
      });
    },
  };

  var prompt = repl.start(options);
  callback(null, prompt);
}

async.auto({
  'program': [program],
  'compiler': ['program', compiler],
  'server': ['program', 'compiler', server],
  'client': ['program', 'server', client],
  'bugger': ['program', 'client', bugger],
  'watcher': ['program', 'bugger', watcher],
  'prompt': ['program', 'bugger', prompt],
}, function(error, data) {
  if (error) {
    console.error(error);
    process.exit(1);
  }
});
<commit_msg>Fix program url when spawning a server<commit_after>#!/usr/bin/env node

var amok = require('./');
var async = require('async');

var fs = require('fs');
var path = require('path');
var repl = require('repl');
var util = require('util');

var bole = require('bole');
var bistre = require('bistre');

function program(callback, data) {
  var cmd = require('commander');
  var pkg = require('./package.json');

  cmd.usage('[options] <script | url>');
  cmd.version(pkg.version);

  cmd.option('--host <HOST>', 'specify http host', 'localhost');
  cmd.option('--port <PORT>', 'specify http port', 9966);

  cmd.option('--debugger-host <HOST>', 'specify debugger host', 'localhost');
  cmd.option('--debugger-port <PORT>', 'specify debugger port', 9222);

  cmd.option('-i, --interactive', 'enable interactive mode');
  cmd.option('-w, --watch <GLOB>', 'specify watch pattern', process.cwd());

  cmd.option('--client <CMD>', 'specify the client to spawn');
  cmd.option('--compiler <CMD>', 'specify the compiler to spawn');

  cmd.option('-v, --verbose', 'enable verbose logging mode');

  cmd.parse(process.argv);
  cmd.cwd = process.cwd();

  if (cmd.args.length < 1) {
    cmd.help();
  }

  var scripts = cmd.args.filter(function(arg) {
    return arg.match(/[^\\/]+$/);
  });

  var url = cmd.args.filter(function(arg) {
    return arg.match(/^(http|https):\/\//);
  }).pop();

  cmd.scripts = scripts.reduce(function(object, value, key) {
    object[value] = path.resolve(value);
    return object;
  }, {});

  cmd.url = url;

  var transform = bistre.createStream();
  transform.pipe(process.stdout);

  bole.output({
    level: cmd.verbose ? 'info' : 'error',
    stream: transform
  });

  callback(null, cmd);
}

function compiler(callback, data) {
  var log = bole('compile');

  if (data.program.compiler === undefined) {
    log.info('skip');
    return callback(null, null);
  }

  log.info('spawn');

  var compiler = amok.compile(data.program, function(error, stdout, stderr) {
    if (error) {
      return callback(error);
    }

    log.info('ok', { pid: compiler.pid });

    data.program.scripts = {
      'bundle.js': compiler.output,
    };

    callback(null, compiler);
  });

  compiler.stdout.on('data', function(data) {
    log.info(data.toString());
  });

  compiler.stderr.on('data', function(data) {
    log.error(data.toString());
  });
}

function watcher(callback, data) {
  var log = bole('watch');

  log.info('start');
  var watcher = amok.watch(data.program, function() {
    log.info('ok');

    callback(null, watcher);
  });

  var emit = function(event, filename) {
    filename = path.relative(process.cwd(), filename);

    var source = 'if (typeof(window) !== \'undefined\') {'
               + '  var e = new CustomEvent(\''+ event + '\','
               + '    { detail: \'' + filename +'\' });'
               + ''
               + '  window.dispatchEvent(e);'
               + '}';
               + ''
               + 'if (typeof(process) !== \'undefined\') {'
               + '  process.emit(\'' + event + '\', \'' + filename + '\');'
               + '}';

    data.bugger.evaluate(source, function(error, result) {
      if (error) {
        log.error(error);
      }
    });
  };

  watcher.on('add', function(filename) {
    log.info('add', { filename: filename });
    emit('add', filename);
  });

  watcher.on('unlink', function(filename) {
    log.info('remove', { filename: filename });
    emit('remove', filename);
  });

  watcher.on('change', function(filename) {
    log.info('change', { filename: filename });
    emit('change', filename);

    var script = Object.keys(data.program.scripts).filter(function(key) {
      return data.program.scripts[key] === filename;
    }).pop();

    if (script == undefined) {
      var scripts = data.bugger._scripts.map(function(obj) {
        return path.basename(obj.url);
      });

      script = scripts.filter(function(basename) {
        return path.resolve(basename) == filename;
      })[0];
    }

    if (script) {
      log.info('re-compile', { filename: filename });

      fs.readFile(filename, 'utf-8', function(error, contents) {
        if (error) {
          log.error(error);
        }

        data.bugger.source(script, contents, function(error) {
          if (error) {
            return log.error(error);
          }

          log.info('ok');
          emit('source', filename);
        });
      });
    }
  });

  watcher.on('error', function(error) {
    log.error(error);
    process.exit(error.errno);
  });
}

function server(callback, data) {
  var log = bole('http');

  if (data.program.url) {
    log.info('skip');
    return callback(null, null);
  }

  log.info('starting');

  var server = amok.serve(data.program, function() {
    var address = server.address();
    log.info('listening', { host: address.address, port: address.port });

    data.program.url = util.format('http://%s:%d', data.program.host, data.program.port);
    callback(null, server);
  });

  server.on('request', function(request, response) {
    log.info(request);
  });

  server.on('error', function(error) {
    log.error(error);
    process.exit(error.errno);
  });
}

function client(callback, data) {
  var log = bole('client');

  if (data.program.client === undefined) {
    log('skip');
    return callback(null, null);
  }

  log.info('spawn');
  var client = amok.open(data.program, function(error, stdout, stderr) {
    if (error) {
      return callback(error);
    }

    log.info('ok', { pid: client.pid });
    callback(null, client);
  });

  client.on('error', function(error) {
    log.error(error);
    process.exit(error.errno);
  });

  client.stdout.on('data', function(data) {
    log.info(data.toString());
  });

  client.stderr.on('data', function(data) {
    log.warn(data.toString());
  });
}

function bugger(callback, data) {
  var log = bole('debugger');

  log.info('connect');

  var bugger = amok.debug(data.program, function(error, target) {
    if (error) {
      return callback(error);
    }

    callback(null, bugger);
  });

  bugger.on('attach', function(target) {
    log.info('attach', { url: target.url, title: target.title });
  });

  bugger.on('detatch', function() {
    log.warn('detatch');
  });

  bugger.on('error', function(error) {
    log.error(error);
    process.exit(error.errno);
  });

  bugger.console.on('data', function(message) {
    if (message.parameters) {
      var parameters = message.parameters.map(function(parameter) {
        return parameter.value;
      });

      if (console[message.level]) {
        console[message.level].apply(console, parameters);
      }
    }
  });
}

function prompt(callback, data) {
  if (data.program.interactive === undefined) {
    return callback(null, null);
  }

  var options = {
    prompt: '> ',
    input: process.stdin,
    output: process.stdout,
    writer: function(result) {
      if (result.value) {
        return util.inspect(result.value, {
          colors: true,
        });
      } else if (result.objectId) {
        return util.format('[class %s]\n%s', result.className, result.description);
      }
    },

    eval: function(cmd, context, filename, write) {
      data.bugger.evaluate(data.program, function(error, result) {
        write(error, result);
      });
    },
  };

  var prompt = repl.start(options);
  callback(null, prompt);
}

async.auto({
  'program': [program],
  'compiler': ['program', compiler],
  'server': ['program', 'compiler', server],
  'client': ['program', 'server', client],
  'bugger': ['program', 'client', bugger],
  'watcher': ['program', 'bugger', watcher],
  'prompt': ['program', 'bugger', prompt],
}, function(error, data) {
  if (error) {
    console.error(error);
    process.exit(1);
  }
});
<|endoftext|>


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

var cmd = require('commander');
var amok = require('./');
var temp = require('temp');
var path = require('path');
var async = require('async');

var pkg = require('./package.json');

cmd.usage('[options] <script>');

cmd.option('-h, --host <HOST>', 'specify http host', 'localhost');
cmd.option('-p, --port <PORT>', 'specify http port', 9966);

cmd.option('-H, --debugger-host <HOST>', 'specify debugger host', 'localhost');
cmd.option('-P, --debugger-port <PORT>', 'specify debugger port', 9222);
cmd.option('-v, --verbose', 'enable verbose logging mode');

cmd.option('--no-bundler', 'disable bundling');
cmd.option('--no-browser', 'disable browsing');
cmd.option('--no-debugger', 'disable debugging');

cmd.version(pkg.version);
cmd.parse(process.argv);

cmd.cwd = process.cwd();
if (cmd.browser !== false) {
  cmd.browser = process.env['BROWSER'] || process.env['AMOK_BROWSER'];
}

if (cmd.bundler !== false) {
  cmd.bundler = process.env['BUNDLER'] || process.env['AMOK_BUNDLER'];
}

async.auto({
  bundler: function(callback, data) {
    if (cmd.bundler) {
      if (cmd.verbose) {
        console.info('Spawning bundler...');
      }

      cmd.scripts = { 'bundle.js': temp.path({suffix: '.js'}) };

      cmd.args.push('-o');
      cmd.args.push(cmd.scripts['bundle.js']);

      var bundler = amok.bundle(cmd, function(error, stdout, stderr) {
        if (error) {
          return callback(error);
        }

        stdout.pipe(process.stdout);
        stderr.pipe(process.stderr);

        callback(null, bundler);
      });

    } else {
      cmd.scripts = cmd.args.reduce(function(object, value, key) {
        object[value] = path.resolve(value);
        return object;
      }, {});

      callback(null, null);
    }
  },

  watcher: ['bundler', 'bugger', function(callback, data) {
    var watcher = amok.watch(cmd, function() {
      if (cmd.verbose) {
        console.info('File watcher ready');
      }
      watcher.on('change', function(filename) {
        if (cmd.verbose) {
          console.info(filename, 'changed');
        }

        var script = Object.keys(cmd.scripts)
          .filter(function(key) {
            return cmd.scripts[key] === filename
          })[0];

        if (script) {
          if (cmd.verbose) {
            console.info('Re-compiling', script, '...');
          }

          data.bugger.source(script, null, function(error) {
            if (error) {
              return console.error(error);
            }

            if (cmd.verbose) {
              console.info('Re-compilation succesful');
            }
          });
        }
      });

      callback(null, watcher);
    });
  }],

  server: function(callback, data) {
    if (cmd.verbose) {
      console.info('Starting server...');
    }

    var server = amok.serve(cmd, function() {
      var address = server.address();
      if (cmd.verbose) {
        console.info('Server listening on http://%s:%d', address.address, address.port);
      }

      callback(null, server);
    });
  },

  browser: ['server', function(callback, data) {
    if (cmd.browser) {
      if (cmd.verbose) {
        console.log('Spawning browser...');
      }

      var browser = amok.browse(cmd, function(error, stdout, stderr) {
        if (error) {
          process.stdout.write(error);
        }

        process.stdout.write(stdout);
        process.stderr.write(stderr);
        callback();
      });
    } else {
      callback();
    }
  }],

  bugger: ['browser', function(callback, data) {
    if (cmd.debugger) {
      if (cmd.verbose) {
        console.info('Attaching debugger...');
      }

      var bugger = amok.debug(cmd, function(target) {
        if (cmd.verbose) {
          console.info('Debugger attached to %s', target.url);
        }

        bugger.on('detach', function() {
          if (cmd.verbose) {
            console.info('Debugger detatched');
          }
        });

        bugger.on('attach', function(target) {
          if (cmd.verbose) {
            console.info('Debugger attached to %s', target.url);
          }
        });

        callback(null, bugger);
      });
    }
  }],
}, function(error) {
  if (error) {
    return console.error(error);
  }
});
<commit_msg>Fix callback invocations<commit_after>#!/usr/bin/env node

var cmd = require('commander');
var amok = require('./');
var temp = require('temp');
var path = require('path');
var async = require('async');

var pkg = require('./package.json');

cmd.usage('[options] <script>');

cmd.option('-h, --host <HOST>', 'specify http host', 'localhost');
cmd.option('-p, --port <PORT>', 'specify http port', 9966);

cmd.option('-H, --debugger-host <HOST>', 'specify debugger host', 'localhost');
cmd.option('-P, --debugger-port <PORT>', 'specify debugger port', 9222);
cmd.option('-v, --verbose', 'enable verbose logging mode');

cmd.option('--no-bundler', 'disable bundling');
cmd.option('--no-browser', 'disable browsing');
cmd.option('--no-debugger', 'disable debugging');

cmd.version(pkg.version);
cmd.parse(process.argv);

cmd.cwd = process.cwd();
if (cmd.browser !== false) {
  cmd.browser = process.env['BROWSER'] || process.env['AMOK_BROWSER'];
}

if (cmd.bundler !== false) {
  cmd.bundler = process.env['BUNDLER'] || process.env['AMOK_BUNDLER'];
}

async.auto({
  bundler: function(callback, data) {
    if (cmd.bundler) {
      if (cmd.verbose) {
        console.info('Spawning bundler...');
      }

      cmd.scripts = { 'bundle.js': temp.path({suffix: '.js'}) };

      cmd.args.push('-o');
      cmd.args.push(cmd.scripts['bundle.js']);

      var bundler = amok.bundle(cmd, function(error, stdout, stderr) {
        if (error) {
          return callback(error);
        }

        stdout.pipe(process.stdout);
        stderr.pipe(process.stderr);

        callback(null, bundler);
      });

    } else {
      cmd.scripts = cmd.args.reduce(function(object, value, key) {
        object[value] = path.resolve(value);
        return object;
      }, {});

      callback(null, null);
    }
  },

  watcher: ['bundler', 'bugger', function(callback, data) {
    var watcher = amok.watch(cmd, function() {
      if (cmd.verbose) {
        console.info('File watcher ready');
      }
      watcher.on('change', function(filename) {
        if (cmd.verbose) {
          console.info(filename, 'changed');
        }

        var script = Object.keys(cmd.scripts)
          .filter(function(key) {
            return cmd.scripts[key] === filename
          })[0];

        if (script) {
          if (cmd.verbose) {
            console.info('Re-compiling', script, '...');
          }

          data.bugger.source(script, null, function(error) {
            if (error) {
              return console.error(error);
            }

            if (cmd.verbose) {
              console.info('Re-compilation succesful');
            }
          });
        }
      });

      callback(null, watcher);
    });
  }],

  server: function(callback, data) {
    if (cmd.verbose) {
      console.info('Starting server...');
    }

    var server = amok.serve(cmd, function() {
      var address = server.address();
      if (cmd.verbose) {
        console.info('Server listening on http://%s:%d', address.address, address.port);
      }

      callback(null, server);
    });
  },

  browser: ['server', function(callback, data) {
    if (cmd.browser) {
      if (cmd.verbose) {
        console.log('Spawning browser...');
      }

      var browser = amok.browse(cmd, function(error, stdout, stderr) {
        if (error) {
          process.stdout.write(error);
        }

        process.stdout.write(stdout);
        process.stderr.write(stderr);
        callback(null, browser);
      });
    } else {
      callback(null, null);
    }
  }],

  bugger: ['browser', function(callback, data) {
    if (cmd.debugger) {
      if (cmd.verbose) {
        console.info('Attaching debugger...');
      }

      var bugger = amok.debug(cmd, function(target) {
        if (cmd.verbose) {
          console.info('Debugger attached to %s', target.url);
        }

        bugger.on('detach', function() {
          if (cmd.verbose) {
            console.info('Debugger detatched');
          }
        });

        bugger.on('attach', function(target) {
          if (cmd.verbose) {
            console.info('Debugger attached to %s', target.url);
          }
        });

        callback(null, bugger);
      });
    }
  }],
}, function(error) {
  if (error) {
    return console.error(error);
  }
});
<|endoftext|>


<commit_before>var clip = function() {
  var nw = map.containerPointToLayerPoint([0, 0]),
      se = map.containerPointToLayerPoint(map.getSize()),
      clipX = nw.x + (se.x - nw.x) * range.value;
  cmp.getContainer().style.clip =
    'rect(' + [nw.y, clipX, se.y, nw.x].join('px,') + 'px)';
}

var main_loop = function() {
  gsimaps = 'http://maps.gsi.go.jp/?ll=' +
    LAT + ',' + LNG + '&z=16&base=std&cd=f2%2Ff2_6&vs=c1j0l0u0&d=l';
  attr = "地理院地図";
  ort = L.tileLayer(BG_URL, {
    attribution: attr, maxNativeZoom: 18, maxZoom: 20
  });
  cmp = L.tileLayer(FG_URL, {
    attribution: attr, maxNativeZoom: 18, maxZoom: 20
  });
  map = L.map('mapdiv', {
    center: [LAT, LNG], zoom: 16, minZoom: 10,
    layers: [ort, cmp], zoomControl: false});
  new L.Control.Zoom({ position: 'bottomright' }).addTo(map);
  var hash = L.hash(map);
  var range = document.getElementById('range');

  range['oninput' in range ? 'oninput' : 'onchange'] = clip;
  map.on('move', clip);
  clip();

  if(L.Browser.ie) {
    if(L.Browser.ielt9) {
      alert("被災前後比較はお使いのブラウザに対応していません。\nChrome, Firefox, Safari でアクセスしてください。\n地理院地図に移動します。");
    } else {
      alert("お使いのブラウザでは写真の境をスライダで調整できません。\nスライダが必要な場合、Chrome, Firefox, Safari でアクセスしてください。");
    }
    if(L.Browser.ielt9) document.location.href = gsimaps;
  }
}
<commit_msg>Update<commit_after>var clip = function() {
  var nw = map.containerPointToLayerPoint([0, 0]),
      se = map.containerPointToLayerPoint(map.getSize()),
      clipX = nw.x + (se.x - nw.x) * range.value;
  cmp.getContainer().style.clip =
    'rect(' + [nw.y, clipX, se.y, nw.x].join('px,') + 'px)';
}

var main_loop = function() {
  gsimaps = 'http://maps.gsi.go.jp/?ll=' +
    LAT + ',' + LNG + '&z=16&base=std&cd=f2%2Ff2_6&vs=c1j0l0u0&d=l';
  attr = "地理院地図";
  ort = L.tileLayer(BG_URL, {
    attribution: attr, maxNativeZoom: 18, maxZoom: 20
  });
  cmp = L.tileLayer(FG_URL, {
    attribution: attr, maxNativeZoom: 18, maxZoom: 20
  });
  map = L.map('mapdiv', {
    center: [LAT, LNG], zoom: 16, minZoom: 10,
    layers: [ort, cmp], zoomControl: false, attributionControl: false});
  L.control.attribution({
    position: 'bottomright',
    prefix: "使い方"
  }).addTo(map);
  L.control.zoom({ position: 'bottomright' }).addTo(map);
  var hash = L.hash(map);
  var range = document.getElementById('range');

  range['oninput' in range ? 'oninput' : 'onchange'] = clip;
  map.on('move', clip);
  clip();

  if(L.Browser.ie) {
    if(L.Browser.ielt9) {
      alert("被災前後比較はお使いのブラウザに対応していません。\nChrome, Firefox, Safari でアクセスしてください。\n地理院地図に移動します。");
    } else {
      alert("お使いのブラウザでは写真の境をスライダで調整できません。\nスライダが必要な場合、Chrome, Firefox, Safari でアクセスしてください。");
    }
    if(L.Browser.ielt9) document.location.href = gsimaps;
  }
}
<|endoftext|>