metasploit-framework/lib/rex/parser/arguments.rb

96 lines
2.1 KiB
Ruby
Raw Normal View History

# -*- coding: binary -*-
2017-03-16 06:29:16 +00:00
# frozen_string_literal: true
require 'shellwords'
module Rex
2017-03-16 06:29:16 +00:00
module Parser
###
#
# 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.
#
###
class Arguments
#
# Initializes the format list with an array of formats like:
#
# Arguments.new(
# '-b' => [ false, "some text" ]
# )
#
def initialize(fmt)
self.fmt = fmt
self.longest = fmt.keys.max_by(&:length)
end
2013-08-30 21:28:33 +00:00
2017-03-16 06:29:16 +00:00
#
# Takes a string and converts it into an array of arguments.
#
def self.from_s(str)
Shellwords.shellwords(str)
end
2013-08-30 21:28:33 +00:00
2017-03-16 06:29:16 +00:00
#
# Parses the supplied arguments into a set of options.
#
def parse(args, &_block)
skip_next = false
2013-08-30 21:28:33 +00:00
2017-03-16 06:29:16 +00:00
args.each_with_index do |arg, idx|
if skip_next
skip_next = false
next
end
2013-08-30 21:28:33 +00:00
if arg.length > 1 && arg[0] == '-' && arg[1] != '-'
arg.split('').each do |flag|
fmt.each_pair do |fmtspec, val|
next if fmtspec != "-#{flag}"
2013-08-30 21:28:33 +00:00
param = nil
2013-08-30 21:28:33 +00:00
if val[0]
param = args[idx + 1]
skip_next = true
end
2013-08-30 21:28:33 +00:00
yield fmtspec, idx, param
2017-03-16 06:29:16 +00:00
end
end
else
yield nil, idx, arg
2013-08-30 21:28:33 +00:00
end
2017-03-16 06:29:16 +00:00
end
2013-08-30 21:28:33 +00:00
end
2017-03-16 06:29:16 +00:00
#
# Returns usage information for this parsing context.
#
def usage
txt = ["\nOPTIONS:\n"]
2013-08-30 21:28:33 +00:00
2017-03-16 06:29:16 +00:00
fmt.sort.each do |entry|
fmtspec, val = entry
opt = val[0] ? " <opt> " : " "
txt << " #{fmtspec.ljust(longest.length)}#{opt}#{val[1]}"
end
2013-08-30 21:28:33 +00:00
2017-03-22 08:29:47 +00:00
txt << ""
2017-03-16 06:29:16 +00:00
txt.join("\n")
end
2013-08-30 21:28:33 +00:00
2017-03-16 06:29:16 +00:00
def include?(search)
fmt.include?(search)
end
2013-08-30 21:28:33 +00:00
2017-03-16 06:29:16 +00:00
def arg_required?(opt)
fmt[opt][0] if fmt[opt]
end
2013-08-30 21:28:33 +00:00
2017-03-16 06:29:16 +00:00
attr_accessor :fmt # :nodoc:
attr_accessor :longest # :nodoc:
end
2013-08-30 21:28:33 +00:00
end
end