class Bogo::Cli::Parser
Parser
for CLI arguments
Constants
- UNSET
@return [Symbol] represent unset value
Attributes
@return [Boolean] generate help content
Public Class Methods
Create a new parser
@param name [String, Symbol] name of root command @return [Parser]
# File lib/bogo-cli/parser.rb, line 318 def initialize(name: nil) name = self.class.root_name unless name @root = Command.new(name) end
Parse a command setup block, process arguments and execute command if match found
@param help [Boolean] generate help content @return [Object] result
# File lib/bogo-cli/parser.rb, line 307 def self.parse(help: true, &block) parser = self.new parser.generate_help = !!help parser.load(&block) parser.execute end
Private Class Methods
# File lib/bogo-cli/parser.rb, line 382 def self.root_name File.basename($0) end
Public Instance Methods
Add a new command
@param name [String, Symbol] name of command
# File lib/bogo-cli/parser.rb, line 326 def command(name, &block) @root.command(name, &block) end
Execute command based on CLI arguments
# File lib/bogo-cli/parser.rb, line 358 def execute cmds = @root.generate base_args = arguments line = base_args.join(' ') cmd_key = cmds.keys.find_all { |k| line.start_with?(k) }.sort_by(&:size).last if cmd_key.nil? return cmds[@root.name].parser end base_args = base_args.slice(cmd_key.split(' ').size, base_args.size) a = cmds[cmd_key].parse(base_args) return cmds[cmd_key] unless cmds[cmd_key].callable cmds[cmd_key].callable.call(*a) exit 0 end
Generate all parsers
@return [Hash<String,Hash<Parser,Command>>]
# File lib/bogo-cli/parser.rb, line 353 def generate @root.generate(add_help: generate_help) end
Load a command configuration block
# File lib/bogo-cli/parser.rb, line 346 def load(&block) @root.load(&block) end
Add a new flag
@param short [String, Symbol] short flag @param long [String, Symbol] long flag @param description [String] description of flag @param default [String] default flag value
# File lib/bogo-cli/parser.rb, line 336 def on(short, long, description, **options, &block) @root.on(short, long, description, options, &block) end
Register callable for command
# File lib/bogo-cli/parser.rb, line 341 def run(&block) @root.run(&block) end
Private Instance Methods
@return [Array<String>]
# File lib/bogo-cli/parser.rb, line 378 def arguments [self.class.root_name] + ARGV end