wtch 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,297 @@
1
+ require 'fileutils'
2
+ require 'uri'
3
+ require 'thor/core_ext/file_binary_read'
4
+
5
+ Dir[File.join(File.dirname(__FILE__), "actions", "*.rb")].each do |action|
6
+ require action
7
+ end
8
+
9
+ class Thor
10
+ module Actions
11
+ attr_accessor :behavior
12
+
13
+ def self.included(base) #:nodoc:
14
+ base.extend ClassMethods
15
+ end
16
+
17
+ module ClassMethods
18
+ # Hold source paths for one Thor instance. source_paths_for_search is the
19
+ # method responsible to gather source_paths from this current class,
20
+ # inherited paths and the source root.
21
+ #
22
+ def source_paths
23
+ @_source_paths ||= []
24
+ end
25
+
26
+ # Stores and return the source root for this class
27
+ def source_root(path=nil)
28
+ @_source_root = path if path
29
+ @_source_root
30
+ end
31
+
32
+ # Returns the source paths in the following order:
33
+ #
34
+ # 1) This class source paths
35
+ # 2) Source root
36
+ # 3) Parents source paths
37
+ #
38
+ def source_paths_for_search
39
+ paths = []
40
+ paths += self.source_paths
41
+ paths << self.source_root if self.source_root
42
+ paths += from_superclass(:source_paths, [])
43
+ paths
44
+ end
45
+
46
+ # Add runtime options that help actions execution.
47
+ #
48
+ def add_runtime_options!
49
+ class_option :force, :type => :boolean, :aliases => "-f", :group => :runtime,
50
+ :desc => "Overwrite files that already exist"
51
+
52
+ class_option :pretend, :type => :boolean, :aliases => "-p", :group => :runtime,
53
+ :desc => "Run but do not make any changes"
54
+
55
+ class_option :quiet, :type => :boolean, :aliases => "-q", :group => :runtime,
56
+ :desc => "Supress status output"
57
+
58
+ class_option :skip, :type => :boolean, :aliases => "-s", :group => :runtime,
59
+ :desc => "Skip files that already exist"
60
+ end
61
+ end
62
+
63
+ # Extends initializer to add more configuration options.
64
+ #
65
+ # ==== Configuration
66
+ # behavior<Symbol>:: The actions default behavior. Can be :invoke or :revoke.
67
+ # It also accepts :force, :skip and :pretend to set the behavior
68
+ # and the respective option.
69
+ #
70
+ # destination_root<String>:: The root directory needed for some actions.
71
+ #
72
+ def initialize(args=[], options={}, config={})
73
+ self.behavior = case config[:behavior].to_s
74
+ when "force", "skip"
75
+ _cleanup_options_and_set(options, config[:behavior])
76
+ :invoke
77
+ when "revoke"
78
+ :revoke
79
+ else
80
+ :invoke
81
+ end
82
+
83
+ super
84
+ self.destination_root = config[:destination_root]
85
+ end
86
+
87
+ # Wraps an action object and call it accordingly to the thor class behavior.
88
+ #
89
+ def action(instance) #:nodoc:
90
+ if behavior == :revoke
91
+ instance.revoke!
92
+ else
93
+ instance.invoke!
94
+ end
95
+ end
96
+
97
+ # Returns the root for this thor class (also aliased as destination root).
98
+ #
99
+ def destination_root
100
+ @destination_stack.last
101
+ end
102
+
103
+ # Sets the root for this thor class. Relatives path are added to the
104
+ # directory where the script was invoked and expanded.
105
+ #
106
+ def destination_root=(root)
107
+ @destination_stack ||= []
108
+ @destination_stack[0] = File.expand_path(root || '')
109
+ end
110
+
111
+ # Returns the given path relative to the absolute root (ie, root where
112
+ # the script started).
113
+ #
114
+ def relative_to_original_destination_root(path, remove_dot=true)
115
+ path = path.gsub(@destination_stack[0], '.')
116
+ remove_dot ? (path[2..-1] || '') : path
117
+ end
118
+
119
+ # Holds source paths in instance so they can be manipulated.
120
+ #
121
+ def source_paths
122
+ @source_paths ||= self.class.source_paths_for_search
123
+ end
124
+
125
+ # Receives a file or directory and search for it in the source paths.
126
+ #
127
+ def find_in_source_paths(file)
128
+ relative_root = relative_to_original_destination_root(destination_root, false)
129
+
130
+ source_paths.each do |source|
131
+ source_file = File.expand_path(file, File.join(source, relative_root))
132
+ return source_file if File.exists?(source_file)
133
+ end
134
+
135
+ message = "Could not find #{file.inspect} in any of your source paths. "
136
+
137
+ unless self.class.source_root
138
+ message << "Please invoke #{self.class.name}.source_root(PATH) with the PATH containing your templates. "
139
+ end
140
+
141
+ if source_paths.empty?
142
+ message << "Currently you have no source paths."
143
+ else
144
+ message << "Your current source paths are: \n#{source_paths.join("\n")}"
145
+ end
146
+
147
+ raise Error, message
148
+ end
149
+
150
+ # Do something in the root or on a provided subfolder. If a relative path
151
+ # is given it's referenced from the current root. The full path is yielded
152
+ # to the block you provide. The path is set back to the previous path when
153
+ # the method exits.
154
+ #
155
+ # ==== Parameters
156
+ # dir<String>:: the directory to move to.
157
+ # config<Hash>:: give :verbose => true to log and use padding.
158
+ #
159
+ def inside(dir='', config={}, &block)
160
+ verbose = config.fetch(:verbose, false)
161
+
162
+ say_status :inside, dir, verbose
163
+ shell.padding += 1 if verbose
164
+ @destination_stack.push File.expand_path(dir, destination_root)
165
+
166
+ FileUtils.mkdir_p(destination_root) unless File.exist?(destination_root)
167
+ FileUtils.cd(destination_root) { block.arity == 1 ? yield(destination_root) : yield }
168
+
169
+ @destination_stack.pop
170
+ shell.padding -= 1 if verbose
171
+ end
172
+
173
+ # Goes to the root and execute the given block.
174
+ #
175
+ def in_root
176
+ inside(@destination_stack.first) { yield }
177
+ end
178
+
179
+ # Loads an external file and execute it in the instance binding.
180
+ #
181
+ # ==== Parameters
182
+ # path<String>:: The path to the file to execute. Can be a web address or
183
+ # a relative path from the source root.
184
+ #
185
+ # ==== Examples
186
+ #
187
+ # apply "http://gist.github.com/103208"
188
+ #
189
+ # apply "recipes/jquery.rb"
190
+ #
191
+ def apply(path, config={})
192
+ verbose = config.fetch(:verbose, true)
193
+ is_uri = path =~ /^https?\:\/\//
194
+ path = find_in_source_paths(path) unless is_uri
195
+
196
+ say_status :apply, path, verbose
197
+ shell.padding += 1 if verbose
198
+
199
+ if is_uri
200
+ contents = open(path, "Accept" => "application/x-thor-template") {|io| io.read }
201
+ else
202
+ contents = open(path) {|io| io.read }
203
+ end
204
+
205
+ instance_eval(contents, path)
206
+ shell.padding -= 1 if verbose
207
+ end
208
+
209
+ # Executes a command returning the contents of the command.
210
+ #
211
+ # ==== Parameters
212
+ # command<String>:: the command to be executed.
213
+ # config<Hash>:: give :verbose => false to not log the status. Specify :with
214
+ # to append an executable to command executation.
215
+ #
216
+ # ==== Example
217
+ #
218
+ # inside('vendor') do
219
+ # run('ln -s ~/edge rails')
220
+ # end
221
+ #
222
+ def run(command, config={})
223
+ return unless behavior == :invoke
224
+
225
+ destination = relative_to_original_destination_root(destination_root, false)
226
+ desc = "#{command} from #{destination.inspect}"
227
+
228
+ if config[:with]
229
+ desc = "#{File.basename(config[:with].to_s)} #{desc}"
230
+ command = "#{config[:with]} #{command}"
231
+ end
232
+
233
+ say_status :run, desc, config.fetch(:verbose, true)
234
+ `#{command}` unless options[:pretend]
235
+ end
236
+
237
+ # Executes a ruby script (taking into account WIN32 platform quirks).
238
+ #
239
+ # ==== Parameters
240
+ # command<String>:: the command to be executed.
241
+ # config<Hash>:: give :verbose => false to not log the status.
242
+ #
243
+ def run_ruby_script(command, config={})
244
+ return unless behavior == :invoke
245
+ run command, config.merge(:with => Thor::Util.ruby_command)
246
+ end
247
+
248
+ # Run a thor command. A hash of options can be given and it's converted to
249
+ # switches.
250
+ #
251
+ # ==== Parameters
252
+ # task<String>:: the task to be invoked
253
+ # args<Array>:: arguments to the task
254
+ # config<Hash>:: give :verbose => false to not log the status. Other options
255
+ # are given as parameter to Thor.
256
+ #
257
+ # ==== Examples
258
+ #
259
+ # thor :install, "http://gist.github.com/103208"
260
+ # #=> thor install http://gist.github.com/103208
261
+ #
262
+ # thor :list, :all => true, :substring => 'rails'
263
+ # #=> thor list --all --substring=rails
264
+ #
265
+ def thor(task, *args)
266
+ config = args.last.is_a?(Hash) ? args.pop : {}
267
+ verbose = config.key?(:verbose) ? config.delete(:verbose) : true
268
+ pretend = config.key?(:pretend) ? config.delete(:pretend) : false
269
+
270
+ args.unshift task
271
+ args.push Thor::Options.to_switches(config)
272
+ command = args.join(' ').strip
273
+
274
+ run command, :with => :thor, :verbose => verbose, :pretend => pretend
275
+ end
276
+
277
+ protected
278
+
279
+ # Allow current root to be shared between invocations.
280
+ #
281
+ def _shared_configuration #:nodoc:
282
+ super.merge!(:destination_root => self.destination_root)
283
+ end
284
+
285
+ def _cleanup_options_and_set(options, key) #:nodoc:
286
+ case options
287
+ when Array
288
+ %w(--force -f --skip -s).each { |i| options.delete(i) }
289
+ options << "--#{key}"
290
+ when Hash
291
+ [:force, :skip, "force", "skip"].each { |i| options.delete(i) }
292
+ options.merge!(key => true)
293
+ end
294
+ end
295
+
296
+ end
297
+ end
@@ -0,0 +1,105 @@
1
+ require 'thor/actions/empty_directory'
2
+
3
+ class Thor
4
+ module Actions
5
+
6
+ # Create a new file relative to the destination root with the given data,
7
+ # which is the return value of a block or a data string.
8
+ #
9
+ # ==== Parameters
10
+ # destination<String>:: the relative path to the destination root.
11
+ # data<String|NilClass>:: the data to append to the file.
12
+ # config<Hash>:: give :verbose => false to not log the status.
13
+ #
14
+ # ==== Examples
15
+ #
16
+ # create_file "lib/fun_party.rb" do
17
+ # hostname = ask("What is the virtual hostname I should use?")
18
+ # "vhost.name = #{hostname}"
19
+ # end
20
+ #
21
+ # create_file "config/apach.conf", "your apache config"
22
+ #
23
+ def create_file(destination, *args, &block)
24
+ config = args.last.is_a?(Hash) ? args.pop : {}
25
+ data = args.first
26
+ action CreateFile.new(self, destination, block || data.to_s, config)
27
+ end
28
+ alias :add_file :create_file
29
+
30
+ # AddFile is a subset of Template, which instead of rendering a file with
31
+ # ERB, it gets the content from the user.
32
+ #
33
+ class CreateFile < EmptyDirectory #:nodoc:
34
+ attr_reader :data
35
+
36
+ def initialize(base, destination, data, config={})
37
+ @data = data
38
+ super(base, destination, config)
39
+ end
40
+
41
+ # Checks if the content of the file at the destination is identical to the rendered result.
42
+ #
43
+ # ==== Returns
44
+ # Boolean:: true if it is identical, false otherwise.
45
+ #
46
+ def identical?
47
+ exists? && File.binread(destination) == render
48
+ end
49
+
50
+ # Holds the content to be added to the file.
51
+ #
52
+ def render
53
+ @render ||= if data.is_a?(Proc)
54
+ data.call
55
+ else
56
+ data
57
+ end
58
+ end
59
+
60
+ def invoke!
61
+ invoke_with_conflict_check do
62
+ FileUtils.mkdir_p(File.dirname(destination))
63
+ File.open(destination, 'wb') { |f| f.write render }
64
+ end
65
+ given_destination
66
+ end
67
+
68
+ protected
69
+
70
+ # Now on conflict we check if the file is identical or not.
71
+ #
72
+ def on_conflict_behavior(&block)
73
+ if identical?
74
+ say_status :identical, :blue
75
+ else
76
+ options = base.options.merge(config)
77
+ force_or_skip_or_conflict(options[:force], options[:skip], &block)
78
+ end
79
+ end
80
+
81
+ # If force is true, run the action, otherwise check if it's not being
82
+ # skipped. If both are false, show the file_collision menu, if the menu
83
+ # returns true, force it, otherwise skip.
84
+ #
85
+ def force_or_skip_or_conflict(force, skip, &block)
86
+ if force
87
+ say_status :force, :yellow
88
+ block.call unless pretend?
89
+ elsif skip
90
+ say_status :skip, :yellow
91
+ else
92
+ say_status :conflict, :red
93
+ force_or_skip_or_conflict(force_on_collision?, true, &block)
94
+ end
95
+ end
96
+
97
+ # Shows the file collision menu to the user and gets the result.
98
+ #
99
+ def force_on_collision?
100
+ base.shell.file_collision(destination){ render }
101
+ end
102
+
103
+ end
104
+ end
105
+ end
@@ -0,0 +1,93 @@
1
+ require 'thor/actions/empty_directory'
2
+
3
+ class Thor
4
+ module Actions
5
+
6
+ # Copies recursively the files from source directory to root directory.
7
+ # If any of the files finishes with .tt, it's considered to be a template
8
+ # and is placed in the destination without the extension .tt. If any
9
+ # empty directory is found, it's copied and all .empty_directory files are
10
+ # ignored. Remember that file paths can also be encoded, let's suppose a doc
11
+ # directory with the following files:
12
+ #
13
+ # doc/
14
+ # components/.empty_directory
15
+ # README
16
+ # rdoc.rb.tt
17
+ # %app_name%.rb
18
+ #
19
+ # When invoked as:
20
+ #
21
+ # directory "doc"
22
+ #
23
+ # It will create a doc directory in the destination with the following
24
+ # files (assuming that the app_name is "blog"):
25
+ #
26
+ # doc/
27
+ # components/
28
+ # README
29
+ # rdoc.rb
30
+ # blog.rb
31
+ #
32
+ # ==== Parameters
33
+ # source<String>:: the relative path to the source root.
34
+ # destination<String>:: the relative path to the destination root.
35
+ # config<Hash>:: give :verbose => false to not log the status.
36
+ # If :recursive => false, does not look for paths recursively.
37
+ #
38
+ # ==== Examples
39
+ #
40
+ # directory "doc"
41
+ # directory "doc", "docs", :recursive => false
42
+ #
43
+ def directory(source, *args, &block)
44
+ config = args.last.is_a?(Hash) ? args.pop : {}
45
+ destination = args.first || source
46
+ action Directory.new(self, source, destination || source, config, &block)
47
+ end
48
+
49
+ class Directory < EmptyDirectory #:nodoc:
50
+ attr_reader :source
51
+
52
+ def initialize(base, source, destination=nil, config={}, &block)
53
+ @source = File.expand_path(base.find_in_source_paths(source.to_s))
54
+ @block = block
55
+ super(base, destination, { :recursive => true }.merge(config))
56
+ end
57
+
58
+ def invoke!
59
+ base.empty_directory given_destination, config
60
+ execute!
61
+ end
62
+
63
+ def revoke!
64
+ execute!
65
+ end
66
+
67
+ protected
68
+
69
+ def execute!
70
+ lookup = config[:recursive] ? File.join(source, '**') : source
71
+ lookup = File.join(lookup, '{*,.[a-z]*}')
72
+
73
+ Dir[lookup].each do |file_source|
74
+ next if File.directory?(file_source)
75
+ file_destination = File.join(given_destination, file_source.gsub(source, '.'))
76
+ file_destination.gsub!('/./', '/')
77
+
78
+ case file_source
79
+ when /\.empty_directory$/
80
+ dirname = File.dirname(file_destination).gsub(/\/\.$/, '')
81
+ next if dirname == given_destination
82
+ base.empty_directory(dirname, config)
83
+ when /\.tt$/
84
+ destination = base.template(file_source, file_destination[0..-4], config, &@block)
85
+ else
86
+ destination = base.copy_file(file_source, file_destination, config, &@block)
87
+ end
88
+ end
89
+ end
90
+
91
+ end
92
+ end
93
+ end