Class: CommandLine::Application

Inherits:
Object
  • Object
show all
Defined in:
lib/commandline/application.rb

Defined Under Namespace

Classes: ApplicationError, ArgumentError, InvalidArgumentArityError, MissingMainError, OptionError

Constant Summary collapse

DEFAULT_CONSOLE_WIDTH =

TODO: Consolidate these with OptionParser - put in command line

70
MIN_CONSOLE_WIDTH =
10
DEFAULT_BODY_INDENT =
4

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeApplication

Returns a new instance of Application.



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/commandline/application.rb', line 36

def initialize
  @synopsis       = ""
  @arg_arity     = [0,0]
  @options       = []
  @arg_names     = []
  @args          = []
  @argv        ||= ARGV

  __init_format

  __child_initialize if 
    self.class.private_instance_methods(false).include?("__child_initialize")

  @option_parser ||= CommandLine::OptionParser.new(@options)
end

Class Method Details

.inherited(child_class) ⇒ Object



238
239
240
241
242
243
244
# File 'lib/commandline/application.rb', line 238

def self.inherited(child_class)
  @@appname = caller[0][/.*:/][0..-2]
  @@child_class = child_class
  if @@appname == $0
    at_exit { @@child_class.run }
  end
end

.run(argv = ARGV) ⇒ Object



217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'lib/commandline/application.rb', line 217

def self.run(argv=ARGV)
  if self.private_instance_methods(false).include?("initialize")
    $VERBOSE, verbose = nil, $VERBOSE
    self.class_eval {
      alias :__child_initialize :initialize
      remove_method :initialize
    }
    $VERBOSE = verbose
  end
  obj = self.new
  obj.__parse_command_line(argv)
  obj.main

  #alias :user_init :initialize
  #@@child_class.new.main if ($0 == @@appname)
  obj
  rescue => err
    puts "ERROR: #{err}"
    exit(-1)
end

Instance Method Details

#__debugObject



347
348
349
350
351
352
353
354
355
# File 'lib/commandline/application.rb', line 347

def __debug
   {
     :names           => %w(--debug -d),
     :arity           => [0,0],
     :opt_description => "Sets debug to true.",
     :arg_description => "",
     :opt_found       => lambda { $DEBUG = true }
   }
end

#__helpObject



306
307
308
309
310
311
312
313
314
315
# File 'lib/commandline/application.rb', line 306

def __help
   {
     :names           => %w(--help -h),
     :arity           => [0,0],
     :opt_description => "Displays help page.",
     :arg_description => "",
     :opt_found       => lambda { puts man; exit },
     :opt_not_found   => false
   }
end

#__init_formatObject



276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/commandline/application.rb', line 276

def __init_format
  #
  # Formatting defaults
  #
  console_width = ENV["COLUMNS"]
  @columns = 
    if console_width.nil?
      DEFAULT_CONSOLE_WIDTH
    elsif console_width < MIN_CONSOLE_WIDTH
      console_width
    else
      console_width - DEFAULT_BODY_INDENT
    end
  @body_indent   = DEFAULT_BODY_INDENT
  @tag_paragraph = false
  @order         = :index  # | :alpha
end

#__parse_command_line(argv) ⇒ Object



252
253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/commandline/application.rb', line 252

def __parse_command_line(argv)
  if argv.empty? && [0,0] != @arg_arity
    puts usage
    exit(0)
  end

  @option_data = @option_parser.parse(argv)

  __validate_args(@option_data.args)
  @arg_names.each_with_index { |name, idx|
    instance_variable_set("@#{name}", @option_data.args[idx])
  }
end

#__validate_arg_arity(arity) ⇒ Object



266
267
268
269
270
271
272
273
274
# File 'lib/commandline/application.rb', line 266

def __validate_arg_arity(arity)
  min, max = *arity
  raise(InvalidArgumentArityError, "Minimum argument arity '#{min}' must be "+
    "greater than or equal to 0.") unless min >= 0
  raise(InvalidArgumentArityError, "Maximum argument arity '#{max}' must be "+
    "greater than or equal to -1.") if max < -1
  raise(InvalidArgumentArityError, "Maximum argument arity '#{max}' must be "+
    "greater than minimum arg_arity '#{min}'.") if max < min && max != -1
end

#__validate_args(od_args) ⇒ Object

Raises:



294
295
296
297
298
299
300
301
302
303
# File 'lib/commandline/application.rb', line 294

def __validate_args(od_args)
  size = od_args.size
  min, max = @arg_arity
  max = 1.0/0.0 if -1 == max
  raise(ArgumentError, 
    "Missing expected arguments. Found #{size} but expected #{min}.\n"+
    "#{usage}") if size < min
  raise(ArgumentError, "Too many arguments. Found #{size} but "+
    "expected #{max}.\n#{usage}") if size > max
end

#__verboseObject



317
318
319
320
321
322
323
324
325
326
327
# File 'lib/commandline/application.rb', line 317

def __verbose
   {
     :names           => %w(--verbose -v),
     :arity           => [0,0],
     :opt_description => "Sets verbosity level. Subsequent "+
                         "flags increase verbosity level",
     :arg_description => "",
     :opt_found       => lambda { @verbose ||= -1; @verbose += 1 },
     :opt_not_found   => nil
   }
end

#__versionObject



329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
# File 'lib/commandline/application.rb', line 329

def __version
   {
     :names           => %w(--version -V),
     :arity           => [0,0],
     :opt_description => "Displays application version.",
     :arg_description => "",
     :opt_found       => lambda { 
                           begin 
                             version 
                           rescue 
                             puts "No version specified" 
                           end; 
                           exit 
                         },
     :opt_not_found   => nil
   }
end

#append_argObject



213
214
215
# File 'lib/commandline/application.rb', line 213

def append_arg
  CommandLine::OptionParser::GET_ARG_ARRAY
end

#expected_args(*expected_args) ⇒ Object

expected_args :cmd

Now, what to do if command line has more args than expected
app --app-option cmd --cmd-option arg-for-cmd


122
123
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/commandline/application.rb', line 122

def expected_args(*expected_args)
  @arg_names = []
  case expected_args.size
  when 0 then @arg_arity = [0,0]
  when 1
    case expected_args[0]
    when Fixnum 
      v = expected_args[0]
      @arg_arity = [v,v]
    when Symbol
      @arg_names = expected_args
      @arg_arity = [1,1]
    when Array
      v = expected_args[0]
      __validate_arg_arity(v)
      @arg_arity = v
    else 
      raise(InvalidArgumentArityError, 
        "Args must be a Fixnum or Array: #{expected_args[0].inspect}.")
    end
  else
    @arg_names = expected_args
    size = expected_args.size
    @arg_arity = [size, size]
  end
end

#get_argObject Also known as: get_args



208
209
210
# File 'lib/commandline/application.rb', line 208

def get_arg
  CommandLine::OptionParser::GET_ARGS
end

#mainObject



246
247
248
249
250
# File 'lib/commandline/application.rb', line 246

def main
  #raise(MissingMainError, "Method #main must be defined in class #{@@child_class}.")
  @@child_class.class_eval %{ def main; end }
  #self.class_eval %{ def main; end }
end

#manObject Also known as: help



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
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
# File 'lib/commandline/application.rb', line 153

def man
  require 'text/format'
  f = Text::Format.new
  f = Text::Format.new
  f.columns = @columns
  f.first_indent  = 4
  f.body_indent   = @body_indent
  f.tag_paragraph = false

  s = []
  s << ["NAME\n"]

  nm = "#{short_description}".empty? ? name : "#{name} - #{short_description}"
  s << f.format(nm)

  sn = "#{synopsis}".empty? ? "" : "#{name} #{synopsis}"
  unless sn.empty?
    s << "SYNOPSIS\n"
    s << f.format(sn)
  end

  dc = "#{long_description}"
  unless dc.empty?
    s << "DESCRIPTION\n"
    s << f.format(dc)
  end

  op = option_parser.to_s
  unless op.empty?
    s << option_parser.to_s
  end

  ar = "#{author}"
  unless ar.empty?
    s << "AUTHOR:  #{ar}"
  end


  ct = "#{copyright}"
  unless ct.empty?
    s << ct
  end

  s.join("\n")
end

#nameObject



200
201
202
# File 'lib/commandline/application.rb', line 200

def name
  File.basename(pathname)
end

#option(*args) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/commandline/application.rb', line 56

def option(*args)
  @options ||= []
  new_list = []
  args.each { |arg|
    new_list << 
    case arg
      when :help    then __help
      when :debug   then __debug
      when :verbose then __verbose
      when :version then __version
      else arg
    end
  }
  #p new_list
  @options << CommandLine::Option.new(*new_list)
end

#options(*opts) ⇒ Object



52
53
54
# File 'lib/commandline/application.rb', line 52

def options(*opts)
  opts.each { |opt| option(*[opt].flatten) }
end

#pathnameObject



204
205
206
# File 'lib/commandline/application.rb', line 204

def pathname
  @@appname
end

#usageObject



149
150
151
# File 'lib/commandline/application.rb', line 149

def usage
  " Usage: #{name} #{synopsis}"
end