Method: Sass::Util#atomic_create_and_write_file

Defined in:
lib/sass/util.rb

#atomic_create_and_write_file(filename, perms = 0666) {|tmpfile| ... }

This creates a temp file and yields it for writing. When the write is complete, the file is moved into the desired location. The atomicity of this operation is provided by the filesystem's rename operation.

Yield Parameters:

  • tmpfile (Tempfile)

    The temp file that can be written to.



1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
# File 'lib/sass/util.rb', line 1054

def atomic_create_and_write_file(filename, perms = 0666)
  require 'tempfile'
  tmpfile = Tempfile.new(File.basename(filename), File.dirname(filename))
  tmpfile.binmode if tmpfile.respond_to?(:binmode)
  result = yield tmpfile
  tmpfile.close
  ATOMIC_WRITE_MUTEX.synchronize do
    begin
      File.chmod(perms & ~File.umask, tmpfile.path)
    rescue Errno::EPERM
      # If we don't have permissions to chmod the file, don't let that crash
      # the compilation. See issue 1215.
    end
    File.rename tmpfile.path, filename
  end
  result
ensure
  # close and remove the tempfile if it still exists,
  # presumably due to an error during write
  tmpfile.close if tmpfile
  tmpfile.unlink if tmpfile
end