Sha256: d55607b9c8aa4a314f6890231c19c1b2221b5ced49a3ace20ea060b2593e99de

Contents?: true

Size: 1.62 KB

Versions: 13

Compression:

Stored size: 1.62 KB

Contents

require "logger"

module Simple::CLI
  # A DefaultOptions object holds values for default options.
  class DefaultOptions
    # extract default CLI options and the  "help" command. Returns a DefaultOptions object
    def extract!(args:)
      new args
    end

    # verbosity (one of ::Logger::WARN, ::Logger::INFO, ::Logger::DEBUG)
    attr_reader :log_level

    # returns true if we run in verbose mode.
    def verbose?
      log_level == ::Logger::DEBUG
    end

    # command
    attr_reader :command

    # The help flag. Is set when
    #
    # - running the "help" command
    # - when a "-h" or "--help" CLI flag was given.
    def help?
      @help
    end

    private

    LOG_LEVEL_FLAGS = {
      "--verbose" => ::Logger::DEBUG,
      "-v" => ::Logger::DEBUG,
      "--quiet" => ::Logger::WARN,
      "-q" => ::Logger::WARN,
      default: ::Logger::INFO
    }

    HELP_FLAGS = {
      "--help" => true,
      "-h" => true,
      default: false
    }

    def initialize(args)
      @args = args

      @log_level = extract_w_lookup!(LOG_LEVEL_FLAGS)  # get -v/--verbose and -q7--quiet flags
      @command   = extract_command!                    # extract the command
      if @command == "help"
        @help = true
        @command = extract_command!
      else
        @help = extract_w_lookup!(HELP_FLAGS)          # extract --help flag
      end
    end

    def extract_w_lookup!(hsh)
      value = hsh[:default]
      @args.reject! do |str|
        next unless hsh.key?(str)
        value = hsh[str]
      end
      value
    end

    def extract_command!
      return nil if /^-/ =~ @args.first
      @args.shift
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
simple-cli-0.4.2 lib/simple/cli/default_options.rb
simple-cli-0.4.1 lib/simple/cli/default_options.rb
simple-cli-0.4.0 lib/simple/cli/default_options.rb
simple-cli-0.3.13 lib/simple/cli/default_options.rb
simple-cli-0.3.12 lib/simple/cli/default_options.rb
simple-cli-0.3.11 lib/simple/cli/default_options.rb
simple-cli-0.3.10 lib/simple/cli/default_options.rb
simple-cli-0.3.9 lib/simple/cli/default_options.rb
simple-cli-0.3.8 lib/simple/cli/default_options.rb
simple-cli-0.3.7 lib/simple/cli/default_options.rb
simple-cli-0.3.5 lib/simple/cli/default_options.rb
simple-cli-0.3.4 lib/simple/cli/default_options.rb
simple-cli-0.3.3 lib/simple/cli/default_options.rb