diff --git a/lib/thor/actions/inject_into_file.rb b/lib/thor/actions/inject_into_file.rb index 6062e5a8..4f7791da 100644 --- a/lib/thor/actions/inject_into_file.rb +++ b/lib/thor/actions/inject_into_file.rb @@ -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) } diff --git a/spec/actions/inject_into_file_spec.rb b/spec/actions/inject_into_file_spec.rb index eca16fb9..36b8d7b5 100644 --- a/spec/actions/inject_into_file_spec.rb +++ b/spec/actions/inject_into_file_spec.rb @@ -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")