@@ -659,11 +659,21 @@ internal func _NSCreateTemporaryFile(_ filePath: String) throws -> (Int32, Strin
659
659
guard " SCF " . withCString ( encodedAs: UTF16 . self, {
660
660
return GetTempFileNameW ( buf, $0, 0 , & buf) != 0
661
661
} ) else {
662
- throw _NSErrorWithErrno ( Int32 ( GetLastError ( ) ) , reading: false ,
663
- path: filePath)
662
+ throw _NSErrorWithWindowsError ( GetLastError ( ) , reading: false )
664
663
}
665
664
let pathResult = FileManager . default. string ( withFileSystemRepresentation: String ( decoding: buf, as: UTF16 . self) , length: wcslen ( buf) )
666
- let fd = open ( pathResult, _O_CREAT)
665
+ guard let h = CreateFileW ( buf,
666
+ GENERIC_READ | DWORD ( GENERIC_WRITE) ,
667
+ DWORD ( FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE) ,
668
+ nil ,
669
+ DWORD ( OPEN_EXISTING) ,
670
+ DWORD ( FILE_ATTRIBUTE_NORMAL) ,
671
+ nil ) ,
672
+ h != INVALID_HANDLE_VALUE else {
673
+ throw _NSErrorWithWindowsError ( GetLastError ( ) , reading: false )
674
+ }
675
+ // Don't close h, fd is transferred ownership
676
+ let fd = _open_osfhandle ( intptr_t ( bitPattern: h) , 0 )
667
677
#else
668
678
let maxLength = Int ( PATH_MAX) + 1
669
679
var buf = [ Int8] ( repeating: 0 , count: maxLength)
@@ -678,10 +688,22 @@ internal func _NSCreateTemporaryFile(_ filePath: String) throws -> (Int32, Strin
678
688
}
679
689
680
690
internal func _NSCleanupTemporaryFile( _ auxFilePath: String , _ filePath: String ) throws {
691
+ #if os(Windows)
692
+ try auxFilePath. withCString ( encodedAs: UTF16 . self) { fromPath in
693
+ try filePath. withCString ( encodedAs: UTF16 . self) { toPath in
694
+ let res = CopyFileW ( fromPath, toPath, /*bFailIfExists=*/false )
695
+ try ? FileManager . default. removeItem ( atPath: auxFilePath)
696
+ if !res {
697
+ throw _NSErrorWithWindowsError ( GetLastError ( ) , reading: false )
698
+ }
699
+ }
700
+ }
701
+ #else
681
702
try FileManager . default. _fileSystemRepresentation ( withPath: auxFilePath, andPath: filePath, {
682
703
if rename ( $0, $1) != 0 {
683
704
try ? FileManager . default. removeItem ( atPath: auxFilePath)
684
705
throw _NSErrorWithErrno ( errno, reading: false , path: filePath)
685
706
}
686
707
} )
708
+ #endif
687
709
}
0 commit comments