2019-04-19 15:38:03 +09:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2013-07-11 21:55:02 -05:00
|
|
|
module Utils
|
2014-09-28 01:08:31 -05:00
|
|
|
class InreplaceError < RuntimeError
|
|
|
|
def initialize(errors)
|
2019-04-20 14:07:29 +09:00
|
|
|
formatted_errors = errors.reduce(+"inreplace failed\n") do |s, (path, errs)|
|
2014-09-28 01:08:31 -05:00
|
|
|
s << "#{path}:\n" << errs.map { |e| " #{e}\n" }.join
|
2016-09-11 17:47:04 +01:00
|
|
|
end
|
2019-04-20 14:07:29 +09:00
|
|
|
super formatted_errors.freeze
|
2014-09-28 01:08:31 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2013-07-11 21:55:02 -05:00
|
|
|
module Inreplace
|
2015-08-29 10:56:24 +01:00
|
|
|
# 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
|
2018-10-18 21:42:43 -04:00
|
|
|
# `HOMEBREW_PREFIX` is available in the embedded patch.
|
|
|
|
#
|
|
|
|
# `inreplace` supports regular expressions:
|
2015-08-29 10:56:24 +01:00
|
|
|
# <pre>inreplace "somefile.cfg", /look[for]what?/, "replace by #{bin}/tool"</pre>
|
2016-07-18 08:49:52 -07:00
|
|
|
def inreplace(paths, before = nil, after = nil, audit_result = true)
|
2014-09-28 01:08:31 -05:00
|
|
|
errors = {}
|
|
|
|
|
2019-11-20 19:10:15 +00:00
|
|
|
errors["`paths` (first) parameter"] = ["`paths` was empty"] if paths.blank?
|
|
|
|
|
2013-07-11 21:55:02 -05:00
|
|
|
Array(paths).each do |path|
|
2020-07-25 00:48:15 +05:30
|
|
|
str = File.open(path, "rb", &:read) || ""
|
|
|
|
s = StringInreplaceExtension.new(str)
|
2013-07-11 21:55:02 -05:00
|
|
|
|
|
|
|
if before.nil? && after.nil?
|
2014-09-28 01:08:31 -05:00
|
|
|
yield s
|
2013-07-11 21:55:02 -05:00
|
|
|
else
|
2016-09-11 17:47:04 +01:00
|
|
|
after = after.to_s if after.is_a? Symbol
|
2016-07-18 08:49:52 -07:00
|
|
|
s.gsub!(before, after, audit_result)
|
2013-07-11 21:55:02 -05:00
|
|
|
end
|
|
|
|
|
2016-08-05 22:01:32 +08:00
|
|
|
errors[path] = s.errors unless s.errors.empty?
|
2014-09-28 01:08:31 -05:00
|
|
|
|
2020-07-25 00:48:15 +05:30
|
|
|
Pathname(path).atomic_write(s.inreplace_string)
|
2013-07-11 21:55:02 -05:00
|
|
|
end
|
2014-09-28 01:08:31 -05:00
|
|
|
|
2016-09-11 17:47:04 +01:00
|
|
|
raise InreplaceError, errors unless errors.empty?
|
2013-07-11 21:55:02 -05:00
|
|
|
end
|
2014-06-18 19:23:42 -05:00
|
|
|
module_function :inreplace
|
2013-07-11 21:55:02 -05:00
|
|
|
end
|
|
|
|
end
|