Skip to content

Commit 592fca1

Browse files
authored
Only enable terminal colors when supported (#241)
1 parent 8269473 commit 592fca1

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

Sources/JavaKitShared/TerminalColors.swift

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,19 @@
1212
//
1313
//===----------------------------------------------------------------------===//
1414

15+
import Foundation
16+
17+
private var isColorSupported: Bool {
18+
let env = ProcessInfo.processInfo.environment
19+
if env["NO_COLOR"] != nil {
20+
return false
21+
}
22+
if let term = env["TERM"], term.contains("color") || env["COLORTERM"] != nil {
23+
return true
24+
}
25+
return false
26+
}
27+
1528
package enum Rainbow: String {
1629
case black = "\u{001B}[0;30m"
1730
case red = "\u{001B}[0;31m"
@@ -139,13 +152,17 @@ package extension String {
139152
self
140153
}
141154
}
142-
155+
143156
var `default`: String {
144157
self.colored(as: .default)
145158
}
146159

147160
func colored(as color: Rainbow) -> String {
148-
"\(color.rawValue)\(self)\(Rainbow.default.rawValue)"
161+
return if isColorSupported {
162+
"\(color.rawValue)\(self)\(Rainbow.default.rawValue)"
163+
} else {
164+
self
165+
}
149166
}
150167
}
151168

@@ -185,12 +202,16 @@ package extension Substring {
185202
var bold: String {
186203
self.colored(as: .bold)
187204
}
188-
205+
189206
var `default`: String {
190207
self.colored(as: .default)
191208
}
192209

193210
func colored(as color: Rainbow) -> String {
194-
"\(color.rawValue)\(self)\(Rainbow.default.rawValue)"
211+
return if isColorSupported {
212+
"\(color.rawValue)\(self)\(Rainbow.default.rawValue)"
213+
} else {
214+
String(self)
215+
}
195216
}
196217
}

0 commit comments

Comments
 (0)