Class: Doodle::App

Inherits:
Doodle show all
Defined in:
lib/doodle/app.rb

Overview

command line option handling DSL implemented using Doodle

Defined Under Namespace

Classes: Filename, HelpExit, Option

Constant Summary collapse

RX_ISODATE =

regular expression for ISO date

/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(\.\d+)? ?Z$/

Class Method Summary collapse

Methods inherited from Doodle

TypedArray, raise_exception_on_error, raise_exception_on_error=

Methods included from ClassMethods

#context, #parent

Methods included from JSON

included

Methods included from Core::ModuleMethods

#included

Class Method Details

.boolean(*args, &block) ⇒ Object

expect an on/off flag, e.g. -b

  • doesn’t take any arguments (mere presence sets it to true)

  • booleans are false by default



190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/doodle/app.rb', line 190

def boolean(*args, &block)
  args = [{ :using => Option, :default => false, :arity => 0}, *args]
  da = option(*args, &block)
  da.instance_eval do
    kind FalseClass, TrueClass
    from NilClass do
      false
    end
    from Numeric do |n|
      n == 0 ? false : true
    end
    from String do |s|
      case s
      when "on", "true", "yes", "1"
        true
      when "off", "false", "no", "0"
        false
      else
        raise Doodle::ValidationError, "unknown value for boolean: #{s}"
      end
    end
  end
end

.date(*args, &block) ⇒ Object

date: -d 2008-09-28



226
227
228
229
230
231
232
233
234
# File 'lib/doodle/app.rb', line 226

def date(*args, &block)
  args = [{ :using => Option, :kind => Date }, *args]
  da = option(*args, &block)
  da.instance_eval do
    from String do |s|
      Date.parse(s)
    end
  end
end

.filename(*args, &block) ⇒ Object

expect a filename - set :existing => true to specify that the file must exist

filename :input, :existing => true, :flag => "i", :doc => "input file name"


171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/doodle/app.rb', line 171

def filename(*args, &block)
  args = [{ :using => Filename, :kind => String }, *args ]
  da = option(*args, &block)
  da.instance_eval do
    if da.existing
      must "exist" do |s|
        File.exist?(s)
      end
    end
    if da.expand
      from String do |s|
        File.expand_path(s)
      end
    end
  end
end

.help_textObject

defines the help text displayed when option –help passed



444
445
446
447
448
449
450
451
452
453
454
455
456
457
# File 'lib/doodle/app.rb', line 444

def help_text
  format_block = proc {|key, flag, doc, required, kind|
    sprintf("  %-3s %-14s %-10s %s %s", flag, key, kind, doc, required ? '(REQUIRED)' : '')
  }
  required, options = help_attributes.partition{ |a| a[3]}
  [
   self.doc,
   "\n",
   self.usage ? ["Usage: " + self.usage, "\n"] : [],
   required.size > 0 ? ["Required args:", required.map(&format_block), "\n"] : [],
   options.size > 0 ? ["Options:", options.map(&format_block), "\n"] : [],
   (self.examples && self.examples.size > 0) ? "Examples:\n" + "  " + self.examples.join("\n  ") : [],
  ]
end

.integer(*args, &block) ⇒ Object

whole number, e.g. -n 10

  • you can use, e.g. :values => [1,2,3] or :values => (0..99) to restrict the range of valid values



215
216
217
218
219
220
221
222
223
224
# File 'lib/doodle/app.rb', line 215

def integer(*args, &block)
  args = [{ :using => Option, :kind => Integer }, *args]
  da = option(*args, &block)
  da.instance_eval do
    from String do |s|
      s =~ /^\d+$/ or raise "must be a whole number"
      s.to_i
    end
  end
end

.option(*args, &block) ⇒ Object

the generic option - can be any type



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
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
148
149
150
151
152
153
# File 'lib/doodle/app.rb', line 104

def option(*args, &block)
  #p [:option, args, :optional, optional?]
  key_values, args = args.partition{ |x| x.kind_of?(Hash)}
  key_values = key_values.inject({ }){ |hash, kv| hash.merge(kv)}

  errors = []

  # handle optional/required flipflop
  if optional?
    required = { :default => nil }
    if key_values.delete(:required)
      if key_values.key?(:optional)
        errors << "Can't specify both :required and :optional"
      end
      if key_values.key?(:default)
        errors << "Can't specify both :required and :default"
      end
      required = { }
    elsif key_values.delete(:optional) && !key_values.key?(:default)
      required = { :default => nil }
    end
  else
    key_values.delete(:required)
    required = { }
  end
  args = [{ :using => Option }.merge(required).merge(key_values), *args]
  da = has(*args, &block)
  if errors.size > 0
    raise ArgumentError, "#{da.name}: #{errors.join(', ')}", [caller[-1]]
  end
  da.instance_eval do
    #p [:checking_values, values, values.class]
    if da.values.kind_of?(Range)
      must "be in range #{da.values}" do |s|
        da.values.include?(s)
      end
    elsif da.values.respond_to?(:size) && da.values.size > 0
      must "be one of #{da.values.join(', ')}" do |s|
        da.values.include?(s)
      end
    end
    if da.match
      must "match pattern #{da.match.inspect}" do |s|
        #p [:matching, s, da.match.inspect]
        s.to_s =~ da.match
      end
    end
  end
  da
end

.optionalObject Also known as: options



92
93
94
# File 'lib/doodle/app.rb', line 92

def optional
  @optional = true
end

.optional?Boolean

Returns:

  • (Boolean)


95
96
97
# File 'lib/doodle/app.rb', line 95

def optional?
  instance_variable_defined?("@optional") ? @optional : false
end

.requiredObject



89
90
91
# File 'lib/doodle/app.rb', line 89

def required
  @optional = false
end

.required_argsObject



98
99
100
# File 'lib/doodle/app.rb', line 98

def required_args
  doodle.attributes.select{ |k, v| v.required?}.map{ |k,v| v}
end

.run(argv = ARGV) ⇒ Object

call App.run to start your application (calls instance.run)



272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/doodle/app.rb', line 272

def run(argv = ARGV)
  begin
    # cheating
    if argv.include?('-h') or argv.include?('--help')
      puts help_text
    else
      app = from_argv(argv)
      app.run
    end
  rescue Exception => e
    if exit_status == 0
      exit_status 1
    end
    puts "\nERROR: #{e}"
  ensure
    exit(exit_status)
  end
end

.std_flagsObject

use this to include ‘standard’ flags: help (-h, –help), verbose (-v, –verbose) and debug (-d, –debug)



261
262
263
264
265
266
267
# File 'lib/doodle/app.rb', line 261

def std_flags
  # FIXME: this is bogus
  m = method(:help_text)
  boolean :help, :flag => "h", :doc => "display this help"
  boolean :verbose, :flag => "v", :doc => "verbose output"
  boolean :debug, :flag => "D", :doc => "turn on debugging"
end

.string(*args, &block) ⇒ Object

expect a string



155
156
157
158
# File 'lib/doodle/app.rb', line 155

def string(*args, &block)
  args = [{ :using => Option, :kind => String }, *args]
  da = option(*args, &block)
end

.symbol(*args, &block) ⇒ Object

expect a symbol (and convert from String)



160
161
162
163
164
165
166
167
168
# File 'lib/doodle/app.rb', line 160

def symbol(*args, &block)
  args = [{ :using => Option, :kind => Symbol }, *args]
  da = option(*args, &block)
  da.instance_eval do
    from String do |s|
      s.to_sym
    end
  end
end

.tidy_dir(path) ⇒ Object

replace the full directory path with ./ where appropriate



35
36
37
# File 'lib/doodle/app.rb', line 35

def self.tidy_dir(path)
  path.to_s.gsub(Regexp.new("^#{ Regexp.escape(Dir.pwd) }/"), './')
end

.time(*args, &block) ⇒ Object

time: -d 2008-09-28T18:00:00



236
237
238
239
240
241
242
243
244
# File 'lib/doodle/app.rb', line 236

def time(*args, &block)
  args = [{ :using => Option, :kind => Time }, *args]
  da = option(*args, &block)
  da.instance_eval do
    from String do |s|
      Time.parse(s)
    end
  end
end

.utcdate(*args, &block) ⇒ Object

utcdate: -d 2008-09-28T21:41:29Z

  • actually uses Time (so restricted range)



247
248
249
250
251
252
253
254
255
256
257
258
# File 'lib/doodle/app.rb', line 247

def utcdate(*args, &block)
  args = [{ :using => Option, :kind => Time }, *args]
  da = option(*args, &block)
  da.instance_eval do
    from String do |s|
      if s !~ RX_ISODATE
        raise ArgumentError, "date must be in ISO format (YYYY-MM-DDTHH:MM:SS, e.g. #{Time.now.utc.xmlschema})"
      end
      Time.parse(s)
    end
  end
end