Module: Canon::Rebaseliner::AtomicWriter
- Defined in:
- lib/canon/rebaseliner/atomic_writer.rb
Overview
Write a file atomically by writing to a same-directory tempfile and renaming over the target. Preserves the original file's mode. Avoids half-written files on Ctrl-C.
Class Method Summary collapse
Class Method Details
.write(path, contents) ⇒ void
This method returns an undefined value.
17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/canon/rebaseliner/atomic_writer.rb', line 17 def write(path, contents) original_mode = File.stat(path).mode dir = File.dirname(path) Tempfile.create(["canon-rebaseline", ".tmp"], dir) do |tmp| tmp.binmode tmp.write(contents) tmp.flush tmp.fsync tmp.close File.chmod(original_mode, tmp.path) File.rename(tmp.path, path) end end |