Skip to content

Commit

Permalink
Force file removal in Windows _removeItem
Browse files Browse the repository at this point in the history
unlink on posix ignores if a file is read only since it only needs write
permissions on the parent directory to remove it. To emulate this on
Windows, if a file is read only, unset the read only bit and then remove
it.
  • Loading branch information
gmittert committed Jun 11, 2019
1 parent e1071a9 commit a762b87
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions Foundation/FileManager+Win32.swift
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,14 @@ extension FileManager {
let fsrPath = String(utf16CodeUnits: &fsrBuf, count: length)

let faAttributes = try windowsFileAttributes(atPath: fsrPath)

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)
}
}

if faAttributes.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY) == 0 {
if !fsrPath.withCString(encodedAs: UTF16.self, DeleteFileW) {
throw _NSErrorWithWindowsError(GetLastError(), reading: false)
Expand Down Expand Up @@ -458,6 +466,14 @@ extension FileManager {
count: MemoryLayout.size(ofValue: ffd.cFileName)))
let file = String(decodingCString: fileArr, as: UTF16.self)
itemPath = "\(currentDir)\\\(file)"

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)
}
}

if (ffd.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY) != 0) {
if file != "." && file != ".." {
dirStack.append(itemPath)
Expand Down

0 comments on commit a762b87

Please sign in to comment.