From a377eb18fddcd96ad1663e13ea53168d1672f7c5 Mon Sep 17 00:00:00 2001 From: Kare Morstol Date: Sun, 23 Nov 2014 23:28:06 +0100 Subject: [PATCH] =?UTF-8?q?Add=20better=20error=20reporting=20to=20?= =?UTF-8?q?=E2=80=9Copen=E2=80=9D=20function.=20Add=20public=20function=20?= =?UTF-8?q?"printErrorAndExit".?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- SwiftShell/FileHandle.swift | 41 +++++++++++++------------- SwiftShellTests/FileHandle_Tests.swift | 3 +- 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/SwiftShell/FileHandle.swift b/SwiftShell/FileHandle.swift index 24bb2e6..f20c197 100644 --- a/SwiftShell/FileHandle.swift +++ b/SwiftShell/FileHandle.swift @@ -58,30 +58,31 @@ extension FileHandle: WriteableStreamType { } } - -public enum FileMode { - case Read, Write, ReadAndWrite +/** Print message to standard error and halt execution */ +@noreturn public func printErrorAndExit (errormessage: String) { + standarderror.writeln("SwiftShell: " + errormessage) + exit(EXIT_FAILURE) } -public func open (path: String, mode: FileMode = .Read) -> FileHandle { - var filehandle: FileHandle? - switch mode { - case .Read: - filehandle = FileHandle(forReadingAtPath: path) - case .Write: - filehandle = FileHandle(forWritingAtPath: path) - case .ReadAndWrite: - filehandle = FileHandle(forUpdatingAtPath: path) - } +/** Open a file for reading, and exit if an error occurs. */ +public func open (path: String) -> ReadableStreamType { - // file may be nil if for instance path is invalid - // TODO: it physically pains me to write the next lines. Proper error handling is forthcoming. - if filehandle == nil { - standarderror.write("Error: Opening file \"\(path)\" failed.\n") - exit(EXIT_FAILURE) - } + if let url = NSURL(fileURLWithPath: path) { - return filehandle! + var error: NSError? + let filehandle = FileHandle(forReadingFromURL: url, error: &error) + + if let error = error { + var fileaccesserror: NSError? + url.checkResourceIsReachableAndReturnError(&fileaccesserror) + printErrorAndExit( fileaccesserror?.localizedDescription ?? error.localizedDescription ) + } + + return filehandle! + + } else { + printErrorAndExit("Invalid file path: \(path)") + } } diff --git a/SwiftShellTests/FileHandle_Tests.swift b/SwiftShellTests/FileHandle_Tests.swift index 255e2cb..594d6ee 100644 --- a/SwiftShellTests/FileHandle_Tests.swift +++ b/SwiftShellTests/FileHandle_Tests.swift @@ -11,10 +11,9 @@ import XCTest class FileHandle_Tests: XCTestCase { - // waiting for error handling to be implemented func notestOpenForReadingFileWhichDoesNotExist () { + // prints error message and stops execution. let file = open("file which does not exist") - XCTFail("not implemented yet") } func testReadFileLineByLine () {