get()
public
Get next option name and its argument, as an Array of two elements.
The option name is always converted to the first (preferred) name given in
the original options to GetoptLong.new.
Example: [‘–option’, ‘value’]
Returns nil if the processing is complete (as determined by
STATUS_TERMINATED).
Show source
def get
option_name, option_argument = nil, ''
return nil if @error != nil
case @status
when STATUS_YET
@status = STATUS_STARTED
when STATUS_TERMINATED
return nil
end
if 0 < @rest_singles.length
argument = '-' + @rest_singles
elsif (ARGV.length == 0)
terminate
return nil
elsif @ordering == PERMUTE
while 0 < ARGV.length && ARGV[0] !~ /^-./
@non_option_arguments.push(ARGV.shift)
end
if ARGV.length == 0
terminate
return nil
end
argument = ARGV.shift
elsif @ordering == REQUIRE_ORDER
if (ARGV[0] !~ /^-./)
terminate
return nil
end
argument = ARGV.shift
else
argument = ARGV.shift
end
if argument == '--' && @rest_singles.length == 0
terminate
return nil
end
if argument =~ /^(--[^=]+)/ && @rest_singles.length == 0
pattern = $1
if @canonical_names.include?(pattern)
option_name = pattern
else
matches = []
@canonical_names.each_key do |key|
if key.index(pattern) == 0
option_name = key
matches << key
end
end
if 2 <= matches.length
set_error(AmbiguousOption, "option `#{argument}' is ambiguous between #{matches.join(', ')}")
elsif matches.length == 0
set_error(InvalidOption, "unrecognized option `#{argument}'")
end
end
if @argument_flags[option_name] == REQUIRED_ARGUMENT
if argument =~ /=(.*)$/
option_argument = $1
elsif 0 < ARGV.length
option_argument = ARGV.shift
else
set_error(MissingArgument,
"option `#{argument}' requires an argument")
end
elsif @argument_flags[option_name] == OPTIONAL_ARGUMENT
if argument =~ /=(.*)$/
option_argument = $1
elsif 0 < ARGV.length && ARGV[0] !~ /^-./
option_argument = ARGV.shift
else
option_argument = ''
end
elsif argument =~ /=(.*)$/
set_error(NeedlessArgument,
"option `#{option_name}' doesn't allow an argument")
end
elsif argument =~ /^(-(.))(.*)/
option_name, ch, @rest_singles = $1, $2, $3
if @canonical_names.include?(option_name)
if @argument_flags[option_name] == REQUIRED_ARGUMENT
if 0 < @rest_singles.length
option_argument = @rest_singles
@rest_singles = ''
elsif 0 < ARGV.length
option_argument = ARGV.shift
else
set_error(MissingArgument, "option requires an argument -- #{ch}")
end
elsif @argument_flags[option_name] == OPTIONAL_ARGUMENT
if 0 < @rest_singles.length
option_argument = @rest_singles
@rest_singles = ''
elsif 0 < ARGV.length && ARGV[0] !~ /^-./
option_argument = ARGV.shift
else
option_argument = ''
end
end
else
if ENV.include?('POSIXLY_CORRECT')
set_error(InvalidOption, "invalid option -- #{ch}")
else
set_error(InvalidOption, "invalid option -- #{ch}")
end
end
else
return '', argument
end
return @canonical_names[option_name], option_argument
end