blob: 74373a9ae06209c6a63700169f2cf08995a92042 [file] [log] [blame]
Brian Silvermancbbc3c42014-02-22 18:33:17 -08001require 'tempfile'
2
3# Writes a file like normal except doesn't do anything if the new contents are
4# the same as what's already there. Useful for helping build tools not rebuild
5# if generated files are re-generated but don't change.
6# Usable as a standard File, including to redirect to with IO.popen etc.
7class WriteIffChanged < Tempfile
8 def initialize(filename)
9 super('write_iff_changed')
10 @filename = filename
11 end
12 def WriteIffChanged.open(filename)
13 out = WriteIffChanged.new(filename)
14 yield out
15 out.close
16 end
17 def close
18 flush
19 contents = File.open(path, 'r') do |f|
20 f.readlines(nil)
21 end
22 if !File.exists?(@filename) ||
23 File.new(@filename, 'r').readlines(nil) != contents
24 File.open(@filename, 'w') do |out|
25 out.write(contents[0])
26 end
27 end
28 super
29 end
30end