blob: 8ed32bc5b3c63c060bedb8d85a628a8ef9d7daf5 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
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
|