Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Only use red color for errors if terminal supports ANSI #58

Closed
wants to merge 3 commits into from
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)
}
}
}