@@ -21,9 +21,14 @@ module Actions
21
21
# gems.split(" ").map{ |gem| " config.gem :#{gem}" }.join("\n")
22
22
# end
23
23
#
24
+ WARNINGS = { unchanged_no_flag : 'File unchanged! The supplied flag value not found!' }
25
+
24
26
def insert_into_file ( destination , *args , &block )
25
27
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
+
27
32
action InjectIntoFile . new ( self , destination , data , config )
28
33
end
29
34
alias_method :inject_into_file , :insert_into_file
@@ -45,16 +50,18 @@ def initialize(base, destination, data, config)
45
50
end
46
51
47
52
def invoke!
48
- say_status :invoke
49
-
50
53
content = if @behavior == :after
51
54
'\0' + replacement
52
55
else
53
56
replacement + '\0'
54
57
end
55
58
56
59
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
58
65
else
59
66
unless pretend?
60
67
raise Thor ::Error , "The file #{ destination } does not appear to exist"
@@ -78,7 +85,7 @@ def revoke!
78
85
79
86
protected
80
87
81
- def say_status ( behavior )
88
+ def say_status ( behavior , warning : nil , color : nil )
82
89
status = if behavior == :invoke
83
90
if flag == /\A /
84
91
:prepend
@@ -87,11 +94,13 @@ def say_status(behavior)
87
94
else
88
95
:insert
89
96
end
97
+ elsif warning
98
+ warning
90
99
else
91
100
:subtract
92
101
end
93
102
94
- super ( status , config [ :verbose ] )
103
+ super ( status , ( color || config [ :verbose ] ) )
95
104
end
96
105
97
106
# Adds the content to the file.
@@ -100,8 +109,10 @@ def replace!(regexp, string, force)
100
109
return if pretend?
101
110
content = File . read ( destination )
102
111
if force || !content . include? ( replacement )
103
- content . gsub! ( regexp , string )
112
+ success = content . gsub! ( regexp , string )
113
+
104
114
File . open ( destination , "wb" ) { |file | file . write ( content ) }
115
+ success
105
116
end
106
117
end
107
118
end
0 commit comments