# OptionParser::Switch (Class)

In: | optparse.rb
Parent: | Object

## Methods

abort accept accept banner base conv_arg def_head_option def_option def_tail_option define define_head define_tail environment guess help inc inc incompatible_argument_styles load make_switch new new new on on_head on_tail order order! parse parse! parse_arg pattern permute permute! program_name reject reject release remove separator summarize summarize terminate terminate to_a to_s top top ver version warn with

## Constants

ArgumentStyle | = | {}
DefaultList | = | List.new
DecimalInteger | = | /\A[-+]?#{decimal}/io
OctalInteger | = | /\A[-+]?(?:[0-7]+(?:_[0-7]+)*|0(?:#{binary}|#{hex}))/io
DecimalNumeric | = | floatpat # decimal integer is allowed as float also.

## External Aliases

banner= -> set_banner
program_name= -> set_program_name
summary_width= -> set_summary_width
summary_indent= -> set_summary_indent

## Attributes

arg | [R] |
banner | [W] |
block | [R] |
conv | [R] |
desc | [R] |
long | [R] |
pattern | [R] |
program_name | [W] |
release | [W] |
short | [R] |
summary_indent | [RW] |
summary_width | [RW] |
version | [W] |

## Classes and Modules

Module OptionParser::Switch::Acceptables
Module OptionParser::Switch::Arguable
Class OptionParser::Switch::AmbiguousArgument
Class OptionParser::Switch::AmbiguousOption
Class OptionParser::Switch::CompletingHash
Class OptionParser::Switch::InvalidArgument
Class OptionParser::Switch::InvalidOption
Class OptionParser::Switch::List
Class OptionParser::Switch::MissingArgument
Class OptionParser::Switch::NeedlessArgument
Class OptionParser::Switch::NoArgument
Class OptionParser::Switch::OptionalArgument
Class OptionParser::Switch::ParseError
Class OptionParser::Switch::PlacedArgument
Class OptionParser::Switch::RequiredArgument

## Public Class methods

guess(arg)

[Source]

    # File optparse.rb, line 266
        def self.guess(arg)
          case arg
          when ""
            t = self
          when /\A=?\[/
            t = Switch::OptionalArgument
          when /\A\s+\[/
            t = Switch::PlacedArgument
          else
            t = Switch::RequiredArgument
          end
          self >= t or incompatible_argument_styles(arg, t)
          t
        end

incompatible_argument_styles(arg, t)

[Source]

    # File optparse.rb, line 281
        def self.incompatible_argument_styles(arg, t)
          raise ArgumentError, "#{arg}: incompatible argument styles\n  #{self}, #{t}"
        end

pattern()

[Source]

    # File optparse.rb, line 285
        def self.pattern
          NilClass
        end

new(pattern = nil, conv = nil, short = nil, long = nil, arg = nil, desc = ([] if short or long), block = Proc.new)

[Source]

    # File optparse.rb, line 292
        def initialize(pattern = nil, conv = nil,
                       short = nil, long = nil, arg = nil,
                       desc = ([] if short or long), block = Proc.new)
          raise if Array === pattern
          @pattern, @conv, @short, @long, @arg, @desc, @block =
            pattern, conv, short, long, arg, desc, block
        end

with(*args, &block)

[Source]

    # File optparse.rb, line 774
      def self.with(*args, &block)
        opts = new(*args)
        opts.instance_eval(&block)
        opts
      end

inc(arg, default = nil)

[Source]

    # File optparse.rb, line 785
      def self.inc(arg, default = nil)
        case arg
        when Integer
          arg.nonzero?
        when nil
          default.to_i + 1
        end
      end

new(banner = nil, width = 32, indent = ' ' * 4) {|self if block_given?| ...}

[Source]

    # File optparse.rb, line 810
      def initialize(banner = nil, width = 32, indent = ' ' * 4)
        @stack = [DefaultList, List.new, List.new]
        @program_name = nil
        @banner = banner
        @summary_width = width
        @summary_indent = indent
        yield self if block_given?
      end

terminate(arg = nil)

[Source]

    # File optparse.rb, line 830
      def self.terminate(arg = nil)
        throw :terminate, arg
      end

top()

[Source]

    # File optparse.rb, line 835
      def self.top() DefaultList end

accept(*args, &blk)

[Source]

    # File optparse.rb, line 850
      def self.accept(*args, &blk) top.accept(*args, &blk) end

reject(*args, &blk)

[Source]

    # File optparse.rb, line 861
      def self.reject(*args, &blk) top.reject(*args, &blk) end

## Public Instance methods

parse_arg(arg) {|InvalidArgument, arg| ...}

[Source]

    # File optparse.rb, line 313
        def parse_arg(arg)
          pattern or return nil, arg
          unless m = pattern.match(arg)
            yield(InvalidArgument, arg)
            return arg, nil
          end
          if String === m
            m = [s = m]
          else
            m = m.to_a
            s = m[0]
            return nil, m unless String === s
          end
          raise InvalidArgument, arg unless arg.rindex(s, 0)
          return nil, m if s.length == arg.length
          yield(InvalidArgument, arg) # didn't match whole arg

          return arg[s.length..-1], m
        end

conv_arg(arg, val = nil)

[Source]

    # File optparse.rb, line 348
        def conv_arg(arg, val = nil)
          if block
            if conv
              val = conv.call(*val)
            else
              val = *val
            end
            return arg, block, val
          else
            return arg, nil
          end
        end

summarize(sdone = [], ldone = [], width = 1, max = width - 1, indent = "") {|indent + l| ...}

[Source]

    # File optparse.rb, line 380
        def summarize(sdone = [], ldone = [], width = 1, max = width - 1, indent = "")
          sopts, lopts, s = [], [], nil
          @short.each {|s| sdone.fetch(s) {sopts << s}; sdone[s] = true} if @short
          @long.each {|s| ldone.fetch(s) {lopts << s}; ldone[s] = true} if @long
          return if sopts.empty? and lopts.empty? # completely hidden

          left = [sopts.join(', ')]
          right = desc.dup

          while s = lopts.shift
            l = left[-1].length + s.length
            l += arg.length if left.size == 1 && arg
            l < max or left << ''
            left[-1] << if left[-1].empty? then ' ' * 4 else ', ' end << s
          end

          left[0] << arg if arg
          mlen = left.collect {|s| s.length}.max.to_i
          while mlen > width and l = left.shift
            mlen = left.collect {|s| s.length}.max.to_i if l.length == mlen
            yield(indent + l)
          end

          while (l = left.shift; r = right.shift; l or r)
            l = l.to_s.ljust(width) + ' ' + r if r and !r.empty?
            yield(indent + l)
          end

          self
        end

inc(*args)

[Source]

    # File optparse.rb, line 793
      def inc(*args)
        self.class.inc(*args)
      end

terminate(arg = nil)

[Source]

    # File optparse.rb, line 827
      def terminate(arg = nil)
        self.class.terminate(arg)
      end

accept(*args, &blk)

[Source]

    # File optparse.rb, line 849
      def accept(*args, &blk) top.accept(*args, &blk) end

reject(*args, &blk)

[Source]

    # File optparse.rb, line 860
      def reject(*args, &blk) top.reject(*args, &blk) end

banner()

[Source]

    # File optparse.rb, line 886
      def banner
        @banner ||= "Usage: #{program_name} [options]"
      end

program_name()

[Source]

    # File optparse.rb, line 890
      def program_name
        @program_name || File.basename($0, '.*')
      end

version()

[Source]

    # File optparse.rb, line 913
      def version
        @version || (defined?(::Version) && ::Version) || (defined?(::VERSION) && ::VERSION)
      end

release()

[Source]

    # File optparse.rb, line 917
      def release
        @release || (defined?(::Release) && ::Release) || (defined?(::RELEASE) && ::RELEASE)
      end

ver()

[Source]

    # File optparse.rb, line 921
      def ver
        if v = version
          str = "#{program_name} #{[v].join('.')}"
          str << " (#{v})" if v = release
          str
        end
      end

warn(mesg = $!)

[Source]

    # File optparse.rb, line 929
      def warn(mesg = $!)
        super(program_name + ': ' + mesg)
      end

abort(mesg = $!)

[Source]

    # File optparse.rb, line 933
      def abort(mesg = $!)
        super(program_name + ': ' + mesg)
      end

top()

[Source]

    # File optparse.rb, line 941
      def top
        @stack[-1]
      end

base()

[Source]

    # File optparse.rb, line 949
      def base
        @stack[1]
      end

new() {|self| ...}

[Source]

    # File optparse.rb, line 957
      def new
        @stack.push(List.new)
        if block_given?
          yield self
        else
          self
        end
      end

remove()

[Source]

    # File optparse.rb, line 970
      def remove
        @stack.pop
      end

summarize(to = [], width = @summary_width, max = width - 1, indent = @summary_indent, &blk)

[Source]

    # File optparse.rb, line 990
      def summarize(to = [], width = @summary_width, max = width - 1, indent = @summary_indent, &blk)
        visit(:summarize, {}, {}, width, max, indent, &(blk || proc {|l| to << l + $/}))
        to
      end

help()

[Source]

    # File optparse.rb, line 1000
      def help; summarize(banner.to_s.sub(/\n?\z/, "\n")) end

to_s()

Alias for help

to_a()

[Source]

    # File optparse.rb, line 1007
      def to_a; summarize(banner.to_a.dup) end

make_switch(*opts, &block)

[Source]

    # File optparse.rb, line 1072
      def make_switch(*opts, &block)
        short, long, nolong, style, pattern, conv, not_pattern, not_conv, not_style = [], [], []
        ldesc, sdesc, desc, arg = [], [], []
        default_style = Switch::NoArgument
        default_pattern = nil
        klass = nil
        o = nil
        n, q, a = nil

        opts.each do |o|
          # argument class

          next if search(:atype, o) do |pat, c|
            klass = notwice(o, klass, 'type')
            if not_style and not_style != Switch::NoArgument
              not_pattern, not_conv = pat, c
            else
              default_pattern, conv = pat, c
            end
          end

          # directly specified pattern(any object possible to match)

          if !(String === o) and o.respond_to?(:match)
            pattern = notwice(o, pattern, 'pattern')
            conv = (pattern.method(:convert).to_proc if pattern.respond_to?(:convert))
            next
          end

          # anything others

          case o
          when Proc, Method
            block = notwice(o, block, 'block')
          when Array, Hash
            case pattern
            when CompletingHash
            when nil
              pattern = CompletingHash.new
              conv = (pattern.method(:convert).to_proc if pattern.respond_to?(:convert))
            else
              raise ArgumentError, "argument pattern given twice"
            end
            o.each {|(o, *v)| pattern[o] = v.fetch(0) {o}}
          when Module
            raise ArgumentError, "unsupported argument type: #{o}"
          when *ArgumentStyle.keys
            style = notwice(ArgumentStyle[o], style, 'style')
          when /^--no-([^\[\]=\s]*)(.+)?/
            q, a = $1, $2
            o = notwice(a ? Object : TrueClass, klass, 'type')
            not_pattern, not_conv = search(:atype, o) unless not_style
            not_style = (not_style || default_style).guess(arg = a) if a
            default_style = Switch::NoArgument
            default_pattern, conv = search(:atype, FalseClass) unless default_pattern
            ldesc << "--no-#{q}"
            long << 'no-' + (q = q.downcase)
            nolong << q
          when /^--\[no-\]([^\[\]=\s]*)(.+)?/
            q, a = $1, $2
            o = notwice(a ? Object : TrueClass, klass, 'type')
            if a
              default_style = default_style.guess(arg = a)
              default_pattern, conv = search(:atype, o) unless default_pattern
            end
            ldesc << "--#{q}"
            long << (o = q.downcase)
            not_pattern, not_conv = search(:atype, FalseClass) unless not_style
            not_style = Switch::NoArgument
            nolong << 'no-' + o
          when /^--([^\[\]=\s]*)(.+)?/
            q, a = $1, $2
            if a
              o = notwice(NilClass, klass, 'type')
              default_style = default_style.guess(arg = a)
              default_pattern, conv = search(:atype, o) unless default_pattern
            end
            ldesc << "--#{q}"
            long << (o = q.downcase)
          when /^-(\[\^^?\]?(?:[^\\\]]|\\.)*\])(.+)?/
            q, a = $1, $2
            o = notwice(Object, klass, 'type')
            if a
              default_style = default_style.guess(arg = a)
              default_pattern, conv = search(:atype, o) unless default_pattern
            end
            sdesc << "-#{q}"
            short << Regexp.new(q)
          when /^-(.)(.+)?/
            q, a = $1, $2
            if a
              o = notwice(NilClass, klass, 'type')
              default_style = default_style.guess(arg = a)
              default_pattern, conv = search(:atype, o) unless default_pattern
            end
            sdesc << "-#{q}"
            short << q
          when /^=/
            style = notwice(default_style.guess(arg = o), style, 'style')
            default_pattern, conv = search(:atype, Object) unless default_pattern
          else
            desc.push(o)
          end
        end

        default_pattern, conv = search(:atype, default_style.pattern) unless default_pattern
        s = if short.empty? and long.empty?
              raise ArgumentError, "no switch given" if style or pattern or block
              desc
            else
              (style || default_style).new(pattern || default_pattern,
                                           conv, sdesc, ldesc, arg, desc, block)
            end
        return s, short, long,
          (not_style.new(not_pattern, not_conv, sdesc, ldesc, nil, desc, block) if not_style),
          nolong
      end

define(*opts, &block)

[Source]

    # File optparse.rb, line 1200
      def define(*opts, &block)
        top.append(*(sw = make_switch(*opts, &block)))
        sw[0]
      end

on(*opts, &block)

[Source]

    # File optparse.rb, line 1204
      def on(*opts, &block)
        define(*opts, &block)
        self
      end

def_option(*opts, &block)

Alias for define

define_head(*opts, &block)

[Source]

    # File optparse.rb, line 1210
      def define_head(*opts, &block)
        top.prepend(*(sw = make_switch(*opts, &block)))
        sw[0]
      end

on_head(*opts, &block)

[Source]

    # File optparse.rb, line 1214
      def on_head(*opts, &block)
        define_head(*opts, &block)
        self
      end

def_head_option(*opts, &block)

Alias for define_head

define_tail(*opts, &block)

[Source]

    # File optparse.rb, line 1220
      def define_tail(*opts, &block)
        base.append(*(sw = make_switch(*opts, &block)))
        sw[0]
      end

on_tail(*opts, &block)

[Source]

    # File optparse.rb, line 1224
      def on_tail(*opts, &block)
        define_tail(*opts, &block)
        self
      end

def_tail_option(*opts, &block)

Alias for define_tail

separator(string)

[Source]

    # File optparse.rb, line 1230
      def separator(string)
        top.append(string, nil, nil)
      end

order(*argv, &block)

[Source]

    # File optparse.rb, line 1252
      def order(*argv, &block)
        argv = argv[0].dup if argv.size == 1 and Array === argv[0]
        order!(argv, &block)
      end

order!(argv = ARGV, &nonopt)

[Source]

    # File optparse.rb, line 1257
      def order!(argv = ARGV, &nonopt)
        opt, arg, sw, val, rest = nil
        nonopt ||= proc {|arg| throw :terminate, arg}
        argv.unshift(arg) if arg = catch(:terminate) {
          while arg = argv.shift
            case arg
            # long option

            when /\A--([^=]*)(?:=(.*))?/
              opt, rest = $1, $2
              begin
                sw, = complete(:long, opt)
              rescue ParseError
                raise $!.set_option(arg, true)
              end
              begin
                opt, sw, val = sw.parse(rest, argv) {|*exc| raise(*exc)}
                sw.call(val) if sw
              rescue ParseError
                raise $!.set_option(arg, rest)
              end

            # short option

            when /\A-(.)((=).*|.+)?/
              opt, has_arg, eq, val, rest = $1, $3, $3, $2, $2
              begin
                unless sw = search(:short, opt)
                  begin
                    sw, = complete(:short, opt)
                    # short option matched.

                    val = arg.sub(/\A-/, '')
                    has_arg = true
                  rescue InvalidOption
                    # if no short options match, try completion with long

                    # options.

                    sw, = complete(:long, opt)
                    eq ||= !rest
                  end
                end
              rescue ParseError
                raise $!.set_option(arg, true)
              end
              begin
                opt, sw, val = sw.parse(val, argv) {|*exc| raise(*exc) if eq}
                raise InvalidOption, arg if has_arg and !eq and arg == "-#{opt}"
                argv.unshift(opt) if opt and (opt = opt.sub(/\A-*/, '-')) != '-'
                sw.call(val) if sw
              rescue ParseError
                raise $!.set_option(arg, arg.length > 2)
              end

            # non-option argument

            else
              nonopt.call(arg)
            end
          end

          nil
        }

        argv
      end

permute(*argv)

[Source]

    # File optparse.rb, line 1332
      def permute(*argv)
        argv = argv[0].dup if argv.size == 1 and Array === argv[0]
        permute!(argv)
      end

permute!(argv = ARGV)

[Source]

    # File optparse.rb, line 1337
      def permute!(argv = ARGV)
        nonopts = []
        arg = nil
        order!(argv) {|arg| nonopts << arg}
        argv[0, 0] = nonopts
        argv
      end

parse(*argv)

[Source]

    # File optparse.rb, line 1358
      def parse(*argv)
        argv = argv[0].dup if argv.size == 1 and Array === argv[0]
        parse!(argv)
      end

parse!(argv = ARGV)

[Source]

    # File optparse.rb, line 1363
      def parse!(argv = ARGV)
        if ENV.include?('POSIXLY_CORRECT')
          order!(argv)
        else
          permute!(argv)
        end
      end

load(filename = nil)

[Source]

    # File optparse.rb, line 1446
      def load(filename = nil)
        begin
          filename ||= File.expand_path(File.basename($0, '.*'), '~/.options')
        rescue
          return false
        end
        begin
          parse(*IO.readlines(filename).each {|s| s.chomp!})
          true
        rescue Errno::ENOENT, Errno::ENOTDIR
          false
        end
      end

environment(env = File.basename($0, '.*'))

[Source]

    # File optparse.rb, line 1468
      def environment(env = File.basename($0, '.*'))
        env = ENV[env] || ENV[env.upcase] or return
        parse(*Shellwords.shellwords(env))
      end

[Validate]