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

def options

raise(OptionError,
  "Options must be over-written with a valid (or empty) options list.")

end



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/commandline/application.rb', line 41

def initialize
  # Ensure initializations have taken place
  @arg_arity     ||= [0,0]
  @options       ||= []
  @arg_names     ||= []
  @option_parser ||= CommandLine::OptionParser.new(@options)
  _init_format

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

  @option_data = @option_parser.parse 

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

Class Method Details

.inherited(klass) ⇒ Object



257
258
259
260
261
# File 'lib/commandline/application.rb', line 257

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

.runObject



250
251
252
253
254
255
# File 'lib/commandline/application.rb', line 250

def self.run
  @@app.new.main if ($0 == @@appname)
  rescue => err
    puts "ERROR: #{err}"
    exit(-1)
end

Instance Method Details

#_debugObject



309
310
311
312
313
314
315
316
317
# File 'lib/commandline/application.rb', line 309

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

#_helpObject



268
269
270
271
272
273
274
275
276
277
# File 'lib/commandline/application.rb', line 268

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

#_init_formatObject



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/commandline/application.rb', line 62

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

#_verboseObject



279
280
281
282
283
284
285
286
287
288
289
# File 'lib/commandline/application.rb', line 279

def _verbose
   {
     :names           => %w(--verbose -v),
     :arg_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



291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# File 'lib/commandline/application.rb', line 291

def _version
   {
     :names           => %w(--version -V),
     :arg_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



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

def append_arg
  CommandLine::OptionParser::GET_ARG_ARRAY
end

#args(*expected_args) ⇒ Object

args [0,-1] #=> args is array

synopsis: Usage: app [arg [arg...]]


145
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
# File 'lib/commandline/application.rb', line 145

def 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



241
242
243
# File 'lib/commandline/application.rb', line 241

def get_arg
  CommandLine::OptionParser::GET_ARGS
end

#mainObject



263
264
265
266
# File 'lib/commandline/application.rb', line 263

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

#manObject Also known as: help



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
# File 'lib/commandline/application.rb', line 186

def man
  require 'commandline/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}"
  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



237
238
239
# File 'lib/commandline/application.rb', line 237

def name
  File.basename(pathname)
end

#option(*args) ⇒ Object



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/commandline/application.rb', line 91

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

#pathnameObject



233
234
235
# File 'lib/commandline/application.rb', line 233

def pathname
  @@appname
end

#usageObject



182
183
184
# File 'lib/commandline/application.rb', line 182

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

#validate_arg_arity(arity) ⇒ Object



172
173
174
175
176
177
178
179
180
# File 'lib/commandline/application.rb', line 172

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:



80
81
82
83
84
85
86
87
88
89
# File 'lib/commandline/application.rb', line 80

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