Skip to content

Commit 3a928c8

Browse files
authored
Merge pull request #2927 from spevans/pr_mkstemp
2 parents fdbaf50 + 940aa06 commit 3a928c8

File tree

1 file changed

+26
-9
lines changed

1 file changed

+26
-9
lines changed

Diff for: Sources/Foundation/NSPathUtilities.swift

+26-9
Original file line numberDiff line numberDiff line change
@@ -760,17 +760,34 @@ internal func _NSCreateTemporaryFile(_ filePath: String) throws -> (Int32, Strin
760760
// Don't close h, fd is transferred ownership
761761
let fd = _open_osfhandle(intptr_t(bitPattern: h), 0)
762762
#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)
768783
}
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)
772790
}
773-
let pathResult = FileManager.default.string(withFileSystemRepresentation: buf, length: Int(strlen(buf)))
774791
#endif
775792
return (fd, pathResult)
776793
}

0 commit comments

Comments
 (0)