Class: Cowtech::Lib::OptionParser
- Defined in:
- lib/cowtech-lib/option_parser.rb
Overview
A class which parse commandline options.
Instance Attribute Summary collapse
-
#args ⇒ Object
readonly
The other (non-option) provided args.
-
#cmdline ⇒ Object
readonly
The full command line provided.
-
#messages ⇒ Object
readonly
The messages for the help message.
-
#options ⇒ Object
The specified options.
Instance Method Summary collapse
-
#<<(options) ⇒ Object
Add or replace an option to the parser.
-
#[](*options) ⇒ Object
Get a list of value for the requested options.
-
#exists?(name) ⇒ Boolean
Check if an option is defined.
-
#fetch ⇒ Object
Returns option and non option provided arguments.
-
#get(name, default = nil) ⇒ Object
Get a list of value for the requested options.
-
#initialize(args) ⇒ OptionParser
constructor
Creates a new OptionParser.
-
#parse(args = nil) ⇒ Object
Parse the command line.
-
#print_help ⇒ Object
Prints the help message.
-
#provided?(name) ⇒ Boolean
Check if the user provided the option.
Constructor Details
#initialize(args) ⇒ OptionParser
Creates a new OptionParser.
Arguments:
-
name: Application name
-
version: Application version
-
name: Application description
-
name: Application usage
-
messages: Application message for help switch. Supported keys are
-
:pre_usage: Message to print before the usage string
-
:pre_options: Message to print before the options list
-
:post_options: Message to print after the options list
-
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 |
# File 'lib/cowtech-lib/option_parser.rb', line 308 def initialize(args) # Initialize types @@valid_types = {bool: [], string: [String, ""], int: [Integer, 0], float: [Float, 0.0], choice: [String, ""], list: [Array, []], action: []} # Copy arguments @app_name = args[:name] @app_version = args[:version] @description = args[:description] @usage = args[:usage] # Copy messages = args[:messages] || {} if .is_a?(Hash) then @messages = else @console.fatal(msg: "CowtechLib::OptionParser::initialize msgs argument must be an hash.") end # Initialize variables @console = Console.new @inserted = {name: [], short: [], long: []} @options = {} @options_map = {} @args = [] @cmdline = ARGV.clone self << {name: "help", short: "-h", long: "--help", type: :bool, help: "Show this message.", priority: 1000} end |
Instance Attribute Details
#args ⇒ Object (readonly)
The other (non-option) provided args
24 25 26 |
# File 'lib/cowtech-lib/option_parser.rb', line 24 def args @args end |
#cmdline ⇒ Object (readonly)
The full command line provided
18 19 20 |
# File 'lib/cowtech-lib/option_parser.rb', line 18 def cmdline @cmdline end |
#messages ⇒ Object (readonly)
The messages for the help message
21 22 23 |
# File 'lib/cowtech-lib/option_parser.rb', line 21 def @messages end |
#options ⇒ Object
The specified options
15 16 17 |
# File 'lib/cowtech-lib/option_parser.rb', line 15 def @options end |
Instance Method Details
#<<(options) ⇒ Object
Add or replace an option to the parser. Every argument is optional (in the form ATTR => VALUE) with the exception of :name, :short and :long.
Arguments:
-
:name: Option name
-
:short: Option short form, can begin with “-”
-
:long: Option long form, can begin with “–”
-
:type: Option type, valid values are:
-
:bool: Boolean option
-
:string: Option with string argument
-
:int: Option with int argument
-
:float: Option with float argument
-
:choice: Option with string argument that must be valitated from a list of patterns
-
:list: Option with a list of string argument
-
:action: Option with an associated action
-
:help: Option description
-
:choices: Option valid choice (list of regexp), only used with the :choice type
-
:action: Option action block, only used with the :action type
-
:meta: Option meta variable for description
-
:default: Option default value
-
:required: Whether the option is required
-
:priority: Priority for the option. Used only on the help message to sort (by increasing priority) the options.
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
# File 'lib/cowtech-lib/option_parser.rb', line 47 def <<() = [] if !.is_a?(Array) .each do |option| @console.fatal(msg: "Every attribute must be an Hash.", dots: false) if !option.is_a?(Hash) # Use symbols for names option[:name] = option[:name].to_sym # Add the default type, which is :string option[:type] ||= :string # Check if type is valid @console.fatal(msg: "Invalid option type #{option[:type]} for option #{option[:name]}. Valid type are the following:\n\t#{@@valid_types.keys.join(", ")}.", dots: false) if !@@valid_types.keys.include?(option[:type]) # Adjust the default value case option[:type] when :bool then option[:default] = false if !option.has_key?(:default) when :action then option[:required] = false else option[:default] = @@valid_types[option[:type]][1] if !option.has_key?(:default) || !option[:default].is_a?(@@valid_types[option[:type]][0]) end # Adjust priority option[:priority] = option[:priority].to_s.to_i if !option[:priority].is_a?(Integer) # Prepend dashes option[:short] = "-" + option[:short] if !option[:short] =~ /^-/ while option[:long] !~ /^--/ do option[:long] = "-" + option[:long] end @console.fatal(msg: "Invalid short form \"#{option[:short]}\".", dots: false) if option[:short] !~ /^-[0-9a-z]$/i @console.fatal(msg: "Invalid long form \"#{option[:long]}\".", dots: false) if option[:long] !~ /^--([0-9a-z-]+)$/i # Check for choices if the type is choices if option[:type] == :choice then if option[:choices] == nil then @console.fatal(msg: "Option \"#{option[:name]}\" of type choice requires a valid choices list (every element should be a regular expression).") else option[:choices].collect! { |choice| Regexp.new(choice) } end end # Check that action is a block if the type is action @console.fatal("Option \"#{option[:name]}\" of type action requires a action block.") if option[:type] == :action && (option[:action] == nil || !option[:action].is_a?(Proc.class)) # Check for uniqueness of option and its forms @console.fatal("An option with name \"#{option[:name]}\" already exists.", dots: false) if @inserted[:name].include?(option[:name]) @console.fatal("An option with short or long form \"#{option[:short]}\" already exists.", dots: false) if @inserted[:short].include?(option[:short]) @console.fatal("An option with short or long form \"#{option[:long]}\" already exists.", dots: false) if @inserted[:long].include?(option[:long]) # Save @options[option[:name]] = option @options_map[option[:long]] = option[:name] @inserted[:name].push(option[:name]) @inserted[:short].push(option[:short]) @inserted[:long].push(option[:long]) end end |
#[](*options) ⇒ Object
Get a list of value for the requested options. Arguments:
-
options: Options list
Returns: If a single argument is provided, only a value is returned, else an hash (name => value). If no argument is provided, return every option
232 233 234 235 236 237 238 239 240 241 242 243 244 245 |
# File 'lib/cowtech-lib/option_parser.rb', line 232 def [](*) = [] if !.is_a?(Array) = @options.keys if .length == 0 if .length == 1 then self.get([0]) else rv = {} .each do |option| rv[option.to_s] = self.get(option) if self.exists?(option) end rv end end |
#exists?(name) ⇒ Boolean
Check if an option is defined. Arguments:
-
name: Option name
Returns: true if options is defined, false otherwise.
197 198 199 200 |
# File 'lib/cowtech-lib/option_parser.rb', line 197 def exists?(name) name = name.to_sym @options.keys.include?(name) end |
#fetch ⇒ Object
Returns option and non option provided arguments.
248 249 250 |
# File 'lib/cowtech-lib/option_parser.rb', line 248 def fetch [self.[], @args] end |
#get(name, default = nil) ⇒ Object
Get a list of value for the requested options. Arguments:
-
name: Options name
-
name: Default value if option was not provided.
Returns: The option value
216 217 218 219 220 221 222 223 224 225 226 |
# File 'lib/cowtech-lib/option_parser.rb', line 216 def get(name, default = nil) name = name.to_sym if @options[name][:value] != nil then @options[name][:value] elsif default != nil then default else @options[name][:default] end end |
#parse(args = nil) ⇒ Object
Parse the command line.
Arguments:
-
ignore_unknown: Whether ignore unknown options
-
ignore_unknown: Whether ignore help options
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 180 181 182 183 184 185 186 187 188 189 190 191 |
# File 'lib/cowtech-lib/option_parser.rb', line 112 def parse(args = nil) args ||= {} # Create options noat = [:bool, :action] sopts = @options.each_value.collect { |option| [option[:long], option[:short], noat.include?(option[:type]) ? GetoptLong::NO_ARGUMENT : GetoptLong::REQUIRED_ARGUMENT] } opts = GetoptLong.new(*sopts) opts.quiet = true # Parse option begin opts.each do |given, arg| optname = @options_map[given] option = @options[optname] value = nil # VALIDATE ARGUMENT DUE TO CASE case option[:type] when :string then value = arg when :int then if arg.strip =~ /^(-?)(\d+)$/ then value = arg.to_i(10) else @console.fatal(msg: "Argument of option \"#{given}\" must be an integer.", dots: false) end when :float then if arg.strip =~ /^(-?)(\d*)(\.(\d+))?$/ && arg.strip() != "." then value = arg.to_f else @console.fatal(msg: "Argument of option \"#{given}\" must be a float.", dots: false) end when :choice then if @options[optname].choices.find_index { |choice| arg =~ choice } then value = arg else @console.fatal(msg: "Invalid argument (invalid choice) for option \"#{given}\".", dots: false) end when :list then value = arg.split(",") else value = true end @options[optname][:value] = value end rescue StandardError => exception if exception. =~ /.+-- (.+)$/ then given = $1 if exception.is_a?(GetoptLong::InvalidOption) then @console.fatal(msg: "Unknown option \"#{given}\".", dots: false) if !args[:ignore_unknown] elsif exception.is_a?(GetoptLong::MissingArgument) then @console.fatal(msg: "Option \"-#{given}\" requires an argument.", dots: false) end else @console.fatal("Unexpected error: #{exc.}.") end end # SET OTHER ARGUMENTS @args = ARGV # CHECK IF HELP WAS REQUESTED if self.provided?("help") && !args[:ignore_help] then self.print_help exit(0) end # NOW CHECK IF SOME REQUIRED OPTION WAS NOT SPECIFIED OR IF WE HAVE TO EXECUTE AN ACTION @inserted[:name].each do |key| option = @options[key] if option[:required] == true && option[:value] == nil then @console.fatal(msg: "Required option \"#{option[:name]}\" not specified.", dots: false) elsif option[:value] == true && option[:type] == :action then option.action.call end end end |
#print_help ⇒ Object
Prints the help message.
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 |
# File 'lib/cowtech-lib/option_parser.rb', line 253 def print_help # Print app name if @app_name then print "#{@app_name}" print " #{@app_version}" if @app_version > 0 print " - #{@description}" if @description print "\n" end # Print usage print "#{@messages["pre_usage"]}\n" if @messages["pre_usage"] print "#{@usage ? @usage : "Usage: #{ARGV[0]} [OPTIONS]"}\n" # Print pre_options print "#{@messages["pre_options"]}\n" if @messages["pre_options"] print "\nValid options are:\n" # Order options for printing @sorted_opts = @inserted[:name].sort do |first, second| @options[first][:priority] != @options[second][:priority] ? @options[first][:priority] <=> @options[second][:priority] : @inserted[:name].index(first) <=> @inserted[:name].index(second) end # Add options, saving max length popts = {} maxlen = -1 @sorted_opts.each do |key| opt = @options[key] popt = "#{[opt[:short], opt[:long]].join(", ")}" popt += ("=" + (opt[:meta] ? opt[:meta] : "ARG")) if ![:bool, :action].include?(opt[:type]) popts[key] = popt maxlen = popt.length if popt.length > maxlen end # Print options @sorted_opts.each do |key| val = popts[key] print "\t#{val}#{" " * (5 + (maxlen - val.length))}#{@options[key][:help]}\n" end # Print post_options print "#{@messages["post_options"]}\n" if @messages["post_options"] end |
#provided?(name) ⇒ Boolean
Check if the user provided the option. Arguments:
-
name: Option name
Returns: true if options was provided, false otherwise.
206 207 208 209 |
# File 'lib/cowtech-lib/option_parser.rb', line 206 def provided?(name) name = name.to_sym (@options[name] || {})[:value] != nil end |