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, 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

context, parent, raise_exception_on_error, raise_exception_on_error=

Methods included from Core

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



182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/doodle/app.rb', line 182

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



218
219
220
221
222
223
224
225
226
# File 'lib/doodle/app.rb', line 218

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"


168
169
170
171
172
173
174
175
176
177
178
# File 'lib/doodle/app.rb', line 168

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

.help_textObject

defines the help text displayed when option –help passed



433
434
435
436
437
438
439
440
441
442
443
444
445
446
# File 'lib/doodle/app.rb', line 433

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



207
208
209
210
211
212
213
214
215
216
# File 'lib/doodle/app.rb', line 207

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



101
102
103
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
# File 'lib/doodle/app.rb', line 101

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



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

def optional
  @optional = true
end

.optional?Boolean

Returns:

  • (Boolean)


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

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

.requiredObject



86
87
88
# File 'lib/doodle/app.rb', line 86

def required
  @optional = false
end

.required_argsObject



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

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)



262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# File 'lib/doodle/app.rb', line 262

def run(argv = ARGV)
  begin
    app = from_argv(argv)
    if app.help
      puts help_text
    else
      app.run
    end
  rescue Object => 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)



253
254
255
256
257
# File 'lib/doodle/app.rb', line 253

def std_flags
  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



152
153
154
155
# File 'lib/doodle/app.rb', line 152

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)



157
158
159
160
161
162
163
164
165
# File 'lib/doodle/app.rb', line 157

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



33
34
35
# File 'lib/doodle/app.rb', line 33

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



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

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)



239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/doodle/app.rb', line 239

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