Add 'open' functions for reading files.
This commit is contained in:
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user