Function which sets up the commander object with all of our options and customisations.

@param {Array} argv
@returns {undefined}
345140
function setupCliObject(argv) {
	// Set cli options
	cliOptions
		.version(packageJson.version)
		.usage('[options] <component_path ...>')
		.option('-v, --verbose',
			'Be verbose during tests. (cannot be used with --quiet or --silent)')
		.option('-q, --quiet',
			'Display only the final outcome.')
		.option('-s, --silent',
			'Suppress all output.')
		.option('-r, --recursive',
			'Recurse into local and external dependencies.')
		.option('-d, --dep-paths <paths>',
			'Colon separated list of paths to external dependencies. (default: "./components")')
		.option('-w, --warn-paths <paths>',
			'Colon separated list of paths where component errors will be converted to warnings. (supports minimatch globbing)')
		.option('-i, --ignore-paths <paths>',
			'Colon separated list of paths component-hint should ignore. (supports minimatch globbing)')
		.option('-l, --lookup-paths <paths>',
			'Colon separated list of paths to check for the existence of missing local ' +
			'dependencies. This is used to give the user a hint where they can find them.')
		.option('    --reporter <path>',
			'Path to reporter file to use for output formatting.',
			path.join(__dirname, './reporters/default.js'));

	// Cleanup option strings and re-format them
	formatOptionStrings(cliOptions.options, 100);

	// Add additional info at the bottom of our help
	cliOptions.on('--help', function () {
		var scriptName = path.basename(argv[1]);

		process.stdout.write('  Examples:\n');
		process.stdout.write('\n');
		process.stdout.write('    Check multiple component entry points\n');
		process.stdout.write('    $ ' + scriptName + ' /path/to/single/component /path/to/another/component\n');
		process.stdout.write('\n');
		process.stdout.write('    Check multiple component entry point which exist in the same folder\n');
		process.stdout.write('    $ ' + scriptName + ' /path/to/multiple/component/folder/*/\n');
		process.stdout.write('\n');
	});

	// Parse arguments
	cliOptions.parse(argv);
}
777457
function aggregateOptions(program, command) {
	const argv = minimist(process.argv.slice(2));
	let options = _.merge({}, defaultOptions, program.opts(), command.opts());

	const configFile = path.resolve(process.cwd(), 'config/tamia.config.js');
	if (fs.existsSync(configFile)) {
		options = require(configFile)(options, argv);
	}

	return options;
}
562050
function(command, arg) {
    if (!arg) {
      arg = 'default';
    }

    if (!commands[command]) {
      grunt.fail.fatal('Command [' + command + '] not found.');
    }

    // Check arg
    if (typeof (commands[command]) !== 'function') {
      if (!commands[command][arg]) {
        grunt.fail.fatal('Argument [' + arg + '] for [' + command
            + '] not found.');
      }
    }

    var func = (arg) ? commands[command][arg] : commands[command];
    if (!func) {
      func = commands[command]; // fallback to the main function
    }

    var options = this.options();
    var docker = (options.docker) ? new Docker(options.docker) : null;
    var done = this.async();

    var callback = function(e) {
      if (e) {
        grunt.fail.warn(e);
      }
      done();
    };

    func.apply(this, [ grunt, docker, options, callback, arg ]);
  }
1014914
def process_command_line(argv):
    
    setup = {}
    for handler in ACCEPTED_ARG_HANDLERS:
        setup[handler.arg_name] = handler.default_val
    setup['file'] = ''
    setup['qt-support'] = ''

    i = 0
    del argv[0]
    while i < len(argv):
        handler = ARGV_REP_TO_HANDLER.get(argv[i])
        if handler is not None:
            handler.handle_argv(argv, i, setup)

        elif argv[i].startswith('--qt-support'):
            # The --qt-support is special because we want to keep backward compatibility:
            # Previously, just passing '--qt-support' meant that we should use the auto-discovery mode
            # whereas now, if --qt-support is passed, it should be passed as --qt-support=<mode>, where
            # mode can be one of 'auto', 'none', 'pyqt5', 'pyqt4', 'pyside'.
            if argv[i] == '--qt-support':
                setup['qt-support'] = 'auto'

            elif argv[i].startswith('--qt-support='):
                qt_support = argv[i][len('--qt-support='):]
                valid_modes = ('none', 'auto', 'pyqt5', 'pyqt4', 'pyside')
                if qt_support not in valid_modes:
                    raise ValueError("qt-support mode invalid: " + qt_support)
                if qt_support == 'none':
                    # On none, actually set an empty string to evaluate to False.
                    setup['qt-support'] = ''
                else:
                    setup['qt-support'] = qt_support
            else:
                raise ValueError("Unexpected definition for qt-support flag: " + argv[i])

            del argv[i]

        elif argv[i] == '--file':
            # --file is special because it's the last one (so, no handler for it).
            del argv[i]
            setup['file'] = argv[i]
            i = len(argv) # pop out, file is our last argument

        elif argv[i] == '--DEBUG':
            from pydevd import set_debug
            del argv[i]
            set_debug(setup)

        else:
            raise ValueError("Unexpected option: " + argv[i])
    return setup
271468
function ParseArguments(cmd, args) {
  assert(_.isObject(cmd), 'require an object argument for "cmd".');
  assert(_.isObject(args), 'require an object argument for "args".');
  const argSpec = cmd.argSpec || [];
  const cmdName = cmd.name;

  //
  // Build a map of all flag aliases.
  //
  const allAliases = _.fromPairs(_.map(_.flatten(_.map(argSpec, 'flags')), (flagAlias) => {
    return [flagAlias, true];
  }));

  //
  // Make sure all provided flags are specified in the argSpec.
  //
  _.forEach(args, (argVal, argKey) => {
    if (argKey === '_') return; // ignore positional arguments
    if (!(argKey in allAliases)) {
      const d = argKey.length === 1 ? '-' : '--';
      throw new Error(
        `Unknown command-line option "${col.bold(d + argKey)}" specified ` +
        `for command "${col.bold(cmdName)}".`);
    }
  });

  //
  // Handle boolean flags specified as string values on the command line.
  //
  args = _.mapValues(args, (flagVal) => {
    if (_.isString(flagVal)) {
      if (flagVal === 'true') {
        return true;
      }
      if (flagVal === 'false') {
        return false;
      }
    }
    return flagVal;
  });

  //
  // For each flag in the argSpec, see if any alias of the flag is
  // present in `args`. If it is, then assign that value to *all*
  // aliases of the flag. If it is not present, then assign the
  // default value. Throw on unspecified required flags.
  //
  const finalFlags = {};
  _.forEach(argSpec, (aspec, idx) => {
    // Find the first alias of this flag that is specified in args, if at all.
    const foundAlias = _.find(aspec.flags, (flagAlias) => {
      return flagAlias && (flagAlias in args);
    });
    let assignValue = foundAlias ? args[foundAlias] : (aspec.defVal || aspec.default);

    // If defVal is an object, then we need to execute a function to get the
    // default value.
    if (_.isObject(assignValue)) {
      assert(
        _.isFunction(assignValue.fn),
        `Argspec entry ${idx} has an invalid 'defVal'/'default' property.`);
      assignValue = assignValue.fn.call(argSpec);
    }

    if (!_.isUndefined(assignValue)) {
      // Assign value to all aliases of flag.
      _.forEach(aspec.flags, (flagAlias) => {
        finalFlags[flagAlias] = assignValue;
      });
    }
  });

  // Copy positional arguments to finalFlags.
  finalFlags._ = args._;

  return finalFlags;
}
1372089
function CommandArgLength(cmd) {
  this.name = CommandArgLength.name;
  if(arguments.length > 1) {
    cmd = slice.call(arguments, 0).join(' ');
  }
  StoreError.apply(
    this, [null, 'wrong number of arguments for \'%s\' command', cmd]);
}
912739
function(options) {
		var program = new Commander();
		if (options) {
			//hack to emulate process.argv
			options.unshift('', '');
		}
		//process short command names
		var args = options || process.argv.slice();
		var command = args[2];
		var validCommand = config.aliases[command];

		if (validCommand) {
			args[2] = validCommand;
		}
		program.parse(args);
	}
473341
function _initializeCommands(session, callback, _commands) {
    _commands = _commands || _.values(session.commands().all());
    if (_.isEmpty(_commands)) {
        return callback();
    }

    // Get the next command to initialize
    var command = _commands.pop();
    if (!_.isFunction(command.init)) {
        // If it does not have the optional init function we just skip it
        return _initializeCommands(session, callback, _commands);
    }

    // Initialize the command
    command.init(session, function(err) {
        if (err) {
            return callback(err);
        }

        // Recursively move on to the next command
        return _initializeCommands(session, callback, _commands);
    });
}
530260
function main (processArgv, conf) {

  // CLI input
  var opts = getOpts(processArgv);
  var argv = opts.argv;

  // Update notifier
  if (!argv["no-notifier"]) {
    checkUpdate();
  }

  // Convert options "--help" and "-h" into command "help"
  if (argv.help) {
    processArgv = transformHelpArgs(processArgv);
    // Regenerate opts from newly forged process.argv
    opts = getOpts(processArgv);
    argv = opts.argv;
  }

  // "--version"
  if (argv.version) {
    showVersion();
  }

  var commandName = argv._[0];

  // Demand command name
  if (!commandName) {
    console.error("No command specified");
    opts.showHelp();
    process.exit(127);
  }

  // Load command module
  var command = commands.load(commandName);

  // Demand valid command
  if (!command) {
    console.error("Unknown command: " + commandName);
    opts.showHelp();
    process.exit(127);
  }

  process.on("exit", function () {
    ttys.stdin.end();
  });

  // Configure opts and run command (inside a domain to catch any error)
  commands.run(command, opts, conf).then(ok, fail);

  function ok () {
    process.exit(0);
  }

  function fail (e) {
    if (e.code === "EINTERRUPT") {
      process.exit(127);
    } else {
      console.error("%s", e);
      if (process.env.DEBUG) {
        throw e;
      }
      process.exit(1);
    }
  }
}
713523
function bin(argv) {
  // setup config
  var config = require('../config/config.js')

  program
  .option('-d, --database <database>', 'Database')
  .parse(argv)

  var defaultDatabase = 'media'

  config.database = program.database || config.database || defaultDatabase
  var url = process.argv[2] || 'https://www.reddit.com/r/perfectloops/top/?sort=top&t=all&count=25&after=t3_4j0v4f'

  qpm_media.getLastSeen(function(err, ret){
    if (err) {
      console.error(err)
    } else {
      console.log(ret[0][0].uri);
    }
  })


}
1052824
function execute(argv) {
  const opts = Options.parse(argv);

  if (opts.version) {
    /* eslint-disable global-require */
    console.log(`v${ require('../package.json').version }`);
    return Promise.resolve(0);
  }

  if (opts.help || !opts._.length) {
    console.log(Options.generateHelp());
    return Promise.resolve(0);
  }

  return lint(resolvePatterns(opts), opts);
}
1053673
function argv(args) {
  var out = {directives: {}}
    , i = 0;

  /* istanbul ignore next: never use process.argv in tests */
  args = args || process.argv.slice(2);
  if(!args.length) return out;

  // read conf from stdin
  if(args[i] === STDIN) {
    out.stdin = true;
    i++;
  // conf should be first arg
  }else if(!PTN.test(args[i])) {
    out.file = args[i];
    i++;
  }

  function add(key, value) {
    if(!key || value === null) return;
    if(!out.directives[key]) {
      out.directives[key] = value;
    // handle repeated directives, create an array
    }else if(out.directives[key]
      && !Array.isArray(out.directives[key])){
      out.directives[key] = [out.directives[key]];
      out.directives[key].push(value)
    // append to existing array value
    }else{
      out.directives[key].push(value)
    }
  }

  function gobble(arg, key, value) {
    if(arg === undefined) return add(key, value);
    value = value || '';
    if(PTN.test(arg)) {
      key = arg.replace(PTN, '');
      // gobble up value arguments
      while((arg = args[i++]) !== undefined && !PTN.test(arg)) {
        if(value) value += ' ';
        value += arg;
      }
      if(PTN.test(arg)) i--;
      add(key, value);
      value = null;
    }else{
      if(value) value += ' ';
      value += arg;
    }
    gobble(args[i++], key, value);
  }
  gobble(args[i]);
  return out;
}
335599
function parseCommandLine(args) {

    var parsed_cmds = [];

    if (args.length <= 2) {
        parsed_cmds.push(defaultCommand());
    } else {

        var cli = args.slice(2);

        var pos = 0;
        var cmd;

        cli.forEach(function(element, index, array) {

            //replace alias name with real name.
            if (element.indexOf('--') === -1 && element.indexOf('-') === 0) {
                cli[index] = alias_map[element];
            }

            //parse command and args
            if (cli[index].indexOf('--') === -1) {
                cmd.args.push(cli[index]);
            } else {

                if (keys[cli[index]] == "undefined") {
                    throw new Error("not support command:" + cli[index]);
                };

                pos = index;
                cmd = commands[cli[index]];
                if (typeof cmd.args == 'undefined') {
                    cmd.args = [];
                };
                parsed_cmds.push(cmd);
            }
        });
    };

    return parsed_cmds;
}
1126409
def parsed_options_from_arguments(argv)
      options_to_merge = {}

      OptionParser.new do |opts|
        opts.banner = 'Usage: phare [options]'

        opts.on('--version', 'Display Phare’s version') do
          options_to_merge[:version] = true
        end

        opts.on('--directory x', 'The directory in which to run the checks (default is the current directory') do |directory|
          options_to_merge[:directory] = directory
        end

        opts.on('--skip x,y,z', 'Skip checks') do |checks|
          options_to_merge[:skip] = checks.split(',')
        end

        opts.on('--only x,y,z', 'Only run the specified checks') do |checks|
          options_to_merge[:only] = checks.split(',')
        end

        opts.on('--diff', 'Only run checks on modified files') do
          options_to_merge[:diff] = true
        end
      end.parse! argv

      options_to_merge
    end
663859
function bin(argv) {
  // setup config
  var config = require('../config/config.js')

  program
  .option('-d, --database <database>', 'Database')
  .parse(argv)

  var defaultDatabase = 'media'

  config.database = program.database || config.database || defaultDatabase
  var url = process.argv[2] || 'https://www.reddit.com/r/perfectloops/top/?sort=top&t=all&count=25&after=t3_4j0v4f'


  qpm_media.getRandomUnseenFragment(null, config).then(function(ret){
    console.table(ret.ret[0])
    ret.conn.close()
  }).catch(function (err) {
    console.error(err)
  })


}
561165
def _build_cmdargs(argv):
    
    parser = _build_arg_parser()
    namespace = parser.parse_args(argv[1:])

    cmdargs = vars(namespace)
    return cmdargs
628098
def go(argv)
      logger.debug("Using args passed in: #{argv.inspect}")

      cmd = nil

      @optparse = OptionParser.new do |opts|
        cmd = super(argv, opts, @config)
      end

      begin
        @optparse.parse!(argv)
      rescue OptionParser::InvalidOption => e
        logger.error "Whoops, we can't understand your command."
        logger.error e.message.to_s
        logger.error "Run your command again with the --help switch to see available options."
        abort
      end

      logger.debug("Parsed config: #{@config.inspect}")

      begin
        cmd.execute(argv, @config)
      rescue => e
        if cmd.trace
          raise e
        else
          logger.error e.message
          abort
        end
      end
    end