Class: Commander

Inherits:
Object
  • Object
show all
Defined in:
lib/nub/commander.rb

Overview

An implementation of git like command syntax for ruby applications: see github.com/phR0ze/ruby-nub

Defined Under Namespace

Classes: OptionMatch

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app: nil, version: nil, examples: nil) ⇒ Commander

Initialize the commands for your application

Parameters:

  • app (String) (defaults to: nil)

    application name e.g. reduce

  • version (String) (defaults to: nil)

    version of the application e.g. 1.0.0

  • examples (String) (defaults to: nil)

    optional examples to list after the title before usage



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
# File 'lib/nub/commander.rb', line 146

def initialize(app:nil, version:nil, examples:nil)
  @k = OpenStruct.new({
    global: 'global'
  })

  @app = app
  @app_default = Sys.caller_filename
  @version = version
  @examples = examples
  @just = 40

  # Regexps
  @short_regex = /^(-\w).*$/
  @long_regex = /(--[\w\-]+)(=.+)*$/
  @value_regex = /.*=(.*)$/

  # Command line expression results
  # {command_name => {}}
  @cmds = {}

  # Configuration - ordered list of commands
  @config = []

  # Configure default global options
  add_global('-h|--help', 'Print command/options help')
end

Instance Attribute Details

Returns banner string

Returns:

  • (String)

    the app’s banner



225
226
227
# File 'lib/nub/commander.rb', line 225

def banner
  @banner
end

#cmdsObject

Returns the value of attribute cmds.



140
141
142
# File 'lib/nub/commander.rb', line 140

def cmds
  @cmds
end

#configObject (readonly)

Returns the value of attribute config.



138
139
140
# File 'lib/nub/commander.rb', line 138

def config
  @config
end

Instance Method Details

#[](key) ⇒ Object

Hash like accessor for checking if a command or option is set



174
175
176
# File 'lib/nub/commander.rb', line 174

def [](key)
  return @cmds[key] if @cmds[key]
end

#add(cmd, desc, nodes: []) ⇒ Object

Add a command to the command list

Parameters:

  • cmd (String)

    name of the command

  • desc (String)

    description of the command

  • nodes (List) (defaults to: [])

    list of command nodes (i.e. options or commands)



187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/nub/commander.rb', line 187

def add(cmd, desc, nodes:[])
  Log.die("'#{@k.global}' is a reserved command name") if cmd == @k.global
  Log.die("'#{cmd}' already exists") if @config.any?{|x| x.name == cmd}
  Log.die("'help' is a reserved option name") if nodes.any?{|x| x.class == Option && !x.key.nil? && x.key.include?('help')}
  Log.die("command names must be pure lowercase letters or hypen") if cmd =~ /[^a-z-]/

  # Validate sub command key words
  validate_subcmd = ->(subcmd){
    subcmd.nodes = [] if !subcmd.nodes
    Log.die("'#{@k.global}' is a reserved command name") if subcmd.name == @k.global
    Log.die("'help' is a reserved option name") if subcmd.nodes.any?{|x| x.class == Option && !x.key.nil? && x.key.include?('help')}
    Log.die("command names must be pure lowercase letters or hypen") if subcmd.name =~ /[^a-z-]/
    subcmd.nodes.select{|x| x.class != Option}.each{|x| validate_subcmd.(x)}
  }
  nodes.select{|x| x.class != Option}.each{|x| validate_subcmd.(x)}

  @config << add_cmd(cmd, desc, nodes)
end

#add_global(key, desc, type: nil, required: false, allowed: {}) ⇒ Object

Add global options (any option coming before all commands)

Parameters:

  • key (String)

    option short hand, long hand and hint e.g. -s|–skip=COMPONENTS

  • desc (String)

    the option’s description

  • type (Type) (defaults to: nil)

    the option’s type

  • required (Bool) (defaults to: false)

    require the option if true else optional

  • allowed (Hash) (defaults to: {})

    hash of allowed values to description map



212
213
214
215
216
217
218
219
220
221
# File 'lib/nub/commander.rb', line 212

def add_global(key, desc, type:nil, required:false, allowed:{})
  options = [Option.new(key, desc, type:type, required:required, allowed:allowed)]

  # Aggregate global options
  if (global = @config.find{|x| x.name == @k.global})
    global.nodes.each{|x| options << x}
    @config.reject!{|x| x.name == @k.global}
  end
  @config << add_cmd(@k.global, 'Global options:', options)
end

#helpString

Return the app’s help string

Returns:

  • (String)

    the app’s help string



233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# File 'lib/nub/commander.rb', line 233

def help

  # Global help
  help = @app.nil? ? "" : "#{banner}\n"
  if !@examples.nil? && !@examples.empty?
    newline = @examples.strip_color[-1] != "\n" ? "\n" : ""
    help += "Examples:\n#{@examples}\n#{newline}"
  end
  app = @app || @app_default
  help += "Usage: ./#{app} [commands] [options]\n"
  help += @config.find{|x| x.name == @k.global}.help
  help += "COMMANDS:\n"
  @config.select{|x| x.name != @k.global}.each{|x| help += "    #{x.name.ljust(@just)}#{x.desc}\n" }
  help += "\nsee './#{app} COMMAND --help' for specific command help\n"

  return help
end

#key?(key) ⇒ Boolean

Test if the key exists

Returns:

  • (Boolean)


179
180
181
# File 'lib/nub/commander.rb', line 179

def key?(key)
  return @cmds.key?(key)
end

#parse!Object

Construct the command line parser and parse



252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'lib/nub/commander.rb', line 252

def parse!

  # Clear out the previous run every time, in case run more than once
  @cmds = {}

  # Set help if nothing was given
  ARGV.clear and ARGV << '-h' if ARGV.empty?

  # Parse commands recursively
  move_globals_to_front!
  expand_chained_options!
  while (cmd = @config.find{|x| x.name == ARGV.first})
    ARGV.shift && parse_commands(cmd, nil, @config.select{|x| x.name != cmd.name}, ARGV, @cmds)
  end

  # Ensure specials (global) are always set
  @cmds[:global] = {} if !@cmds[:global]

  # Ensure all options were consumed
  Log.die("invalid options #{ARGV}") if ARGV.any?

  # Print banner on success
  puts(banner) if @app
end