Skip to content

Only enable terminal colors when supported #241

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

Merged
merged 1 commit into from
Jun 2, 2025
Merged
Changes from all 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
29 changes: 25 additions & 4 deletions Sources/JavaKitShared/TerminalColors.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,19 @@
//
//===----------------------------------------------------------------------===//

import Foundation

private var isColorSupported: Bool {
let env = ProcessInfo.processInfo.environment
if env["NO_COLOR"] != nil {
return false
}
if let term = env["TERM"], term.contains("color") || env["COLORTERM"] != nil {
return true
}
return false
}

package enum Rainbow: String {
case black = "\u{001B}[0;30m"
case red = "\u{001B}[0;31m"
Expand Down Expand Up @@ -139,13 +152,17 @@ package extension String {
self
}
}

var `default`: String {
self.colored(as: .default)
}

func colored(as color: Rainbow) -> String {
"\(color.rawValue)\(self)\(Rainbow.default.rawValue)"
return if isColorSupported {
"\(color.rawValue)\(self)\(Rainbow.default.rawValue)"
} else {
self
}
}
}

Expand Down Expand Up @@ -185,12 +202,16 @@ package extension Substring {
var bold: String {
self.colored(as: .bold)
}

var `default`: String {
self.colored(as: .default)
}

func colored(as color: Rainbow) -> String {
"\(color.rawValue)\(self)\(Rainbow.default.rawValue)"
return if isColorSupported {
"\(color.rawValue)\(self)\(Rainbow.default.rawValue)"
} else {
String(self)
}
}
}