Post-command tasks: - if there's no command, display help then exit - if command is unknown, display error message then exit - if there's command, validate arguments and options then exit
191874
function _postCommand(args, commandsConfig, globalOptsConfig) {

  function _validate(value, name, desc) {
    return function (rule) {
      if (iz.hasOwnProperty(rule)) {
        var isValid = iz[rule](value);
        if (isValid === null || isValid === false) {
          exit(new Error(util.format('Invalid %s: <%s> must be %s', desc, name, rule)));
        }
      } else {
        exit(new Error(util.format('Invalid %s rule: %s', desc, rule)));
      }
    };
  }

  if (!args) {
    return;

  } else if (args.length === 0) {
    // 2 -> 'node' and 'somecommand'
    // which means that the command is executed without args, hence display help menu
    // NOTE: this check is needed because for some reason commander.args
    // also returns empty array when one of the args is an opt (-- prefixed)
    if (process.argv.length === 2) {
      commander.help();
    }

  } else {
    var lastArg = args[args.length - 1],
      commandName = lastArg._name,
      commandArgs = (commandsConfig[commandName]) ? commandsConfig[commandName].args : undefined,
      commandOpts = (commandsConfig[commandName]) ? commandsConfig[commandName].options : undefined;

    // non-object last arg means command is not configured in setup
    if (typeof lastArg !== 'object') {
      exit(new Error(util.format('Unknown command: %s, use --help for more info', lastArg)));

    } else if (commandArgs && commandArgs.length > 0) {
      var programName = lastArg.parent._name;

      // display usage info when expected arguments don't exist
      if (args.length === 1) {
        exit(new Error(util.format('Usage: %s %s %s', programName, commandName, commandArgs.map(function (arg) {
          return util.format((arg.optional) ? '[%s]' : '<%s>', arg.name);
        }).join(' '))));
      } else {
        // validate arguments as configured in commands setup
        for (var i = 0, ln = commandArgs.length; i < ln; i += 1) {
          if (!commandArgs[i].optional) {
            commandArgs[i].rules.forEach(_validate(args[i], commandArgs[i].name, 'argument'));
          }
        }
      }
    }

    // validate command opts as configured in commands setup
    if (commandOpts) {
      commandOpts.forEach(function (commandOpt) {
        if (commandOpt.rules) {
          var name = commandOpt.arg,
            value = lastArg[name.match(/<.*>/)[0].replace(/[<>]/g, '')];
          commandOpt.rules.forEach(_validate(value, name, 'option'));
        }
      });
    }

    // validate global opts as configured in commands setup
    if (globalOptsConfig) {
      globalOptsConfig.forEach(function (globalOptConfig) {
        if (globalOptConfig.rules) {
          var name = globalOptConfig.arg,
            value = lastArg.parent[name.match(/<.*>/)[0].replace(/[<>]/g, '')];
          globalOptConfig.rules.forEach(_validate(value, name, 'option'));
        }
      });
    }
  }
}
917004
def command_post_hook(*args)
      command = args.shift
      method = to_method_name("#{command}_post_hook")
      if respond_to?(method)
        send(method, *args)
      end
    end
1200549
def do_help(self, args: argparse.Namespace) -> None:
        """"""
        if not args.command or args.verbose:
            self._help_menu(args.verbose)

        else:
            # Getting help for a specific command
            func = self.cmd_func(args.command)
            help_func = getattr(self, HELP_FUNC_PREFIX + args.command, None)

            # If the command function uses argparse, then use argparse's help
            if func and hasattr(func, 'argparser'):
                completer = AutoCompleter(getattr(func, 'argparser'), self)
                tokens = [args.command] + args.subcommand
                self.poutput(completer.format_help(tokens))

            # If there is no help information then print an error
            elif help_func is None and (func is None or not func.__doc__):
                err_msg = self.help_error.format(args.command)
                self.decolorized_write(sys.stderr, "{}\n".format(err_msg))

            # Otherwise delegate to cmd base class do_help()
            else:
                super().do_help(args.command)
1260985
def exec_or_exit(cmd)
      status = execute(cmd)
      if (status.to_i.nonzero?)
        error("The command '#{cmd}' failed with exit status #{status.to_i}")
      end
      status
    end
306251
def check_command(args):
    """"""
    outdated = check_requirements_file(args.requirements_file,
                                       args.skip_packages)

    if outdated:
        print('Requirements in {} are out of date:'.format(
            args.requirements_file))

        for item in outdated:
            print(' * {} is {} latest is {}.'.format(*item))

        sys.exit(1)
    else:
        print('Requirements in {} are up to date.'.format(
            args.requirements_file))
526875
def execute(command, silent = false, &block)
      result = run_with_timeout(command)
      if result.success? or silent
        warn command if @verbose
        return result unless block
        return block.call(result)
      end
      raise Error, cmd_error_message(command, result.data)
    rescue Errno::ENOENT
      raise Error, cmd_error_message(command, $!.message)
    end
804153
def cmd(self, args=None, interact=True):
        """"""
        if args is None:
            parsed_args = arguments.parse_args()
        else:
            parsed_args = arguments.parse_args(args)
        self.exit_code = 0
        with self.handling_exceptions():
            self.use_args(parsed_args, interact, original_args=args)
        self.exit_on_error()
510613
def post_build_app
      command = BuildCommandGenerator.post_build

      return if command.empty?

      print_command(command, "Generated Post-Build Command") if FastlaneCore::Globals.verbose?
      FastlaneCore::CommandExecutor.execute(command: command,
                                          print_all: true,
                                      print_command: !Gym.config[:silent],
                                              error: proc do |output|
                                                ErrorHandler.handle_build_error(output)
                                              end)
    end
931669
def handle_missing_or_unknown_args
      if first_arg_not_a_flag_or_file?
        exit_with_unknown_command
      elsif has_output_flag? || has_format_flag?
        check_for_output_file if has_output_flag?
        check_for_format_type if has_format_flag?
      elsif only_has_flag_arguments?
        add_test_command
      else
        exit_with_cannot_understand
      end
    end
1271054
def exit_ok(self, message, exit_code=None):
        
        logger.info("Exiting...")
        if message:
            logger.info("-----")
            logger.error("Exit message: %s", message)
            logger.info("-----")

        self.request_stop()

        if exit_code is not None:
            exit(exit_code)
281643
protected void validateArgumentList(String[] args) {
        checkRequiredArguments(args);

        // Skip the first argument as it is the task name
        // Arguments and values come in pairs (expect -password).
        // Anything outside of that pattern is invalid.
        // Loop through, jumping in pairs except when we encounter
        // -password -- that may be an interactive prompt which won't
        // define a value.
        for (int i = 1; i < args.length; i++) {
            String argPair = args[i];
            String arg = null;
            String value = null;
            if (argPair.contains("=")) {
                arg = argPair.split("=")[0];
                value = getValue(argPair);
            } else {
                arg = argPair;
            }

            if (!isKnownArgument(arg)) {
                throw new IllegalArgumentException(getMessage("invalidArg", arg));
            } else {
                if (value == null) {
                    throw new IllegalArgumentException(getMessage("missingValue", arg));
                }
            }
        }
    }
489156
function _validateCommand(name, command) {
    if (!_.isString(command.description)) {
        throw new Error(sprintf('Command "%s" must have a description string', name));
    } else if (!_.isFunction(command.invoke)) {
        throw new Error(sprintf('Command "%s" must have an invoke function', name));
    }
}
615269
function CommandAsker(questions, options) {
    options = options || {};
    
    if (!_.isArray(questions)) {
        throw "there are no questions available :'(";
    }
    
    this.questions = questions;
    this.response = {};
    this.cli = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    this.askCallback = null;
    this.errorMsg = options.errorMsg || clc.xterm(160);
    this.currentQuestion = 0;
}
578407
function validate(cmd, args, info) {
  AbstractCommand.prototype.validate.apply(this, arguments);
  if(args[0]) {
    var arg = ('' + args[0]).toLowerCase();
    if(arg !== Constants.SHUTDOWN.SAVE && arg !== Constants.SHUTDOWN.NOSAVE) {
      throw CommandSyntax;
    }

    // rewrite with boolean
    args[0] = (arg === Constants.SHUTDOWN.SAVE);
  }
}
489139
def call
      if arguments.valid?
        Qiita::Commands::Request.new(arguments)
      else
        Qiita::Commands::Error.new(arguments)
      end
    end
1170210
function run(params, command, callback)
{
  var job;

  // decouple commands
  command = clone(command);

  // start command execution and get job reference
  job = executioner(command, stringify(extend(this, params)), this.options || {}, callback);

  // make ready to call task termination function
  return partial(executioner.terminate, job);
}
436211
def post_command_event(target, msg_cls, **kwargs):
    

    msg = msg_cls(id=-1, **kwargs)
    wx.PostEvent(target, msg)