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: Command, 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



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/nub/commander.rb', line 98

def initialize(app:nil, version:nil, examples:nil)
  @app = app
  @app_default = Sys.caller_filename
  @version = version
  @examples = examples
  @just = 40

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

  # Incoming user set commands/options
  # {command_name => {}}
  @cmds = {}

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

  # List of options that will be added to all commands
  @shared = []

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

Instance Attribute Details

Returns banner string

Returns:

  • (String)

    the app’s banner



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

def banner
  @banner
end

#cmdsObject

Returns the value of attribute cmds.



90
91
92
# File 'lib/nub/commander.rb', line 90

def cmds
  @cmds
end

#configObject (readonly)

Returns the value of attribute config.



88
89
90
# File 'lib/nub/commander.rb', line 88

def config
  @config
end

Instance Method Details

#[](key) ⇒ Object

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



125
126
127
# File 'lib/nub/commander.rb', line 125

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

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

Add a command to the command list

Parameters:

  • cmd (String)

    name of the command

  • desc (String)

    description of the command

  • opts (List)

    list of command options



138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/nub/commander.rb', line 138

def add(cmd, desc, options:[])
  Log.die("'global' is a reserved command name") if cmd == 'global'
  Log.die("'shared' is a reserved command name") if cmd == 'shared'
  Log.die("'#{cmd}' already exists") if @config.any?{|x| x.name == cmd}
  Log.die("'help' is a reserved option name") if options.any?{|x| !x.key.nil? && x.key.include?('help')}

  # Add shared options
  @shared.each{|x| options.unshift(x)}

  cmd = add_cmd(cmd, desc, options)
  @config << cmd
end

#add_global(options) ⇒ Object

Add global options (any option coming before all commands)

Parameters:

  • option/s (Array/Option)

    array or single option/s



153
154
155
156
157
158
159
160
161
162
# File 'lib/nub/commander.rb', line 153

def add_global(options)
  options = [options] if options.class == Option

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

#add_shared(options) ⇒ Object

Add shared option (options that are added to all commands)

Parameters:

  • option/s (Array/Option)

    array or single option/s



166
167
168
169
170
171
172
173
174
175
# File 'lib/nub/commander.rb', line 166

def add_shared(options)
  options = [options] if options.class == Option
  options.each{|x|
    Log.die("duplicate shared option '#{x.desc}' given") if @shared
      .any?{|y| y.key == x.key && y.desc == x.desc && y.type == x.type}
    x.shared = true
    x.required = true
    @shared << x
  }
end

#helpString

Return the app’s help string

Returns:

  • (String)

    the app’s help string



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

def 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 == 'global'}.help
  help += "COMMANDS:\n"
  @config.select{|x| x.name != '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)


130
131
132
# File 'lib/nub/commander.rb', line 130

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

#parse!Object

Construct the command line parser and parse



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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
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
296
297
298
299
# File 'lib/nub/commander.rb', line 204

def parse!
  cmd_names = @config.map{|x| x.name }

  # Set help if nothing was given
  ARGV.clear and ARGV << '-h' if ARGV.empty?
  
  # Process command options
  #---------------------------------------------------------------------------
  order_globals!
  expand_chained_options!
  loop {
    break if ARGV.first.nil?

    if !(cmd = @config.find{|x| x.name == ARGV.first}).nil?
      @cmds[ARGV.shift.to_sym] = {}             # Create command results entry
      cmd_names.reject!{|x| x == cmd.name}      # Remove command from possible commands

      # Collect command options from args to compare against
      opts = ARGV.take_while{|x| !cmd_names.include?(x) }
      ARGV.shift(opts.size)
 
      # Handle help upfront before anything else
      if opts.any?{|x| m = match_named(x, cmd); m.hit? && m.sym == :help }
        !puts(help) and exit if cmd.name == 'global'
        !puts(cmd.help) and exit
      end

      # Check that all required options were given
      cmd_pos_opts = cmd.opts.select{|x| x.key.nil? }
      cmd_named_opts = cmd.opts.select{|x| !x.key.nil? }

      !puts("Error: positional option required!".colorize(:red)) && !puts(cmd.help) and
        exit if opts.select{|x| !x.start_with?('-')}.size < cmd_pos_opts.select{|x| x.required}.size

      named_opts = opts.select{|x| x.start_with?('-')}
      cmd_named_opts.select{|x| x.required}.each{|x|
        !puts("Error: required option #{x.key} not given!".colorize(:red)) && !puts(cmd.help) and
          exit if !named_opts.find{|y| y.start_with?(x.short) || y.start_with?(x.long)}
      }

      # Process command options
      pos = -1
      loop {
        break if opts.first.nil?
        opt = opts.shift
        cmd_opt = nil
        value = nil
        sym = nil

        # Validate/set named options
        # --------------------------------------------------------------------
        # e.g. -s, --skip, --skip=VALUE
        if (match = match_named(opt, cmd)).hit?
          sym = match.sym
          cmd_opt = match.opt
          value = match.value
          value = match.flag? || opts.shift if !value

        # Validate/set positional options
        # --------------------------------------------------------------------
        else
          pos += 1
          value = opt
          cmd_opt = cmd_pos_opts.shift
          !puts("Error: invalid positional option '#{opt}'!".colorize(:red)) && !puts(cmd.help) and
            exit if cmd_opt.nil? || cmd_names.include?(value)
          sym = "#{cmd.name}#{pos}".to_sym
        end

        # Convert value to appropriate type and validate against allowed
        # --------------------------------------------------------------------
        value = convert_value(value, cmd, cmd_opt)

        # Set option with value
        # --------------------------------------------------------------------
        !puts("Error: unknown named option '#{opt}' given!".colorize(:red)) && !puts(cmd.help) and exit if !sym
        @cmds[cmd.name.to_sym][sym] = value
        if cmd_opt.shared
          sym = "shared#{pos}".to_sym if cmd_opt.key.nil?
          @cmds[:shared] = {} if !@cmds.key?(:shared)
          @cmds[:shared][sym] = value
        end
      }
    end
  }

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

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

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