Skip to content

Commit 0b1fd4c

Browse files
authored
Merge pull request #1906 from spevans/pr_set_attributes_chmod_42
[4.2] FileManager: setAttributes(ofItemAtPath:) should throw if chmod fails.
2 parents 430bdf0 + 1712f5b commit 0b1fd4c

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

Foundation/FileManager.swift

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -188,9 +188,11 @@ open class FileManager : NSObject {
188188
#elseif os(Linux) || os(Android) || CYGWIN
189189
let modeT = number.uint32Value
190190
#endif
191-
if chmod(path, mode_t(modeT)) != 0 {
192-
fatalError("errno \(errno)")
193-
}
191+
try _fileSystemRepresentation(withPath: path, {
192+
guard chmod($0, mode_t(modeT)) == 0 else {
193+
throw _NSErrorWithErrno(errno, reading: false, path: path)
194+
}
195+
})
194196
} else {
195197
fatalError("Attribute type not implemented: \(attribute)")
196198
}
@@ -964,7 +966,13 @@ open class FileManager : NSObject {
964966
}
965967
return UnsafePointer(buf)
966968
}
967-
969+
970+
internal func _fileSystemRepresentation<ResultType>(withPath path: String, _ body: (UnsafePointer<Int8>) throws -> ResultType) rethrows -> ResultType {
971+
let fsRep = fileSystemRepresentation(withPath: path)
972+
defer { fsRep.deallocate() }
973+
return try body(fsRep)
974+
}
975+
968976
/* stringWithFileSystemRepresentation:length: returns an NSString created from an array of bytes that are in the filesystem representation.
969977
*/
970978
open func string(withFileSystemRepresentation str: UnsafePointer<Int8>, length len: Int) -> String {

TestFoundation/TestFileManager.swift

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,15 @@ class TestFileManager : XCTestCase {
326326
} catch {
327327
XCTFail("Failed to clean up files")
328328
}
329+
330+
// test non existant file
331+
let noSuchFile = NSTemporaryDirectory() + "fileThatDoesntExist"
332+
try? fm.removeItem(atPath: noSuchFile)
333+
do {
334+
try fm.setAttributes([.posixPermissions: 0], ofItemAtPath: noSuchFile)
335+
XCTFail("Setting permissions of non-existant file should throw")
336+
} catch {
337+
}
329338
}
330339

331340
func test_pathEnumerator() {

0 commit comments

Comments
 (0)