@@ -21,9 +21,14 @@ module Actions
2121 # gems.split(" ").map{ |gem| " config.gem :#{gem}" }.join("\n")
2222 # end
2323 #
24+ WARNINGS = { unchanged_no_flag : 'File unchanged! The supplied flag value not found!' }
25+
2426 def insert_into_file ( destination , *args , &block )
2527 data = block_given? ? block : args . shift
26- config = args . shift
28+
29+ config = args . shift || { }
30+ config [ :after ] = /\z / unless config . key? ( :before ) || config . key? ( :after )
31+
2732 action InjectIntoFile . new ( self , destination , data , config )
2833 end
2934 alias_method :inject_into_file , :insert_into_file
@@ -45,16 +50,18 @@ def initialize(base, destination, data, config)
4550 end
4651
4752 def invoke!
48- say_status :invoke
49-
5053 content = if @behavior == :after
5154 '\0' + replacement
5255 else
5356 replacement + '\0'
5457 end
5558
5659 if exists?
57- replace! ( /#{ flag } / , content , config [ :force ] )
60+ if replace! ( /#{ flag } / , content , config [ :force ] )
61+ say_status ( :invoke )
62+ else
63+ say_status ( :unchanged , warning : WARNINGS [ :unchanged_no_flag ] , color : :red )
64+ end
5865 else
5966 unless pretend?
6067 raise Thor ::Error , "The file #{ destination } does not appear to exist"
@@ -78,7 +85,7 @@ def revoke!
7885
7986 protected
8087
81- def say_status ( behavior )
88+ def say_status ( behavior , warning : nil , color : nil )
8289 status = if behavior == :invoke
8390 if flag == /\A /
8491 :prepend
@@ -87,11 +94,13 @@ def say_status(behavior)
8794 else
8895 :insert
8996 end
97+ elsif warning
98+ warning
9099 else
91100 :subtract
92101 end
93102
94- super ( status , config [ :verbose ] )
103+ super ( status , ( color || config [ :verbose ] ) )
95104 end
96105
97106 # Adds the content to the file.
@@ -100,8 +109,10 @@ def replace!(regexp, string, force)
100109 return if pretend?
101110 content = File . read ( destination )
102111 if force || !content . include? ( replacement )
103- content . gsub! ( regexp , string )
112+ success = content . gsub! ( regexp , string )
113+
104114 File . open ( destination , "wb" ) { |file | file . write ( content ) }
115+ success
105116 end
106117 end
107118 end
0 commit comments