Class: Rex::Parser::Arguments

Inherits:
Object
  • Object
show all
Defined in:
lib/rex/parser/arguments.rb

Overview

This class parses arguments in a getopt style format, kind of. Unfortunately, the default ruby getopt implementation will only work on ARGV, so we can’t use it.

Constant Summary collapse

HasArgument =

Specifies that an option is expected to have an argument

(1 << 0)

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(fmt) ⇒ Arguments

Initializes the format list with an array of formats like:

Arguments.new(

'-b' => [ false, "some text" ]

)



28
29
30
31
32
33
34
35
# File 'lib/rex/parser/arguments.rb', line 28

def initialize(fmt)
  self.fmt = fmt
  # I think reduce is a better name for this method, but it doesn't exist
  # before 1.8.7, so use the stupid inject instead.
  self.longest = fmt.keys.inject(0) { |max, str|
    max = ((max > str.length) ? max : str.length)
  }
end

Instance Attribute Details

#fmtObject

:nodoc:



102
103
104
# File 'lib/rex/parser/arguments.rb', line 102

def fmt
  @fmt
end

#longestObject

:nodoc:



103
104
105
# File 'lib/rex/parser/arguments.rb', line 103

def longest
  @longest
end

Class Method Details

.from_s(str) ⇒ Object

Takes a string and converts it into an array of arguments.



40
41
42
# File 'lib/rex/parser/arguments.rb', line 40

def self.from_s(str)
  Shellwords.shellwords(str)
end

Instance Method Details

#arg_required?(opt) ⇒ Boolean

Returns:

  • (Boolean)


98
99
100
# File 'lib/rex/parser/arguments.rb', line 98

def arg_required?(opt)
  fmt[opt][0] if fmt[opt]
end

#include?(search) ⇒ Boolean

Returns:

  • (Boolean)


94
95
96
# File 'lib/rex/parser/arguments.rb', line 94

def include?(search)
  return fmt.include?(search)
end

#parse(args, &block) ⇒ Object

Parses the supplied arguments into a set of options.



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/rex/parser/arguments.rb', line 47

def parse(args, &block)
  skip_next = false

  args.each_with_index { |arg, idx|
    if (skip_next == true)
      skip_next = false
      next
    end

    if (arg.match(/^-/))
      cfs = arg[0..2]

      fmt.each_pair { |fmtspec, val|
        next if (fmtspec != cfs)

        param = nil

        if (val[0])
          param = args[idx+1]
          skip_next = true
        end

        yield fmtspec, idx, param
      }
    else
      yield nil, idx, arg
    end
  }
end

#usageObject

Returns usage information for this parsing context.



80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/rex/parser/arguments.rb', line 80

def usage
  txt = "\nOPTIONS:\n\n"

  fmt.sort.each { |entry|
    fmtspec, val = entry

    txt << "    #{fmtspec.ljust(longest)}" + ((val[0] == true) ? " <opt>  " : "        ")
    txt << val[1] + "\n"
  }

  txt << "\n"

  return txt
end