diff --git a/SwiftShell/Files.swift b/SwiftShell/Files.swift index 9c876b2..a542dfc 100644 --- a/SwiftShell/Files.swift +++ b/SwiftShell/Files.swift @@ -14,3 +14,24 @@ public let Files = NSFileManager.defaultManager() public func / (leftpath: NSURL, rightpath: String) -> NSURL { return leftpath.URLByAppendingPathComponent(rightpath) } + +/** Run a function which takes a NSErrorPointer. If an NSError occurs, throw it, otherwise return result. */ +func makeThrowable (nserrorfunc: (NSErrorPointer) -> T) throws -> T { + var maybeerror: NSError? + let result = nserrorfunc(&maybeerror) + if let actualerror = maybeerror { + throw actualerror + } + return result +} + +/** Open a file for reading, throw if an error occurs. */ +public func open (path: String, encoding: NSStringEncoding = main.encoding) throws -> ReadableStream { + return try open(NSURL(fileURLWithPath: path, isDirectory: false), encoding: encoding) +} + +/** Open a file for reading, throw if an error occurs. */ +public func open (path: NSURL, encoding: NSStringEncoding = main.encoding) throws -> ReadableStream { + try makeThrowable(path.checkResourceIsReachableAndReturnError) + return ReadableStream(try NSFileHandle(forReadingFromURL: path), encoding: encoding) +} diff --git a/SwiftShellTests/Files_Tests.swift b/SwiftShellTests/Files_Tests.swift index b6a8b37..3e2d8da 100644 --- a/SwiftShellTests/Files_Tests.swift +++ b/SwiftShellTests/Files_Tests.swift @@ -17,3 +17,24 @@ class UrlAppendationOperator: XCTestCase { XCTAssertEqual( NSURL(string: "dir")! / "file.txt", NSURL(string: "dir/file.txt")) } } + +class Open: XCTestCase { + + func testReadFile () { + let shorttextpath = pathForTestResource("shorttext", type: "txt") + + AssertNoThrow { + let file = try open(shorttextpath) + XCTAssert(file.read().hasPrefix("Lorem ipsum dolor")) + } + } + + func testReadFileWhichDoesNotExist () { + do { + let _ = try open("/nonexistingfile.txt") + XCTFail("Creating stream from non-existing file did not throw error") + } catch { + + } + } +}