Class: Lich::Util::Opts
- Inherits:
-
Object
- Object
- Lich::Util::Opts
- Defined in:
- documented/util/opts.rb
Overview
Provides utility methods for parsing command line options.
Class Method Summary collapse
-
.parse(argv, schema = {}) ⇒ OpenStruct
Parses command line arguments based on the provided schema.
-
.parse_value(argv, index, config) ⇒ Object
Parses the value of a command line option based on its configuration.
-
.parse_value_with_content(value, config) ⇒ Object
Parses a value with content based on the provided configuration.
Class Method Details
.parse(argv, schema = {}) ⇒ OpenStruct
Parses command line arguments based on the provided schema.
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'documented/util/opts.rb', line 17 def self.parse(argv, schema = {}) = {} # Set defaults schema.each do |key, config| [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 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 [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 value = Regexp.last_match(1) [key] = parse_value_with_content(value, config) break end end i += 1 end # Return frozen OpenStruct OpenStruct.new().freeze end |
.parse_value(argv, index, config) ⇒ Object
Parses the value of a command line option based on its configuration.
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
# File 'documented/util/opts.rb', line 65 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
Parses a value with content based on the provided configuration.
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
# File 'documented/util/opts.rb', line 93 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 |