Skip to content

Commit

Permalink
fix(ansi): Don't print errors in red if terminal dont support ANSI
Browse files Browse the repository at this point in the history
Closes #58
  • Loading branch information
Olivier Halligon authored and kylef committed Nov 25, 2017
1 parent cfbcb29 commit d08cd61
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
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 d08cd61

Please sign in to comment.