Skip to content

Commit 0d3a1dd

Browse files
authored
Merge pull request #735 from excid3/improve-insert-into-file
Check for duplicate content in relevant section when inserting into files
2 parents ae18824 + b9060e0 commit 0d3a1dd

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

lib/thor/actions/inject_into_file.rb

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,10 @@ def say_status(behavior, warning: nil, color: nil)
108108
def replace!(regexp, string, force)
109109
return if pretend?
110110
content = File.read(destination)
111-
if force || !content.include?(replacement)
111+
before, after = content.split(regexp, 2)
112+
snippet = (behavior == :after ? after : before).to_s
113+
114+
if force || !snippet.include?(replacement)
112115
success = content.gsub!(regexp, string)
113116

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

spec/actions/inject_into_file_spec.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,11 +34,21 @@ def file
3434
expect(File.read(file)).to eq("__start__\nmore content\nREADME\n__end__\n")
3535
end
3636

37+
it "ignores duplicates before the after flag" do
38+
invoke! "doc/README", "\nREADME", :after => "README"
39+
expect(File.read(file)).to eq("__start__\nREADME\nREADME\n__end__\n")
40+
end
41+
3742
it "changes the file adding content before the flag" do
3843
invoke! "doc/README", "more content\n", :before => "__end__"
3944
expect(File.read(file)).to eq("__start__\nREADME\nmore content\n__end__\n")
4045
end
4146

47+
it "ignores duplicates before the before flag" do
48+
invoke! "doc/README", "README\n", :before => "README"
49+
expect(File.read(file)).to eq("__start__\nREADME\nREADME\n__end__\n")
50+
end
51+
4252
it "appends content to the file if before and after arguments not provided" do
4353
invoke!("doc/README", "more content\n")
4454
expect(File.read(file)).to eq("__start__\nREADME\n__end__\nmore content\n")

0 commit comments

Comments
 (0)