Class: Lich::Util::Opts

Inherits:
Object
  • Object
show all
Defined in:
documented/util/opts.rb

Overview

Generic CLI argument parser for any command-line parsing task Separates concerns: parsing, validation, execution

Examples:

opts = Lich::Util::Opts.parse(ARGV, {
  gui: { type: :boolean, default: true },
  account: { type: :string },
  password: { type: :string }
})
# => OpenStruct with frozen attributes

Nested values

opts = Lich::Util::Opts.parse(['--host=localhost:4000'], {
  host: { type: :string, parser: ->(v) { h,p = v.split(':'); {host: h, port: p.to_i} } }
})

Class Method Summary collapse

Class Method Details

.parse(argv, schema = {}) ⇒ OpenStruct

Parse ARGV into an immutable OpenStruct

Parameters:

  • argv (Array<String>) —

    Argument list (usually ARGV)

  • schema (Hash) (defaults to: {}) —

    Option definitions with metadata

Options Hash (schema):

  • :type (Symbol) —

    Type coercion (:string, :boolean, :integer, :array)

  • :default (Object) —

    Default value if not provided

  • :parser (Proc) —

    Custom parser function

Returns:

  • (OpenStruct) —

    Frozen options with all specified keys



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'documented/util/opts.rb', line 32

def self.parse(argv, schema = {})
  options = {}

  # Set defaults
  schema.each do |key, config|
    options[key] = config[:default] if config.key?(:default)
  end

  # Parse ARGV
  i = 0
  while i < argv.length
    arg = argv[i]

    # Try each schema key to find a match
    matched = false # rubocop:disable Lint/UselessAssignment
    schema.each do |key, config|
      option_name = "--#{key.to_s.gsub(/_/, '-')}"
      short_option = config[:short] ? "-#{config[:short]}" : nil

      if arg == option_name || (short_option && arg == short_option)
        matched = true # rubocop:disable Lint/UselessAssignment
        options[key] = parse_value(argv, i, config)
        # Skip next arg if this option consumed it (not boolean or custom parser with = form)
        i += 1 if config[:type] != :boolean && !config[:parser]
        break
      elsif arg =~ /^#{option_name}=(.+)$/
        matched = true # rubocop:disable Lint/UselessAssignment
        value = Regexp.last_match(1)
        options[key] = parse_value_with_content(value, config)
        break
      end
    end

    i += 1
  end

  # Return frozen OpenStruct
  OpenStruct.new(options).freeze
end

.parse_value(argv, index, config) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parses a single option value and applies type coercion based on config.

Handles standard types (:boolean, :string, :integer, :array) and custom parsers. For :array type, collects consecutive non-flag arguments. For :boolean with no custom parser, returns true (the flag itself is the assertion). Falls back to custom :parser if provided and no standard type matches.

Parameters:

  • argv (Array<String>) —

    the full argument list

  • index (Integer) —

    position of the current argument in argv

  • config (Hash) —

    option configuration with :type and optional :parser keys

Returns:

  • (Object) —

    parsed value; type depends on config and presence of parser



86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'documented/util/opts.rb', line 86

def self.parse_value(argv, index, config)
  case config[:type]
  when :boolean
    true
  when :string
    argv[index + 1]
  when :integer
    argv[index + 1]&.to_i
  when :array
    # Collect following args until next --flag
    values = []
    j = index + 1
    while j < argv.length && !argv[j].start_with?('-')
      values << argv[j]
      j += 1
    end
    values
  else
    config[:parser] ? config[:parser].call(argv[index + 1]) : argv[index + 1]
  end
end

.parse_value_with_content(value, config) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parses an option value extracted from a --name=value argument.

If a custom :parser is provided in config, it is always invoked first and its result is returned. Otherwise applies standard type coercion: :boolean matches against case-insensitive patterns (true/on/yes/1), :string and :integer use their respective conversions, and unknown types return the raw string.

Parameters:

  • value (String) —

    the value portion from the --name=value argument

  • config (Hash) —

    option configuration with :type and optional :parser keys

Returns:

  • (Object) —

    parsed value; type depends on config and presence of parser



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'documented/util/opts.rb', line 119

def self.parse_value_with_content(value, config)
  # If custom parser provided, use it first
  return config[:parser].call(value) if config[:parser]

  case config[:type]
  when :boolean
    value.match?(/^(true|on|yes|1)$/i)
  when :string
    value
  when :integer
    value.to_i
  else
    value
  end
end