Skip to content

Commit 52eedd1

Browse files
committed
Add check to make sure file exists before inject
1 parent f0c2166 commit 52eedd1

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

lib/thor/actions/inject_into_file.rb

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
require "thor/actions/empty_directory"
2+
require "pry"
23

34
class Thor
45
module Actions
@@ -56,7 +57,11 @@ def invoke!
5657
replacement + '\0'
5758
end
5859

59-
replace!(/#{flag}/, content, config[:force])
60+
if File.exist?(destination)
61+
replace!(/#{flag}/, content, config[:force])
62+
else
63+
raise MalformattedArgumentError, "The file #{ destination } does not appear to exist"
64+
end
6065
end
6166

6267
def revoke!

spec/actions/inject_into_file_spec.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,21 @@ def file
7070
expect(File.read(file)).to eq("__start__\nREADME\nmore content\n__end__\n")
7171
end
7272

73+
it "does not attempt to change the file if it doesn't exist" do
74+
expect_any_instance_of(Thor::Actions::InjectIntoFile).not_to receive(:replace!)
75+
invoker.inject_into_file "idontexist", :before => "something" do
76+
"any content"
77+
end rescue nil
78+
end
79+
80+
it "raises a malformatted argument error including filename if file doesn't exist" do
81+
expect do
82+
invoker.inject_into_file "idontexist", :before => "something" do
83+
"any content"
84+
end
85+
end.to raise_error(Thor::MalformattedArgumentError, /does not appear to exist/)
86+
end
87+
7388
it "does change the file if already includes content and :force is true" do
7489
invoke! "doc/README", :before => "__end__" do
7590
"more content\n"

0 commit comments

Comments
 (0)