示例#1
0
文件: index.js 项目: wuchu/mpt-cli
co(function *() {
    let input = yield new Promise((resovle, reject, notify) => {
        let result = [];
        process.stdin.on('readable', () => {
            let buf = process.stdin.read();
            result.push(buf);
            if(null === buf) {
                resovle(result.join(''));
            }
        });
    });
    let tStats = yield program.args.map(file => fs.stat(file));
    let files = program.args.filter((file, i) => tStats[i].isFile());
    let sources = yield files.map(file => fs.readFile(file));
    let parsed = sources.map(source => source.toString('utf8'));
    let source = '';
    if (parsed.length > 0) {
        source = parsed.reduce((prev, next) => prev + '\n' + next);
    }
    let output = mpt({
        source: input + '\n' + source,
        queryList: program.queryList,
        uiWidth: program.uiWidth,
        baseWidth: program.baseWidth
    });
    console.log(output);
}).catch(function (err) {
示例#2
0
文件: cmd.js 项目: dhenson02/amok
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);
}
示例#3
0
文件: cli.js 项目: anthonydpaul/adp
function broccoliCLI () {
  program
    .usage('[options] <command> [<args ...>]')
    .on('--help', function () {
      console.log('  Available commands:')
      console.log()
      console.log('    serve')
      console.log('    build <output-dir>')
      console.log()
    })
    .parse(process.argv)

  var command = program.args.shift()

  if (command === 'serve') {
    if (program.args.length !== 0) program.help()
    broccoli.server.serve(getBuilder())
  } else if (command === 'build') {
    if (program.args.length !== 1) program.help()
    var outputDir = program.args.shift()
    var builder = getBuilder()
    builder.build()
      .then(function (dir) {
        try {
          fs.mkdirSync(outputDir)
        } catch (err) {
          if (err.code !== 'EEXIST') throw err
          console.error('Error: Directory "' + outputDir + '" already exists. Refusing to overwrite files.')
          process.exit(1)
        }
        return RSVP.denodeify(ncp)(dir, outputDir, {
          clobber: false,
          stopOnErr: true
        })
      })
      .then(function () {
        process.exit(0)
      })
      .catch(function (err) {
        // Should show file and line/col if present
        console.error(err.stack)
        console.error('\nBuild failed')
        process.exit(1)
      })
  } else {
    program.help()
  }
}
示例#4
0
function requestData() {
	log("Commencing initial data request.\nSpooled URLs are:");
	basCLI.args.forEach(function(url) {
		log(("\t" + url).blue);
	});
	log("\n");
	
	
	if (basCLI.crawl) {
		log("We're crawling based on these URLs.");
		startCrawl();
	} else {
		// Build a sequence for async!
		var sequence = [];
		seedURLs.forEach(function(url) {
			sequence.push(function(done) {
				request(url,function(err,res,body) {
					if (err) return done(err);
					handleResponse(url,res,body,done);
				});
			});
		});
		
		async.series(sequence,printReport);
	}
}
示例#5
0
(function () {
    //Requiring files
    var fs = require('fs');
    var mt = require('./../lib/metatags');
    var carrier = require('carrier')
    var program = require('commander')

    process.stdin.resume()
    process.stdin.setEncoding('utf8')
    var rl = carrier.carry(process.stdin)

    rl.on('line', function (data) {
        //Reading files
        var stream = fs.createReadStream(data)
        mt.metatags(stream, function (result) {
            result.file = data
            console.log(JSON.stringify(result))
        })
    })


    program.version('1.0.0')
        .parse(process.argv)

    // only process if arguments are provided
    if (program.args.length > 0) {
        program.args.forEach(function (a) {
            process.stdin.push(a)
            process.stdin.push('\n')
        })
        process.stdin.push(null)
    }

}).call(this)
示例#6
0
program.commands.forEach(function (command) {
    program.args.forEach(function (arg) {
        if (command._name === arg) {
            found = 1;
        }
    });
});
示例#7
0
function startRelay () {
  config.relay = Commander.args.shift();
  config.portMap = new PortMap();

  Commander.args.forEach((portString) => {
    try {
      config.portMap.addFromString(portString);
    } catch (e) {
      console.log('Error: port map failed. %s', e);
      process.exit(1);
    }
  });

  // required late so we can change process.env.LOG_LEVEL with option
  const Relay = require('../lib/index');

  state.relay = new Relay(config);
}
示例#8
0
version(function kickoff(success, v) {
	if(success) {
		program
			.version(v)
			.usage('[options] <folder ...> <file ...> [<destination.json>]\n\t NOTE: Does not support animated gif')			
			.option('-p. --prefix <prefix>', 'prefix the src in the output JSON - the first argument after -p must be the <prefix>\n\t\t\t   Example: -p "../assets/images/highres"')
			.option('-f, --filter <filter>', 'filter image files - the first argument after -f must be the <filter>\n\t\t\t   Example: -f "image\\d{2}"')
			.option('-v, --verbose', 'output process information - error messages will always be output')
			.parse(process.argv);

		if(program.args.length === 0)
			program.help();

/*log(' args: %j', program.args);
log(' args: %j', program.prefix);
log(' args: %j', program.filter);
log(' args: %j', program.verbose);*/

		if( hasDestination.test(program.args.slice(-1)[0]) )
			destination = program.args.splice(-1)[0];

		program.args.forEach(function(argument, i, all) {
			fs.stat(argument, function folderOrFile(err, stat) {
				if(err) {
					log(err);
					return;
				}
				//console.log(argument, program.prefix);

				if(stat.isFile()) {
					im.readFile(argument, imageHandler, { verbose: program.verbose, filter: program.filter, prefix: program.prefix });
				} else if(stat.isDirectory()) {
					im.readFolder(argument, imageHandler, { verbose: program.verbose,filter: program.filter, prefix: program.prefix });	
				}
			});			
		});
		
	} else {
		log("Error: can not read file package.json.\nTERMINATING!")
		process.stdin.destroy();
		return;
	}	
});
示例#9
0
DummyCommand.run = function(args) {
  program.version('0.0.1').usage('<arguments...>').option('-t, --tacos', 'Add tacos').description(this.longDescription).parse (args);

  debugger;

  if (program.args.length) {
    console.log(program.args.join(" "));
  } else {
    console.log('Dummy success!');
  }
}
示例#10
0
function main() {
    var commander = require('commander');

    commander.version('0.0.1')
        .option('-o, --output [dest]', 'destination file')
        .usage('[options] <file ...> ')
        .parse(process.argv);


    if (commander.output && commander.args.length > 1) {
        console.log('Only one file can be supplied with "output".');
        commander.help();
    }
    if (commander.args.length === 0) {
        console.log('No files supplied');
        commander.help();
    }

    if (commander.output) {
        var obj = {
            src: commander.args.pop(),
            dst: commander.output
        };
        return JavaLZ4.uncompress(obj);
    }

    var index = -1;

    function decompress() {
        index ++;
        if (index >= commander.args.length) {
            return;
        }
        var filename = commander.args[index];



        if (filename.lastIndexOf('.lz4') !== filename.length - 4) {
            console.log('Refusing to decompress "' + filename + '" as it doest end with ".lz4"');
            return decompress();
        }

        console.log('Decompressing "' + filename + '"');
        var obj = {
            src: filename,
            dst: filename.substring(0, filename.length - 4)
        };

        JavaLZ4.uncompress(obj, decompress);
    }

    decompress();
}
示例#11
0
文件: cli.js 项目: spiralx/mongolab
exports.run = function(program) {
  // var conn = mongolab.get_connection(program.db);

  var sources = program.args.forEach(function(v) {
    if (path.extname(v) === '') {
      v += '.json';
    }
    if ('.\\/'.indexOf(v[0]) == -1) {
      v = path.join(__dirname, '..', 'data', v);
    }

    mongolab.load_data_file2(v)
      .then(function(data_file) {
        _.logger.info('Loaded data file: {0}', v);
      });
  });

}
示例#12
0
var runCLI = function() {
  // Parse command line options
  commander
    .arguments('<regexp> <dir> <cmd> [args...]')
    .action(function(regexp, dir, cmd, args) {
      commander.regexp = regexp;
      commander.dir = dir;
      commander.cmd = cmd;
      commander.args = args;
    })
    .parse(process.argv);

  // Running an npm command with program options requires '--'
  // before the program options
  var oidx = findIndex(commander.args, function(arg) {
    return /^-/.test(arg) && !/^--/.test(arg);
  });
  if (commander.cmd === 'npm' && oidx >= 0)
    commander.args.splice(oidx, 0, '--');

  // Use the given regular expression to filter modules
  var rx = new RegExp(commander.regexp);

  // Look for modules in the dependencies and devDependencies of the current
  // module
  var mod = require(path.join(process.cwd(), 'package.json'));
  map(filter(pairs(mod.dependencies).concat(pairs(mod.devDependencies)),
    function(dep) {
      return rx.test(dep[0]) && /^file:/.test(dep[1]);
    }), function(dep) {
    var resolve = function(s) {
      return s.replace(/\:name/, dep[0])
        .replace(/:path/, dep[1].split(':')[1]);
    };

    // Run the given command on each module
    exec(resolve([commander.cmd].concat(commander.args).join(' ')),
      resolve(commander.dir), function(err, val) {
        if(err) process.exit(err);
      });
  });
};
示例#13
0
文件: cli.js 项目: akoutmos/pug-lint
/* istanbul ignore next */
function run (args) {

  program
    .version(packageDetails.version)
    .description(packageDetails.description)
    .usage('[options] <file ...>')
    .option('-c, --config <path>', 'configuration file path')
    .option('-r, --reporter <reporter>', 'error reporter; console - default, inline', 'console')
    .parse(args)

  var config
    , reporter
    , linter = new Linter()
    , errors = []

  if (!program.args.length) {
    program.help()
  }

  config = configFile.load(program.config)
  reporter = configFile.getReporter(program.reporter)

  if (!reporter.writer) {
    console.error('Reporter "' + program.reporter + '" does not exist')
    process.exit(1)
  }

  linter.configure(config)

  program.args.forEach(function (arg) {
    errors = errors.concat(linter.checkPath(arg))
  })

  if (errors.length) {
    reporter.writer(errors)
    process.exit(2)
  } else {
    process.exit(0)
  }

}
示例#14
0
var pkg = require(__dirname + "/../package.json");

program.version(pkg.version);
program.usage('[options] <args ...>');
program.option('-v, --verbose', 'output verbose messages');
program.option('-f, --foo', 'option foo without arguments');
program.option('-b, --bar <arg>', 'option bar with an argument');
program.parse(process.argv);

// die when called without arguments
if (!program.args.length) {
    program.outputHelp();
    process.exit(1);
}

var arg = program.args.shift();

// call JavaScript API
var __short__ = new __module__(program);
__short__.on("complete", complete);
__short__.on("error", error);
__short__.on("progress", progress);
__short__.__method__(arg, callback);

// callback function
function callback(err, res) {
    if (err) {
        // console.log("failure:", err);
    } else {
        // console.log("success:", res);
    }
示例#15
0
文件: srv.js 项目: alfg/srv
// Parse CLI args.
program
  .version(pkg.version)
  .usage('entrypoint.js [options]')
  .option('-p, --port [n]', 'Port to listen on', process.env.PORT)
  .option('-H, --host [value]', 'Host to listen on', process.env.HOST)
  .option('-D, --docs [value]', 'Generate Docs from folder', config.docs.folder)
  .option('-L, --lint', 'Lint code with ESLint')
  .option('-n, --no-babel', 'Skip Babel transformation')
  .option('-C, --config [value]', 'Configuration file')
  .parse(process.argv);


// Parse entrypoint file.
let file = program.args.pop();
if (!file) {
  try {
    const packageJson = require(resolve(  // eslint-disable-line global-require
      process.cwd(), 'package.json'));
    file = packageJson.main;
  } catch (e) {
    console.error(chalk.red(e));
    process.exit(1);
  }
}

if (!file) {
  console.error(chalk.red('Error! Please supply a file.'));
  process.exit(1);
}
示例#16
0
                }
            }
        } else {
            console.log('Template configuration file ' + config.template + ' was not found.');
            process.exit(1);
        }
    }

    console.time('spent');

    config.verbose = program.verbose === true || config.verbose;
    config.lint = program.lint;

    comb.configure(config);

    vow.all(program.args.map(comb.processPath.bind(comb)))
    .then(function(changedFiles) {
        changedFiles = [].concat.apply([], changedFiles)
            .filter(function(isChanged) {
                return isChanged !== undefined;
            });

        for (var i = changedFiles.length, tbchanged = 0; i--;) {
            tbchanged += changedFiles[i];
        }

        var changed = config.lint ? 0 : tbchanged;

        if (config.verbose) {
            console.log('');
            console.log(changedFiles.length + ' file' + (changedFiles.length === 1 ? '' : 's') + ' processed');
示例#17
0
/// the program
cmd
  .version(require('../../package.json').version)
  .usage('[options] <file ...>')
  .option('-c, --config', 'use files from config')
  .option('-o, --output <file>', 'write output to <file>; default is js/caps.js')
  .parse(process.argv)

if (cmd.output) {
  config.fastload = config.output
}
if (cmd.args && cmd.args.length > 0) {
  config.yaml = cmd.args.forEach(function (file) {
    if (path.extname(file) === '.yaml') {
      return file
    }
  })
}
if (!config.files) {
  cmd.help()
  process.exit(0)
}

console.log('... reading files')
config.files.forEach(function (file) {
  console.log('    ' + file)
})
serialized = caps2js(config.files)
console.log('... writing to ' + config.fastload)
fs.writeFileSync(config.fastload, serialized, 'utf8')
示例#18
0
文件: cli.js 项目: ButuzGOL/gdem
program.on('*', function() {
  console.log('Unknown Command: ' + program.args.join(' '));
  program.help();
});
示例#19
0
'use strict'

const program = require('commander')

const List = require('../lib/list')
const Table = require('../lib/table')
const Utils = require('../lib/utils')

program
  .arguments('[repository]')
  .description('Lists all repositories and services. Specify a repository to list its containers.')
  .parse(process.argv)

const options = {
  repository: program.args.shift()
}

if (options.repository) {
  List.listContainersForRepository(options)
    .then((results) => {
      Table.log(results)
    })
    .catch(Utils.handleError)
} else {
  List.listContainerSummary(options)
    .then((results) => {
      function tableFormatter (obj, cell) {
        for (const key in obj) {
          if (!obj.hasOwnProperty(key)) continue
          cell(key === 'Count' ? '' : key, obj[key])
        }
示例#20
0
文件: cli.js 项目: a1ip/yaspeller
program.args.forEach(function(resource) {
    tasks.push(function(cb) {
        var subTasks = [];
        if(utils.isUrl(resource)) {
            if(utils.isSitemap(resource)) {
                yaspeller.checkSitemap(resource, function() {
                    cb();
                }, settings, onResource);
            } else {
                yaspeller.checkUrl(resource, function(err, data) {
                    onResource(err, data);
                    cb();
                }, settings);
            }
        } else {
            if(fs.existsSync(resource)) {
                if(utils.isDir(resource)) {
                    utils
                        .findFiles(resource, settings.fileExtensions, settings.excludeFiles)
                        .forEach(function(file) {
                            subTasks.push(function(subcb) {
                                yaspeller.checkFile(file, function(err, data) {
                                    onResource(err, data);
                                    subcb();
                                }, settings);
                            });
                        });

                    async.parallelLimit(subTasks, settings.maxRequests, function() {
                        cb();
                    });
                } else {
                    var file = pth.resolve(resource);
                    if(utils.isExcludedFile(file, settings.excludeFiles)) {
                        cb();
                    } else {
                        yaspeller.checkFile(file, function(err, data) {
                            onResource(err, data);
                            cb();
                        }, settings);
                    }
                }
            } else {
                onResource(true, Error(resource + ': is not exists'));
                cb();
            }
        }
    });
});
示例#21
0
文件: index.js 项目: SevenOutman/yarn
export function main({
  startArgs,
  args,
  endArgs,
}: {
  startArgs: Array<string>,
  args: Array<string>,
  endArgs: Array<string>,
}) {
  loudRejection();
  handleSignals();

  // set global options
  commander.version(version, '-v, --version');
  commander.usage('[command] [flags]');
  commander.option('--verbose', 'output verbose messages on internal operations');
  commander.option('--offline', 'trigger an error if any required dependencies are not available in local cache');
  commander.option('--prefer-offline', 'use network only if dependencies are not available in local cache');
  commander.option('--strict-semver');
  commander.option('--json', 'format Yarn log messages as lines of JSON (see jsonlines.org)');
  commander.option('--ignore-scripts', "don't run lifecycle scripts");
  commander.option('--har', 'save HAR output of network traffic');
  commander.option('--ignore-platform', 'ignore platform checks');
  commander.option('--ignore-engines', 'ignore engines check');
  commander.option('--ignore-optional', 'ignore optional dependencies');
  commander.option('--force', 'install and build packages even if they were built before, overwrite lockfile');
  commander.option('--skip-integrity-check', 'run install without checking if node_modules is installed');
  commander.option('--check-files', 'install will verify file tree of packages for consistency');
  commander.option('--no-bin-links', "don't generate bin links when setting up packages");
  commander.option('--flat', 'only allow one version of a package');
  commander.option('--prod, --production [prod]', '', boolify);
  commander.option('--no-lockfile', "don't read or generate a lockfile");
  commander.option('--pure-lockfile', "don't generate a lockfile");
  commander.option('--frozen-lockfile', "don't generate a lockfile and fail if an update is needed");
  commander.option('--update-checksums', 'update package checksums from current repository');
  commander.option('--link-duplicates', 'create hardlinks to the repeated modules in node_modules');
  commander.option('--link-folder <path>', 'specify a custom folder to store global links');
  commander.option('--global-folder <path>', 'specify a custom folder to store global packages');
  commander.option(
    '--modules-folder <path>',
    'rather than installing modules into the node_modules folder relative to the cwd, output them here',
  );
  commander.option('--preferred-cache-folder <path>', 'specify a custom folder to store the yarn cache if possible');
  commander.option('--cache-folder <path>', 'specify a custom folder that must be used to store the yarn cache');
  commander.option('--mutex <type>[:specifier]', 'use a mutex to ensure only one yarn instance is executing');
  commander.option('--emoji [bool]', 'enable emoji in output', boolify, process.platform === 'darwin');
  commander.option('-s, --silent', 'skip Yarn console logs, other types of logs (script output) will be printed');
  commander.option('--cwd <cwd>', 'working directory to use', process.cwd());
  commander.option('--proxy <host>', '');
  commander.option('--https-proxy <host>', '');
  commander.option('--registry <url>', 'override configuration registry');
  commander.option('--no-progress', 'disable progress bar');
  commander.option('--network-concurrency <number>', 'maximum number of concurrent network requests', parseInt);
  commander.option('--network-timeout <milliseconds>', 'TCP timeout for network requests', parseInt);
  commander.option('--non-interactive', 'do not show interactive prompts');
  commander.option(
    '--scripts-prepend-node-path [bool]',
    'prepend the node executable dir to the PATH in scripts',
    boolify,
  );
  commander.option('--no-node-version-check', 'do not warn when using a potentially unsupported Node version');

  // if -v is the first command, then always exit after returning the version
  if (args[0] === '-v') {
    console.log(version.trim());
    process.exitCode = 0;
    return;
  }

  // get command name
  const firstNonFlagIndex = args.findIndex((arg, idx, arr) => {
    const isOption = arg.startsWith('-');
    const prev = idx > 0 && arr[idx - 1];
    const prevOption = prev && prev.startsWith('-') && commander.optionFor(prev);
    const boundToPrevOption = prevOption && (prevOption.optional || prevOption.required);

    return !isOption && !boundToPrevOption;
  });
  let preCommandArgs;
  let commandName = '';
  if (firstNonFlagIndex > -1) {
    preCommandArgs = args.slice(0, firstNonFlagIndex);
    commandName = args[firstNonFlagIndex];
    args = args.slice(firstNonFlagIndex + 1);
  } else {
    preCommandArgs = args;
    args = [];
  }

  let isKnownCommand = Object.prototype.hasOwnProperty.call(commands, commandName);
  const isHelp = arg => arg === '--help' || arg === '-h';
  const helpInPre = preCommandArgs.findIndex(isHelp);
  const helpInArgs = args.findIndex(isHelp);
  const setHelpMode = () => {
    if (isKnownCommand) {
      args.unshift(commandName);
    }
    commandName = 'help';
    isKnownCommand = true;
  };

  if (helpInPre > -1) {
    preCommandArgs.splice(helpInPre);
    setHelpMode();
  } else if (isKnownCommand && helpInArgs === 0) {
    args.splice(helpInArgs);
    setHelpMode();
  }

  if (!commandName) {
    commandName = 'install';
    isKnownCommand = true;
  }

  if (!isKnownCommand) {
    // if command is not recognized, then set default to `run`
    args.unshift(commandName);
    commandName = 'run';
  }
  const command = commands[commandName];

  let warnAboutRunDashDash = false;
  // we are using "yarn <script> -abc", "yarn run <script> -abc", or "yarn node -abc", we want -abc
  // to be script options, not yarn options
  const PROXY_COMMANDS = new Set([`run`, `create`, `node`]);
  if (PROXY_COMMANDS.has(commandName)) {
    if (endArgs.length === 0) {
      // the "run" and "create" command take one argument that we want to parse as usual (the
      // script/package name), hence the splice(1)
      if (command === commands.run || command === commands.create) {
        endArgs = ['--', ...args.splice(1)];
      } else {
        endArgs = ['--', ...args];
      }
    } else {
      warnAboutRunDashDash = true;
    }
  }

  commander.originalArgs = args;
  args = [...preCommandArgs, ...args];

  command.setFlags(commander);
  commander.parse([
    ...startArgs,
    // we use this for https://github.com/tj/commander.js/issues/346, otherwise
    // it will strip some args that match with any options
    'this-arg-will-get-stripped-later',
    ...getRcArgs(commandName, args),
    ...args,
  ]);
  commander.args = commander.args.concat(endArgs.slice(1));

  // we strip cmd
  console.assert(commander.args.length >= 1);
  console.assert(commander.args[0] === 'this-arg-will-get-stripped-later');
  commander.args.shift();

  //
  const Reporter = commander.json ? JSONReporter : ConsoleReporter;
  const reporter = new Reporter({
    emoji: process.stdout.isTTY && commander.emoji,
    verbose: commander.verbose,
    noProgress: !commander.progress,
    isSilent: boolifyWithDefault(process.env.YARN_SILENT, false) || commander.silent,
    nonInteractive: commander.nonInteractive,
  });

  const exit = exitCode => {
    process.exitCode = exitCode || 0;
    reporter.close();
  };

  reporter.initPeakMemoryCounter();

  const config = new Config(reporter);
  const outputWrapperEnabled = boolifyWithDefault(process.env.YARN_WRAP_OUTPUT, true);
  const shouldWrapOutput = outputWrapperEnabled && !commander.json && command.hasWrapper(commander, commander.args);

  if (shouldWrapOutput) {
    reporter.header(commandName, {name: 'yarn', version});
  }

  if (commander.nodeVersionCheck && !semver.satisfies(process.versions.node, constants.SUPPORTED_NODE_VERSIONS)) {
    reporter.warn(reporter.lang('unsupportedNodeVersion', process.versions.node, constants.SUPPORTED_NODE_VERSIONS));
  }

  if (command.noArguments && commander.args.length) {
    reporter.error(reporter.lang('noArguments'));
    reporter.info(command.getDocsInfo);
    exit(1);
    return;
  }

  //
  if (commander.yes) {
    reporter.warn(reporter.lang('yesWarning'));
  }

  //
  if (!commander.offline && network.isOffline()) {
    reporter.warn(reporter.lang('networkWarning'));
  }

  //
  const run = (): Promise<void> => {
    invariant(command, 'missing command');

    if (warnAboutRunDashDash) {
      reporter.warn(reporter.lang('dashDashDeprecation'));
    }

    return command.run(config, reporter, commander, commander.args).then(exitCode => {
      if (shouldWrapOutput) {
        reporter.footer(false);
      }
      return exitCode;
    });
  };

  //
  const runEventuallyWithFile = (mutexFilename: ?string, isFirstTime?: boolean): Promise<void> => {
    return new Promise(resolve => {
      const lockFilename = mutexFilename || path.join(config.cwd, constants.SINGLE_INSTANCE_FILENAME);
      lockfile.lock(lockFilename, {realpath: false}, (err: mixed, release: () => void) => {
        if (err) {
          if (isFirstTime) {
            reporter.warn(reporter.lang('waitingInstance'));
          }
          setTimeout(() => {
            resolve(runEventuallyWithFile(mutexFilename, false));
          }, 200); // do not starve the CPU
        } else {
          onDeath(() => {
            process.exitCode = 1;
          });
          resolve(run().then(release));
        }
      });
    });
  };

  const runEventuallyWithNetwork = (mutexPort: ?string): Promise<void> => {
    return new Promise((resolve, reject) => {
      const connectionOptions = {
        port: +mutexPort || constants.SINGLE_INSTANCE_PORT,
        host: 'localhost',
      };

      function startServer() {
        const clients = new Set();
        const server = http.createServer(manager);

        // The server must not prevent us from exiting
        server.unref();

        // No socket must timeout, so that they aren't closed before we exit
        server.timeout = 0;

        // If we fail to setup the server, we ask the existing one for its name
        server.on('error', () => {
          reportServerName();
        });

        // If we succeed, keep track of all the connected sockets to close them later
        server.on('connection', socket => {
          clients.add(socket);
          socket.on('close', () => {
            clients.delete(socket);
          });
        });

        server.listen(connectionOptions, () => {
          // Don't forget to kill the sockets if we're being killed via signals
          onDeath(killSockets);

          // Also kill the sockets if we finish, whether it's a success or a failure
          run().then(
            res => {
              killSockets();
              resolve(res);
            },
            err => {
              killSockets();
              reject(err);
            },
          );
        });

        function manager(request, response) {
          response.writeHead(200);
          response.end(JSON.stringify({cwd: config.cwd, pid: process.pid}));
        }

        function killSockets() {
          try {
            server.close();
          } catch (err) {
            // best effort
          }

          for (const socket of clients) {
            try {
              socket.destroy();
            } catch (err) {
              // best effort
            }
          }

          // If the process hasn't exited in the next 5s, it has stalled and we abort
          const timeout = setTimeout(() => {
            console.error('Process stalled');
            if (process._getActiveHandles) {
              console.error('Active handles:');
              // $FlowFixMe: getActiveHandles is undocumented, but it exists
              for (const handle of process._getActiveHandles()) {
                console.error(`  - ${handle.constructor.name}`);
              }
            }
            // eslint-disable-next-line no-process-exit
            process.exit(1);
          }, 5000);

          // This timeout must not prevent us from exiting
          // $FlowFixMe: Node's setTimeout returns a Timeout, not a Number
          timeout.unref();
        }
      }

      function reportServerName() {
        const request = http.get(connectionOptions, response => {
          const buffers = [];

          response.on('data', buffer => {
            buffers.push(buffer);
          });

          response.on('end', () => {
            try {
              const {cwd, pid} = JSON.parse(Buffer.concat(buffers).toString());
              reporter.warn(reporter.lang('waitingNamedInstance', pid, cwd));
            } catch (error) {
              reporter.verbose(error);
              reject(new Error(reporter.lang('mutexPortBusy', connectionOptions.port)));
              return;
            }
            waitForTheNetwork();
          });

          response.on('error', () => {
            startServer();
          });
        });

        request.on('error', () => {
          startServer();
        });
      }

      function waitForTheNetwork() {
        const socket = net.createConnection(connectionOptions);

        socket.on('error', () => {
          // catch & ignore, the retry is handled in 'close'
        });

        socket.on('close', () => {
          startServer();
        });
      }

      startServer();
    });
  };

  function onUnexpectedError(err: Error) {
    function indent(str: string): string {
      return '\n  ' + str.trim().split('\n').join('\n  ');
    }

    const log = [];
    log.push(`Arguments: ${indent(process.argv.join(' '))}`);
    log.push(`PATH: ${indent(process.env.PATH || 'undefined')}`);
    log.push(`Yarn version: ${indent(version)}`);
    log.push(`Node version: ${indent(process.versions.node)}`);
    log.push(`Platform: ${indent(process.platform + ' ' + process.arch)}`);

    log.push(`Trace: ${indent(err.stack)}`);

    // add manifests
    for (const registryName of registryNames) {
      const possibleLoc = path.join(config.cwd, registries[registryName].filename);
      const manifest = fs.existsSync(possibleLoc) ? fs.readFileSync(possibleLoc, 'utf8') : 'No manifest';
      log.push(`${registryName} manifest: ${indent(manifest)}`);
    }

    // lockfile
    const lockLoc = path.join(
      config.lockfileFolder || config.cwd, // lockfileFolder might not be set at this point
      constants.LOCKFILE_FILENAME,
    );
    const lockfile = fs.existsSync(lockLoc) ? fs.readFileSync(lockLoc, 'utf8') : 'No lockfile';
    log.push(`Lockfile: ${indent(lockfile)}`);

    const errorReportLoc = writeErrorReport(log);

    reporter.error(reporter.lang('unexpectedError', err.message));

    if (errorReportLoc) {
      reporter.info(reporter.lang('bugReport', errorReportLoc));
    }
  }

  function writeErrorReport(log): ?string {
    const errorReportLoc = config.enableMetaFolder
      ? path.join(config.cwd, constants.META_FOLDER, 'yarn-error.log')
      : path.join(config.cwd, 'yarn-error.log');

    try {
      fs.writeFileSync(errorReportLoc, log.join('\n\n') + '\n');
    } catch (err) {
      reporter.error(reporter.lang('fileWriteError', errorReportLoc, err.message));
      return undefined;
    }

    return errorReportLoc;
  }

  const cwd = command.shouldRunInCurrentCwd ? commander.cwd : findProjectRoot(commander.cwd);

  config
    .init({
      cwd,
      commandName,

      binLinks: commander.binLinks,
      modulesFolder: commander.modulesFolder,
      linkFolder: commander.linkFolder,
      globalFolder: commander.globalFolder,
      preferredCacheFolder: commander.preferredCacheFolder,
      cacheFolder: commander.cacheFolder,
      preferOffline: commander.preferOffline,
      captureHar: commander.har,
      ignorePlatform: commander.ignorePlatform,
      ignoreEngines: commander.ignoreEngines,
      ignoreScripts: commander.ignoreScripts,
      offline: commander.preferOffline || commander.offline,
      looseSemver: !commander.strictSemver,
      production: commander.production,
      httpProxy: commander.proxy,
      httpsProxy: commander.httpsProxy,
      registry: commander.registry,
      networkConcurrency: commander.networkConcurrency,
      networkTimeout: commander.networkTimeout,
      nonInteractive: commander.nonInteractive,
      scriptsPrependNodePath: commander.scriptsPrependNodePath,
      updateChecksums: commander.updateChecksums,
    })
    .then(() => {
      // lockfile check must happen after config.init sets lockfileFolder
      if (command.requireLockfile && !fs.existsSync(path.join(config.lockfileFolder, constants.LOCKFILE_FILENAME))) {
        throw new MessageError(reporter.lang('noRequiredLockfile'));
      }

      // option "no-progress" stored in yarn config
      const noProgressConfig = config.registries.yarn.getOption('no-progress');

      if (noProgressConfig) {
        reporter.disableProgress();
      }

      // verbose logs outputs process.uptime() with this line we can sync uptime to absolute time on the computer
      reporter.verbose(`current time: ${new Date().toISOString()}`);

      const mutex: mixed = commander.mutex;
      if (mutex && typeof mutex === 'string') {
        const separatorLoc = mutex.indexOf(':');
        let mutexType;
        let mutexSpecifier;
        if (separatorLoc === -1) {
          mutexType = mutex;
          mutexSpecifier = undefined;
        } else {
          mutexType = mutex.substring(0, separatorLoc);
          mutexSpecifier = mutex.substring(separatorLoc + 1);
        }

        if (mutexType === 'file') {
          return runEventuallyWithFile(mutexSpecifier, true).then(exit);
        } else if (mutexType === 'network') {
          return runEventuallyWithNetwork(mutexSpecifier).then(exit);
        } else {
          throw new MessageError(`Unknown single instance type ${mutexType}`);
        }
      } else {
        return run().then(exit);
      }
    })
    .catch((err: Error) => {
      reporter.verbose(err.stack);

      if (err instanceof MessageError) {
        reporter.error(err.message);
      } else {
        onUnexpectedError(err);
      }

      if (command.getDocsInfo) {
        reporter.info(command.getDocsInfo);
      }

      return exit(1);
    });
}
示例#22
0
文件: cli.js 项目: Soyhuce/cinabre
var Path      = require('path')
var URL       = require('url')
var server    = require('./index')
var Utils     = require('./utils')
var pkg_file  = '../package.json'
var pkg       = fs.readFileSync(__dirname+'/'+ pkg_file, 'utf8')

commander
  .option('-l, --listen <[host:]port>', 'host:port number to listen on (default: localhost:4873)')
  .option('-c, --config <config.yaml>', 'use this configuration file (default: ./config.yaml)')
  .version(pkg.version)
  .parse(process.argv)

if (commander.args.length == 1 && !commander.config) {
  // handling "sinopia [config]" case if "-c" is missing in commandline
  commander.config = commander.args.pop()
}

if (commander.args.length != 0) {
  commander.help()
}

var config, config_path
try {
  if (commander.config) {
    config_path = Path.resolve(commander.config)
  } else {
    config_path = require('./config-path')()
  }
  config = YAML.safeLoad(fs.readFileSync(config_path, 'utf8'))
  logger.logger.warn({ file: config_path }, 'config file  - @{file}')
示例#23
0
  fn = linklocal[command].named
  dir = process.cwd()
}

var format = ''
if (program.files) format = '%h'
if (program.links) format = '%s'
if (program.long) format = '%s -> %h'
if (!format) format = program.format

if (program.absolute) format = format.toUpperCase()

if (named) {
  options = {
    cwd: program.args[program.args.length - 1],
    packages: program.args.slice(0, program.args.length - 1),
    recursive: recursive
  }
}

else options = {};

fn(dir, function(err, items) {
  if (err) throw err
  items = items || []
  var formattedItems = getFormattedItems(items, format)
  .filter(Boolean)

  if (program.unique) {
    formattedItems = formattedItems.filter(function(item, index, arr) {
      // uniqueness
示例#24
0
    return null;
  }
}

program.args.forEach(function(pptxFile) {
  var cards = [];
  fs.readFile(pptxFile, function(err, data) {
    if (err) throw err;
    var zip = new JSZip(data);
    // console.log(zip);
    Object.keys(zip.files).forEach(function(f) {
      if (slideMatch.test(f)) {
        var slideNumber = f.replace("ppt/slides/slide", "").replace(".xml", "");
        var text = extractText(zip.file(f).asText(), slideNumber);
        var notesText = getNotes(zip, f);
        cards.push({
          slideNumber: slideNumber,
          text: text,
          notes: notesText
        });
      }
    });
    cards.sort(function(a, b) {
      return a.slideNumber - b.slideNumber
    });
    jsonfile.writeFileSync(pptxFile + '.json', cards, {
      spaces: 2
    });
  });
})
示例#25
0
program.command('generate'.blue+' <type> <name>'.white)
		.description('    generate a new alloy type such as a controller'.grey);

program.parse(process.argv);
	

// Setup up logging output
if (program.allStackTrace) { Error.stackTraceLimit = Infinity; }
logger.stripColors = (program.colors===false);
banner();

if (program.args.length === 0)
{
	var help = program.helpInformation();
	help = help.replace('Usage: alloy ACTION [ARGS] [OPTIONS]','Usage: '+'alloy'.blue+' ACTION'.white+' [ARGS] [OPTIONS]'.grey);
	help = logger.stripColors ? colors.stripColors(help) : help;
	console.log(help);
	process.exit(1);
}

// Validate the command line action
var action = program.args[0];
if (!_.contains(ACTIONS, action)) {
	U.die('Unknown action: ' + action.red);
}

// Launch command with given arguments and options
(require('./commands/' + action + '/index'))(program.args.slice(1), program);

示例#26
0
文件: cli.js 项目: IEEEDTU/OnCourse
    return glob(pattern)
        .map(function (name) {
            return Deferred.props({
                contents: readFile(name, {encoding: 'utf8'}),
                name: name
            });
        })
        .each(function (file) {
            bootlint.lintHtml(file.contents, buildReporter(file.name), disabledIds);
            totalFileCount++;
            return Deferred.resolve();
        });
}

if (!program.args.length) {
    program.args.push('-');
}

program.args.forEach(function (pattern) {
    lintedFiles.push(pattern === '-' ? handleStdin() : handlePath(pattern));
});

Deferred.all(lintedFiles).then(function () {
    console.log("");

    if (totalErrCount > 0) {
        console.log("For details, look up the lint problem IDs in the Bootlint wiki: https://github.com/twbs/bootlint/wiki");
    }

    console.log("" + totalErrCount + " lint error(s) found across " + totalFileCount + " file(s).");
示例#27
0
文件: cli.js 项目: sibnerian/stubbify
program._name = 'stubbify';
program._usage = '[file ...] [targetDir]';

program
  .version('0.1.1')
  .option('-b, --begin-stub [string]', 'RegEx string (JS-style) for stub begin delimiter (case-insensitive)')
  .option('-e, --end-stub [string]', 'RegEx string (JS-style) for stub end delimiter (case-insensitive)')
  .option('-s, --silent', 'Suppress printing of stubbified file paths')
  .parse(process.argv);

if (program.args.length < 2) {
  console.log('Not enough arguments - must provide at least one file and a target directory.');
  process.exit();
}

var targetDir = program.args.pop();
var stubbify = stubbifier(targetDir, program.beginStub, program.endStub);

hl(program.args)
  .flatMap(hl.wrapCallback(glob)).series()
  .flatMap(hl.wrapCallback(stubbify))
  .toArray(function (files) {
    if (!program.silent) {
      console.log('Stubbified the following files:');
      files.forEach(function (file) {
        console.log(file + ' -> ' + path.join(targetDir, file));
      });
    }
  });
示例#28
0
#!/usr/bin/env node

var program = require('commander')
  , fs = require('fs')
  , path = require('path')
  , formatter = require('./src/formatter')

  , input
  , output

program
	.version(require('./package').version)
	.usage('path/to/input')
	.parse(process.argv)

if(!program.args.length) {
	program.parse(['bla', 'bla', '--help'])
	program.exit(1)
}

program.args.forEach(function(input) {
	output = input

	var original = fs.readFileSync(input, 'utf8')
	  , formatted = formatter.parse(original)

	fs.writeFileSync(output, formatted + '\n')
})
示例#29
0
program.command('serve'.blue)
    .description('Start a local mobilenode server in dev mode'.grey);

program.command('bundle'.blue)
    .description('Create a JavaScript file to bundle in a mobilenode native project'.grey);

program.command('help'.blue)
    .description('Print this help message'.grey);

// Parse arguments
program.parse(process.argv);

// Invoke the proper command
if (program.args.length == 0 || program.args[0] === 'help') {
    program.on('--help', function() {
        console.log('  Type "[command] help" for command-specific help.\n');
    });
    program.help();
} else {
    var command;
    try {
        // try to load command - we'll throw if it doesn't exist
        command = require('./commands/'+program.args[0]);
    } catch (e) {
        console.log('\n  error: command unrecognized. Run "mnode" with no arguments for usage.\n');
    }

    // Call command with arguments supplied, with program set as "this"
    command.call(program, program.args.slice(1));
}
示例#30
0
export default function parseArgv(args: Array<string>) {
  //
  commander.parse(args);

  const errors = [];

  let filenames = commander.args.reduce(function(globbed, input) {
    let files = glob.sync(input);
    if (!files.length) files = [input];
    return globbed.concat(files);
  }, []);

  filenames = uniq(filenames);

  filenames.forEach(function(filename) {
    if (!fs.existsSync(filename)) {
      errors.push(filename + " doesn't exist");
    }
  });

  if (commander.outDir && !filenames.length) {
    errors.push("filenames required for --out-dir");
  }

  if (commander.outFile && commander.outDir) {
    errors.push("cannot have --out-file and --out-dir");
  }

  if (commander.relative && !commander.outDir) {
    errors.push("output directory required for --relative");
  }

  if (commander.watch) {
    if (!commander.outFile && !commander.outDir) {
      errors.push("--watch requires --out-file or --out-dir");
    }

    if (!filenames.length) {
      errors.push("--watch requires filenames");
    }
  }

  if (commander.skipInitialBuild && !commander.watch) {
    errors.push("--skip-initial-build requires --watch");
  }
  if (commander.deleteDirOnStart && !commander.outDir) {
    errors.push("--delete-dir-on-start requires --out-dir");
  }

  if (
    !commander.outDir &&
    filenames.length === 0 &&
    typeof commander.filename !== "string" &&
    commander.babelrc !== false
  ) {
    errors.push(
      "stdin compilation requires either -f/--filename [filename] or --no-babelrc",
    );
  }

  if (errors.length) {
    console.error(errors.join(". "));
    process.exit(2);
  }

  const opts = commander.opts();

  return {
    babelOptions: {
      presets: opts.presets,
      plugins: opts.plugins,
      configFile: opts.configFile,
      envName: opts.envName,
      sourceType: opts.sourceType,
      ignore: opts.ignore,
      only: opts.only,
      retainLines: opts.retainLines,
      compact: opts.compact,
      minified: opts.minified,
      auxiliaryCommentBefore: opts.auxiliaryCommentBefore,
      auxiliaryCommentAfter: opts.auxiliaryCommentAfter,
      sourceMaps: opts.sourceMaps,
      sourceFileName: opts.sourceFileName,
      sourceRoot: opts.sourceRoot,
      moduleRoot: opts.moduleRoot,
      moduleIds: opts.moduleIds,
      moduleId: opts.moduleId,

      // Commander will default the "--no-" arguments to true, but we want to
      // leave them undefined so that @babel/core can handle the
      // default-assignment logic on its own.
      babelrc: opts.babelrc === true ? undefined : opts.babelrc,
      highlightCode:
        opts.highlightCode === true ? undefined : opts.highlightCode,
      comments: opts.comments === true ? undefined : opts.comments,
    },
    cliOptions: {
      filename: opts.filename,
      filenames,
      extensions: opts.extensions,
      keepFileExtension: opts.keepFileExtension,
      watch: opts.watch,
      skipInitialBuild: opts.skipInitialBuild,
      outFile: opts.outFile,
      outDir: opts.outDir,
      relative: opts.relative,
      copyFiles: opts.copyFiles,
      includeDotfiles: opts.includeDotfiles,
      verbose: opts.verbose,
      deleteDirOnStart: opts.deleteDirOnStart,
      sourceMapTarget: opts.sourceMapTarget,
    },
  };
}