diff --git a/Library/Homebrew/extend/pathname.rb b/Library/Homebrew/extend/pathname.rb index 6950b041f4..80d5b8e5aa 100644 --- a/Library/Homebrew/extend/pathname.rb +++ b/Library/Homebrew/extend/pathname.rb @@ -163,9 +163,31 @@ 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 + # Changing file ownership failed, moving on. + nil + end + begin + # This operation will affect filesystem ACL's + chmod(old_stat.mode) + rescue Errno::EPERM, Errno::EACCES + # Changing file permissions failed, moving on. + nil + end end # @private