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, version, examples: nil) ⇒ Commander

Initialize the commands for your application

Parameters:

  • application name e.g. reduce

  • version of the application e.g. 1.0.0

  • (defaults to: nil)

    optional examples to list after the title before usage



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

def initialize(app, version, examples:nil)
  @app = app
  @version = version
  @examples = examples
  !puts("Error: app name and version are required".colorize(:red)) and
    exit if @app.nil? or @app.empty? or @version.nil? or @version.empty?

  @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



151
152
153
# File 'lib/nub/commander.rb', line 151

def banner
  @banner
end

#cmdsObject

Returns the value of attribute cmds.



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

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



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:

  • name of the command

  • description of the command

  • 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
# 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
  help = "#{banner}\n#{desc}\n\nUsage: ./#{@app} #{cmd} [options]\n"
  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



158
159
160
161
162
163
164
165
166
167
168
# File 'lib/nub/commander.rb', line 158

def help
  help = "#{banner}\n"
  help += "Examples:\n#{@examples}\n\n" if !@examples.nil? && !@examples.empty?
  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



171
172
173
174
175
176
177
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
# File 'lib/nub/commander.rb', line 171

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}

      # Collect command options
      opts = ARGV.take_while{|x| !cmd_names.include?(x) }
      ARGV.shift(opts.size)
      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.size < cmd_pos_opts.size

      # 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
        # --------------------------------------------------------------------
        if value
          if cmd_opt.type == Integer
            value = value.to_i

            # Validate allowed values
            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(',')

            # Validate allowed values
            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?
end