diff --git a/CHANGELOG.md b/CHANGELOG.md index ee9ad12..b80fafb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ - Showing default values for custom `ArgumentConvertible` types are now supported in the `--help` output of commands. +- Only print errors in red if the output terminal supports ANSI colour codes. + [#58](https://github.com/kylef/Commander/pull/58) ## 0.8.0 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) + } + } }