thor 0.9.9 → 0.11.5

Sign up to get free protection for your applications and to get access to all the features.
Files changed (65) hide show
  1. data/CHANGELOG.rdoc +29 -4
  2. data/README.rdoc +234 -0
  3. data/Thorfile +57 -0
  4. data/VERSION +1 -0
  5. data/bin/rake2thor +4 -0
  6. data/bin/thor +1 -1
  7. data/lib/thor.rb +216 -119
  8. data/lib/thor/actions.rb +272 -0
  9. data/lib/thor/actions/create_file.rb +102 -0
  10. data/lib/thor/actions/directory.rb +87 -0
  11. data/lib/thor/actions/empty_directory.rb +133 -0
  12. data/lib/thor/actions/file_manipulation.rb +195 -0
  13. data/lib/thor/actions/inject_into_file.rb +78 -0
  14. data/lib/thor/base.rb +510 -0
  15. data/lib/thor/core_ext/hash_with_indifferent_access.rb +75 -0
  16. data/lib/thor/core_ext/ordered_hash.rb +100 -0
  17. data/lib/thor/error.rb +25 -1
  18. data/lib/thor/group.rb +263 -0
  19. data/lib/thor/invocation.rb +178 -0
  20. data/lib/thor/parser.rb +4 -0
  21. data/lib/thor/parser/argument.rb +67 -0
  22. data/lib/thor/parser/arguments.rb +145 -0
  23. data/lib/thor/parser/option.rb +132 -0
  24. data/lib/thor/parser/options.rb +142 -0
  25. data/lib/thor/rake_compat.rb +67 -0
  26. data/lib/thor/runner.rb +232 -242
  27. data/lib/thor/shell.rb +72 -0
  28. data/lib/thor/shell/basic.rb +220 -0
  29. data/lib/thor/shell/color.rb +108 -0
  30. data/lib/thor/task.rb +97 -60
  31. data/lib/thor/util.rb +230 -55
  32. data/spec/actions/create_file_spec.rb +170 -0
  33. data/spec/actions/directory_spec.rb +118 -0
  34. data/spec/actions/empty_directory_spec.rb +91 -0
  35. data/spec/actions/file_manipulation_spec.rb +242 -0
  36. data/spec/actions/inject_into_file_spec.rb +80 -0
  37. data/spec/actions_spec.rb +291 -0
  38. data/spec/base_spec.rb +236 -0
  39. data/spec/core_ext/hash_with_indifferent_access_spec.rb +43 -0
  40. data/spec/core_ext/ordered_hash_spec.rb +115 -0
  41. data/spec/fixtures/bundle/execute.rb +6 -0
  42. data/spec/fixtures/doc/config.rb +1 -0
  43. data/spec/group_spec.rb +177 -0
  44. data/spec/invocation_spec.rb +107 -0
  45. data/spec/parser/argument_spec.rb +47 -0
  46. data/spec/parser/arguments_spec.rb +64 -0
  47. data/spec/parser/option_spec.rb +212 -0
  48. data/spec/parser/options_spec.rb +255 -0
  49. data/spec/rake_compat_spec.rb +64 -0
  50. data/spec/runner_spec.rb +204 -0
  51. data/spec/shell/basic_spec.rb +206 -0
  52. data/spec/shell/color_spec.rb +41 -0
  53. data/spec/shell_spec.rb +25 -0
  54. data/spec/spec_helper.rb +52 -0
  55. data/spec/task_spec.rb +82 -0
  56. data/spec/thor_spec.rb +234 -0
  57. data/spec/util_spec.rb +196 -0
  58. metadata +69 -25
  59. data/README.markdown +0 -76
  60. data/Rakefile +0 -6
  61. data/lib/thor/options.rb +0 -242
  62. data/lib/thor/ordered_hash.rb +0 -64
  63. data/lib/thor/task_hash.rb +0 -22
  64. data/lib/thor/tasks.rb +0 -77
  65. data/lib/thor/tasks/package.rb +0 -18
data/lib/thor/shell.rb ADDED
@@ -0,0 +1,72 @@
1
+ require 'thor/shell/color'
2
+
3
+ class Thor
4
+ module Base
5
+ # Returns the shell used in all Thor classes. Default to color one.
6
+ #
7
+ def self.shell
8
+ @shell ||= Thor::Shell::Color
9
+ end
10
+
11
+ # Sets the shell used in all Thor classes.
12
+ #
13
+ def self.shell=(klass)
14
+ @shell = klass
15
+ end
16
+ end
17
+
18
+ module Shell
19
+ SHELL_DELEGATED_METHODS = [:ask, :yes?, :no?, :say, :say_status, :print_list, :print_table]
20
+
21
+ # Add shell to initialize config values.
22
+ #
23
+ # ==== Configuration
24
+ # shell<Object>:: An instance of the shell to be used.
25
+ #
26
+ # ==== Examples
27
+ #
28
+ # class MyScript < Thor
29
+ # argument :first, :type => :numeric
30
+ # end
31
+ #
32
+ # MyScript.new [1.0], { :foo => :bar }, :shell => Thor::Shell::Basic.new
33
+ #
34
+ def initialize(args=[], options={}, config={})
35
+ super
36
+ self.shell = config[:shell]
37
+ self.shell.base ||= self if self.shell.respond_to?(:base)
38
+ end
39
+
40
+ # Holds the shell for the given Thor instance. If no shell is given,
41
+ # it gets a default shell from Thor::Base.shell.
42
+ #
43
+ def shell
44
+ @shell ||= Thor::Base.shell.new
45
+ end
46
+
47
+ # Sets the shell for this thor class.
48
+ #
49
+ def shell=(shell)
50
+ @shell = shell
51
+ end
52
+
53
+ # Common methods that are delegated to the shell.
54
+ #
55
+ SHELL_DELEGATED_METHODS.each do |method|
56
+ module_eval <<-METHOD, __FILE__, __LINE__
57
+ def #{method}(*args)
58
+ shell.#{method}(*args)
59
+ end
60
+ METHOD
61
+ end
62
+
63
+ protected
64
+
65
+ # Allow shell to be shared between invocations.
66
+ #
67
+ def _shared_configuration #:nodoc:
68
+ super.merge!(:shell => self.shell)
69
+ end
70
+
71
+ end
72
+ end
@@ -0,0 +1,220 @@
1
+ require 'tempfile'
2
+
3
+ class Thor
4
+ module Shell
5
+ class Basic
6
+ attr_accessor :base, :padding
7
+
8
+ # Initialize base and padding to nil.
9
+ #
10
+ def initialize #:nodoc:
11
+ @base, @padding = nil, 0
12
+ end
13
+
14
+ # Sets the output padding, not allowing less than zero values.
15
+ #
16
+ def padding=(value)
17
+ @padding = [0, value].max
18
+ end
19
+
20
+ # Ask something to the user and receives a response.
21
+ #
22
+ # ==== Example
23
+ # ask("What is your name?")
24
+ #
25
+ def ask(statement, color=nil)
26
+ say("#{statement} ", color)
27
+ $stdin.gets.strip
28
+ end
29
+
30
+ # Say (print) something to the user. If the sentence ends with a whitespace
31
+ # or tab character, a new line is not appended (print + flush). Otherwise
32
+ # are passed straight to puts (behavior got from Highline).
33
+ #
34
+ # ==== Example
35
+ # say("I know you knew that.")
36
+ #
37
+ def say(message="", color=nil, force_new_line=false)
38
+ message = message.to_s
39
+ new_line = force_new_line || !(message[-1, 1] == " " || message[-1, 1] == "\t")
40
+ message = set_color(message, color) if color
41
+
42
+ if new_line
43
+ $stdout.puts(message)
44
+ else
45
+ $stdout.print(message)
46
+ $stdout.flush
47
+ end
48
+ end
49
+
50
+ # Say a status with the given color and appends the message. Since this
51
+ # method is used frequently by actions, it allows nil or false to be given
52
+ # in log_status, avoiding the message from being shown. If a Symbol is
53
+ # given in log_status, it's used as the color.
54
+ #
55
+ def say_status(status, message, log_status=true)
56
+ return if quiet? || log_status == false
57
+ spaces = " " * (padding + 1)
58
+ color = log_status.is_a?(Symbol) ? log_status : :green
59
+
60
+ status = status.to_s.rjust(12)
61
+ status = set_color status, color, true if color
62
+ say "#{status}#{spaces}#{message}", nil, true
63
+ end
64
+
65
+ # Make a question the to user and returns true if the user replies "y" or
66
+ # "yes".
67
+ #
68
+ def yes?(statement, color=nil)
69
+ ask(statement, color) =~ is?(:yes)
70
+ end
71
+
72
+ # Make a question the to user and returns true if the user replies "n" or
73
+ # "no".
74
+ #
75
+ def no?(statement, color=nil)
76
+ !yes?(statement, color)
77
+ end
78
+
79
+ # Prints a list of items.
80
+ #
81
+ # ==== Parameters
82
+ # list<Array[String, String, ...]>
83
+ #
84
+ # ==== Options
85
+ # mode:: Can be :rows or :inline. Defaults to :rows.
86
+ # ident:: Ident each item with the value given.
87
+ #
88
+ def print_list(list, options={})
89
+ return if list.empty?
90
+
91
+ ident = " " * (options[:ident] || 0)
92
+ content = case options[:mode]
93
+ when :inline
94
+ last = list.pop
95
+ "#{list.join(", ")}, and #{last}"
96
+ else # rows
97
+ ident + list.join("\n#{ident}")
98
+ end
99
+
100
+ $stdout.puts content
101
+ end
102
+
103
+ # Prints a table.
104
+ #
105
+ # ==== Parameters
106
+ # Array[Array[String, String, ...]]
107
+ #
108
+ # ==== Options
109
+ # ident<Integer>:: Ident the first column by ident value.
110
+ #
111
+ def print_table(table, options={})
112
+ return if table.empty?
113
+
114
+ formats = []
115
+ 0.upto(table.first.length - 2) do |i|
116
+ maxima = table.max{ |a,b| a[i].size <=> b[i].size }[i].size
117
+ formats << "%-#{maxima + 2}s"
118
+ end
119
+
120
+ formats[0] = formats[0].insert(0, " " * options[:ident]) if options[:ident]
121
+ formats << "%s"
122
+
123
+ table.each do |row|
124
+ row.each_with_index do |column, i|
125
+ $stdout.print formats[i] % column.to_s
126
+ end
127
+ $stdout.puts
128
+ end
129
+ end
130
+
131
+ # Deals with file collision and returns true if the file should be
132
+ # overwriten and false otherwise. If a block is given, it uses the block
133
+ # response as the content for the diff.
134
+ #
135
+ # ==== Parameters
136
+ # destination<String>:: the destination file to solve conflicts
137
+ # block<Proc>:: an optional block that returns the value to be used in diff
138
+ #
139
+ def file_collision(destination)
140
+ return true if @always_force
141
+ options = block_given? ? "[Ynaqdh]" : "[Ynaqh]"
142
+
143
+ while true
144
+ answer = ask %[Overwrite #{destination}? (enter "h" for help) #{options}]
145
+
146
+ case answer
147
+ when is?(:yes), is?(:force)
148
+ return true
149
+ when is?(:no), is?(:skip)
150
+ return false
151
+ when is?(:always)
152
+ return @always_force = true
153
+ when is?(:quit)
154
+ say 'Aborting...'
155
+ raise SystemExit
156
+ when is?(:diff)
157
+ show_diff(destination, yield) if block_given?
158
+ say 'Retrying...'
159
+ else
160
+ say file_collision_help
161
+ end
162
+ end
163
+ end
164
+
165
+ # Called if something goes wrong during the execution. This is used by Thor
166
+ # internally and should not be used inside your scripts. If someone went
167
+ # wrong, you can always raise an exception. If you raise a Thor::Error, it
168
+ # will be rescued and wrapped in the method below.
169
+ #
170
+ def error(statement)
171
+ $stderr.puts statement
172
+ end
173
+
174
+ # Apply color to the given string with optional bold. Disabled in the
175
+ # Thor::Shell::Basic class.
176
+ #
177
+ def set_color(string, color, bold=false) #:nodoc:
178
+ string
179
+ end
180
+
181
+ protected
182
+
183
+ def is?(value) #:nodoc:
184
+ value = value.to_s
185
+
186
+ if value.size == 1
187
+ /\A#{value}\z/i
188
+ else
189
+ /\A(#{value}|#{value[0,1]})\z/i
190
+ end
191
+ end
192
+
193
+ def file_collision_help #:nodoc:
194
+ <<HELP
195
+ Y - yes, overwrite
196
+ n - no, do not overwrite
197
+ a - all, overwrite this and all others
198
+ q - quit, abort
199
+ d - diff, show the differences between the old and the new
200
+ h - help, show this help
201
+ HELP
202
+ end
203
+
204
+ def show_diff(destination, content) #:nodoc:
205
+ diff_cmd = ENV['THOR_DIFF'] || ENV['RAILS_DIFF'] || 'diff -u'
206
+
207
+ Tempfile.open(File.basename(destination), File.dirname(destination)) do |temp|
208
+ temp.write content
209
+ temp.rewind
210
+ system %(#{diff_cmd} "#{destination}" "#{temp.path}")
211
+ end
212
+ end
213
+
214
+ def quiet? #:nodoc:
215
+ base && base.options[:quiet]
216
+ end
217
+
218
+ end
219
+ end
220
+ end
@@ -0,0 +1,108 @@
1
+ require 'thor/shell/basic'
2
+
3
+ class Thor
4
+ module Shell
5
+ # Inherit from Thor::Shell::Basic and add set_color behavior. Check
6
+ # Thor::Shell::Basic to see all available methods.
7
+ #
8
+ class Color < Basic
9
+ # Embed in a String to clear all previous ANSI sequences.
10
+ CLEAR = "\e[0m"
11
+ # The start of an ANSI bold sequence.
12
+ BOLD = "\e[1m"
13
+
14
+ # Set the terminal's foreground ANSI color to black.
15
+ BLACK = "\e[30m"
16
+ # Set the terminal's foreground ANSI color to red.
17
+ RED = "\e[31m"
18
+ # Set the terminal's foreground ANSI color to green.
19
+ GREEN = "\e[32m"
20
+ # Set the terminal's foreground ANSI color to yellow.
21
+ YELLOW = "\e[33m"
22
+ # Set the terminal's foreground ANSI color to blue.
23
+ BLUE = "\e[34m"
24
+ # Set the terminal's foreground ANSI color to magenta.
25
+ MAGENTA = "\e[35m"
26
+ # Set the terminal's foreground ANSI color to cyan.
27
+ CYAN = "\e[36m"
28
+ # Set the terminal's foreground ANSI color to white.
29
+ WHITE = "\e[37m"
30
+
31
+ # Set the terminal's background ANSI color to black.
32
+ ON_BLACK = "\e[40m"
33
+ # Set the terminal's background ANSI color to red.
34
+ ON_RED = "\e[41m"
35
+ # Set the terminal's background ANSI color to green.
36
+ ON_GREEN = "\e[42m"
37
+ # Set the terminal's background ANSI color to yellow.
38
+ ON_YELLOW = "\e[43m"
39
+ # Set the terminal's background ANSI color to blue.
40
+ ON_BLUE = "\e[44m"
41
+ # Set the terminal's background ANSI color to magenta.
42
+ ON_MAGENTA = "\e[45m"
43
+ # Set the terminal's background ANSI color to cyan.
44
+ ON_CYAN = "\e[46m"
45
+ # Set the terminal's background ANSI color to white.
46
+ ON_WHITE = "\e[47m"
47
+
48
+ # Set color by using a string or one of the defined constants. If a third
49
+ # option is set to true, it also adds bold to the string. This is based
50
+ # on Highline implementation and it automatically appends CLEAR to the end
51
+ # of the returned String.
52
+ #
53
+ def set_color(string, color, bold=false)
54
+ color = self.class.const_get(color.to_s.upcase) if color.is_a?(Symbol)
55
+ bold = bold ? BOLD : ""
56
+ "#{bold}#{color}#{string}#{CLEAR}"
57
+ end
58
+
59
+ protected
60
+
61
+ # Overwrite show_diff to show diff with colors if Diff::LCS is
62
+ # available.
63
+ #
64
+ def show_diff(destination, content) #:nodoc:
65
+ if diff_lcs_loaded? && ENV['THOR_DIFF'].nil? && ENV['RAILS_DIFF'].nil?
66
+ actual = File.read(destination).to_s.split("\n")
67
+ content = content.to_s.split("\n")
68
+
69
+ Diff::LCS.sdiff(actual, content).each do |diff|
70
+ output_diff_line(diff)
71
+ end
72
+ else
73
+ super
74
+ end
75
+ end
76
+
77
+ def output_diff_line(diff) #:nodoc:
78
+ case diff.action
79
+ when '-'
80
+ say "- #{diff.old_element.chomp}", :red, true
81
+ when '+'
82
+ say "+ #{diff.new_element.chomp}", :green, true
83
+ when '!'
84
+ say "- #{diff.old_element.chomp}", :red, true
85
+ say "+ #{diff.new_element.chomp}", :green, true
86
+ else
87
+ say " #{diff.old_element.chomp}", nil, true
88
+ end
89
+ end
90
+
91
+ # Check if Diff::LCS is loaded. If it is, use it to create pretty output
92
+ # for diff.
93
+ #
94
+ def diff_lcs_loaded? #:nodoc:
95
+ return true if defined?(Diff::LCS)
96
+ return @diff_lcs_loaded unless @diff_lcs_loaded.nil?
97
+
98
+ @diff_lcs_loaded = begin
99
+ require 'diff/lcs'
100
+ true
101
+ rescue LoadError
102
+ false
103
+ end
104
+ end
105
+
106
+ end
107
+ end
108
+ end
data/lib/thor/task.rb CHANGED
@@ -1,79 +1,116 @@
1
- require 'thor/error'
2
- require 'thor/util'
3
-
4
1
  class Thor
5
- class Task < Struct.new(:meth, :description, :usage, :opts, :klass)
6
-
7
- def self.dynamic(meth, klass)
8
- new(meth, "A dynamically-generated task", meth.to_s, nil, klass)
2
+ class Task < Struct.new(:name, :description, :usage, :options)
3
+
4
+ # Creates a dynamic task. Dynamic tasks are created on demand to allow method
5
+ # missing calls (since a method missing does not have a task object for it).
6
+ #
7
+ def self.dynamic(name)
8
+ new(name, "A dynamically-generated task", name.to_s)
9
+ end
10
+
11
+ def initialize(name, description, usage, options=nil)
12
+ super(name.to_s, description, usage, options || {})
9
13
  end
10
-
11
- def initialize(*args)
12
- # keep the original opts - we need them later on
13
- @options = args[3] || {}
14
- super
14
+
15
+ def initialize_copy(other) #:nodoc:
16
+ super(other)
17
+ self.options = other.options.dup if other.options
15
18
  end
16
19
 
17
- def parse(obj, args)
18
- list, hash = parse_args(args)
19
- obj.options = hash
20
- run(obj, *list)
20
+ def short_description
21
+ description.split("\n").first if description
21
22
  end
22
23
 
23
- def run(obj, *params)
24
- raise NoMethodError, "the `#{meth}' task of #{obj.class} is private" if
25
- (obj.private_methods + obj.protected_methods).include?(meth)
26
-
27
- obj.send(meth, *params)
24
+ # By default, a task invokes a method in the thor class. You can change this
25
+ # implementation to create custom tasks.
26
+ #
27
+ def run(instance, args=[])
28
+ raise UndefinedTaskError, "the '#{name}' task of #{instance.class} is private" unless public_method?(instance)
29
+ instance.send(name, *args)
28
30
  rescue ArgumentError => e
29
- # backtrace sans anything in this file
30
- backtrace = e.backtrace.reject {|frame| frame =~ /^#{Regexp.escape(__FILE__)}/}
31
- # and sans anything that got us here
32
- backtrace -= caller
33
- raise e unless backtrace.empty?
34
-
35
- # okay, they really did call it wrong
36
- raise Error, "`#{meth}' was called incorrectly. Call as `#{formatted_usage}'"
31
+ parse_argument_error(instance, e, caller)
37
32
  rescue NoMethodError => e
38
- begin
39
- raise e unless e.message =~ /^undefined method `#{meth}' for #{Regexp.escape(obj.inspect)}$/
40
- rescue
41
- raise e
42
- end
43
- raise Error, "The #{namespace false} namespace doesn't have a `#{meth}' task"
33
+ parse_no_method_error(instance, e)
44
34
  end
45
35
 
46
- def namespace(remove_default = true)
47
- Thor::Util.constant_to_thor_path(klass, remove_default)
48
- end
36
+ # Returns the formatted usage. If a class is given, the class arguments are
37
+ # injected in the usage.
38
+ #
39
+ def formatted_usage(klass=nil, namespace=false, show_options=true)
40
+ formatted = ''
49
41
 
50
- def with_klass(klass)
51
- new = self.dup
52
- new.klass = klass
53
- new
54
- end
55
-
56
- def opts
57
- return super unless super.kind_of? Hash
58
- @_opts ||= Options.new(super)
42
+ formatted = if namespace.is_a?(String)
43
+ "#{namespace}:"
44
+ elsif klass && namespace
45
+ "#{klass.namespace.gsub(/^default/,'')}:"
46
+ else
47
+ ""
48
+ end
49
+
50
+ formatted << formatted_arguments(klass)
51
+ formatted << " #{formatted_options}" if show_options
52
+ formatted.strip!
53
+ formatted
59
54
  end
60
-
61
- def full_opts
62
- @_full_opts ||= Options.new((klass.opts || {}).merge(@options))
55
+
56
+ # Injects the class arguments into the task usage.
57
+ #
58
+ def formatted_arguments(klass)
59
+ if klass && !klass.arguments.empty?
60
+ usage.to_s.gsub(/^#{name}/) do |match|
61
+ match << " " << klass.arguments.map{ |a| a.usage }.join(' ')
62
+ end
63
+ else
64
+ usage.to_s
65
+ end
63
66
  end
64
-
65
- def formatted_usage(namespace = false)
66
- (namespace ? self.namespace + ':' : '') + usage +
67
- (opts ? " " + opts.formatted_usage : "")
67
+
68
+ # Returns the options usage for this task.
69
+ #
70
+ def formatted_options
71
+ @formatted_options ||= options.map{ |_, o| o.usage }.sort.join(" ")
68
72
  end
69
73
 
70
74
  protected
71
75
 
72
- def parse_args(args)
73
- return [[], {}] if args.nil?
74
- hash = full_opts.parse(args)
75
- list = full_opts.non_opts
76
- [list, hash]
77
- end
76
+ # Given a target, checks if this class name is not a private/protected method.
77
+ #
78
+ def public_method?(instance) #:nodoc:
79
+ collection = instance.private_methods + instance.protected_methods
80
+ !(collection).include?(name.to_s) && !(collection).include?(name.to_sym) # For Ruby 1.9
81
+ end
82
+
83
+ # Clean everything that comes from the Thor gempath and remove the caller.
84
+ #
85
+ def sans_backtrace(backtrace, caller) #:nodoc:
86
+ dirname = /^#{Regexp.escape(File.dirname(__FILE__))}/
87
+ saned = backtrace.reject { |frame| frame =~ dirname }
88
+ saned -= caller
89
+ end
90
+
91
+ def parse_argument_error(instance, e, caller) #:nodoc:
92
+ backtrace = sans_backtrace(e.backtrace, caller)
93
+
94
+ if backtrace.empty? && e.message =~ /wrong number of arguments/
95
+ if instance.is_a?(Thor::Group)
96
+ raise e, "'#{name}' was called incorrectly. Are you sure it has arity equals to 0?"
97
+ else
98
+ raise InvocationError, "'#{name}' was called incorrectly. Call as " <<
99
+ "'#{formatted_usage(instance.class, true)}'"
100
+ end
101
+ else
102
+ raise e
103
+ end
104
+ end
105
+
106
+ def parse_no_method_error(instance, e) #:nodoc:
107
+ if e.message =~ /^undefined method `#{name}' for #{Regexp.escape(instance.to_s)}$/
108
+ raise UndefinedTaskError, "The #{instance.class.namespace} namespace " <<
109
+ "doesn't have a '#{name}' task"
110
+ else
111
+ raise e
112
+ end
113
+ end
114
+
78
115
  end
79
116
  end