brew/Library/Homebrew/utils/inreplace.rb
BrewTestBot 13d544e11e Core files style updates.
Closes Homebrew/homebrew#42354.

Signed-off-by: Mike McQuaid <mike@mikemcquaid.com>
2015-08-03 13:22:35 +01:00

34 lines
797 B
Ruby

module Utils
class InreplaceError < RuntimeError
def initialize(errors)
super errors.inject("inreplace failed\n") { |s, (path, errs)|
s << "#{path}:\n" << errs.map { |e| " #{e}\n" }.join
}
end
end
module Inreplace
def inreplace(paths, before = nil, after = nil)
errors = {}
Array(paths).each do |path|
s = File.open(path, "rb", &:read).extend(StringInreplaceExtension)
if before.nil? && after.nil?
yield s
else
after = after.to_s if Symbol === after
s.gsub!(before, after)
end
errors[path] = s.errors if s.errors.any?
Pathname(path).atomic_write(s)
end
raise InreplaceError.new(errors) if errors.any?
end
module_function :inreplace
end
end