atomic_write: repair permissions after writing

This restores the original file uid, gid and permissions separately.
(ActiveSupport does it in a single step - atomically. This is not
useful in our use case because it may lead to ACL changes.)

Fixes #5916
This commit is contained in:
L. E. Segovia 2019-04-12 18:46:57 +00:00
parent 73d2d956cf
commit f706fffc6c
No known key found for this signature in database
GPG Key ID: D5D1DC48B52B7AD5

View File

@ -163,9 +163,29 @@ class Pathname
# NOTE: This always overwrites.
def atomic_write(content)
old_stat = (stat if exist?)
File.atomic_write(self) do |file|
file.write(content)
end
return unless old_stat
# Try to restore original file's permissions separately
# atomic_write does it itself, but it actually erases
# them if chown fails
begin
# Set correct permissions on new file
chown(old_stat.uid, nil)
chown(nil, old_stat.gid)
rescue Errno::EPERM, Errno::EACCES # rubocop:disable Lint/HandleExceptions
# Changing file ownership failed, moving on.
end
begin
# This operation will affect filesystem ACL's
chmod(old_stat.mode)
rescue Errno::EPERM, Errno::EACCES # rubocop:disable Lint/HandleExceptions
# Changing file permissions failed, moving on.
end
end
# @private