Skip to content

Fixing up Windows TestFileManager #2339

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 11, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 35 additions & 29 deletions Foundation/FileManager+Win32.swift
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ extension FileManager {
try path.withCString(encodedAs: UTF16.self) {
if !CreateDirectoryW($0, psaAttributes) {
// FIXME(compnerd) pass along path
throw _NSErrorWithWindowsError(GetLastError(), reading: false)
throw _NSErrorWithWindowsError(GetLastError(), reading: false, paths: [path])
}
}
if let attr = attributes {
Expand All @@ -197,7 +197,7 @@ extension FileManager {

let hDirectory: HANDLE = FindFirstFileW($0, &ffd)
if hDirectory == INVALID_HANDLE_VALUE {
throw _NSErrorWithWindowsError(GetLastError(), reading: true)
throw _NSErrorWithWindowsError(GetLastError(), reading: true, paths: [path])
}
defer { FindClose(hDirectory) }

Expand All @@ -208,7 +208,7 @@ extension FileManager {
}
}
if path != "." && path != ".." {
try closure(path, Int32(ffd.dwFileAttributes))
try closure(path.standardizingPath, Int32(ffd.dwFileAttributes))
}
} while FindNextFileW(hDirectory, &ffd)
}
Expand All @@ -222,7 +222,7 @@ extension FileManager {
if entryType & FILE_ATTRIBUTE_DIRECTORY == FILE_ATTRIBUTE_DIRECTORY {
let subPath: String = joinPath(prefix: path, suffix: entryName)
let entries = try subpathsOfDirectory(atPath: subPath)
contents.append(contentsOf: entries.map { joinPath(prefix: entryName, suffix: $0) })
contents.append(contentsOf: entries.map { joinPath(prefix: entryName, suffix: $0).standardizingPath })
}
})
return contents
Expand All @@ -232,7 +232,7 @@ extension FileManager {
var faAttributes: WIN32_FILE_ATTRIBUTE_DATA = WIN32_FILE_ATTRIBUTE_DATA()
return try path.withCString(encodedAs: UTF16.self) {
if !GetFileAttributesExW($0, GetFileExInfoStandard, &faAttributes) {
throw _NSErrorWithWindowsError(GetLastError(), reading: true)
throw _NSErrorWithWindowsError(GetLastError(), reading: true, paths: [path])
}
return faAttributes
}
Expand All @@ -248,24 +248,24 @@ extension FileManager {
try path.withCString(encodedAs: UTF16.self) {
let dwLength: DWORD = GetFullPathNameW($0, 0, nil, nil)
guard dwLength != 0 else {
throw _NSErrorWithWindowsError(GetLastError(), reading: true)
throw _NSErrorWithWindowsError(GetLastError(), reading: true, paths: [path])
}
var szVolumePath: [WCHAR] = Array<WCHAR>(repeating: 0, count: Int(dwLength + 1))

guard GetVolumePathNameW($0, &szVolumePath, dwLength) else {
throw _NSErrorWithWindowsError(GetLastError(), reading: true)
throw _NSErrorWithWindowsError(GetLastError(), reading: true, paths: [path])
}

var liTotal: ULARGE_INTEGER = ULARGE_INTEGER()
var liFree: ULARGE_INTEGER = ULARGE_INTEGER()

guard GetDiskFreeSpaceExW(&szVolumePath, nil, &liTotal, &liFree) else {
throw _NSErrorWithWindowsError(GetLastError(), reading: true)
throw _NSErrorWithWindowsError(GetLastError(), reading: true, paths: [path])
}

var volumeSerialNumber: DWORD = 0
guard GetVolumeInformationW(&szVolumePath, nil, 0, &volumeSerialNumber, nil, nil, nil, 0) else {
throw _NSErrorWithWindowsError(GetLastError(), reading: true)
throw _NSErrorWithWindowsError(GetLastError(), reading: true, paths: [path])
}

result[.systemSize] = NSNumber(value: liTotal.QuadPart)
Expand All @@ -284,15 +284,17 @@ extension FileManager {
// other doesn't make a lot of sense, we allow it to throw, thus
// disallowing the creation of broken symlinks on Windows (unlike with
// POSIX).
let faAttributes = try windowsFileAttributes(atPath: destPath)
guard let faAttributes = try? windowsFileAttributes(atPath: destPath) else {
throw _NSErrorWithWindowsError(GetLastError(), reading: true, paths: [path, destPath])
}
if faAttributes.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY) == DWORD(FILE_ATTRIBUTE_DIRECTORY) {
dwFlags |= DWORD(SYMBOLIC_LINK_FLAG_DIRECTORY)
}

try path.withCString(encodedAs: UTF16.self) { name in
try destPath.withCString(encodedAs: UTF16.self) { dest in
guard CreateSymbolicLinkW(name, dest, dwFlags) != 0 else {
throw _NSErrorWithWindowsError(GetLastError(), reading: false)
throw _NSErrorWithWindowsError(GetLastError(), reading: true, paths: [path, destPath])
}
}
}
Expand All @@ -317,7 +319,7 @@ extension FileManager {
var szPath = Array<WCHAR>(repeating: 0, count: Int(dwLength + 1))
dwLength = GetFullPathNameW($0, DWORD(szPath.count), &szPath, nil)
guard dwLength > 0 && dwLength <= szPath.count else {
throw _NSErrorWithWindowsError(GetLastError(), reading: true)
throw _NSErrorWithWindowsError(GetLastError(), reading: true, paths: [path])
}
return String(decodingCString: szPath, as: UTF16.self)
}
Expand All @@ -335,7 +337,7 @@ extension FileManager {
try srcPath.withCString(encodedAs: UTF16.self) { src in
try dstPath.withCString(encodedAs: UTF16.self) { dst in
if !CopyFileW(src, dst, false) {
throw _NSErrorWithWindowsError(GetLastError(), reading: false)
throw _NSErrorWithWindowsError(GetLastError(), reading: true, paths: [srcPath, dstPath])
}
}
}
Expand All @@ -358,8 +360,7 @@ extension FileManager {
}

internal func _copyOrLinkDirectoryHelper(atPath srcPath: String, toPath dstPath: String, variant: String = "Copy", _ body: (String, String, FileAttributeType) throws -> ()) throws {
var faAttributes: WIN32_FILE_ATTRIBUTE_DATA = WIN32_FILE_ATTRIBUTE_DATA()
do { faAttributes = try windowsFileAttributes(atPath: srcPath) } catch { return }
let faAttributes = try windowsFileAttributes(atPath: srcPath)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How come we don't need the exception to propagate here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previously, if srcPath didn't exist, it would catch the error from windowsFileAttributes and _copyItem would silently not do anything. This way it bubbles up the exception and throws a file not found as it should.


var fileType = FileAttributeType(attributes: faAttributes, atPath: srcPath)
if fileType == .typeDirectory {
Expand All @@ -372,7 +373,7 @@ extension FileManager {
let src = joinPath(prefix: srcPath, suffix: item)
let dst = joinPath(prefix: dstPath, suffix: item)

do { faAttributes = try windowsFileAttributes(atPath: src) } catch { return }
let faAttributes = try windowsFileAttributes(atPath: src)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And here

fileType = FileAttributeType(attributes: faAttributes, atPath: srcPath)
if fileType == .typeDirectory {
try createDirectory(atPath: dst, withIntermediateDirectories: false, attributes: nil)
Expand All @@ -397,7 +398,7 @@ extension FileManager {
try srcPath.withCString(encodedAs: UTF16.self) { src in
try dstPath.withCString(encodedAs: UTF16.self) { dst in
if !MoveFileExW(src, dst, DWORD(MOVEFILE_COPY_ALLOWED | MOVEFILE_WRITE_THROUGH)) {
throw _NSErrorWithWindowsError(GetLastError(), reading: false)
throw _NSErrorWithWindowsError(GetLastError(), reading: false, paths: [srcPath, dstPath])
}
}
}
Expand All @@ -415,7 +416,7 @@ extension FileManager {
try srcPath.withCString(encodedAs: UTF16.self) { src in
try dstPath.withCString(encodedAs: UTF16.self) { dst in
if !CreateHardLinkW(dst, src, nil) {
throw _NSErrorWithWindowsError(GetLastError(), reading: false)
throw _NSErrorWithWindowsError(GetLastError(), reading: false, paths: [srcPath, dstPath])
}
}
}
Expand All @@ -436,6 +437,11 @@ extension FileManager {
guard alreadyConfirmed || shouldRemoveItemAtPath(path, isURL: isURL) else {
return
}

guard path != "" else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadInvalidFileName.rawValue, userInfo: [NSFilePathErrorKey : NSString(path)])
}

let url = URL(fileURLWithPath: path)
var fsrBuf: [WCHAR] = Array<WCHAR>(repeating: 0, count: Int(MAX_PATH))
_CFURLGetWideFileSystemRepresentation(url._cfObject, false, &fsrBuf, Int(MAX_PATH))
Expand All @@ -447,13 +453,13 @@ extension FileManager {
if faAttributes.dwFileAttributes & DWORD(FILE_ATTRIBUTE_READONLY) == FILE_ATTRIBUTE_READONLY {
let readableAttributes = faAttributes.dwFileAttributes & DWORD(bitPattern: ~FILE_ATTRIBUTE_READONLY)
guard fsrPath.withCString(encodedAs: UTF16.self, { SetFileAttributesW($0, readableAttributes) }) else {
throw _NSErrorWithWindowsError(GetLastError(), reading: false)
throw _NSErrorWithWindowsError(GetLastError(), reading: false, paths: [path])
}
}

if faAttributes.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY) == 0 {
if !fsrPath.withCString(encodedAs: UTF16.self, DeleteFileW) {
throw _NSErrorWithWindowsError(GetLastError(), reading: false)
throw _NSErrorWithWindowsError(GetLastError(), reading: false, paths: [path])
}
return
}
Expand All @@ -469,15 +475,15 @@ extension FileManager {
continue
}
guard GetLastError() == ERROR_DIR_NOT_EMPTY else {
throw _NSErrorWithWindowsError(GetLastError(), reading: false)
throw _NSErrorWithWindowsError(GetLastError(), reading: false, paths: [itemPath])
}
dirStack.append(itemPath)
var ffd: WIN32_FIND_DATAW = WIN32_FIND_DATAW()
let h: HANDLE = (itemPath + "\\*").withCString(encodedAs: UTF16.self, {
FindFirstFileW($0, &ffd)
})
guard h != INVALID_HANDLE_VALUE else {
throw _NSErrorWithWindowsError(GetLastError(), reading: false)
throw _NSErrorWithWindowsError(GetLastError(), reading: false, paths: [itemPath])
}
defer { FindClose(h) }

Expand All @@ -491,7 +497,7 @@ extension FileManager {
if ffd.dwFileAttributes & DWORD(FILE_ATTRIBUTE_READONLY) == FILE_ATTRIBUTE_READONLY {
let readableAttributes = ffd.dwFileAttributes & DWORD(bitPattern: ~FILE_ATTRIBUTE_READONLY)
guard file.withCString(encodedAs: UTF16.self, { SetFileAttributesW($0, readableAttributes) }) else {
throw _NSErrorWithWindowsError(GetLastError(), reading: false)
throw _NSErrorWithWindowsError(GetLastError(), reading: false, paths: [file])
}
}

Expand All @@ -504,7 +510,7 @@ extension FileManager {
continue
}
if !itemPath.withCString(encodedAs: UTF16.self, DeleteFileW) {
throw _NSErrorWithWindowsError(GetLastError(), reading: false)
throw _NSErrorWithWindowsError(GetLastError(), reading: false, paths: [file])
}
}
} while FindNextFileW(h, &ffd)
Expand Down Expand Up @@ -604,7 +610,7 @@ extension FileManager {
/*hTemplateFile=*/nil)
}
if h == INVALID_HANDLE_VALUE {
throw _NSErrorWithWindowsError(GetLastError(), reading: false)
throw _NSErrorWithWindowsError(GetLastError(), reading: false, paths: [path])
}
var info: BY_HANDLE_FILE_INFORMATION = BY_HANDLE_FILE_INFORMATION()
GetFileInformationByHandle(h, &info)
Expand Down Expand Up @@ -675,12 +681,12 @@ extension FileManager {
nil, DWORD(OPEN_EXISTING), 0, nil)
}
if hFile == INVALID_HANDLE_VALUE {
throw _NSErrorWithWindowsError(GetLastError(), reading: true)
throw _NSErrorWithWindowsError(GetLastError(), reading: true, paths: [path])
}
defer { CloseHandle(hFile) }

if !SetFileTime(hFile, nil, &atime, &mtime) {
throw _NSErrorWithWindowsError(GetLastError(), reading: false)
throw _NSErrorWithWindowsError(GetLastError(), reading: false, paths: [path])
}

}
Expand All @@ -705,7 +711,7 @@ extension FileManager {
while let url = _stack.popLast() {
if !FileManager.default.fileExists(atPath: url.path, isDirectory: nil) {
guard let handler = _errorHandler,
handler(url, _NSErrorWithWindowsError(GetLastError(), reading: true))
handler(url, _NSErrorWithWindowsError(GetLastError(), reading: true, paths: [url.path]))
else { return nil }
continue
}
Expand All @@ -719,7 +725,7 @@ extension FileManager {
var isDir: ObjCBool = false
guard FileManager.default.fileExists(atPath: _lastReturned.path, isDirectory: &isDir) else {
guard let handler = _errorHandler,
handler(_lastReturned, _NSErrorWithWindowsError(GetLastError(), reading: true))
handler(_lastReturned, _NSErrorWithWindowsError(GetLastError(), reading: true, paths: [_lastReturned.path]))
else { return nil }
return firstValidItem()
}
Expand Down
18 changes: 13 additions & 5 deletions Foundation/FoundationErrors.swift
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ internal func _NSErrorWithErrno(_ posixErrno : Int32, reading : Bool, path : Str
// https://docs.microsoft.com/en-us/windows/desktop/Debug/system-error-codes
internal let _NSWindowsErrorDomain = "org.swift.Foundation.WindowsError"

internal func _NSErrorWithWindowsError(_ windowsError: DWORD, reading: Bool) -> NSError {
internal func _NSErrorWithWindowsError(_ windowsError: DWORD, reading: Bool, paths: [String]? = nil) -> NSError {
var cocoaError : CocoaError.Code
switch Int32(bitPattern: windowsError) {
case ERROR_LOCK_VIOLATION: cocoaError = .fileLocking
Expand All @@ -225,8 +225,12 @@ internal func _NSErrorWithWindowsError(_ windowsError: DWORD, reading: Bool) ->
default:
if reading {
switch Int32(bitPattern: windowsError) {
case ERROR_FILE_NOT_FOUND: cocoaError = .fileReadNoSuchFile
case ERROR_PATH_NOT_FOUND: cocoaError = .fileReadNoSuchFile
case ERROR_FILE_NOT_FOUND, ERROR_PATH_NOT_FOUND:
// On an empty path, Windows will return FILE/PATH_NOT_FOUND
// rather than invalid path as posix does
cocoaError = paths?.contains("") ?? false
? .fileReadInvalidFileName
: .fileReadNoSuchFile
case ERROR_ACCESS_DENIED: cocoaError = .fileReadNoPermission
case ERROR_INVALID_ACCESS: cocoaError = .fileReadNoPermission
case ERROR_INVALID_DRIVE: cocoaError = .fileReadNoSuchFile
Expand All @@ -240,8 +244,12 @@ internal func _NSErrorWithWindowsError(_ windowsError: DWORD, reading: Bool) ->
}
} else {
switch Int32(bitPattern: windowsError) {
case ERROR_FILE_NOT_FOUND: cocoaError = .fileNoSuchFile
case ERROR_PATH_NOT_FOUND: cocoaError = .fileNoSuchFile
case ERROR_FILE_NOT_FOUND, ERROR_PATH_NOT_FOUND:
// On an empty path, Windows will return FILE/PATH_NOT_FOUND
// rather than invalid path as posix does
cocoaError = paths?.contains("") ?? false
? .fileReadInvalidFileName
: .fileReadNoSuchFile
case ERROR_ACCESS_DENIED: cocoaError = .fileWriteNoPermission
case ERROR_INVALID_ACCESS: cocoaError = .fileWriteNoPermission
case ERROR_INVALID_DRIVE: cocoaError = .fileNoSuchFile
Expand Down
25 changes: 25 additions & 0 deletions TestFoundation/TestFileManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,11 @@ class TestFileManager : XCTestCase {
XCTFail("Failed to clean up file")
}

#if os(Windows)
let permissions = NSNumber(value: Int16(0o700))
#else
let permissions = NSNumber(value: Int16(0o753))
#endif
let attributes = [FileAttributeKey.posixPermissions: permissions]
XCTAssertTrue(fm.createFile(atPath: path, contents: Data(),
attributes: attributes))
Expand Down Expand Up @@ -155,7 +159,12 @@ class TestFileManager : XCTestCase {
try fm.createDirectory(atPath: tmpDir.path, withIntermediateDirectories: false, attributes: nil)
XCTAssertTrue(fm.createFile(atPath: testFile.path, contents: Data()))
try fm.createSymbolicLink(atPath: goodSymLink.path, withDestinationPath: testFile.path)
#if os(Windows)
// Creating a broken symlink is expected to fail on Windows
XCTAssertNil(try? fm.createSymbolicLink(atPath: badSymLink.path, withDestinationPath: "no_such_file"))
#else
try fm.createSymbolicLink(atPath: badSymLink.path, withDestinationPath: "no_such_file")
#endif
try fm.createSymbolicLink(atPath: dirSymLink.path, withDestinationPath: "..")

var isDirFlag: ObjCBool = false
Expand Down Expand Up @@ -197,7 +206,12 @@ class TestFileManager : XCTestCase {

// test unReadable if file has no permissions
try fm.setAttributes([.posixPermissions : NSNumber(value: Int16(0o0000))], ofItemAtPath: path)
#if os(Windows)
// Files are always readable on Windows
XCTAssertTrue(fm.isReadableFile(atPath: path))
#else
XCTAssertFalse(fm.isReadableFile(atPath: path))
#endif

// test readable if file has read permissions
try fm.setAttributes([.posixPermissions : NSNumber(value: Int16(0o0400))], ofItemAtPath: path)
Expand Down Expand Up @@ -237,7 +251,12 @@ class TestFileManager : XCTestCase {

// test unExecutable if file has no permissions
try fm.setAttributes([.posixPermissions : NSNumber(value: Int16(0o0000))], ofItemAtPath: path)
#if os(Windows)
// Files are always executable on Windows
XCTAssertTrue(fm.isExecutableFile(atPath: path))
#else
XCTAssertFalse(fm.isExecutableFile(atPath: path))
#endif

// test executable if file has execute permissions
try fm.setAttributes([.posixPermissions : NSNumber(value: Int16(0o0100))], ofItemAtPath: path)
Expand Down Expand Up @@ -300,8 +319,10 @@ class TestFileManager : XCTestCase {
let fileSystemNumber = attrs[.systemNumber] as? NSNumber
XCTAssertNotEqual(fileSystemNumber!.int64Value, 0)

#if !os(Windows)
let fileSystemFileNumber = attrs[.systemFileNumber] as? NSNumber
XCTAssertNotEqual(fileSystemFileNumber!.int64Value, 0)
#endif

let fileType = attrs[.type] as? FileAttributeType
XCTAssertEqual(fileType!, .typeRegular)
Expand Down Expand Up @@ -401,7 +422,11 @@ class TestFileManager : XCTestCase {
//read back the attributes
do {
let attributes = try fm.attributesOfItem(atPath: path)
#if os(Windows)
XCTAssert((attributes[.posixPermissions] as? NSNumber)?.int16Value == 0o0700)
#else
XCTAssert((attributes[.posixPermissions] as? NSNumber)?.int16Value == 0o0600)
#endif
}
catch { XCTFail("\(error)") }

Expand Down