-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrake.rb
2485 lines (2218 loc) · 70.2 KB
/
rake.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#--
# Copyright 2003, 2004, 2005, 2006, 2007, 2008 by Jim Weirich ([email protected])
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#++
#
# = Rake -- Ruby Make
#
# This is the main file for the Rake application. Normally it is referenced
# as a library via a require statement, but it can be distributed
# independently as an application.
RAKEVERSION = '0.8.7'
require 'rbconfig'
require 'fileutils'
require 'singleton'
require 'monitor'
require 'optparse'
require 'ostruct'
require 'rake/win32'
$trace = false
######################################################################
# Rake extensions to Module.
#
class Module
# Check for an existing method in the current class before extending. IF
# the method already exists, then a warning is printed and the extension is
# not added. Otherwise the block is yielded and any definitions in the
# block will take effect.
#
# Usage:
#
# class String
# rake_extension("xyz") do
# def xyz
# ...
# end
# end
# end
#
def rake_extension(method)
if method_defined?(method)
$stderr.puts "WARNING: Possible conflict with Rake extension: #{self}##{method} already exists"
else
yield
end
end
end # module Module
######################################################################
# User defined methods to be added to String.
#
class String
rake_extension("ext") do
# Replace the file extension with +newext+. If there is no extension on
# the string, append the new extension to the end. If the new extension
# is not given, or is the empty string, remove any existing extension.
#
# +ext+ is a user added method for the String class.
def ext(newext='')
return self.dup if ['.', '..'].include? self
if newext != ''
newext = (newext =~ /^\./) ? newext : ("." + newext)
end
self.chomp(File.extname(self)) << newext
end
end
rake_extension("pathmap") do
# Explode a path into individual components. Used by +pathmap+.
def pathmap_explode
head, tail = File.split(self)
return [self] if head == self
return [tail] if head == '.' || tail == '/'
return [head, tail] if head == '/'
return head.pathmap_explode + [tail]
end
protected :pathmap_explode
# Extract a partial path from the path. Include +n+ directories from the
# front end (left hand side) if +n+ is positive. Include |+n+|
# directories from the back end (right hand side) if +n+ is negative.
def pathmap_partial(n)
dirs = File.dirname(self).pathmap_explode
partial_dirs =
if n > 0
dirs[0...n]
elsif n < 0
dirs.reverse[0...-n].reverse
else
"."
end
File.join(partial_dirs)
end
protected :pathmap_partial
# Preform the pathmap replacement operations on the given path. The
# patterns take the form 'pat1,rep1;pat2,rep2...'.
def pathmap_replace(patterns, &block)
result = self
patterns.split(';').each do |pair|
pattern, replacement = pair.split(',')
pattern = Regexp.new(pattern)
if replacement == '*' && block_given?
result = result.sub(pattern, &block)
elsif replacement
result = result.sub(pattern, replacement)
else
result = result.sub(pattern, '')
end
end
result
end
protected :pathmap_replace
# Map the path according to the given specification. The specification
# controls the details of the mapping. The following special patterns are
# recognized:
#
# * <b>%p</b> -- The complete path.
# * <b>%f</b> -- The base file name of the path, with its file extension,
# but without any directories.
# * <b>%n</b> -- The file name of the path without its file extension.
# * <b>%d</b> -- The directory list of the path.
# * <b>%x</b> -- The file extension of the path. An empty string if there
# is no extension.
# * <b>%X</b> -- Everything *but* the file extension.
# * <b>%s</b> -- The alternate file separater if defined, otherwise use
# the standard file separator.
# * <b>%%</b> -- A percent sign.
#
# The %d specifier can also have a numeric prefix (e.g. '%2d'). If the
# number is positive, only return (up to) +n+ directories in the path,
# starting from the left hand side. If +n+ is negative, return (up to)
# |+n+| directories from the right hand side of the path.
#
# Examples:
#
# 'a/b/c/d/file.txt'.pathmap("%2d") => 'a/b'
# 'a/b/c/d/file.txt'.pathmap("%-2d") => 'c/d'
#
# Also the %d, %p, %f, %n, %x, and %X operators can take a
# pattern/replacement argument to perform simple string substititions on a
# particular part of the path. The pattern and replacement are speparated
# by a comma and are enclosed by curly braces. The replacement spec comes
# after the % character but before the operator letter. (e.g.
# "%{old,new}d"). Muliple replacement specs should be separated by
# semi-colons (e.g. "%{old,new;src,bin}d").
#
# Regular expressions may be used for the pattern, and back refs may be
# used in the replacement text. Curly braces, commas and semi-colons are
# excluded from both the pattern and replacement text (let's keep parsing
# reasonable).
#
# For example:
#
# "src/org/onestepback/proj/A.java".pathmap("%{^src,bin}X.class")
#
# returns:
#
# "bin/org/onestepback/proj/A.class"
#
# If the replacement text is '*', then a block may be provided to perform
# some arbitrary calculation for the replacement.
#
# For example:
#
# "/path/to/file.TXT".pathmap("%X%{.*,*}x") { |ext|
# ext.downcase
# }
#
# Returns:
#
# "/path/to/file.txt"
#
def pathmap(spec=nil, &block)
return self if spec.nil?
result = ''
spec.scan(/%\{[^}]*\}-?\d*[sdpfnxX%]|%-?\d+d|%.|[^%]+/) do |frag|
case frag
when '%f'
result << File.basename(self)
when '%n'
result << File.basename(self).ext
when '%d'
result << File.dirname(self)
when '%x'
result << File.extname(self)
when '%X'
result << self.ext
when '%p'
result << self
when '%s'
result << (File::ALT_SEPARATOR || File::SEPARATOR)
when '%-'
# do nothing
when '%%'
result << "%"
when /%(-?\d+)d/
result << pathmap_partial($1.to_i)
when /^%\{([^}]*)\}(\d*[dpfnxX])/
patterns, operator = $1, $2
result << pathmap('%' + operator).pathmap_replace(patterns, &block)
when /^%/
fail ArgumentError, "Unknown pathmap specifier #{frag} in '#{spec}'"
else
result << frag
end
end
result
end
end
end # class String
##############################################################################
module Rake
# Errors -----------------------------------------------------------
# Error indicating an ill-formed task declaration.
class TaskArgumentError < ArgumentError
end
# Error indicating a recursion overflow error in task selection.
class RuleRecursionOverflowError < StandardError
def initialize(*args)
super
@targets = []
end
def add_target(target)
@targets << target
end
def message
super + ": [" + @targets.reverse.join(' => ') + "]"
end
end
# --------------------------------------------------------------------------
# Rake module singleton methods.
#
class << self
# Current Rake Application
def application
@application ||= Rake::Application.new
end
# Set the current Rake application object.
def application=(app)
@application = app
end
# Return the original directory where the Rake application was started.
def original_dir
application.original_dir
end
end
####################################################################
# Mixin for creating easily cloned objects.
#
module Cloneable
# Clone an object by making a new object and setting all the instance
# variables to the same values.
def dup
sibling = self.class.new
instance_variables.each do |ivar|
value = self.instance_variable_get(ivar)
new_value = value.clone rescue value
sibling.instance_variable_set(ivar, new_value)
end
sibling.taint if tainted?
sibling
end
def clone
sibling = dup
sibling.freeze if frozen?
sibling
end
end
####################################################################
# Exit status class for times the system just gives us a nil.
class PseudoStatus
attr_reader :exitstatus
def initialize(code=0)
@exitstatus = code
end
def to_i
@exitstatus << 8
end
def >>(n)
to_i >> n
end
def stopped?
false
end
def exited?
true
end
end
####################################################################
# TaskAguments manage the arguments passed to a task.
#
class TaskArguments
include Enumerable
attr_reader :names
# Create a TaskArgument object with a list of named arguments
# (given by :names) and a set of associated values (given by
# :values). :parent is the parent argument object.
def initialize(names, values, parent=nil)
@names = names
@parent = parent
@hash = {}
names.each_with_index { |name, i|
@hash[name.to_sym] = values[i] unless values[i].nil?
}
end
# Create a new argument scope using the prerequisite argument
# names.
def new_scope(names)
values = names.collect { |n| self[n] }
self.class.new(names, values, self)
end
# Find an argument value by name or index.
def [](index)
lookup(index.to_sym)
end
# Specify a hash of default values for task arguments. Use the
# defaults only if there is no specific value for the given
# argument.
def with_defaults(defaults)
@hash = defaults.merge(@hash)
end
def each(&block)
@hash.each(&block)
end
def method_missing(sym, *args, &block)
lookup(sym.to_sym)
end
def to_hash
@hash
end
def to_s
@hash.inspect
end
def inspect
to_s
end
protected
def lookup(name)
if @hash.has_key?(name)
@hash[name]
elsif ENV.has_key?(name.to_s)
ENV[name.to_s]
elsif ENV.has_key?(name.to_s.upcase)
ENV[name.to_s.upcase]
elsif @parent
@parent.lookup(name)
end
end
end
EMPTY_TASK_ARGS = TaskArguments.new([], [])
####################################################################
# InvocationChain tracks the chain of task invocations to detect
# circular dependencies.
class InvocationChain
def initialize(value, tail)
@value = value
@tail = tail
end
def member?(obj)
@value == obj || @tail.member?(obj)
end
def append(value)
if member?(value)
fail RuntimeError, "Circular dependency detected: #{to_s} => #{value}"
end
self.class.new(value, self)
end
def to_s
"#{prefix}#{@value}"
end
def self.append(value, chain)
chain.append(value)
end
private
def prefix
"#{@tail.to_s} => "
end
class EmptyInvocationChain
def member?(obj)
false
end
def append(value)
InvocationChain.new(value, self)
end
def to_s
"TOP"
end
end
EMPTY = EmptyInvocationChain.new
end # class InvocationChain
end # module Rake
module Rake
###########################################################################
# A Task is the basic unit of work in a Rakefile. Tasks have associated
# actions (possibly more than one) and a list of prerequisites. When
# invoked, a task will first ensure that all of its prerequisites have an
# opportunity to run and then it will execute its own actions.
#
# Tasks are not usually created directly using the new method, but rather
# use the +file+ and +task+ convenience methods.
#
class Task
# List of prerequisites for a task.
attr_reader :prerequisites
# List of actions attached to a task.
attr_reader :actions
# Application owning this task.
attr_accessor :application
# Comment for this task. Restricted to a single line of no more than 50
# characters.
attr_reader :comment
# Full text of the (possibly multi-line) comment.
attr_reader :full_comment
# Array of nested namespaces names used for task lookup by this task.
attr_reader :scope
# Return task name
def to_s
name
end
def inspect
"<#{self.class} #{name} => [#{prerequisites.join(', ')}]>"
end
# List of sources for task.
attr_writer :sources
def sources
@sources ||= []
end
# First source from a rule (nil if no sources)
def source
@sources.first if defined?(@sources)
end
# Create a task named +task_name+ with no actions or prerequisites. Use
# +enhance+ to add actions and prerequisites.
def initialize(task_name, app)
@name = task_name.to_s
@prerequisites = []
@actions = []
@already_invoked = false
@full_comment = nil
@comment = nil
@lock = Monitor.new
@application = app
@scope = app.current_scope
@arg_names = nil
end
# Enhance a task with prerequisites or actions. Returns self.
def enhance(deps=nil, &block)
@prerequisites |= deps if deps
@actions << block if block_given?
self
end
# Name of the task, including any namespace qualifiers.
def name
@name.to_s
end
# Name of task with argument list description.
def name_with_args # :nodoc:
if arg_description
"#{name}#{arg_description}"
else
name
end
end
# Argument description (nil if none).
def arg_description # :nodoc:
@arg_names ? "[#{(arg_names || []).join(',')}]" : nil
end
# Name of arguments for this task.
def arg_names
@arg_names || []
end
# Reenable the task, allowing its tasks to be executed if the task
# is invoked again.
def reenable
@already_invoked = false
end
# Clear the existing prerequisites and actions of a rake task.
def clear
clear_prerequisites
clear_actions
self
end
# Clear the existing prerequisites of a rake task.
def clear_prerequisites
prerequisites.clear
self
end
# Clear the existing actions on a rake task.
def clear_actions
actions.clear
self
end
# Invoke the task if it is needed. Prerequites are invoked first.
def invoke(*args)
task_args = TaskArguments.new(arg_names, args)
invoke_with_call_chain(task_args, InvocationChain::EMPTY)
end
# Same as invoke, but explicitly pass a call chain to detect
# circular dependencies.
def invoke_with_call_chain(task_args, invocation_chain) # :nodoc:
new_chain = InvocationChain.append(self, invocation_chain)
@lock.synchronize do
if application.options.trace
puts "** Invoke #{name} #{format_trace_flags}"
end
return if @already_invoked
@already_invoked = true
invoke_prerequisites(task_args, new_chain)
execute(task_args) if needed?
end
end
protected :invoke_with_call_chain
# Invoke all the prerequisites of a task.
def invoke_prerequisites(task_args, invocation_chain) # :nodoc:
@prerequisites.each { |n|
prereq = application[n, @scope]
prereq_args = task_args.new_scope(prereq.arg_names)
prereq.invoke_with_call_chain(prereq_args, invocation_chain)
}
end
# Format the trace flags for display.
def format_trace_flags
flags = []
flags << "first_time" unless @already_invoked
flags << "not_needed" unless needed?
flags.empty? ? "" : "(" + flags.join(", ") + ")"
end
private :format_trace_flags
# Execute the actions associated with this task.
def execute(args=nil)
args ||= EMPTY_TASK_ARGS
if application.options.dryrun
puts "** Execute (dry run) #{name}"
return
end
if application.options.trace
puts "** Execute #{name}"
end
application.enhance_with_matching_rule(name) if @actions.empty?
@actions.each do |act|
case act.arity
when 1
act.call(self)
else
act.call(self, args)
end
end
end
# Is this task needed?
def needed?
true
end
# Timestamp for this task. Basic tasks return the current time for their
# time stamp. Other tasks can be more sophisticated.
def timestamp
@prerequisites.collect { |p| application[p].timestamp }.max || Time.now
end
# Add a description to the task. The description can consist of an option
# argument list (enclosed brackets) and an optional comment.
def add_description(description)
return if ! description
comment = description.strip
add_comment(comment) if comment && ! comment.empty?
end
# Writing to the comment attribute is the same as adding a description.
def comment=(description)
add_description(description)
end
# Add a comment to the task. If a comment alread exists, separate
# the new comment with " / ".
def add_comment(comment)
if @full_comment
@full_comment << " / "
else
@full_comment = ''
end
@full_comment << comment
if @full_comment =~ /\A([^.]+?\.)( |$)/
@comment = $1
else
@comment = @full_comment
end
end
private :add_comment
# Set the names of the arguments for this task. +args+ should be
# an array of symbols, one for each argument name.
def set_arg_names(args)
@arg_names = args.map { |a| a.to_sym }
end
# Return a string describing the internal state of a task. Useful for
# debugging.
def investigation
result = "------------------------------\n"
result << "Investigating #{name}\n"
result << "class: #{self.class}\n"
result << "task needed: #{needed?}\n"
result << "timestamp: #{timestamp}\n"
result << "pre-requisites: \n"
prereqs = @prerequisites.collect {|name| application[name]}
prereqs.sort! {|a,b| a.timestamp <=> b.timestamp}
prereqs.each do |p|
result << "--#{p.name} (#{p.timestamp})\n"
end
latest_prereq = @prerequisites.collect{|n| application[n].timestamp}.max
result << "latest-prerequisite time: #{latest_prereq}\n"
result << "................................\n\n"
return result
end
# ----------------------------------------------------------------
# Rake Module Methods
#
class << self
# Clear the task list. This cause rake to immediately forget all the
# tasks that have been assigned. (Normally used in the unit tests.)
def clear
Rake.application.clear
end
# List of all defined tasks.
def tasks
Rake.application.tasks
end
# Return a task with the given name. If the task is not currently
# known, try to synthesize one from the defined rules. If no rules are
# found, but an existing file matches the task name, assume it is a file
# task with no dependencies or actions.
def [](task_name)
Rake.application[task_name]
end
# TRUE if the task name is already defined.
def task_defined?(task_name)
Rake.application.lookup(task_name) != nil
end
# Define a task given +args+ and an option block. If a rule with the
# given name already exists, the prerequisites and actions are added to
# the existing task. Returns the defined task.
def define_task(*args, &block)
Rake.application.define_task(self, *args, &block)
end
# Define a rule for synthesizing tasks.
def create_rule(*args, &block)
Rake.application.create_rule(*args, &block)
end
# Apply the scope to the task name according to the rules for
# this kind of task. Generic tasks will accept the scope as
# part of the name.
def scope_name(scope, task_name)
(scope + [task_name]).join(':')
end
end # class << Rake::Task
end # class Rake::Task
###########################################################################
# A FileTask is a task that includes time based dependencies. If any of a
# FileTask's prerequisites have a timestamp that is later than the file
# represented by this task, then the file must be rebuilt (using the
# supplied actions).
#
class FileTask < Task
# Is this file task needed? Yes if it doesn't exist, or if its time stamp
# is out of date.
def needed?
! File.exist?(name) || out_of_date?(timestamp)
end
# Time stamp for file task.
def timestamp
if File.exist?(name)
File.mtime(name.to_s)
else
Rake::EARLY
end
end
private
# Are there any prerequisites with a later time than the given time stamp?
def out_of_date?(stamp)
@prerequisites.any? { |n| application[n].timestamp > stamp}
end
# ----------------------------------------------------------------
# Task class methods.
#
class << self
# Apply the scope to the task name according to the rules for this kind
# of task. File based tasks ignore the scope when creating the name.
def scope_name(scope, task_name)
task_name
end
end
end # class Rake::FileTask
###########################################################################
# A FileCreationTask is a file task that when used as a dependency will be
# needed if and only if the file has not been created. Once created, it is
# not re-triggered if any of its dependencies are newer, nor does trigger
# any rebuilds of tasks that depend on it whenever it is updated.
#
class FileCreationTask < FileTask
# Is this file task needed? Yes if it doesn't exist.
def needed?
! File.exist?(name)
end
# Time stamp for file creation task. This time stamp is earlier
# than any other time stamp.
def timestamp
Rake::EARLY
end
end
###########################################################################
# Same as a regular task, but the immediate prerequisites are done in
# parallel using Ruby threads.
#
class MultiTask < Task
private
def invoke_prerequisites(args, invocation_chain)
threads = @prerequisites.collect { |p|
Thread.new(p) { |r| application[r].invoke_with_call_chain(args, invocation_chain) }
}
threads.each { |t| t.join }
end
end
end # module Rake
## ###########################################################################
# Task Definition Functions ...
# Declare a basic task.
#
# Example:
# task :clobber => [:clean] do
# rm_rf "html"
# end
#
def task(*args, &block)
Rake::Task.define_task(*args, &block)
end
# Declare a file task.
#
# Example:
# file "config.cfg" => ["config.template"] do
# open("config.cfg", "w") do |outfile|
# open("config.template") do |infile|
# while line = infile.gets
# outfile.puts line
# end
# end
# end
# end
#
def file(*args, &block)
Rake::FileTask.define_task(*args, &block)
end
# Declare a file creation task.
# (Mainly used for the directory command).
def file_create(args, &block)
Rake::FileCreationTask.define_task(args, &block)
end
# Declare a set of files tasks to create the given directories on demand.
#
# Example:
# directory "testdata/doc"
#
def directory(dir)
Rake.each_dir_parent(dir) do |d|
file_create d do |t|
mkdir_p t.name if ! File.exist?(t.name)
end
end
end
# Declare a task that performs its prerequisites in parallel. Multitasks does
# *not* guarantee that its prerequisites will execute in any given order
# (which is obvious when you think about it)
#
# Example:
# multitask :deploy => [:deploy_gem, :deploy_rdoc]
#
def multitask(args, &block)
Rake::MultiTask.define_task(args, &block)
end
# Create a new rake namespace and use it for evaluating the given block.
# Returns a NameSpace object that can be used to lookup tasks defined in the
# namespace.
#
# E.g.
#
# ns = namespace "nested" do
# task :run
# end
# task_run = ns[:run] # find :run in the given namespace.
#
def namespace(name=nil, &block)
Rake.application.in_namespace(name, &block)
end
# Declare a rule for auto-tasks.
#
# Example:
# rule '.o' => '.c' do |t|
# sh %{cc -o #{t.name} #{t.source}}
# end
#
def rule(*args, &block)
Rake::Task.create_rule(*args, &block)
end
# Describe the next rake task.
#
# Example:
# desc "Run the Unit Tests"
# task :test => [:build]
# runtests
# end
#
def desc(description)
Rake.application.last_description = description
end
# Import the partial Rakefiles +fn+. Imported files are loaded _after_ the
# current file is completely loaded. This allows the import statement to
# appear anywhere in the importing file, and yet allowing the imported files
# to depend on objects defined in the importing file.
#
# A common use of the import statement is to include files containing
# dependency declarations.
#
# See also the --rakelibdir command line option.
#
# Example:
# import ".depend", "my_rules"
#
def import(*fns)
fns.each do |fn|
Rake.application.add_import(fn)
end
end
#############################################################################
# This a FileUtils extension that defines several additional commands to be
# added to the FileUtils utility functions.
#
module FileUtils
RUBY_EXT = ((RbConfig::CONFIG['ruby_install_name'] =~ /\.(com|cmd|exe|bat|rb|sh)$/) ?
"" :
RbConfig::CONFIG['EXEEXT'])
RUBY = File.join(
RbConfig::CONFIG['bindir'],
RbConfig::CONFIG['ruby_install_name'] + RUBY_EXT).
sub(/.*\s.*/m, '"\&"')
OPT_TABLE['sh'] = %w(noop verbose)
OPT_TABLE['ruby'] = %w(noop verbose)
# Run the system command +cmd+. If multiple arguments are given the command
# is not run with the shell (same semantics as Kernel::exec and
# Kernel::system).
#
# Example:
# sh %{ls -ltr}
#
# sh 'ls', 'file with spaces'
#
# # check exit status after command runs
# sh %{grep pattern file} do |ok, res|
# if ! ok
# puts "pattern not found (status = #{res.exitstatus})"
# end
# end
#
def sh(*cmd, &block)
options = (Hash === cmd.last) ? cmd.pop : {}
unless block_given?
show_command = cmd.join(" ")
show_command = show_command[0,42] + "..." unless $trace
# TODO code application logic heref show_command.length > 45
block = lambda { |ok, status|
ok or fail "Command failed with status (#{status.exitstatus}): [#{show_command}]"
}
end
if RakeFileUtils.verbose_flag == :default
options[:verbose] = true
else
options[:verbose] ||= RakeFileUtils.verbose_flag
end