Class: ArgParser::Parser
- Inherits:
-
Object
- Object
- ArgParser::Parser
- Defined in:
- lib/arg-parser/parser.rb
Overview
Parser for parsing a command-line
Defined Under Namespace
Classes: EmptyArgs
Instance Attribute Summary collapse
-
#definition ⇒ Definition
readonly
The supported Arguments to be used when parsing the command-line.
-
#errors ⇒ Array
readonly
An Array of error message Strings generated during parsing.
Instance Method Summary collapse
-
#classify_tokens(tokens) ⇒ Object
Evaluate the list of values in
tokens
, and classify them as either keyword/value pairs, or positional arguments. -
#initialize(definition = nil) ⇒ Parser
constructor
Instantiates a new command-line parser, with the specified command- line definition.
-
#method_missing(mthd, *args) ⇒ Object
Delegate unknown methods to the associated argument Definition object.
-
#parse(tokens = ARGV) ⇒ False|OpenStruct
Parse the specified Array<String> of
tokens
, or ARGV iftokens
is nil. -
#process_args(pos_vals, kw_vals, rest_vals) ⇒ Object
Process arguments using the supplied
pos_vals
Array of positional argument values, and thekw_vals
Hash of keyword/value. -
#show_help? ⇒ Boolean
Flag set during parsing if the user has requested the help display to be shown (via –help or /?).
-
#show_usage? ⇒ Boolean
Flag set during parsing if the usage display should be shown.
Constructor Details
#initialize(definition = nil) ⇒ Parser
Instantiates a new command-line parser, with the specified command- line definition. A Parser instance delegates unknown methods to the Definition, so its possible to work only with a Parser instance to both define and parse a command-line.
37 38 39 40 |
# File 'lib/arg-parser/parser.rb', line 37 def initialize(definition = nil) @definition = definition || Definition.new @errors = [] end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(mthd, *args) ⇒ Object
Delegate unknown methods to the associated argument Definition object.
80 81 82 83 84 85 86 |
# File 'lib/arg-parser/parser.rb', line 80 def method_missing(mthd, *args) if @definition.respond_to?(mthd) @definition.send(mthd, *args) else super end end |
Instance Attribute Details
#definition ⇒ Definition (readonly)
Returns The supported Arguments to be used when parsing the command-line.
13 14 15 |
# File 'lib/arg-parser/parser.rb', line 13 def definition @definition end |
#errors ⇒ Array (readonly)
Returns An Array of error message Strings generated during parsing.
16 17 18 |
# File 'lib/arg-parser/parser.rb', line 16 def errors @errors end |
Instance Method Details
#classify_tokens(tokens) ⇒ Object
Evaluate the list of values in tokens
, and classify them as either keyword/value pairs, or positional arguments. Ideally this would be done without any reference to the defined arguments, but unfortunately there are a couple of issues that require context to be able to handle properly:
-
a keyword arg cannot be distinguished from a flag arg followed by a positional arg without the context of what arguments are expected.
-
command arguments will normally have their own set of additional arguments that must be added once we know which command has been entered.
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 |
# File 'lib/arg-parser/parser.rb', line 99 def classify_tokens(tokens) if tokens.is_a?(String) require 'csv' tokens = CSV.parse(tokens, col_sep: ' ').first end tokens = [] unless tokens pos_vals = [] kw_vals = {} rest_vals = [] arg = nil pos_args = @definition.positional_args tokens.each_with_index do |token, i| if token.downcase == 'help' && i == 0 # Accept 'help' as the first token @show_help = true next end case token when '/?', '-?', '--help' @show_help = true when /^[-\/]([a-z0-9]+)$/i # One or more short keys $1.to_s.each_char do |sk| kw_vals[arg] = nil if arg arg = @definition[sk] if FlagArgument === arg kw_vals[arg] = true arg = nil elsif PositionalArgument == arg pos_args.delete(arg) end end when /^--(no[nt]?-)?(.+)/i # Long key kw_vals[arg] = nil if arg arg = @definition[$2] if FlagArgument === arg || (KeywordArgument === arg && $1) kw_vals[arg] = $1 ? false : true arg = nil elsif PositionalArgument === arg pos_args.delete(arg) end when '--' # All subsequent values are rest args kw_vals[arg] = nil if arg unless rest_vals.empty? self.errors << "Too many positional arguments supplied before -- token" end rest_vals = tokens[(i + 1)..-1] break else if arg kw_vals[arg] = token elsif pos_args.size > 0 arg = pos_args.shift if CommandArgument === arg if cmd_inst = arg[token] # Merge command's arg set with the current definition @definition = @definition.collapse(cmd_inst) # Insert command positional arguments pos_args.insert(0, *cmd_inst.argument_scope.positional_args) pos_vals << cmd_inst.command_value else self.errors << "'#{token}' is not a valid value for #{arg}; valid values are: #{ arg.commands.keys.join(', ')}" end arg = nil # Commands can't be sensitive else pos_vals << token end else rest_vals << token end tokens[i] = '******' if arg && arg.sensitive? arg = nil end end kw_vals[arg] = nil if arg [pos_vals, kw_vals, rest_vals] end |
#parse(tokens = ARGV) ⇒ False|OpenStruct
After parse has been called, the argument Definition used by the
Parse the specified Array<String> of tokens
, or ARGV if tokens
is nil. If the parse is successful, an OpenStruct object is returned with values for all defined arguments as members of the OpenStruct. If parsing is not succssful, it may be due to parse errors or because a help flag was encountered. The show_usage
or show_help
flags will be set (the former in the case of parse errors, and the latter if help was requested), as well as the errors
property if there were parse errors.
parser may have been replaced if a command argument value was specified. This new definition can be used to show context-specific help or usage details.
an OpenStruct with accessors for every defined argument if the parse was successful. Arguments whose values are not specified will contain the agument default value, or nil if no default is specified.
64 65 66 67 68 69 70 71 72 73 74 75 76 |
# File 'lib/arg-parser/parser.rb', line 64 def parse(tokens = ARGV) @show_usage = nil @show_help = nil @errors = [] begin pos_vals, kw_vals, rest_vals = classify_tokens(tokens) args = process_args(pos_vals, kw_vals, rest_vals) unless @show_help rescue NoSuchArgumentError => ex self.errors << ex. @show_usage = true end (@show_usage || @show_help) ? false : args end |
#process_args(pos_vals, kw_vals, rest_vals) ⇒ Object
Process arguments using the supplied pos_vals
Array of positional argument values, and the kw_vals
Hash of keyword/value.
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 |
# File 'lib/arg-parser/parser.rb', line 184 def process_args(pos_vals, kw_vals, rest_vals) result = {} # Process positional arguments pos_args = @definition.positional_args pos_args.each_with_index do |arg, i| break if i >= pos_vals.length result[arg.key] = process_arg_val(arg, pos_vals[i], result) end if pos_vals.size > pos_args.size if @definition.rest_args? rest_vals = pos_vals[pos_args.size..-1] + rest_vals else self.errors << "#{pos_vals.size} positional #{pos_vals.size == 1 ? 'argument' : 'arguments'} #{ pos_vals.size == 1 ? 'was' : 'were'} supplied, but only #{pos_args.size} #{ pos_args.size == 1 ? 'is' : 'are'} defined" end end # Process key-word based arguments kw_vals.each do |arg, val| result[arg.key] = process_arg_val(arg, val, result) end # Process rest values if rest_vals.size > 0 if rest_arg = @definition.rest_args result[rest_arg.key] = process_arg_val(rest_arg, rest_vals, result) else self.errors << "#{rest_vals.size} rest #{rest_vals.size == 1 ? 'value' : 'values'} #{ rest_vals.size == 1 ? 'was' : 'were'} supplied (#{rest_vals.join(', ') }), but no rest argument is defined" end end # Default unspecified arguments @definition.args.select{ |arg| !result.has_key?(arg.key) }.each do |arg| result[arg.key] = process_arg_val(arg, arg.default, result, true) end # Validate if any set requirements have been satisfied self.errors.concat(@definition.validate_requirements(result)) if self.errors.size > 0 @show_usage = true elsif result.empty? EmptyArgs.new else props = result.keys @definition.args.each{ |arg| props << arg.key unless result.has_key?(arg.key) } args = Struct.new(*props) args.new(*result.values) end end |
#show_help? ⇒ Boolean
Returns Flag set during parsing if the user has requested the help display to be shown (via –help or /?).
24 25 26 |
# File 'lib/arg-parser/parser.rb', line 24 def show_help? @show_help end |
#show_usage? ⇒ Boolean
Returns Flag set during parsing if the usage display should be shown. Set if there are any parse errors encountered.
19 20 21 |
# File 'lib/arg-parser/parser.rb', line 19 def show_usage? @show_usage end |