wtch 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,556 @@
1
+ require 'thor/core_ext/hash_with_indifferent_access'
2
+ require 'thor/core_ext/ordered_hash'
3
+ require 'thor/error'
4
+ require 'thor/shell'
5
+ require 'thor/invocation'
6
+ require 'thor/parser'
7
+ require 'thor/task'
8
+ require 'thor/util'
9
+
10
+ class Thor
11
+ autoload :Actions, 'thor/actions'
12
+ autoload :RakeCompat, 'thor/rake_compat'
13
+
14
+ # Shortcuts for help.
15
+ HELP_MAPPINGS = %w(-h -? --help -D)
16
+
17
+ # Thor methods that should not be overwritten by the user.
18
+ THOR_RESERVED_WORDS = %w(invoke shell options behavior root destination_root relative_root
19
+ action add_file create_file in_root inside run run_ruby_script)
20
+
21
+ module Base
22
+ attr_accessor :options
23
+
24
+ # It receives arguments in an Array and two hashes, one for options and
25
+ # other for configuration.
26
+ #
27
+ # Notice that it does not check if all required arguments were supplied.
28
+ # It should be done by the parser.
29
+ #
30
+ # ==== Parameters
31
+ # args<Array[Object]>:: An array of objects. The objects are applied to their
32
+ # respective accessors declared with <tt>argument</tt>.
33
+ #
34
+ # options<Hash>:: An options hash that will be available as self.options.
35
+ # The hash given is converted to a hash with indifferent
36
+ # access, magic predicates (options.skip?) and then frozen.
37
+ #
38
+ # config<Hash>:: Configuration for this Thor class.
39
+ #
40
+ def initialize(args=[], options={}, config={})
41
+ args = Thor::Arguments.parse(self.class.arguments, args)
42
+ args.each { |key, value| send("#{key}=", value) }
43
+
44
+ parse_options = self.class.class_options
45
+
46
+ if options.is_a?(Array)
47
+ task_options = config.delete(:task_options) # hook for start
48
+ parse_options = parse_options.merge(task_options) if task_options
49
+ array_options, hash_options = options, {}
50
+ else
51
+ array_options, hash_options = [], options
52
+ end
53
+
54
+ opts = Thor::Options.new(parse_options, hash_options)
55
+ self.options = opts.parse(array_options)
56
+ opts.check_unknown! if self.class.check_unknown_options?(config)
57
+ end
58
+
59
+ class << self
60
+ def included(base) #:nodoc:
61
+ base.send :extend, ClassMethods
62
+ base.send :include, Invocation
63
+ base.send :include, Shell
64
+ end
65
+
66
+ # Returns the classes that inherits from Thor or Thor::Group.
67
+ #
68
+ # ==== Returns
69
+ # Array[Class]
70
+ #
71
+ def subclasses
72
+ @subclasses ||= []
73
+ end
74
+
75
+ # Returns the files where the subclasses are kept.
76
+ #
77
+ # ==== Returns
78
+ # Hash[path<String> => Class]
79
+ #
80
+ def subclass_files
81
+ @subclass_files ||= Hash.new{ |h,k| h[k] = [] }
82
+ end
83
+
84
+ # Whenever a class inherits from Thor or Thor::Group, we should track the
85
+ # class and the file on Thor::Base. This is the method responsable for it.
86
+ #
87
+ def register_klass_file(klass) #:nodoc:
88
+ file = caller[1].match(/(.*):\d+/)[1]
89
+ Thor::Base.subclasses << klass unless Thor::Base.subclasses.include?(klass)
90
+
91
+ file_subclasses = Thor::Base.subclass_files[File.expand_path(file)]
92
+ file_subclasses << klass unless file_subclasses.include?(klass)
93
+ end
94
+ end
95
+
96
+ module ClassMethods
97
+ attr_accessor :debugging
98
+
99
+ def attr_reader(*) #:nodoc:
100
+ no_tasks { super }
101
+ end
102
+
103
+ def attr_writer(*) #:nodoc:
104
+ no_tasks { super }
105
+ end
106
+
107
+ def attr_accessor(*) #:nodoc:
108
+ no_tasks { super }
109
+ end
110
+
111
+ # If you want to raise an error for unknown options, call check_unknown_options!
112
+ # This is disabled by default to allow dynamic invocations.
113
+ def check_unknown_options!
114
+ @check_unknown_options = true
115
+ end
116
+
117
+ def check_unknown_options #:nodoc:
118
+ @check_unknown_options ||= from_superclass(:check_unknown_options, false)
119
+ end
120
+
121
+ def check_unknown_options?(config) #:nodoc:
122
+ !!check_unknown_options
123
+ end
124
+
125
+ # Adds an argument to the class and creates an attr_accessor for it.
126
+ #
127
+ # Arguments are different from options in several aspects. The first one
128
+ # is how they are parsed from the command line, arguments are retrieved
129
+ # from position:
130
+ #
131
+ # thor task NAME
132
+ #
133
+ # Instead of:
134
+ #
135
+ # thor task --name=NAME
136
+ #
137
+ # Besides, arguments are used inside your code as an accessor (self.argument),
138
+ # while options are all kept in a hash (self.options).
139
+ #
140
+ # Finally, arguments cannot have type :default or :boolean but can be
141
+ # optional (supplying :optional => :true or :required => false), although
142
+ # you cannot have a required argument after a non-required argument. If you
143
+ # try it, an error is raised.
144
+ #
145
+ # ==== Parameters
146
+ # name<Symbol>:: The name of the argument.
147
+ # options<Hash>:: Described below.
148
+ #
149
+ # ==== Options
150
+ # :desc - Description for the argument.
151
+ # :required - If the argument is required or not.
152
+ # :optional - If the argument is optional or not.
153
+ # :type - The type of the argument, can be :string, :hash, :array, :numeric.
154
+ # :default - Default value for this argument. It cannot be required and have default values.
155
+ # :banner - String to show on usage notes.
156
+ #
157
+ # ==== Errors
158
+ # ArgumentError:: Raised if you supply a required argument after a non required one.
159
+ #
160
+ def argument(name, options={})
161
+ is_thor_reserved_word?(name, :argument)
162
+ no_tasks { attr_accessor name }
163
+
164
+ required = if options.key?(:optional)
165
+ !options[:optional]
166
+ elsif options.key?(:required)
167
+ options[:required]
168
+ else
169
+ options[:default].nil?
170
+ end
171
+
172
+ remove_argument name
173
+
174
+ arguments.each do |argument|
175
+ next if argument.required?
176
+ raise ArgumentError, "You cannot have #{name.to_s.inspect} as required argument after " <<
177
+ "the non-required argument #{argument.human_name.inspect}."
178
+ end if required
179
+
180
+ arguments << Thor::Argument.new(name, options[:desc], required, options[:type],
181
+ options[:default], options[:banner])
182
+ end
183
+
184
+ # Returns this class arguments, looking up in the ancestors chain.
185
+ #
186
+ # ==== Returns
187
+ # Array[Thor::Argument]
188
+ #
189
+ def arguments
190
+ @arguments ||= from_superclass(:arguments, [])
191
+ end
192
+
193
+ # Adds a bunch of options to the set of class options.
194
+ #
195
+ # class_options :foo => false, :bar => :required, :baz => :string
196
+ #
197
+ # If you prefer more detailed declaration, check class_option.
198
+ #
199
+ # ==== Parameters
200
+ # Hash[Symbol => Object]
201
+ #
202
+ def class_options(options=nil)
203
+ @class_options ||= from_superclass(:class_options, {})
204
+ build_options(options, @class_options) if options
205
+ @class_options
206
+ end
207
+
208
+ # Adds an option to the set of class options
209
+ #
210
+ # ==== Parameters
211
+ # name<Symbol>:: The name of the argument.
212
+ # options<Hash>:: Described below.
213
+ #
214
+ # ==== Options
215
+ # :desc - Description for the argument.
216
+ # :required - If the argument is required or not.
217
+ # :default - Default value for this argument.
218
+ # :group - The group for this options. Use by class options to output options in different levels.
219
+ # :aliases - Aliases for this option.
220
+ # :type - The type of the argument, can be :string, :hash, :array, :numeric or :boolean.
221
+ # :banner - String to show on usage notes.
222
+ #
223
+ def class_option(name, options={})
224
+ build_option(name, options, class_options)
225
+ end
226
+
227
+ # Removes a previous defined argument. If :undefine is given, undefine
228
+ # accessors as well.
229
+ #
230
+ # ==== Paremeters
231
+ # names<Array>:: Arguments to be removed
232
+ #
233
+ # ==== Examples
234
+ #
235
+ # remove_argument :foo
236
+ # remove_argument :foo, :bar, :baz, :undefine => true
237
+ #
238
+ def remove_argument(*names)
239
+ options = names.last.is_a?(Hash) ? names.pop : {}
240
+
241
+ names.each do |name|
242
+ arguments.delete_if { |a| a.name == name.to_s }
243
+ undef_method name, "#{name}=" if options[:undefine]
244
+ end
245
+ end
246
+
247
+ # Removes a previous defined class option.
248
+ #
249
+ # ==== Paremeters
250
+ # names<Array>:: Class options to be removed
251
+ #
252
+ # ==== Examples
253
+ #
254
+ # remove_class_option :foo
255
+ # remove_class_option :foo, :bar, :baz
256
+ #
257
+ def remove_class_option(*names)
258
+ names.each do |name|
259
+ class_options.delete(name)
260
+ end
261
+ end
262
+
263
+ # Defines the group. This is used when thor list is invoked so you can specify
264
+ # that only tasks from a pre-defined group will be shown. Defaults to standard.
265
+ #
266
+ # ==== Parameters
267
+ # name<String|Symbol>
268
+ #
269
+ def group(name=nil)
270
+ case name
271
+ when nil
272
+ @group ||= from_superclass(:group, 'standard')
273
+ else
274
+ @group = name.to_s
275
+ end
276
+ end
277
+
278
+ # Returns the tasks for this Thor class.
279
+ #
280
+ # ==== Returns
281
+ # OrderedHash:: An ordered hash with tasks names as keys and Thor::Task
282
+ # objects as values.
283
+ #
284
+ def tasks
285
+ @tasks ||= Thor::CoreExt::OrderedHash.new
286
+ end
287
+
288
+ # Returns the tasks for this Thor class and all subclasses.
289
+ #
290
+ # ==== Returns
291
+ # OrderedHash:: An ordered hash with tasks names as keys and Thor::Task
292
+ # objects as values.
293
+ #
294
+ def all_tasks
295
+ @all_tasks ||= from_superclass(:all_tasks, Thor::CoreExt::OrderedHash.new)
296
+ @all_tasks.merge(tasks)
297
+ end
298
+
299
+ # Removes a given task from this Thor class. This is usually done if you
300
+ # are inheriting from another class and don't want it to be available
301
+ # anymore.
302
+ #
303
+ # By default it only remove the mapping to the task. But you can supply
304
+ # :undefine => true to undefine the method from the class as well.
305
+ #
306
+ # ==== Parameters
307
+ # name<Symbol|String>:: The name of the task to be removed
308
+ # options<Hash>:: You can give :undefine => true if you want tasks the method
309
+ # to be undefined from the class as well.
310
+ #
311
+ def remove_task(*names)
312
+ options = names.last.is_a?(Hash) ? names.pop : {}
313
+
314
+ names.each do |name|
315
+ tasks.delete(name.to_s)
316
+ all_tasks.delete(name.to_s)
317
+ undef_method name if options[:undefine]
318
+ end
319
+ end
320
+
321
+ # All methods defined inside the given block are not added as tasks.
322
+ #
323
+ # So you can do:
324
+ #
325
+ # class MyScript < Thor
326
+ # no_tasks do
327
+ # def this_is_not_a_task
328
+ # end
329
+ # end
330
+ # end
331
+ #
332
+ # You can also add the method and remove it from the task list:
333
+ #
334
+ # class MyScript < Thor
335
+ # def this_is_not_a_task
336
+ # end
337
+ # remove_task :this_is_not_a_task
338
+ # end
339
+ #
340
+ def no_tasks
341
+ @no_tasks = true
342
+ yield
343
+ ensure
344
+ @no_tasks = false
345
+ end
346
+
347
+ # Sets the namespace for the Thor or Thor::Group class. By default the
348
+ # namespace is retrieved from the class name. If your Thor class is named
349
+ # Scripts::MyScript, the help method, for example, will be called as:
350
+ #
351
+ # thor scripts:my_script -h
352
+ #
353
+ # If you change the namespace:
354
+ #
355
+ # namespace :my_scripts
356
+ #
357
+ # You change how your tasks are invoked:
358
+ #
359
+ # thor my_scripts -h
360
+ #
361
+ # Finally, if you change your namespace to default:
362
+ #
363
+ # namespace :default
364
+ #
365
+ # Your tasks can be invoked with a shortcut. Instead of:
366
+ #
367
+ # thor :my_task
368
+ #
369
+ def namespace(name=nil)
370
+ case name
371
+ when nil
372
+ @namespace ||= Thor::Util.namespace_from_thor_class(self)
373
+ else
374
+ @namespace = name.to_s
375
+ end
376
+ end
377
+
378
+ # Parses the task and options from the given args, instantiate the class
379
+ # and invoke the task. This method is used when the arguments must be parsed
380
+ # from an array. If you are inside Ruby and want to use a Thor class, you
381
+ # can simply initialize it:
382
+ #
383
+ # script = MyScript.new(args, options, config)
384
+ # script.invoke(:task, first_arg, second_arg, third_arg)
385
+ #
386
+ def start(given_args=ARGV, config={})
387
+ self.debugging = given_args.delete("--debug")
388
+ config[:shell] ||= Thor::Base.shell.new
389
+ dispatch(nil, given_args.dup, nil, config)
390
+ rescue Thor::Error => e
391
+ debugging ? (raise e) : config[:shell].error(e.message)
392
+ exit(1) if exit_on_failure?
393
+ end
394
+
395
+ def handle_no_task_error(task) #:nodoc:
396
+ if $thor_runner
397
+ raise UndefinedTaskError, "Could not find task #{task.inspect} in #{namespace.inspect} namespace."
398
+ else
399
+ raise UndefinedTaskError, "Could not find task #{task.inspect}."
400
+ end
401
+ end
402
+
403
+ def handle_argument_error(task, error) #:nodoc:
404
+ raise InvocationError, "#{task.name.inspect} was called incorrectly. Call as #{self.banner(task).inspect}."
405
+ end
406
+
407
+ protected
408
+
409
+ # Prints the class options per group. If an option does not belong to
410
+ # any group, it's printed as Class option.
411
+ #
412
+ def class_options_help(shell, groups={}) #:nodoc:
413
+ # Group options by group
414
+ class_options.each do |_, value|
415
+ groups[value.group] ||= []
416
+ groups[value.group] << value
417
+ end
418
+
419
+ # Deal with default group
420
+ global_options = groups.delete(nil) || []
421
+ print_options(shell, global_options)
422
+
423
+ # Print all others
424
+ groups.each do |group_name, options|
425
+ print_options(shell, options, group_name)
426
+ end
427
+ end
428
+
429
+ # Receives a set of options and print them.
430
+ def print_options(shell, options, group_name=nil)
431
+ return if options.empty?
432
+
433
+ list = []
434
+ padding = options.collect{ |o| o.aliases.size }.max.to_i * 4
435
+
436
+ options.each do |option|
437
+ item = [ option.usage(padding) ]
438
+ item.push(option.description ? "# #{option.description}" : "")
439
+
440
+ list << item
441
+ list << [ "", "# Default: #{option.default}" ] if option.show_default?
442
+ end
443
+
444
+ shell.say(group_name ? "#{group_name} options:" : "Options:")
445
+ shell.print_table(list, :ident => 2)
446
+ shell.say ""
447
+ end
448
+
449
+ # Raises an error if the word given is a Thor reserved word.
450
+ def is_thor_reserved_word?(word, type) #:nodoc:
451
+ return false unless THOR_RESERVED_WORDS.include?(word.to_s)
452
+ raise "#{word.inspect} is a Thor reserved word and cannot be defined as #{type}"
453
+ end
454
+
455
+ # Build an option and adds it to the given scope.
456
+ #
457
+ # ==== Parameters
458
+ # name<Symbol>:: The name of the argument.
459
+ # options<Hash>:: Described in both class_option and method_option.
460
+ def build_option(name, options, scope) #:nodoc:
461
+ scope[name] = Thor::Option.new(name, options[:desc], options[:required],
462
+ options[:type], options[:default], options[:banner],
463
+ options[:lazy_default], options[:group], options[:aliases])
464
+ end
465
+
466
+ # Receives a hash of options, parse them and add to the scope. This is a
467
+ # fast way to set a bunch of options:
468
+ #
469
+ # build_options :foo => true, :bar => :required, :baz => :string
470
+ #
471
+ # ==== Parameters
472
+ # Hash[Symbol => Object]
473
+ def build_options(options, scope) #:nodoc:
474
+ options.each do |key, value|
475
+ scope[key] = Thor::Option.parse(key, value)
476
+ end
477
+ end
478
+
479
+ # Finds a task with the given name. If the task belongs to the current
480
+ # class, just return it, otherwise dup it and add the fresh copy to the
481
+ # current task hash.
482
+ def find_and_refresh_task(name) #:nodoc:
483
+ task = if task = tasks[name.to_s]
484
+ task
485
+ elsif task = all_tasks[name.to_s]
486
+ tasks[name.to_s] = task.clone
487
+ else
488
+ raise ArgumentError, "You supplied :for => #{name.inspect}, but the task #{name.inspect} could not be found."
489
+ end
490
+ end
491
+
492
+ # Everytime someone inherits from a Thor class, register the klass
493
+ # and file into baseclass.
494
+ def inherited(klass)
495
+ Thor::Base.register_klass_file(klass)
496
+ end
497
+
498
+ # Fire this callback whenever a method is added. Added methods are
499
+ # tracked as tasks by invoking the create_task method.
500
+ def method_added(meth)
501
+ meth = meth.to_s
502
+
503
+ if meth == "initialize"
504
+ initialize_added
505
+ return
506
+ end
507
+
508
+ # Return if it's not a public instance method
509
+ return unless public_instance_methods.include?(meth) ||
510
+ public_instance_methods.include?(meth.to_sym)
511
+
512
+ return if @no_tasks || !create_task(meth)
513
+
514
+ is_thor_reserved_word?(meth, :task)
515
+ Thor::Base.register_klass_file(self)
516
+ end
517
+
518
+ # Retrieves a value from superclass. If it reaches the baseclass,
519
+ # returns default.
520
+ def from_superclass(method, default=nil)
521
+ if self == baseclass || !superclass.respond_to?(method, true)
522
+ default
523
+ else
524
+ value = superclass.send(method)
525
+ value.dup if value
526
+ end
527
+ end
528
+
529
+ # A flag that makes the process exit with status 1 if any error happens.
530
+ def exit_on_failure?
531
+ false
532
+ end
533
+
534
+ # SIGNATURE: Sets the baseclass. This is where the superclass lookup
535
+ # finishes.
536
+ def baseclass #:nodoc:
537
+ end
538
+
539
+ # SIGNATURE: Creates a new task if valid_task? is true. This method is
540
+ # called when a new method is added to the class.
541
+ def create_task(meth) #:nodoc:
542
+ end
543
+
544
+ # SIGNATURE: Defines behavior when the initialize method is added to the
545
+ # class.
546
+ def initialize_added #:nodoc:
547
+ end
548
+
549
+ # SIGNATURE: The hook invoked by start.
550
+ def dispatch(task, given_args, given_opts, config) #:nodoc:
551
+ raise NotImplementedError
552
+ end
553
+
554
+ end
555
+ end
556
+ end