wycats-thor 0.9.8 → 0.10.26

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,221 @@
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
+ # Do not allow padding to be less than zero.
15
+ #
16
+ def padding=(value) #:nodoc:
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) #:nodoc:
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
+ # mode<Symbol>:: Can be :rows or :inline. Defaults to :rows.
84
+ #
85
+ def print_list(list, mode=:rows)
86
+ return if list.empty?
87
+
88
+ content = case mode
89
+ when :inline
90
+ last = list.pop
91
+ "#{list.join(", ")}, and #{last}"
92
+ else # rows
93
+ list.join("\n")
94
+ end
95
+
96
+ $stdout.puts content
97
+ end
98
+
99
+ # Prints a table.
100
+ #
101
+ # ==== Parameters
102
+ # Array[Array[String, String, ...]]
103
+ #
104
+ # ==== Options
105
+ # ident<Integer>:: Ident the first column by ident value.
106
+ # emphasize_last<Boolean>:: When true, add a different behavior to the last column.
107
+ #
108
+ def print_table(table, options={})
109
+ return if table.empty?
110
+
111
+ formats = []
112
+ 0.upto(table.first.length - 2) do |i|
113
+ maxima = table.max{ |a,b| a[i].size <=> b[i].size }[i].size
114
+ formats << "%-#{maxima + 2}s"
115
+ end
116
+
117
+ formats[0] = formats[0].insert(0, " " * options[:ident]) if options[:ident]
118
+ formats << "%s"
119
+
120
+ if options[:emphasize_last]
121
+ table.each do |row|
122
+ next if row[-1].empty?
123
+ row[-1] = "# #{row[-1]}"
124
+ end
125
+ end
126
+
127
+ table.each do |row|
128
+ row.each_with_index do |column, i|
129
+ $stdout.print formats[i] % column.to_s
130
+ end
131
+ $stdout.puts
132
+ end
133
+ end
134
+
135
+ # Deals with file collision and returns true if the file should be
136
+ # overwriten and false otherwise. If a block is given, it uses the block
137
+ # response as the content for the diff.
138
+ #
139
+ # ==== Parameters
140
+ # destination<String>:: the destination file to solve conflicts
141
+ # block<Proc>:: an optional proc that returns the value to be used in diff
142
+ #
143
+ def file_collision(destination)
144
+ return true if @always_force
145
+ options = block_given? ? "[Ynaqdh]" : "[Ynaqh]"
146
+
147
+ while true
148
+ answer = ask %[Overwrite #{destination}? (enter "h" for help) #{options}]
149
+
150
+ case answer
151
+ when is?(:yes), is?(:force)
152
+ return true
153
+ when is?(:no), is?(:skip)
154
+ return false
155
+ when is?(:always)
156
+ return @always_force = true
157
+ when is?(:quit)
158
+ say 'Aborting...'
159
+ raise SystemExit
160
+ when is?(:diff)
161
+ show_diff(destination, yield) if block_given?
162
+ say 'Retrying...'
163
+ else
164
+ say file_collision_help
165
+ end
166
+ end
167
+ end
168
+
169
+ # Called if something goes wrong during the execution. This is used by Thor
170
+ # internally and should not be used inside your scripts. If someone went
171
+ # wrong, you can always raise an exception. If you raise a Thor::Error, it
172
+ # will be rescued and wrapped in the method below.
173
+ #
174
+ def error(statement) #:nodoc:
175
+ $stderr.puts statement
176
+ end
177
+
178
+ protected
179
+
180
+ def set_color(string, color, bold=false)
181
+ string
182
+ end
183
+
184
+ def is?(value)
185
+ value = value.to_s
186
+
187
+ if value.size == 1
188
+ /\A#{value}\z/i
189
+ else
190
+ /\A(#{value}|#{value[0,1]})\z/i
191
+ end
192
+ end
193
+
194
+ def file_collision_help
195
+ <<HELP
196
+ Y - yes, overwrite
197
+ n - no, do not overwrite
198
+ a - all, overwrite this and all others
199
+ q - quit, abort
200
+ d - diff, show the differences between the old and the new
201
+ h - help, show this help
202
+ HELP
203
+ end
204
+
205
+ def show_diff(destination, content)
206
+ diff_cmd = ENV['THOR_DIFF'] || ENV['RAILS_DIFF'] || 'diff -u'
207
+
208
+ Tempfile.open(File.basename(destination), File.dirname(destination)) do |temp|
209
+ temp.write content
210
+ temp.rewind
211
+ say `#{diff_cmd} "#{destination}" "#{temp.path}"`
212
+ end
213
+ end
214
+
215
+ def quiet?
216
+ base && base.options[:quiet]
217
+ end
218
+
219
+ end
220
+ end
221
+ end
@@ -0,0 +1,106 @@
1
+ require 'thor/shell/basic'
2
+
3
+ class Thor
4
+ module Shell
5
+ # Set color in the output. Got color values from HighLine.
6
+ #
7
+ class Color < Basic
8
+ # Embed in a String to clear all previous ANSI sequences.
9
+ CLEAR = "\e[0m"
10
+ # The start of an ANSI bold sequence.
11
+ BOLD = "\e[1m"
12
+
13
+ # Set the terminal's foreground ANSI color to black.
14
+ BLACK = "\e[30m"
15
+ # Set the terminal's foreground ANSI color to red.
16
+ RED = "\e[31m"
17
+ # Set the terminal's foreground ANSI color to green.
18
+ GREEN = "\e[32m"
19
+ # Set the terminal's foreground ANSI color to yellow.
20
+ YELLOW = "\e[33m"
21
+ # Set the terminal's foreground ANSI color to blue.
22
+ BLUE = "\e[34m"
23
+ # Set the terminal's foreground ANSI color to magenta.
24
+ MAGENTA = "\e[35m"
25
+ # Set the terminal's foreground ANSI color to cyan.
26
+ CYAN = "\e[36m"
27
+ # Set the terminal's foreground ANSI color to white.
28
+ WHITE = "\e[37m"
29
+
30
+ # Set the terminal's background ANSI color to black.
31
+ ON_BLACK = "\e[40m"
32
+ # Set the terminal's background ANSI color to red.
33
+ ON_RED = "\e[41m"
34
+ # Set the terminal's background ANSI color to green.
35
+ ON_GREEN = "\e[42m"
36
+ # Set the terminal's background ANSI color to yellow.
37
+ ON_YELLOW = "\e[43m"
38
+ # Set the terminal's background ANSI color to blue.
39
+ ON_BLUE = "\e[44m"
40
+ # Set the terminal's background ANSI color to magenta.
41
+ ON_MAGENTA = "\e[45m"
42
+ # Set the terminal's background ANSI color to cyan.
43
+ ON_CYAN = "\e[46m"
44
+ # Set the terminal's background ANSI color to white.
45
+ ON_WHITE = "\e[47m"
46
+
47
+ protected
48
+
49
+ # Set color by using a string or one of the defined constants. Based
50
+ # on Highline implementation. CLEAR is automatically be embedded to
51
+ # the end 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
+ # Overwrite show_diff to show diff with colors if Diff::LCS is
60
+ # available.
61
+ #
62
+ def show_diff(destination, content)
63
+ if diff_lcs_loaded? && ENV['THOR_DIFF'].nil? && ENV['RAILS_DIFF'].nil?
64
+ actual = File.read(destination).to_s.split("\n")
65
+ content = content.to_s.split("\n")
66
+
67
+ Diff::LCS.sdiff(actual, content).each do |diff|
68
+ output_diff_line(diff)
69
+ end
70
+ else
71
+ super
72
+ end
73
+ end
74
+
75
+ def output_diff_line(diff)
76
+ case diff.action
77
+ when '-'
78
+ say "- #{diff.old_element.chomp}", :red
79
+ when '+'
80
+ say "+ #{diff.new_element.chomp}", :green
81
+ when '!'
82
+ say "- #{diff.old_element.chomp}", :red
83
+ say "+ #{diff.new_element.chomp}", :green
84
+ else
85
+ say " #{diff.old_element.chomp}"
86
+ end
87
+ end
88
+
89
+ # Check if Diff::LCS is loaded. If it is, use it to create pretty output
90
+ # for diff.
91
+ #
92
+ def diff_lcs_loaded?
93
+ return true if defined?(Diff::LCS)
94
+ return @diff_lcs_loaded unless @diff_lcs_loaded.nil?
95
+
96
+ @diff_lcs_loaded = begin
97
+ require 'diff/lcs'
98
+ true
99
+ rescue LoadError
100
+ false
101
+ end
102
+ end
103
+
104
+ end
105
+ end
106
+ end
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
68
+ super.merge!(:shell => self.shell)
69
+ end
70
+
71
+ end
72
+ end
data/lib/thor/task.rb CHANGED
@@ -1,79 +1,108 @@
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
9
  end
10
-
11
- def initialize(*args)
12
- # keep the original opts - we need them later on
13
- @options = args[3] || {}
14
- super
10
+
11
+ def initialize(name, description, usage, options=nil)
12
+ super(name.to_s, description, usage, options || {})
13
+ end
14
+
15
+ def initialize_copy(other)
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)
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)
40
+ formatted = ''
41
+ formatted << "#{klass.namespace.gsub(/^default/,'')}:" if klass && namespace
42
+ formatted << formatted_arguments(klass)
43
+ formatted << " #{formatted_options}"
44
+ formatted.strip!
45
+ formatted
48
46
  end
49
47
 
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)
59
- end
60
-
61
- def full_opts
62
- @_full_opts ||= Options.new((klass.opts || {}).merge(@options))
48
+ # Injects the class arguments into the task usage.
49
+ #
50
+ def formatted_arguments(klass)
51
+ if klass && !klass.arguments.empty?
52
+ usage.to_s.gsub(/^#{name}/) do |match|
53
+ match << " " << klass.arguments.map{ |a| a.usage }.join(' ')
54
+ end
55
+ else
56
+ usage.to_s
57
+ end
63
58
  end
64
-
65
- def formatted_usage(namespace = false)
66
- (namespace ? self.namespace + ':' : '') + usage +
67
- (opts ? " " + opts.formatted_usage : "")
59
+
60
+ # Returns the options usage for this task.
61
+ #
62
+ def formatted_options
63
+ @formatted_options ||= options.map{ |_, o| o.usage }.sort.join(" ")
68
64
  end
69
65
 
70
66
  protected
71
67
 
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
68
+ # Given a target, checks if this class name is not a private/protected method.
69
+ #
70
+ def public_method?(instance)
71
+ collection = instance.private_methods + instance.protected_methods
72
+ !(collection).include?(name.to_s) && !(collection).include?(name.to_sym) # For Ruby 1.9
73
+ end
74
+
75
+ # Clean everything that comes from the Thor gempath and remove the caller.
76
+ #
77
+ def sans_backtrace(backtrace, caller)
78
+ dirname = /^#{Regexp.escape(File.dirname(__FILE__))}/
79
+ saned = backtrace.reject { |frame| frame =~ dirname }
80
+ saned -= caller
81
+ end
82
+
83
+ def parse_argument_error(instance, e, caller)
84
+ backtrace = sans_backtrace(e.backtrace, caller)
85
+
86
+ if backtrace.empty? && e.message =~ /wrong number of arguments/
87
+ if instance.is_a?(Thor::Group)
88
+ raise e, "'#{name}' was called incorrectly. Are you sure it has arity equals to 0?"
89
+ else
90
+ raise InvocationError, "'#{name}' was called incorrectly. Call as " <<
91
+ "'#{formatted_usage(instance.class, true)}'"
92
+ end
93
+ else
94
+ raise e
95
+ end
96
+ end
97
+
98
+ def parse_no_method_error(instance, e)
99
+ if e.message =~ /^undefined method `#{name}' for #{Regexp.escape(instance.to_s)}$/
100
+ raise UndefinedTaskError, "The #{instance.class.namespace} namespace " <<
101
+ "doesn't have a '#{name}' task"
102
+ else
103
+ raise e
104
+ end
105
+ end
106
+
78
107
  end
79
108
  end