Skip to content

Commit e1333f5

Browse files
committed
feat: add option to have gsub_file error if file contents don't change
1 parent f1ba900 commit e1333f5

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

lib/thor/actions/file_manipulation.rb

+8-2
Original file line numberDiff line numberDiff line change
@@ -249,7 +249,8 @@ def inject_into_module(path, module_name, *args, &block)
249249
# path<String>:: path of the file to be changed
250250
# flag<Regexp|String>:: the regexp or string to be replaced
251251
# replacement<String>:: the replacement, can be also given as a block
252-
# config<Hash>:: give :verbose => false to not log the status, and
252+
# config<Hash>:: give :verbose => false to not log the status,
253+
# :error_on_no_change => true to raise an error if the file does not change, and
253254
# :force => true, to force the replacement regardless of runner behavior.
254255
#
255256
# ==== Example
@@ -270,7 +271,12 @@ def gsub_file(path, flag, *args, &block)
270271

271272
unless options[:pretend]
272273
content = File.binread(path)
273-
content.gsub!(flag, *args, &block)
274+
success = content.gsub!(flag, *args, &block)
275+
276+
if success.nil? && config.fetch(:error_on_no_change, false)
277+
raise Thor::Error, "The content of #{path} did not change"
278+
end
279+
274280
File.open(path, "wb") { |file| file.write(content) }
275281
end
276282
end

spec/actions/file_manipulation_spec.rb

+20
Original file line numberDiff line numberDiff line change
@@ -318,6 +318,26 @@ def file
318318
it "does not log status if required" do
319319
expect(action(:gsub_file, file, "__", verbose: false) { |match| match * 2 }).to be_empty
320320
end
321+
322+
it "does not care if the file contents did not change" do
323+
action :gsub_file, "doc/README", "___start___", "START"
324+
expect(File.binread(file)).to eq("__start__\nREADME\n__end__\n")
325+
end
326+
327+
context "with error_on_no_change" do
328+
it "replaces the content in the file" do
329+
action :gsub_file, "doc/README", "__start__", "START", error_on_no_change: true
330+
expect(File.binread(file)).to eq("START\nREADME\n__end__\n")
331+
end
332+
333+
it "raises if the file contents did not change" do
334+
expect do
335+
action :gsub_file, "doc/README", "___start___", "START", error_on_no_change: true
336+
end.to raise_error(Thor::Error)
337+
338+
expect(File.binread(file)).to eq("__start__\nREADME\n__end__\n")
339+
end
340+
end
321341
end
322342

323343
context "with revoke behavior" do

0 commit comments

Comments
 (0)