@@ -760,17 +760,34 @@ internal func _NSCreateTemporaryFile(_ filePath: String) throws -> (Int32, Strin
760
760
// Don't close h, fd is transferred ownership
761
761
let fd = _open_osfhandle ( intptr_t ( bitPattern: h) , 0 )
762
762
#else
763
- let maxLength = Int ( PATH_MAX) + 1
764
- var buf = [ Int8] ( repeating: 0 , count: maxLength)
765
- let _ = template. _nsObject. getFileSystemRepresentation ( & buf, maxLength: maxLength)
766
- guard let name = mktemp ( & buf) else {
767
- throw _NSErrorWithErrno ( errno, reading: false , path: filePath)
763
+ var filename = template. utf8CString
764
+
765
+ let result = filename. withUnsafeMutableBufferPointer { ( ptr: inout UnsafeMutableBufferPointer < CChar > ) -> ( Int32 , String ) ? in
766
+ // filename is updated with the temp file name on success.
767
+ let fd = mkstemp ( ptr. baseAddress!)
768
+ if fd == - 1 {
769
+ return nil
770
+ } else {
771
+ guard let fname = String ( utf8String: ptr. baseAddress!) else {
772
+ // Couldnt convert buffer back to filename.
773
+ close ( fd)
774
+ errno = ENOENT
775
+ return nil
776
+ }
777
+ return ( fd, fname)
778
+ }
779
+ }
780
+
781
+ guard let ( fd, pathResult) = result else {
782
+ throw _NSErrorWithErrno ( errno, reading: false , path: template)
768
783
}
769
- let fd = open ( name, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)
770
- if fd == - 1 {
771
- throw _NSErrorWithErrno ( errno, reading: false , path: filePath)
784
+
785
+ // Set the file mode to match macOS
786
+ guard fchmod ( fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH) != - 1 else {
787
+ let _errno = errno
788
+ close ( fd)
789
+ throw _NSErrorWithErrno ( _errno, reading: false , path: pathResult)
772
790
}
773
- let pathResult = FileManager . default. string ( withFileSystemRepresentation: buf, length: Int ( strlen ( buf) ) )
774
791
#endif
775
792
return ( fd, pathResult)
776
793
}
0 commit comments