2010-10-03 21:00:33 +00:00
module Guard
class Watcher
attr_accessor :pattern , :action
def initialize ( pattern , action = nil )
@pattern , @action = pattern , action
2010-12-16 00:22:42 +00:00
@@warning_printed || = false
# deprecation warning
if @pattern . is_a? ( String ) && @pattern =~ / (^( \ ^))|(>?( \\ \ .)|( \ . \ *))|( \ (.* \ ))|( \ [.* \ ])|( \ $$) /
unless @@warning_printed
2010-12-16 08:15:14 +00:00
UI . info " * " * 20 + " \n DEPRECATION WARNING! \n " + " * " * 20
UI . info " You have strings in your Guardfile's watch patterns that seem to represent regexps. \n Guard matchs String with == and Regexp with Regexp # match. \n You should either use plain String (without Regexp special characters) or real Regexp. \n "
2010-12-16 00:22:42 +00:00
@@warning_printed = true
end
UI . info " \" #{ @pattern } \" has been converted to #{ Regexp . new ( @pattern ) . inspect } \n "
@pattern = Regexp . new ( @pattern )
end
2010-10-03 21:00:33 +00:00
end
def self . match_files ( guard , files )
guard . watchers . inject ( [ ] ) do | paths , watcher |
files . each do | file |
2010-11-25 23:55:21 +00:00
if matches = watcher . match_file? ( file )
2010-10-03 21:00:33 +00:00
if watcher . action
2010-11-25 23:55:21 +00:00
result = watcher . call_action ( matches )
paths << Array ( result ) if result . respond_to? ( :empty? ) && ! result . empty?
2010-10-03 21:00:33 +00:00
else
paths << matches [ 0 ]
end
end
end
2010-11-25 23:55:21 +00:00
paths . flatten . map { | p | p . to_s }
2010-10-03 21:00:33 +00:00
end
end
2010-11-25 07:52:53 +00:00
def self . match_files? ( guards , files )
2010-11-25 23:55:21 +00:00
guards . any? do | guard |
guard . watchers . any? do | watcher |
files . any? { | file | watcher . match_file? ( file ) }
end
end
end
def match_file? ( file )
2010-12-16 00:22:42 +00:00
if @pattern . is_a? ( Regexp )
file . match ( @pattern )
else
2010-12-16 14:09:36 +00:00
file == @pattern ? [ file ] : nil
2010-12-16 00:22:42 +00:00
end
2010-11-25 23:55:21 +00:00
end
def call_action ( matches )
begin
@action . arity > 0 ? @action . call ( matches ) : @action . call
rescue
UI . error " Problem with watch action! "
end
2010-11-25 07:52:53 +00:00
end
2010-10-03 21:00:33 +00:00
end
end