From 8012f1004847c774f3daf28de625a3f620e17f0f Mon Sep 17 00:00:00 2001 From: Olivier Halligon Date: Tue, 17 Oct 2017 01:36:39 +0200 Subject: [PATCH] Only use red color for errors if terminal supports ANSI --- Sources/Commander/CommandRunner.swift | 4 ++-- Sources/Commander/Error.swift | 20 ++++++++++++++++++-- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/Sources/Commander/CommandRunner.swift b/Sources/Commander/CommandRunner.swift index b344651..c421853 100644 --- a/Sources/Commander/CommandRunner.swift +++ b/Sources/Commander/CommandRunner.swift @@ -38,10 +38,10 @@ extension CommandType { error.print() exit(1) } catch let error as CustomStringConvertible { - fputs("\(ANSI.red)\(error.description)\(ANSI.reset)\n", stderr) + ANSI.red.print(error.description, to: stderr) exit(1) } catch { - fputs("\(ANSI.red)Unknown error occurred.\(ANSI.reset)\n", stderr) + ANSI.red.print("Unknown error occurred.", to: stderr) exit(1) } diff --git a/Sources/Commander/Error.swift b/Sources/Commander/Error.swift index 46815b9..05ad6a8 100644 --- a/Sources/Commander/Error.swift +++ b/Sources/Commander/Error.swift @@ -13,8 +13,7 @@ protocol ANSIConvertible : Error, CustomStringConvertible { extension ANSIConvertible { func print() { // Check if we are in any term env and the output is a tty. - if let termType = getenv("TERM"), String(cString: termType).lowercased() != "dumb" && - isatty(fileno(stdout)) != 0 { + if ANSI.isTerminalSupported { fputs("\(ansiDescription)\n", stderr) } else { fputs("\(description)\n", stderr) @@ -39,4 +38,21 @@ enum ANSI: UInt8, CustomStringConvertible { var description: String { return "\u{001B}[\(self.rawValue)m" } + + static var isTerminalSupported: Bool { + if let termType = getenv("TERM"), String(cString: termType).lowercased() != "dumb" && + isatty(fileno(stdout)) != 0 { + return true + } else { + return false + } + } + + func print(_ string: String, to output: UnsafeMutablePointer = stdout) { + if ANSI.isTerminalSupported { + fputs("\(self)\(string)\(ANSI.reset)\n", output) + } else { + fputs("\(string)\n", output) + } + } }