Skip to content

Commit

Permalink
Only check for duplicate content in relevant section when inserting i…
Browse files Browse the repository at this point in the history
…nto file
  • Loading branch information
excid3 committed Aug 25, 2020
1 parent 34df888 commit b9060e0
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/thor/actions/inject_into_file.rb
Expand Up @@ -108,7 +108,10 @@ def say_status(behavior, warning: nil, color: nil)
def replace!(regexp, string, force)
return if pretend?
content = File.read(destination)
if force || !content.include?(replacement)
before, after = content.split(regexp, 2)
snippet = (behavior == :after ? after : before).to_s

if force || !snippet.include?(replacement)
success = content.gsub!(regexp, string)

File.open(destination, "wb") { |file| file.write(content) }
Expand Down
10 changes: 10 additions & 0 deletions spec/actions/inject_into_file_spec.rb
Expand Up @@ -34,11 +34,21 @@ def file
expect(File.read(file)).to eq("__start__\nmore content\nREADME\n__end__\n")
end

it "ignores duplicates before the after flag" do
invoke! "doc/README", "\nREADME", :after => "README"
expect(File.read(file)).to eq("__start__\nREADME\nREADME\n__end__\n")
end

it "changes the file adding content before the flag" do
invoke! "doc/README", "more content\n", :before => "__end__"
expect(File.read(file)).to eq("__start__\nREADME\nmore content\n__end__\n")
end

it "ignores duplicates before the before flag" do
invoke! "doc/README", "README\n", :before => "README"
expect(File.read(file)).to eq("__start__\nREADME\nREADME\n__end__\n")
end

it "appends content to the file if before and after arguments not provided" do
invoke!("doc/README", "more content\n")
expect(File.read(file)).to eq("__start__\nREADME\n__end__\nmore content\n")
Expand Down

0 comments on commit b9060e0

Please sign in to comment.