brew/Library/Homebrew/utils/inreplace.rb
vidusheeamoli fd382d2ecd srb: set utils/inreplace.rb to true and refactor
- Sorbet gives preference to class methods over methods defined in
  included modules, hence Sorbet was unavailable to resolve the
definition of the gsub! method.
- The gsub! method in StringInreplaceExtension conflicts with the definition in String.
- This PR refactors the call to the gsub! method so that a custom object
  is exposed instead of a string.
2020-07-26 12:43:31 +05:30

48 lines
1.5 KiB
Ruby

# frozen_string_literal: true
module Utils
class InreplaceError < RuntimeError
def initialize(errors)
formatted_errors = errors.reduce(+"inreplace failed\n") do |s, (path, errs)|
s << "#{path}:\n" << errs.map { |e| " #{e}\n" }.join
end
super formatted_errors.freeze
end
end
module Inreplace
# Sometimes we have to change a bit before we install. Mostly we
# prefer a patch but if you need the `prefix` of this formula in the
# patch you have to resort to `inreplace`, because in the patch
# you don't have access to any var defined by the formula. Only
# `HOMEBREW_PREFIX` is available in the embedded patch.
#
# `inreplace` supports regular expressions:
# <pre>inreplace "somefile.cfg", /look[for]what?/, "replace by #{bin}/tool"</pre>
def inreplace(paths, before = nil, after = nil, audit_result = true)
errors = {}
errors["`paths` (first) parameter"] = ["`paths` was empty"] if paths.blank?
Array(paths).each do |path|
str = File.open(path, "rb", &:read) || ""
s = StringInreplaceExtension.new(str)
if before.nil? && after.nil?
yield s
else
after = after.to_s if after.is_a? Symbol
s.gsub!(before, after, audit_result)
end
errors[path] = s.errors unless s.errors.empty?
Pathname(path).atomic_write(s.inreplace_string)
end
raise InreplaceError, errors unless errors.empty?
end
module_function :inreplace
end
end