Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions lib/thor/actions/inject_into_file.rb
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ def invoke!
if exists?
if replace!(/#{flag}/, content, config[:force])
say_status(:invoke)
elsif replacement_present?
say_status(:unchanged, color: :blue)
else
say_status(:unchanged, warning: WARNINGS[:unchanged_no_flag], color: :red)
end
Expand Down Expand Up @@ -96,18 +98,27 @@ def say_status(behavior, warning: nil, color: nil)
end
elsif warning
warning
elsif behavior == :unchanged
:unchanged
else
:subtract
end

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

def content
@content ||= File.read(destination)
end

def replacement_present?
content.include?(replacement)
end

# Adds the content to the file.
#
def replace!(regexp, string, force)
content = File.read(destination)
if force || !content.include?(replacement)
if force || !replacement_present?
success = content.gsub!(regexp, string)

File.open(destination, "wb") { |file| file.write(content) } unless pretend?
Expand Down
7 changes: 7 additions & 0 deletions spec/actions/inject_into_file_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,13 @@ def file
expect(File.read(file)).to eq("__start__\nREADME\n__end__\nmore content\n")
end

it "does not change the file if replacement present in the file" do
invoke!("doc/README", "more specific content\n")
expect(invoke!("doc/README", "more specific content\n")).to(
eq(" unchanged doc/README\n")
)
end

it "does not change the file and logs the warning if flag not found in the file" do
expect(invoke!("doc/README", "more content\n", after: "whatever")).to(
eq("#{Thor::Actions::WARNINGS[:unchanged_no_flag]} doc/README\n")
Expand Down