Parses the command-line options using Trollop

 @return [Hash{Symbol => Object}] the settings entered by the user
501840
def get_settings
      warning_opts = get_warning_options
      Trollop::options do
        banner 'LASER: Lexically- and Semantically-Enriched Ruby'
        opt :fix, 'Should errors be fixed in-line?', short: '-f'
        opt :display, 'Should errors be displayed?', short: '-b', default: true
        opt :'report-fixed', 'Should fixed errors be reported anyway?', short: '-r'
        opt :'line-length', 'Warn at the given line length', short: '-l', type: :int
        opt :only, 'Only consider the given warning (by short or full name)', short: '-O', type: :string
        opt :stdin, 'Read Ruby code from standard input', short: '-s'
        opt :'list-modules', 'Print the discovered, loaded modules'
        opt :profile, 'Run the profiler during execution'
        opt :include, 'specify $LOAD_PATH directory (may be used more than once)', short: '-I', multi: true
        opt :S, 'look for scripts using PATH environment variable', short: '-S'
        warning_opts.each { |warning| opt(*warning) }
      end
    end
816871
def parse_dynamic_options
      if no_options_passed?
        {}
      else
        dynamic_parser.parse!(@params)

        data = dynamic_parser.to_hash
        invalid_key = data.find { |key, value| value.nil? }

        if invalid_key
          raise InvalidOptions.new(invalid_key.first)
        end

        data
      end
    end
1251458
def parse!
      begin
        parse
      rescue StandardError => e
        raise e if @options[:trace] || e.is_a?(SystemExit)
        $stderr.puts "#{e.class}: " + e.message.to_s
        exit 1
      end
      exit 0
    end
817698
def run
      option_parser @options
      
      # Check on include version request.
      if @options[:version].value then
	puts "#{@name}, version #{@version}"
	exit
      end

      # Check on include help request.
      if ARGV[0] == 'help' or ARGV[0] == '--help' or ARGV[0] == '-h' then
	# Help arguments apsent, well then display information about application.
	if ARGV.size == 1 then
	  puts
	  puts "*** #{@name} ***".center(80)
	  # Display about info.
	  if @about.size > 0 then
	    puts '** ABOUT:'
	    @about.each do |line|
	      puts "  #{line}"
	    end
	  end
	  # Display usage info.
	  if @usage.size > 0 then
	    puts
	    puts '** USAGE:'
	    @usage.each do |line|
	      puts "  #{line}"
	    end
	  end
	  # Display options info.
	  puts
	  puts '** OPTIONS:'
	  display_options @options
	  # Display commands info
	  if @commands.size > 0 then
	    @commands.each do |c| c.init end
	    puts
	    puts '** COMMANDS:'
	    display_commands @commands
	    puts
	    puts "For details, type: help [COMMAND]"
	  end
	  puts
	# Help arguments exist, find command in application command list.
	else
	  ARGV.delete_at( 0 )
	  cmd = command_select
	  if ARGV.size != 0 then
	    puts "fatal error: unknown command '#{ARGV[0]}'"
	    exit
	  end
	  # Display describe information on command.
	  puts
	  puts Cmdlib::Describe.outtitle( cmd.name )
	  puts "  #{cmd.brief}"
	  if cmd.details.size > 0 then
	    puts
	    puts '** DETAILS:'
	    cmd.details.each do |e|
	      puts "  #{e}"
	    end
	  end
	  if cmd.example.size > 0 then
	    puts
	    puts '** EXAMPLE:'
	    cmd.example.each do |e|
	      puts "  #{e}"
	    end
	  end
	  # Display options info.
	  if cmd.options.size > 0 then
	    puts
	    puts '** OPTIONS:'	  
	    display_options cmd.options
	  end
	  # Display commands info.
	  if cmd.subcmd.size > 0 then
	    cmd.subcmd.each do |c| c.init end
	    puts
	    puts '** SUBCOMMANDS:'
	    display_commands cmd.subcmd
	    puts
	    puts "For details, type: help #{cmd.name} [SUBCOMMAND]"
	  end
	  puts
	end
	exit
      end
      
      # Handling default command (if exist her).
      if @default != nil then
	option_excess
	if ARGV.size < @default.argnum then
	  puts "fatal error: to few arguments for programm, use <help>."
	else
	  @default.handler( @options, ARGV )
	end
	exit
      end
      
      # Handling commands.
      cmd = command_select
      if cmd == nil then
	puts "fatal error: unknown command or command miss, use <help>."
	exit
      end
      if ARGV.size < cmd.argnum then
	puts "fatal error: to few arguments for command, use: <help> <command name>."
	exit
      end
      # Scaning options fir this command
      option_parser cmd.options
      option_excess
      #cmd.init
      cmd.handler( @options, ARGV )
      exit
    end
682750
def parse(cmdline = ARGV)
    vals = {}
    required = {}

    opt :version, "Print version and exit" if @version && ! (@specs[:version] || @long["version"])
    opt :help, "Show this message" unless @specs[:help] || @long["help"]

    @specs.each do |sym, opts|
      required[sym] = true if opts[:required]
      vals[sym] = opts[:default]
      vals[sym] = [] if opts[:multi] && !opts[:default] # multi arguments default to [], not nil
    end

    resolve_default_short_options!

    ## resolve symbols
    given_args = {}
    @leftovers = each_arg cmdline do |arg, params|
      ## handle --no- forms
      arg, negative_given = if arg =~ /^--no-([^-]\S*)$/
        ["--#{$1}", true]
      else
        [arg, false]
      end

      sym = case arg
        when /^-([^-])$/      then @short[$1]
        when /^--([^-]\S*)$/  then @long[$1] || @long["no-#{$1}"]
        else                       raise CommandlineError, "invalid argument syntax: '#{arg}'"
      end

      sym = nil if arg =~ /--no-/ # explicitly invalidate --no-no- arguments

      next 0 if ignore_invalid_options && !sym
      raise CommandlineError, "unknown argument '#{arg}'" unless sym

      if given_args.include?(sym) && !@specs[sym][:multi]
        raise CommandlineError, "option '#{arg}' specified multiple times"
      end

      given_args[sym] ||= {}
      given_args[sym][:arg] = arg
      given_args[sym][:negative_given] = negative_given
      given_args[sym][:params] ||= []

      # The block returns the number of parameters taken.
      num_params_taken = 0

      unless params.nil?
        if SINGLE_ARG_TYPES.include?(@specs[sym][:type])
          given_args[sym][:params] << params[0, 1]  # take the first parameter
          num_params_taken = 1
        elsif MULTI_ARG_TYPES.include?(@specs[sym][:type])
          given_args[sym][:params] << params        # take all the parameters
          num_params_taken = params.size
        end
      end

      num_params_taken
    end

    ## check for version and help args
    raise VersionNeeded if given_args.include? :version
    raise HelpNeeded if given_args.include? :help

    ## check constraint satisfaction
    @constraints.each do |type, syms|
      constraint_sym = syms.find { |sym| given_args[sym] }
      next unless constraint_sym

      case type
      when :depends
        syms.each { |sym| raise CommandlineError, "--#{@specs[constraint_sym][:long]} requires --#{@specs[sym][:long]}" unless given_args.include? sym }
      when :conflicts
        syms.each { |sym| raise CommandlineError, "--#{@specs[constraint_sym][:long]} conflicts with --#{@specs[sym][:long]}" if given_args.include?(sym) && (sym != constraint_sym) }
      end
    end

    required.each do |sym, val|
      raise CommandlineError, "option --#{@specs[sym][:long]} must be specified" unless given_args.include? sym
    end

    ## parse parameters
    given_args.each do |sym, given_data|
      arg, params, negative_given = given_data.values_at :arg, :params, :negative_given

      opts = @specs[sym]
      if params.empty? && opts[:type] != :flag
        raise CommandlineError, "option '#{arg}' needs a parameter" unless opts[:default]
        params << (opts[:default].kind_of?(Array) ? opts[:default].clone : [opts[:default]])
      end

      vals["#{sym}_given".intern] = true # mark argument as specified on the commandline

      case opts[:type]
      when :flag
        vals[sym] = (sym.to_s =~ /^no_/ ? negative_given : !negative_given)
      when :int, :ints
        vals[sym] = params.map { |pg| pg.map { |p| parse_integer_parameter p, arg } }
      when :float, :floats
        vals[sym] = params.map { |pg| pg.map { |p| parse_float_parameter p, arg } }
      when :string, :strings
        vals[sym] = params.map { |pg| pg.map(&:to_s) }
      when :io, :ios
        vals[sym] = params.map { |pg| pg.map { |p| parse_io_parameter p, arg } }
      when :date, :dates
        vals[sym] = params.map { |pg| pg.map { |p| parse_date_parameter p, arg } }
      end

      if SINGLE_ARG_TYPES.include?(opts[:type])
        if opts[:multi]       # multiple options, each with a single parameter
          vals[sym] = vals[sym].map { |p| p[0] }
        else                  # single parameter
          vals[sym] = vals[sym][0][0]
        end
      elsif MULTI_ARG_TYPES.include?(opts[:type]) && !opts[:multi]
        vals[sym] = vals[sym][0]  # single option, with multiple parameters
      end
      # else: multiple options, with multiple parameters

      opts[:callback].call(vals[sym]) if opts.key?(:callback)
    end

    ## modify input in place with only those
    ## arguments we didn't process
    cmdline.clear
    @leftovers.each { |l| cmdline << l }

    ## allow openstruct-style accessors
    class << vals
      def method_missing(m, *_args)
        self[m] || self[m.to_s]
      end
    end
    vals
  end
249166
def parse
      opts = OptionParser.new(&method(:set_options))
      opts.parse!(@args)
      return process_url if url_present?
      opts.help
    end
1301224
def parse_args
      parser = Trollop::Parser.new do
        opt :max_attempts, "", :default => DEFAULT_MAX_ATTEMPTS, :long => "--attempts", :short => "-a"
        opt :retry_interval, "", :default => DEFAULT_RETRY_INTERVAL
        opt :time_limit, "", :type => :int
        opt :daemon, "", :long => "--start"
        opt :stop
        opt :ping
        opt :verbose
        opt :state_path, "", :type => String
        version ""
      end
      
      parse do
        options = parser.parse
        options.delete(:max_attempts) unless options[:max_attempts] > 0
        if options[:delete]
          options.delete(:time_limit) unless options[:time_limit] > 0
        end
        options.delete(:retry_interval) unless options[:retry_interval] > 0
        options
      end
    end
1282808
def parse_args
      options = {:thin_command_client => false}

      opts = OptionParser.new do |opts|
        parse_common(opts, options)
        parse_other_args(opts, options)

        opts.on("-s", "--start AGENT") do |a|
          options[:action] = 'start'
          options[:agent_name] = a
        end

        opts.on("-p", "--stop AGENT") do |a|
          options[:action] = 'stop'
          options[:agent_name] = a
        end

        opts.on("--stop-agent ID") do |id|
          options[:action] = 'stop'
          options[:identity] = id
        end

        opts.on("-k", "--kill PIDFILE") do |file|
          options[:pid_file] = file
          options[:action] = 'kill'
        end

        opts.on("-K", "--killall") do
          options[:action] = 'killall'
        end

        opts.on("-U", "--status") do
          options[:action] = 'show'
        end

        opts.on("-l", "--list") do
          options[:list] = true
        end

        opts.on("--log-level LVL") do |lvl|
          options[:log_level] = lvl
        end

        opts.on("-c", "--cfg-dir DIR") do |d|
          options[:cfg_dir] = d
        end

        opts.on("-z", "--pid-dir DIR") do |dir|
          options[:pid_dir] = dir
        end

        opts.on("--log-dir DIR") do |dir|
          options[:log_dir] = dir

          # Ensure log directory exists (for windows, etc.)
          FileUtils.mkdir_p(dir) unless File.directory?(dir)
        end

        opts.on("-f", "--foreground") do
          options[:daemonize] = false
          #Squelch Ruby VM warnings about various things
          $VERBOSE = nil
        end

        opts.on("-I", "--interactive") do
          options[:console] = true
        end

        opts.on_tail("--help") do
          puts Usage.scan(__FILE__)
          exit
        end

      end

      begin
        opts.parse(ARGV)
      rescue Exception => e
        exit 0 if e.is_a?(SystemExit)
        fail(e.message, print_usage = true)
      end

      # allow specific arguments to use a thin command client for faster
      # execution (on Windows, etc.)
      unless options[:thin_command_client]
        # require full right_agent for any commands which do not specify thin
        # command client.
        require File.normalize_path(File.join(File.dirname(__FILE__), '..', '..', 'right_agent'))
      end
      resolve_identity(options)
      options
    end
904987
def default_params(h = {})
      raise ArgumentError, 'Default params must be an object which responds to #to_hash' unless h.respond_to?(:to_hash)
      default_options[:default_params] ||= {}
      default_options[:default_params].merge!(h)
    end
1325741
def parse_command_line(args: List[str] = None, final: bool = True) -> List[str]:
    
    return options.parse_command_line(args, final=final)
1369097
def parse(self):
        
        self._options, self._arguments = self._parse_args()
        self._arguments = self._arguments or ['.']

        if not self._validate_options(self._options):
            raise IllegalConfiguration()

        self._run_conf = self._create_run_config(self._options)

        config = self._create_check_config(self._options, use_defaults=False)
        self._override_by_cli = config
1273831
def instance_method_hash(options)
      ChainOptions::Util.slice(options, Option::METHOD_SYMBOLS).each_with_object({}) do |(meth, value), h|
        next h[meth] = value if value.respond_to?(:call)

        h[meth] = instance.public_method(value)
      end
    end
613766
function parseOptions(opts) {
    opts = opts || {};
    if (toString.call(opts) === '[object String]') {
        opts = {
            directory: opts
        };
    }

    opts.cwd = opts.cwd || process.cwd();

    log.verbosity = toString.call(opts.verbosity) === '[object Number]' ? opts.verbosity : DEFAULT_VERBOSITY;
    delete (opts.verbosity);

    cmd = opts.cmd || DEFAULT_CMD;
    delete (opts.cmd);

    // enable bower prompting but ignore the actual prompt if interactive == false
    enablePrompt = opts.interactive || DEFAULT_INTERACTIVE;
    opts.interactive = true;

    if (!opts.directory) {
        opts.directory = getDirectoryFromBowerRc(opts.cwd) || DEFAULT_DIRECTORY;
    }

    return opts;
}
736481
def options
      Hash[*Vault::Configurable.keys.map do |key|
        [key, instance_variable_get(:"@#{key}")]
      end.flatten]
    end
199356
def parse_command_line
      begin
        opts = GetoptLong.new(
          [ '--tag', '-t', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--tag-use-and', '-a', GetoptLong::NO_ARGUMENT ],
          [ '--tag-use-or', '-o', GetoptLong::NO_ARGUMENT ],
          [ '--array', '-r', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--deployment', '-e', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--script', '-s', GetoptLong::OPTIONAL_ARGUMENT ],
          [ '--ssh', '-x', GetoptLong::OPTIONAL_ARGUMENT ],
          [ '--input', '-i', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--set-template', '-m', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--set-tag', '-w', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--report', '-b', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--progress', '-p', GetoptLong::NO_ARGUMENT ],
          [ '--verbose', '-v', GetoptLong::NO_ARGUMENT ],
          [ '--quiet', '-q', GetoptLong::NO_ARGUMENT ],
          [ '--noprompt', '-z', GetoptLong::NO_ARGUMENT ],
          [ '--concurrency', '-c', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--delay', '-d', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--retry', '-y', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--hold', '-7', GetoptLong::NO_ARGUMENT ],
          [ '--dry-run', '-n', GetoptLong::NO_ARGUMENT ],
          [ '--limit', '-l', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--version', '-1', GetoptLong::NO_ARGUMENT ],
          [ '--chimpd', '-f', GetoptLong::OPTIONAL_ARGUMENT ],
          [ '--chimpd-wait-until-done', '-j', GetoptLong::NO_ARGUMENT ],
          [ '--dont-check-templates', '-0', GetoptLong::NO_ARGUMENT ],
          [ '--ignore-errors', '-9', GetoptLong::NO_ARGUMENT ],
          [ '--ssh-user', '-u', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--help', '-h', GetoptLong::NO_ARGUMENT ],
          [ '--group', '-g', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--group-type', '-2', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--group-concurrency', '-3', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--timing-log', '-4', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--timeout', '-5',  GetoptLong::REQUIRED_ARGUMENT ],
          [ '--noverify', '-6', GetoptLong::NO_ARGUMENT ],
          [ '--exact-matching', '-8', GetoptLong::NO_ARGUMENT ],
          [ '--job-notes', '-k', GetoptLong::OPTIONAL_ARGUMENT ]
        )

        opts.each do |opt, arg|
          case opt
            when '--help', '-h'
              help
              exit 0
            when '--tag', '-t'
              @tags << arg
            when '--tag-use-and', '-a'
              @match_all = true
            when '--tag-use-or', '-o'
              @match_all = false
            when '--array', '-a'
              @array_names << arg
            when '--deployment', '-e'
              @deployment_names << arg
            when '--template', '-m'
              @template = arg
            when '--script', '-s'
              set_action(:action_rightscript)
              if arg == ""
                # Empty but not nil means show list of operational scripts to choose from
                @script = ""
              else
                @script = arg
              end
            when '--ssh', '-x'
              set_action(:action_ssh)
              @break_array_into_instances = true
              if arg == ""
                print "Enter SSH command line to execute: "
                @ssh = gets.chomp
              else
                @ssh = arg
              end
            when '--ssh-user', '-u'
              @ssh_user = arg
            when '--input', '-i'
              arg =~ /(.+)=(.+)/
              @inputs[$1]=$2
            when '--set-template', '-m'
              set_action(:action_set)
              @template = arg
            when '--set-tag', '-w'
              set_action(:action_set)
              @set_tags << arg
            when '--report', '-b'
              set_action(:action_report)
              @report = arg
              @@verbose = false
              @@quiet = true
              @break_array_into_instances = true
              @concurrency = 5 if @concurrency == 1
            when '--progress', '-p'
              @progress = @progress ? false : true
            when '--noprompt', '-z'
              @prompt = false
            when '--concurrency', '-c'
              @concurrency = arg.to_i
            when '--delay', '-d'
              @delay = arg.to_i
            when '--hold', '-7'
              @hold = true
            when '--retry', '-y'
              @retry_count = arg.to_i
            when '--limit', '-l'
              @limit_start, @limit_end = arg.split(',')
            when '--verbose', '-v'
              @@verbose = true
              Log.threshold = Logger::DEBUG
            when '--quiet', '-q'
              @@quiet = true
            when '--dont-check-templates', '-0'
              @dont_check_templates_for_script = true
            when '--version'
              puts VERSION
              exit 0
            when '--chimpd'
              @use_chimpd = true
              unless arg.empty?
                if arg =~ /[\d]+\.[\d]+\.[\d]+\.[\d]+:[\d]+/
                  @chimpd_host, @chimpd_port = arg.split(':')
                  @chimpd_port = @chimpd_port.to_i
                else
                  @chimpd_port = arg.to_i
                end
              end
            when '--chimpd-wait-until-done'
              @use_chimpd = true
              @chimpd_wait_until_done = true
            when '--dry-run', '-n'
              @dry_run = true
            when '--ignore-errors', '-9'
              @ignore_errors = true
            when '--group', '-g'
              @group = arg.to_sym
            when '--group-type'
              @group_type = arg.to_sym
            when '--group-concurrency'
              @group_concurrency = arg.to_i
            when '--job-notes'
              @job_notes = arg
            when '--timing-log'
              @timing_log = arg
            when '--timeout'
              @timeout = arg
            when '--noverify'
              @verify = false
            when '--exact-matching'
              @exact = true
          end
        end

        if @use_chimpd && ( @script.nil? || @script.empty? )
          if @chimpd_wait_until_done == false
            puts "#######################################################"
            puts "ERROR: --script cannot be empty when sending to chimpd"
            puts "#######################################################"
            exit 1
          end
        end


      rescue GetoptLong::InvalidOption => ex
        help
        exit 1
      end

      #
      # Before we're totally done parsing command line options,
      # let's make sure that a few things make sense
      #
      if @group_concurrency > @concurrency
        @concurrency = @group_concurrency
      end
    end
14571
def parse_args
      options = { :verbose => false }
      options[:agent_name] = ARGV[0] unless ARGV[0] =~ /^-/

      opts = OptionParser.new do |opts|

        opts.on('-l', '--log-level LEVEL') do |l|
          fail("Invalid log level '#{l}'") unless AgentManager::LEVELS.include?(l.downcase.to_sym)
          options[:level] = l.downcase
        end

        opts.on("-c", "--cfg-dir DIR") do |d|
          options[:cfg_dir] = d
        end

        opts.on('-v', '--verbose') do
          options[:verbose] = true
        end

      end

      opts.on_tail('--help') do
         puts Usage.scan(__FILE__)
         exit
      end

      begin
        opts.parse!(ARGV)
      rescue Exception => e
        exit 0 if e.is_a?(SystemExit)
        fail(e.message + "\nUse 'rlog --help' for additional information")
      end
      options
    end
976593
def get_input
      command_line = super

      # This case statement decides the command mode,
      #  and which part of the input should be used for what...
      #  Note: Regexp match groups are used!
      @result_storage = @result_operator = nil

      @command_mode = case command_line
      # force ruby with a space
      when /^ /
        :ruby
      # regexp match shell commands
      when *Array( Ripl.config[:fresh_patterns] ).compact
        command_line     = $~[:command_line]     if $~.names.include? 'command_line'
        command          = $~[:command]          if $~.names.include? 'command'
        @result_operator = $~[:result_operator]  if $~.names.include? 'result_operator'
        @result_storage  = $~[:result_storage]   if $~.names.include? 'result_storage'
        forced           = !! $~[:force]         if $~.names.include? 'force'

        if forced
          :system
        elsif Ripl.config[:fresh_ruby_commands].include?( command )
          :ruby
        elsif Ripl.config[:fresh_mixed_commands].include?( command )
          :mixed
        elsif Ripl.config[:fresh_system_commands].include?( command )
          :system
        elsif Kernel.respond_to? command.to_sym
          :ruby
        else
          Ripl.config[:fresh_unknown_command_mode]
        end
      else
        Ripl.config[:fresh_default_mode]
      end

      command_line
    end