From 752a13b40a8f7f349e8c47bc63f6fb81e28d5805 Mon Sep 17 00:00:00 2001 From: Saleem Abdulrasool Date: Mon, 24 Jul 2023 10:11:30 -0700 Subject: [PATCH] Foundation: adjust `_NSCleanupTemporaryFile` on Windows Prefer to use `withNTPathRepresentation` over the `_fileSystemRepresentation` usage as the former will not convert to the NT UNC path representation which may break on long paths. --- Sources/Foundation/NSPathUtilities.swift | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/Sources/Foundation/NSPathUtilities.swift b/Sources/Foundation/NSPathUtilities.swift index da9b959e39..beba8d86eb 100644 --- a/Sources/Foundation/NSPathUtilities.swift +++ b/Sources/Foundation/NSPathUtilities.swift @@ -810,20 +810,24 @@ internal func _NSCreateTemporaryFile(_ filePath: String) throws -> (Int32, Strin } internal func _NSCleanupTemporaryFile(_ auxFilePath: String, _ filePath: String) throws { - try FileManager.default._fileSystemRepresentation(withPath: auxFilePath, andPath: filePath, { #if os(Windows) - let res = CopyFileW($0, $1, /*bFailIfExists=*/false) - try? FileManager.default.removeItem(atPath: auxFilePath) - if !res { - throw _NSErrorWithWindowsError(GetLastError(), reading: false) + try withNTPathRepresentation(of: auxFilePath) { pwszSource in + try withNTPathRepresentation(of: filePath) { pwszDestination in + guard CopyFileW(pwszSource, pwszDestination, false) else { + let dwErrorCode = GetLastError() + try? FileManager.default.removeItem(atPath: auxFilePath) + throw _NSErrorWithWindowsError(dwErrorCode, reading: false) + } } + } #else + try FileManager.default._fileSystemRepresentation(withPath: auxFilePath, andPath: filePath, { if rename($0, $1) != 0 { let errorCode = errno try? FileManager.default.removeItem(atPath: auxFilePath) throw _NSErrorWithErrno(errorCode, reading: false, path: filePath) } -#endif }) +#endif } #endif