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

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



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/nub/commander.rb', line 99

def initialize(app:nil, version:nil, examples:nil)
  @app = app
  @app_default = Sys.caller_filename
  @version = version
  @examples = examples
  @help_opt = Option.new('-h|--help', 'Print command/options help')
  @just = 40

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

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

Instance Attribute Details

Returns banner string



153
154
155
# File 'lib/nub/commander.rb', line 153

def banner
  @banner
end

#cmdsObject

Returns the value of attribute cmds.



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

def cmds
  @cmds
end

#configObject (readonly)

Returns the value of attribute config.



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

def config
  @config
end

Instance Method Details

#[](key) ⇒ Object

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



116
117
118
# File 'lib/nub/commander.rb', line 116

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



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

def add(cmd, desc, options:[])
  !puts("Error: command names must be pure lowercase letters".colorize(:red)) and
    exit if cmd =~ /[^a-z]/

  # Build help for command
  app = @app || @app_default
  help = "#{desc}\n\nUsage: ./#{app} #{cmd} [options]\n"
  help = "#{banner}\n#{help}" if @app
  options << @help_opt

  # Add positional options first
  sorted_options = options.select{|x| x.key.nil?}
  sorted_options += options.select{|x| !x.key.nil?}.sort{|x,y| x.key <=> y.key}
  positional_index = -1
  sorted_options.each{|x| 
    required = x.required ? ", Required" : ""
    allowed = x.allowed.empty? ? "" : " (#{x.allowed * ','})"
    positional_index += 1 if x.key.nil?
    key = x.key.nil? ? "#{cmd}#{positional_index}" : x.key
    type = x.type == FalseClass ? "Flag" : x.type
    help += "    #{key.ljust(@just)}#{x.desc}#{allowed}: #{type}#{required}\n"
  }

  # Create the command in the command config
  @config << Command.new(cmd, desc, sorted_options, help)
end

#helpObject

Return the app’s help string



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

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 += "    #{'-h|--help'.ljust(@just)}Print command/options help: Flag\n"
  help += "COMMANDS:\n"
  @config.each{|x| help += "    #{x.name.ljust(@just)}#{x.desc}\n" }
  help += "\nsee './#{app} COMMAND --help' for specific command help\n"

  return help
end

#parse!Object

Construct the command line parser and parse



178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# File 'lib/nub/commander.rb', line 178

def parse!

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

  # Process global options
  #---------------------------------------------------------------------------
  cmd_names = @config.map{|x| x.name }
  globals = ARGV.take_while{|x| !cmd_names.include?(x)}
  !puts(help) and exit if globals.any?
  
  # Process command options
  #---------------------------------------------------------------------------
  loop {
    break if ARGV.first.nil?

    if !(cmd = @config.find{|x| x.name == ARGV.first}).nil?
      @cmds[ARGV.shift.to_sym] = {}
      cmd_names.reject!{|x| x == cmd.name}

      # Command options as defined in configuration
      cmd_pos_opts = cmd.opts.select{|x| x.key.nil? }
      cmd_named_opts = cmd.opts.select{|x| !x.key.nil? }

      # Collect command options from args to compare against
      opts = ARGV.take_while{|x| !cmd_names.include?(x) }
      ARGV.shift(opts.size)

      # All positional options are required. If they are not given then check for the 'chained
      # command expression' case for positional options in the next command that satisfy the
      # previous command's requirements and so on and so forth.
      if opts.size == 0 && (cmd_pos_opts.any? || cmd_named_opts.any?{|x| x.required})
        i = 0
        while (i += 1) < ARGV.size do
          opts = ARGV[i..-1].take_while{|x| !cmd_names.include?(x) }
          break if opts.any? 
        end

        # Check that the chained command options at least match types and size
        if opts.any?
          cmd_required = cmd.opts.select{|x| x.key.nil? || x.required}
          other = @config.find{|x| x.name == ARGV[i-1]}
          other_required = other.opts.select{|x| x.key.nil? || x.required}

          !puts("Error: chained commands must have equal numbers of required optiosn".colorize(:red)) && !puts(cmd.help) and
            exit if cmd_required.size != other_required.size
          cmd_required.each_with_index{|x,i|
            !puts("Error: chained command options are not type consistent".colorize(:red)) && !puts(cmd.help) and
              exit if x.type != other_required[i].type || x.key != other_required[i].key
          }
        end
      end

      # Check that all positional options were given
      !puts("Error: positional option required".colorize(:red)) && !puts(cmd.help) and
        exit if opts.size < cmd_pos_opts.size

      # Check that all required named options where given
      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 opt.start_with?('-')
          short = opt[/^(-\w).*$/, 1]
          long = opt[/(--[\w\-]+)(=.+)*$/, 1]
          value = opt[/.*=(.*)$/, 1]

          # Set symbol converting dashes to underscores for named options
          if (cmd_opt = cmd_named_opts.find{|x| x.short == short || x.long == long})
            sym = cmd_opt.long[2..-1].gsub("-", "_").to_sym

            # Collect value
            if cmd_opt.type == FalseClass
              value = true if !value
            elsif !value
              value = opts.shift
            end
          end

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

        # Convert value to appropriate type and validate against allowed
        # --------------------------------------------------------------------
        if value
          if cmd_opt.type == String
            if cmd_opt.allowed.any?
              !puts("Error: invalid string value '#{value}'".colorize(:red)) && !puts(cmd.help) and
                exit if !cmd_opt.allowed.include?(value)
            end
          elsif cmd_opt.type == Integer
            value = value.to_i
            if cmd_opt.allowed.any?
              !puts("Error: invalid integer value '#{value}'".colorize(:red)) && !puts(cmd.help) and
                exit if !cmd_opt.allowed.include?(value)
            end
          elsif cmd_opt.type == Array
            value = value.split(',')
            if cmd_opt.allowed.any?
              value.each{|x|
                !puts("Error: invalid array value '#{x}'".colorize(:red)) && !puts(cmd.help) and
                  exit if !cmd_opt.allowed.include?(x)
              }
            end
          end
        end

        # 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
      }
    end
  }

  # Ensure all options were consumed
  !puts("Error: invalid options #{ARGV}".colorize(:red)) and exit if ARGV.any?

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