Sha256: da640a657b5b0767fe0ec28cb8b596daf1a98d2ed3e792f3322e7302953156f6

Contents?: true

Size: 1.74 KB

Versions: 5

Compression:

Stored size: 1.74 KB

Contents

module ShellOpts
  module Grammar
    # Program is the root object of the grammar
    class Program < Command
      # Array of non-option litteral arguments (ie. what comes after the double dash ('+--+') in
      # the usage definition). Initially empty but filled out during compilation
      attr_reader :args

      # Initialize a top-level Program object
      def initialize(name, option_list)
        super(nil, name, option_list)
        @args = []
      end

      # Usage string to be used in error messages. The string is kept short by
      # only listing the shortest option (if there is more than one)
      def usage
        (
          render_options(option_list) + 
          subcommand_list.map { |cmd| render_subcommand(cmd) } + 
          args
        ).flatten.join(" ")
      end

      # :nocov:
      def dump(&block)
        super { 
          puts "args: #{args.inspect}" 
          puts "usage: #{usage.inspect}"
        }
      end
      # :nocov:

    private
      def render_subcommand(subcommand)
        [subcommand.name] + render_options(subcommand.option_list) + 
            subcommand.subcommand_list.map { |cmd| render_subcommand(cmd) }.flatten
      end

      def render_options(options)
        options.map { |opt|
          s = opt.names.first
          if opt.argument?
            arg_string = 
                if opt.label
                  opt.label
                elsif opt.integer?
                  "INT"
                elsif opt.float?
                  "FLOAT"
                else
                  "ARG"
                end
            if opt.optional?
              s += "[=#{arg_string}]"
            else
              s += "=#{arg_string}"
            end
          end
          s
        }
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
shellopts-2.0.0.pre.13 lib/shellopts/grammar/program.rb
shellopts-2.0.0.pre.11 lib/shellopts/grammar/program.rb
shellopts-2.0.0.pre.9 lib/shellopts/grammar/program.rb
shellopts-2.0.0.pre.8 lib/shellopts/grammar/program.rb
shellopts-2.0.0.pre.7 lib/shellopts/grammar/program.rb