Skip to content

Commit 2dde972

Browse files
authored
Merge pull request #709 from nicolas-brousse/fix-inject-into-file-warning
Fix inject into file warning
2 parents fb14b99 + 6499e07 commit 2dde972

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

lib/thor/actions/inject_into_file.rb

Lines changed: 13 additions & 2 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,18 +98,27 @@ 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+
content.include?(replacement)
116+
end
117+
106118
# Adds the content to the file.
107119
#
108120
def replace!(regexp, string, force)
109-
content = File.read(destination)
110-
if force || !content.include?(replacement)
121+
if force || !replacement_present?
111122
success = content.gsub!(regexp, string)
112123

113124
File.open(destination, "wb") { |file| file.write(content) } unless pretend?

spec/actions/inject_into_file_spec.rb

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

47+
it "does not change the file if replacement present in the file" do
48+
invoke!("doc/README", "more specific content\n")
49+
expect(invoke!("doc/README", "more specific content\n")).to(
50+
eq(" unchanged doc/README\n")
51+
)
52+
end
53+
4754
it "does not change the file and logs the warning if flag not found in the file" do
4855
expect(invoke!("doc/README", "more content\n", after: "whatever")).to(
4956
eq("#{Thor::Actions::WARNINGS[:unchanged_no_flag]} doc/README\n")

0 commit comments

Comments
 (0)