Skip to content

Commit bf3afab

Browse files
Fix #inject_into_file warning when replacement is already present in file
1 parent 87d73c1 commit bf3afab

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

lib/thor/actions/inject_into_file.rb

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,8 @@ def invoke!
5959
if exists?
6060
if replace!(/#{flag}/, content, config[:force])
6161
say_status(:invoke)
62+
elsif replacement_present?
63+
say_status(:unchanged, color: :blue)
6264
else
6365
say_status(:unchanged, warning: WARNINGS[:unchanged_no_flag], color: :red)
6466
end
@@ -96,22 +98,32 @@ def say_status(behavior, warning: nil, color: nil)
9698
end
9799
elsif warning
98100
warning
101+
elsif behavior == :unchanged
102+
:unchanged
99103
else
100104
:subtract
101105
end
102106

103107
super(status, (color || config[:verbose]))
104108
end
105109

110+
def content
111+
@content ||= File.read(destination)
112+
end
113+
114+
def replacement_present?
115+
before, after = content.split(regexp, 2)
116+
snippet = (behavior == :after ? after : before).to_s
117+
118+
snippet.include?(replacement)
119+
end
120+
106121
# Adds the content to the file.
107122
#
108123
def replace!(regexp, string, force)
109124
return if pretend?
110-
content = File.read(destination)
111-
before, after = content.split(regexp, 2)
112-
snippet = (behavior == :after ? after : before).to_s
113125

114-
if force || !snippet.include?(replacement)
126+
if force || !replacement_present?
115127
success = content.gsub!(regexp, string)
116128

117129
File.open(destination, "wb") { |file| file.write(content) }

spec/actions/inject_into_file_spec.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,13 @@ def file
5454
expect(File.read(file)).to eq("__start__\nREADME\n__end__\nmore content\n")
5555
end
5656

57+
it "does not change the file if replacement present in the file" do
58+
invoke!("doc/README", "more specific content\n")
59+
expect(invoke!("doc/README", "more specific content\n")).to(
60+
eq(" unchanged doc/README\n")
61+
)
62+
end
63+
5764
it "does not change the file and logs the warning if flag not found in the file" do
5865
expect(invoke!("doc/README", "more content\n", after: "whatever")).to(
5966
eq("#{Thor::Actions::WARNINGS[:unchanged_no_flag]} doc/README\n")

0 commit comments

Comments
 (0)