Class: SimpleCommander::Runner
Defined Under Namespace
Classes: CommandError, InvalidCommandError, UndefinedHelperError
Instance Attribute Summary collapse
-
#commands ⇒ Object
readonly
Array of commands.
-
#help_formatter_aliases ⇒ Object
readonly
Hash of help formatter aliases.
-
#options ⇒ Object
readonly
Global options.
Class Method Summary collapse
-
.instance ⇒ Object
Return singleton Runner instance.
-
.separate_switches_from_description(*args) ⇒ Object
Return switches and description separated from the args passed.
-
.switch_to_sym(switch) ⇒ Object
Attempts to generate a method name symbol from
switch
.
Instance Method Summary collapse
-
#active_command ⇒ Object
Get active command within arguments passed to this runner.
-
#add_command(command) ⇒ Object
Add a command object to this runner.
-
#alias?(name) ⇒ Boolean
Check if command name is an alias.
-
#alias_command(alias_name, name, *args) ⇒ Object
Alias command name with alias_name.
-
#always_trace! ⇒ Object
Enable tracing on all executions (bypasses –trace).
-
#args_without_command_name ⇒ Object
Return arguments without the command name.
-
#command(name, &block) ⇒ Object
Creates and yields a command instance when a block is passed.
-
#command_exists?(name) ⇒ Boolean
Check if a command name exists.
-
#command_name_from_args ⇒ Object
Attempts to locate a command name from within the arguments.
-
#create_default_commands ⇒ Object
Creates default commands such as ‘help’ which is essentially the same as using the –help switch.
-
#default_command(name) ⇒ Object
Default command name to be used when no other command is found in the arguments.
-
#expand_optionally_negative_switches(switches) ⇒ Object
expand switches of the style ‘–[no-]blah’ into both their ‘–blah’ and ‘–no-blah’ variants, so that they can be properly detected and removed.
-
#global_option(*args, &block) ⇒ Object
Add a global option; follows the same syntax as Command#option This would be used for switches such as –version, –trace, etc.
-
#global_option_proc(switches, &block) ⇒ Object
Returns a proc allowing for commands to inherit global options.
-
#goto_child_command ⇒ Object
make the child command the active_command and remove the current command from the @args.
-
#have_action? ⇒ Boolean
tests if the current active command have an action block.
-
#help_formatter ⇒ Object
Help formatter instance.
-
#help_formatter_alias_defaults ⇒ Object
Returns hash of help formatter alias defaults.
-
#helper_exist?(helper) ⇒ Boolean
check if the helper exist.
-
#helpers(*args) ⇒ Object
search in the helpers folders for the helpers module and include in the runner.
-
#initialize(args = ARGV) ⇒ Runner
constructor
Initialize a new command runner.
-
#never_trace! ⇒ Object
Hide the trace option from the help menus and don’t add it as a global option.
-
#parse_global_options ⇒ Object
Parse global command options.
-
#program(key, *args, &block) ⇒ Object
Assign program information.
-
#program_defaults ⇒ Object
Returns hash of program defaults.
-
#remove_global_options(options, args) ⇒ Object
Removes global options from args.
-
#require_program(*keys) ⇒ Object
Raises a CommandError when the program any of the keys are not present, or empty.
-
#require_valid_command(command = active_command) ⇒ Object
Raises InvalidCommandError when a command is not found.
-
#run! ⇒ Object
Run command parsing and execution process.
-
#run_active_command ⇒ Object
Run the active command.
-
#say(*args) ⇒ Object
:nodoc:.
-
#valid_command_names_from(*args) ⇒ Object
Returns array of valid command names found within args.
-
#version ⇒ Object
Return program version.
Constructor Details
#initialize(args = ARGV) ⇒ Runner
Initialize a new command runner. Optionally supplying args for mocking, or arbitrary usage.
32 33 34 35 36 37 38 39 |
# File 'lib/simple_commander/runner.rb', line 32 def initialize(args = ARGV) @args, @commands, @aliases, @options = args, {}, {}, [] @help_formatter_aliases = help_formatter_alias_defaults @program = program_defaults @always_trace = false @never_trace = false create_default_commands end |
Instance Attribute Details
#commands ⇒ Object (readonly)
Array of commands.
16 17 18 |
# File 'lib/simple_commander/runner.rb', line 16 def commands @commands end |
#help_formatter_aliases ⇒ Object (readonly)
Hash of help formatter aliases.
26 27 28 |
# File 'lib/simple_commander/runner.rb', line 26 def help_formatter_aliases @help_formatter_aliases end |
#options ⇒ Object (readonly)
Global options.
21 22 23 |
# File 'lib/simple_commander/runner.rb', line 21 def @options end |
Class Method Details
.instance ⇒ Object
Return singleton Runner instance.
66 67 68 |
# File 'lib/simple_commander/runner.rb', line 66 def self.instance @singleton ||= new end |
.separate_switches_from_description(*args) ⇒ Object
Return switches and description separated from the args passed.
461 462 463 464 465 |
# File 'lib/simple_commander/runner.rb', line 461 def self.separate_switches_from_description(*args) switches = args.find_all { |arg| arg.to_s =~ /^-/ } description = args.last if args.last.is_a?(String) && !args.last.match(/^-/) [switches, description] end |
.switch_to_sym(switch) ⇒ Object
Attempts to generate a method name symbol from switch
. For example:
-h # => :h
--trace # => :trace
--some-switch # => :some_switch
--[no-]feature # => :feature
--file FILE # => :file
--list of,things # => :list
479 480 481 |
# File 'lib/simple_commander/runner.rb', line 479 def self.switch_to_sym(switch) switch.scan(/[\-\]](\w+)/).join('_').to_sym rescue nil end |
Instance Method Details
#active_command ⇒ Object
Get active command within arguments passed to this runner.
279 280 281 |
# File 'lib/simple_commander/runner.rb', line 279 def active_command @__active_command ||= command(command_name_from_args) end |
#add_command(command) ⇒ Object
Add a command object to this runner.
256 257 258 |
# File 'lib/simple_commander/runner.rb', line 256 def add_command(command) @commands[command.name] = command end |
#alias?(name) ⇒ Boolean
Check if command name is an alias.
263 264 265 |
# File 'lib/simple_commander/runner.rb', line 263 def alias?(name) @aliases.include? name.to_s end |
#alias_command(alias_name, name, *args) ⇒ Object
Alias command name with alias_name. Optionally args may be passed as if they were being passed straight to the original command via the command-line.
240 241 242 243 |
# File 'lib/simple_commander/runner.rb', line 240 def alias_command(alias_name, name, *args) @commands[alias_name.to_s] = command name @aliases[alias_name.to_s] = args end |
#always_trace! ⇒ Object
Enable tracing on all executions (bypasses –trace)
142 143 144 145 |
# File 'lib/simple_commander/runner.rb', line 142 def always_trace! @always_trace = true @never_trace = false end |
#args_without_command_name ⇒ Object
Return arguments without the command name.
309 310 311 312 313 314 315 |
# File 'lib/simple_commander/runner.rb', line 309 def args_without_command_name removed = [] parts = command_name_from_args.split rescue [] @args.dup.delete_if do |arg| removed << arg if parts.include?(arg) && !removed.include?(arg) end end |
#command(name, &block) ⇒ Object
Creates and yields a command instance when a block is passed. Otherwise attempts to return the command, raising InvalidCommandError when it does not exist.
Examples
command :my_command do |c|
c.when_called do |args|
# Code
end
end
213 214 215 216 217 218 219 220 |
# File 'lib/simple_commander/runner.rb', line 213 def command(name, &block) SimpleCommander::Command.new(name).tap do |cmd| add_command(cmd) if block cmd.super_self = self cmd.instance_eval &block if block end @commands[name.to_s] end |
#command_exists?(name) ⇒ Boolean
Check if a command name exists.
270 271 272 |
# File 'lib/simple_commander/runner.rb', line 270 def command_exists?(name) @commands[name.to_s] end |
#command_name_from_args ⇒ Object
Attempts to locate a command name from within the arguments. Supports multi-word commands, using the largest possible match.
287 288 289 |
# File 'lib/simple_commander/runner.rb', line 287 def command_name_from_args @__command_name_from_args ||= (valid_command_names_from(*@args.dup).sort.last || @default_command) end |
#create_default_commands ⇒ Object
Creates default commands such as ‘help’ which is essentially the same as using the –help switch.
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 |
# File 'lib/simple_commander/runner.rb', line 340 def create_default_commands command :help do syntax 'commander help [command]' description 'Display global or [command] help documentation' example 'Display global help', 'command help' example "Display help for 'foo'", 'command help foo' when_called do |args, | UI.enable_paging if args.empty? say help_formatter.render else command = command args.join(' ') begin require_valid_command command rescue InvalidCommandError => e abort "#{e}. Use --help for more information" end say help_formatter.render_command(command) end end end end |
#default_command(name) ⇒ Object
Default command name to be used when no other command is found in the arguments.
249 250 251 |
# File 'lib/simple_commander/runner.rb', line 249 def default_command(name) @default_command = name end |
#expand_optionally_negative_switches(switches) ⇒ Object
expand switches of the style ‘–[no-]blah’ into both their ‘–blah’ and ‘–no-blah’ variants, so that they can be properly detected and removed
405 406 407 408 409 410 411 412 413 414 |
# File 'lib/simple_commander/runner.rb', line 405 def (switches) switches.reduce([]) do |memo, val| if val =~ /\[no-\]/ memo << val.gsub(/\[no-\]/, '') memo << val.gsub(/\[no-\]/, 'no-') else memo << val end end end |
#global_option(*args, &block) ⇒ Object
Add a global option; follows the same syntax as Command#option This would be used for switches such as –version, –trace, etc.
226 227 228 229 230 231 232 233 234 |
# File 'lib/simple_commander/runner.rb', line 226 def global_option(*args, &block) switches, description = Runner.separate_switches_from_description(*args) @options << { args: args, proc: block, switches: switches, description: description, } end |
#global_option_proc(switches, &block) ⇒ Object
Returns a proc allowing for commands to inherit global options. This functionality works whether a block is present for the global option or not, so simple switches such as –verbose can be used without a block, and used throughout all commands.
440 441 442 443 444 445 446 447 |
# File 'lib/simple_commander/runner.rb', line 440 def global_option_proc(switches, &block) lambda do |value| unless active_command.nil? active_command. << [Runner.switch_to_sym(switches.last), value] end yield value if block && !value.nil? end end |
#goto_child_command ⇒ Object
make the child command the active_command and remove the current command from the @args
125 126 127 128 129 130 |
# File 'lib/simple_commander/runner.rb', line 125 def goto_child_command @args.shift @__active_command = nil @__command_name_from_args = nil have_action? end |
#have_action? ⇒ Boolean
tests if the current active command have an action block
116 117 118 119 |
# File 'lib/simple_commander/runner.rb', line 116 def have_action? require_valid_command goto_child_command if active_command.has_no_action? end |
#help_formatter ⇒ Object
Help formatter instance.
302 303 304 |
# File 'lib/simple_commander/runner.rb', line 302 def help_formatter @__help_formatter ||= program(:help_formatter).new self end |
#help_formatter_alias_defaults ⇒ Object
Returns hash of help formatter alias defaults.
320 321 322 323 324 |
# File 'lib/simple_commander/runner.rb', line 320 def help_formatter_alias_defaults { compact: HelpFormatter::TerminalCompact, } end |
#helper_exist?(helper) ⇒ Boolean
check if the helper exist
58 59 60 61 |
# File 'lib/simple_commander/runner.rb', line 58 def helper_exist?(helper) Object.const_defined?(helper) && Object.const_get(helper).instance_of?(::Module) end |
#helpers(*args) ⇒ Object
search in the helpers folders for the helpers module and include in the runner
45 46 47 48 49 50 51 52 53 |
# File 'lib/simple_commander/runner.rb', line 45 def helpers(*args) args.each do |h| helper_name = "#{h}_helper" fail UndefinedHelperError, "Invalid helper #{helper_name}", caller if !helper_exist? helper_name SimpleCommander::Runner.send(:include, Object.const_get(helper_name)) end end |
#never_trace! ⇒ Object
Hide the trace option from the help menus and don’t add it as a global option
150 151 152 153 |
# File 'lib/simple_commander/runner.rb', line 150 def never_trace! @never_trace = true @always_trace = false end |
#parse_global_options ⇒ Object
Parse global command options.
419 420 421 422 423 424 425 426 427 428 429 430 431 432 |
# File 'lib/simple_commander/runner.rb', line 419 def parser = .inject(OptionParser.new) do |, option| .on(*option[:args], &global_option_proc(option[:switches], &option[:proc])) end = @args.dup begin parser.parse!() rescue OptionParser::InvalidOption => e # Remove the offending args and retry. = .reject { |o| e.args.include?(o) } retry end end |
#program(key, *args, &block) ⇒ Object
Assign program information.
Examples
# Set data
program :name, 'Commander'
program :version, Commander::VERSION
program :description, 'Commander utility program.'
program :help, 'Copyright', '2008 TJ Holowaychuk'
program :help, 'Anything', 'You want'
program :int_message 'Bye bye!'
program :help_formatter, :compact
program :help_formatter, Commander::HelpFormatter::TerminalCompact
# Get data
program :name # => 'Commander'
Keys
:version (required) Program version triple, ex: '0.0.1'
:description (required) Program description
:name Program name, defaults to basename of executable
:help_formatter Defaults to Commander::HelpFormatter::Terminal
:help Allows addition of arbitrary global help blocks
:int_message Message to display when interrupted (CTRL + C)
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 |
# File 'lib/simple_commander/runner.rb', line 183 def program(key, *args, &block) if key == :help && !args.empty? @program[:help] ||= {} @program[:help][args.first] = args.at(1) elsif key == :help_formatter && !args.empty? @program[key] = (@help_formatter_aliases[args.first] || args.first) elsif block @program[key] = block else unless args.empty? @program[key] = (args.count == 1 && args[0]) || args end @program[key] end end |
#program_defaults ⇒ Object
Returns hash of program defaults.
329 330 331 332 333 334 |
# File 'lib/simple_commander/runner.rb', line 329 def program_defaults { help_formatter: HelpFormatter::Terminal, name: File.basename($PROGRAM_NAME), } end |
#remove_global_options(options, args) ⇒ Object
Removes global options from args. This prevents an invalid option error from occurring when options are parsed again for the command.
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 |
# File 'lib/simple_commander/runner.rb', line 375 def (, args) # TODO: refactor with flipflop, please TJ ! have time to refactor me ! .each do |option| switches = option[:switches].dup next if switches.empty? if (switch_has_arg = switches.any? { |s| s =~ /[ =]/ }) switches.map! { |s| s[0, s.index('=') || s.index(' ') || s.length] } end switches = (switches) past_switch, arg_removed = false, false args.delete_if do |arg| if switches.any? { |s| s[0, arg.length] == arg } arg_removed = !switch_has_arg past_switch = true elsif past_switch && !arg_removed && arg !~ /^-/ arg_removed = true else arg_removed = true false end end end end |
#require_program(*keys) ⇒ Object
Raises a CommandError when the program any of the keys are not present, or empty.
452 453 454 455 456 |
# File 'lib/simple_commander/runner.rb', line 452 def require_program(*keys) keys.each do |key| fail CommandError, "program #{key} required" if program(key).nil? || program(key).empty? end end |
#require_valid_command(command = active_command) ⇒ Object
Raises InvalidCommandError when a command is not found.
366 367 368 |
# File 'lib/simple_commander/runner.rb', line 366 def require_valid_command(command = active_command) fail InvalidCommandError, 'invalid command', caller if command.nil? end |
#run! ⇒ Object
Run command parsing and execution process.
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 106 107 108 109 110 111 |
# File 'lib/simple_commander/runner.rb', line 73 def run! trace = @always_trace || false require_program :version, :description trap('INT') { abort program(:int_message) } if program(:int_message) trap('INT') { program(:int_block).call } if program(:int_block) global_option('-h', '--help', 'Display help documentation') do args = @args - %w(-h --help) command(:help).run(*args) return end global_option('-v', '--version', 'Display version information') do say version return end global_option('-t', '--trace', 'Display backtrace when an error occurs') { trace = true } unless @never_trace || @always_trace , @args if trace run_active_command else begin have_action? run_active_command rescue InvalidCommandError => e abort "#{e}. Use --help for more information" rescue \ OptionParser::InvalidOption, OptionParser::InvalidArgument, OptionParser::MissingArgument => e abort e.to_s rescue => e if @never_trace abort "error: #{e}." else abort "error: #{e}. Use --trace to view backtrace" end end end end |
#run_active_command ⇒ Object
Run the active command.
486 487 488 489 490 491 492 493 |
# File 'lib/simple_commander/runner.rb', line 486 def run_active_command require_valid_command if alias? command_name_from_args active_command.run(*(@aliases[command_name_from_args.to_s] + args_without_command_name)) else active_command.run(*args_without_command_name) end end |
#say(*args) ⇒ Object
:nodoc:
495 496 497 |
# File 'lib/simple_commander/runner.rb', line 495 def say(*args) #:nodoc: $terminal.say(*args) end |
#valid_command_names_from(*args) ⇒ Object
Returns array of valid command names found within args.
294 295 296 297 |
# File 'lib/simple_commander/runner.rb', line 294 def valid_command_names_from(*args) arg_string = args.delete_if { |value| value =~ /^-/ }.join ' ' commands.keys.find_all { |name| name if /^#{name}\b/.match arg_string } end |
#version ⇒ Object
Return program version.
135 136 137 |
# File 'lib/simple_commander/runner.rb', line 135 def version format('%s %s', program(:name), program(:version)) end |