Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# Commander Changelog

## Master

### Bug Fixes

- Only print errors in red if the output terminal supports ANSI color codes.
[#58](https://github.com/kylef/Commander/pull/58)

## 0.8.0

### Enhancements
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)
}
}
}