Skip to content

Commit

Permalink
[fmtc] Added method 'IsColorsSupported'
Browse files Browse the repository at this point in the history
  • Loading branch information
andyone committed Nov 21, 2023
1 parent 3e56950 commit b64de02
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
### 12.88.0

* `[pager]` Added new package for pager (`less`/`more`) setup
* `[fmtc]` Added method `IsColorsSupported`

### 12.87.0

Expand Down
4 changes: 4 additions & 0 deletions fmtc/examples_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,10 @@ func ExampleClean() {
// Output: Text
}

func ExampleIsColorsSupported() {
fmt.Printf("16 Colors Supported: %t\n", IsColorsSupported())
}

func ExampleIs256ColorsSupported() {
fmt.Printf("256 Colors Supported: %t\n", Is256ColorsSupported())
}
Expand Down
23 changes: 21 additions & 2 deletions fmtc/fmtc.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,9 @@ var DisableColors = os.Getenv("NO_COLOR") != ""

// ////////////////////////////////////////////////////////////////////////////////// //

var colors256Supported bool
var colorsTCSupported bool
var colorsSupported bool // 16 colors support
var colors256Supported bool // 256 colors support
var colorsTCSupported bool // 24bit (TrueColor) colors support
var colorsSupportChecked bool

var colorsMap *sync.Map
Expand Down Expand Up @@ -328,6 +329,17 @@ func Bell() {
fmt.Print(_CODE_BELL)
}

// IsColorsSupported returns true if 16 colors is supported by terminal
func IsColorsSupported() bool {
if colorsSupportChecked {
return colorsSupported
}

checkForColorsSupport()

return colorsSupported
}

// Is256ColorsSupported returns true if 256 colors is supported by terminal
func Is256ColorsSupported() bool {
if colorsSupportChecked {
Expand Down Expand Up @@ -644,6 +656,13 @@ func isValidNamedTag(tag string) bool {
}

func checkForColorsSupport() {
switch {
case strings.Contains(term, "xterm"),
strings.Contains(term, "color"),
term == "screen":
colorsSupported = true
}

if strings.Contains(term, "256color") {
colors256Supported = true
}
Expand Down
1 change: 1 addition & 0 deletions fmtc/fmtc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ func (s *FormatSuite) Test24BitColors(c *C) {

c.Assert(IsTrueColorSupported(), Equals, true)
c.Assert(Is256ColorsSupported(), Equals, true)
c.Assert(IsColorsSupported(), Equals, true)

colorsSupportChecked = false
colors256Supported = false
Expand Down

0 comments on commit b64de02

Please sign in to comment.