Skip to content

Commit

Permalink
Only use red color for errors if terminal supports ANSI
Browse files Browse the repository at this point in the history
  • Loading branch information
Olivier Halligon committed Oct 16, 2017
1 parent e5b50ad commit 8012f10
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
4 changes: 2 additions & 2 deletions Sources/Commander/CommandRunner.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down
20 changes: 18 additions & 2 deletions Sources/Commander/Error.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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<FILE> = stdout) {
if ANSI.isTerminalSupported {
fputs("\(self)\(string)\(ANSI.reset)\n", output)
} else {
fputs("\(string)\n", output)
}
}
}

0 comments on commit 8012f10

Please sign in to comment.