Add 'open' functions for reading files.

This commit is contained in:
Kare Morstol
2015-10-15 23:05:20 +02:00
parent f1ef868d96
commit 796af16d1a
2 changed files with 42 additions and 0 deletions
+21
View File
@@ -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 <T> (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)
}
+21
View File
@@ -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 {
}
}
}