Skip to content

Commit d08cd61

Browse files
Olivier Halligonkylef
authored andcommitted
fix(ansi): Don't print errors in red if terminal dont support ANSI
Closes #58
1 parent cfbcb29 commit d08cd61

File tree

3 files changed

+22
-4
lines changed

3 files changed

+22
-4
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
- Showing default values for custom `ArgumentConvertible` types are now
88
supported in the `--help` output of commands.
99

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

1113
## 0.8.0
1214

Sources/Commander/CommandRunner.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,10 @@ extension CommandType {
3838
error.print()
3939
exit(1)
4040
} catch let error as CustomStringConvertible {
41-
fputs("\(ANSI.red)\(error.description)\(ANSI.reset)\n", stderr)
41+
ANSI.red.print(error.description, to: stderr)
4242
exit(1)
4343
} catch {
44-
fputs("\(ANSI.red)Unknown error occurred.\(ANSI.reset)\n", stderr)
44+
ANSI.red.print("Unknown error occurred.", to: stderr)
4545
exit(1)
4646
}
4747

Sources/Commander/Error.swift

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,7 @@ protocol ANSIConvertible : Error, CustomStringConvertible {
1313
extension ANSIConvertible {
1414
func print() {
1515
// Check if we are in any term env and the output is a tty.
16-
if let termType = getenv("TERM"), String(cString: termType).lowercased() != "dumb" &&
17-
isatty(fileno(stdout)) != 0 {
16+
if ANSI.isTerminalSupported {
1817
fputs("\(ansiDescription)\n", stderr)
1918
} else {
2019
fputs("\(description)\n", stderr)
@@ -39,4 +38,21 @@ enum ANSI: UInt8, CustomStringConvertible {
3938
var description: String {
4039
return "\u{001B}[\(self.rawValue)m"
4140
}
41+
42+
static var isTerminalSupported: Bool {
43+
if let termType = getenv("TERM"), String(cString: termType).lowercased() != "dumb" &&
44+
isatty(fileno(stdout)) != 0 {
45+
return true
46+
} else {
47+
return false
48+
}
49+
}
50+
51+
func print(_ string: String, to output: UnsafeMutablePointer<FILE> = stdout) {
52+
if ANSI.isTerminalSupported {
53+
fputs("\(self)\(string)\(ANSI.reset)\n", output)
54+
} else {
55+
fputs("\(string)\n", output)
56+
}
57+
}
4258
}

0 commit comments

Comments
 (0)