Method: CommandLine::OptionParser#parse

Defined in:
lib/commandline/optionparser/optionparser.rb

#parse(argv = ARGV) ⇒ Object

Parse the command line



202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/commandline/optionparser/optionparser.rb', line 202

def parse(argv=ARGV)
  argv = [argv] unless Array === argv

  #
  # Holds the results of each option. The key used is 
  # the first in the :names Array.
  #
  opts = Hash.new( :not_found )

  #
  # A command is the first non-option free argument on the command line.
  # This is a user selection and is the first argument in args.
  #  cmd = args.shift
  # Example:
  #  cvs -v cmd --cmd-option arg
  #
  cmd = nil
  cmd_options = {}

  #
  # #parse_argv yields an array containing the option and its arguments.
  #   [opts, array_args]
  # How do we collect all the arguments when OptionParser deal with an 
  # empty option list
  #
  parse_argv(argv) { |optarg|
    user_option  = optarg[0]
    _args        = optarg[1]

    m = nil
    if @opt_lookup_by_any_name.has_key?(user_option) ||
       1 == (m = @opt_lookup_by_any_name.keys.grep(/^#{user_option}/)).size
      user_option = m[0] if m
      opt         = @opt_lookup_by_any_name[user_option]
      opt_key     = opt.names[0]

      opt_args = get_opt_args(opt, user_option, _args)
      opts[opt_key] = 
        if Proc === opt.opt_found
          # Take the arguments depending upon arity
          opt.opt_found.call(opt, user_option, opt_args)
        else
          opt.opt_found
        end
        # Collect any remaining args
        @args += _args
    elsif :collect == @unknown_options_action
      @unknown_options << user_option
    elsif :ignore == @unknown_options_action
    else
      raise(UnknownOptionError, "Unknown option '#{user_option}'"+
        "#{$DEBUG ? ' in ' + @opt_lookup_by_any_name.keys.inspect : ''}.")
    end
  }

  #
  # Call :not_found for all the options not on the command line.
  #
  @options.each { |opt|
    name = opt.names[0]
    if :not_found == opts[name]
      opts[name] = 
      if Proc === opt.opt_not_found
        opt.opt_not_found.call(opt)
      else
        opt.opt_not_found
      end
    end
  }

  OptionData.new(argv, opts, @unknown_options, @args, @not_parsed, cmd)
end