2013-07-11 21:55:02 -05:00
|
|
|
module Utils
|
2014-09-28 01:08:31 -05:00
|
|
|
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
|
|
|
|
|
2013-07-11 21:55:02 -05:00
|
|
|
module Inreplace
|
2015-08-03 13:09:07 +01:00
|
|
|
def inreplace(paths, before = nil, after = nil)
|
2014-09-28 01:08:31 -05:00
|
|
|
errors = {}
|
|
|
|
|
2013-07-11 21:55:02 -05:00
|
|
|
Array(paths).each do |path|
|
2014-09-28 01:08:31 -05:00
|
|
|
s = File.open(path, "rb", &:read).extend(StringInreplaceExtension)
|
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
|
2013-08-16 19:50:52 -04:00
|
|
|
after = after.to_s if Symbol === after
|
2014-09-28 01:08:31 -05:00
|
|
|
s.gsub!(before, after)
|
2013-07-11 21:55:02 -05:00
|
|
|
end
|
|
|
|
|
2014-09-28 01:08:31 -05:00
|
|
|
errors[path] = s.errors if s.errors.any?
|
|
|
|
|
2014-03-26 16:07:49 -05:00
|
|
|
Pathname(path).atomic_write(s)
|
2013-07-11 21:55:02 -05:00
|
|
|
end
|
2014-09-28 01:08:31 -05:00
|
|
|
|
|
|
|
raise InreplaceError.new(errors) if errors.any?
|
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
|