Skip to content

Commit

Permalink
feat: add option to have gsub_file error if file contents don't change
Browse files Browse the repository at this point in the history
  • Loading branch information
G-Rath committed Feb 23, 2024
1 parent f1ba900 commit e1333f5
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
10 changes: 8 additions & 2 deletions lib/thor/actions/file_manipulation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,8 @@ def inject_into_module(path, module_name, *args, &block)
# path<String>:: path of the file to be changed
# flag<Regexp|String>:: the regexp or string to be replaced
# replacement<String>:: the replacement, can be also given as a block
# config<Hash>:: give :verbose => false to not log the status, and
# config<Hash>:: give :verbose => false to not log the status,
# :error_on_no_change => true to raise an error if the file does not change, and
# :force => true, to force the replacement regardless of runner behavior.
#
# ==== Example
Expand All @@ -270,7 +271,12 @@ def gsub_file(path, flag, *args, &block)

unless options[:pretend]
content = File.binread(path)
content.gsub!(flag, *args, &block)
success = content.gsub!(flag, *args, &block)

if success.nil? && config.fetch(:error_on_no_change, false)
raise Thor::Error, "The content of #{path} did not change"
end

File.open(path, "wb") { |file| file.write(content) }
end
end
Expand Down
20 changes: 20 additions & 0 deletions spec/actions/file_manipulation_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,26 @@ def file
it "does not log status if required" do
expect(action(:gsub_file, file, "__", verbose: false) { |match| match * 2 }).to be_empty
end

it "does not care if the file contents did not change" do
action :gsub_file, "doc/README", "___start___", "START"
expect(File.binread(file)).to eq("__start__\nREADME\n__end__\n")
end

context "with error_on_no_change" do
it "replaces the content in the file" do
action :gsub_file, "doc/README", "__start__", "START", error_on_no_change: true
expect(File.binread(file)).to eq("START\nREADME\n__end__\n")
end

it "raises if the file contents did not change" do
expect do
action :gsub_file, "doc/README", "___start___", "START", error_on_no_change: true
end.to raise_error(Thor::Error)

expect(File.binread(file)).to eq("__start__\nREADME\n__end__\n")
end
end
end

context "with revoke behavior" do
Expand Down

0 comments on commit e1333f5

Please sign in to comment.