Skip to content

Commit 2236bd3

Browse files
author
Nate Smith
authored
Merge pull request cli#51 from github/colors
do not use color when stdout is not a terminal
2 parents 817820e + ffa5ce4 commit 2236bd3

File tree

1 file changed

+30
-15
lines changed

1 file changed

+30
-15
lines changed

utils/color.go

Lines changed: 30 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,39 @@
11
package utils
22

3-
import "github.com/mgutz/ansi"
3+
import (
4+
"github.com/mattn/go-isatty"
5+
"github.com/mgutz/ansi"
6+
"os"
7+
)
48

5-
var Black = ansi.ColorFunc("black")
6-
var White = ansi.ColorFunc("white")
9+
func makeColorFunc(color string) func(string) string {
10+
return func(arg string) string {
11+
output := arg
12+
if isatty.IsTerminal(os.Stdout.Fd()) {
13+
output = ansi.Color(color+arg+ansi.Reset, "")
14+
}
715

8-
func Gray(arg string) string {
9-
return ansi.Color(ansi.LightBlack+arg, "")
16+
return output
17+
}
1018
}
1119

12-
var Red = ansi.ColorFunc("red")
13-
var Green = ansi.ColorFunc("green")
14-
var Yellow = ansi.ColorFunc("yellow")
15-
var Blue = ansi.ColorFunc("blue")
16-
var Magenta = ansi.ColorFunc("magenta")
17-
var Cyan = ansi.ColorFunc("cyan")
20+
var Black = makeColorFunc(ansi.Black)
21+
var White = makeColorFunc(ansi.White)
22+
var Magenta = makeColorFunc(ansi.Magenta)
23+
var Cyan = makeColorFunc(ansi.Cyan)
24+
var Red = makeColorFunc(ansi.Red)
25+
var Yellow = makeColorFunc(ansi.Yellow)
26+
var Blue = makeColorFunc(ansi.Blue)
27+
var Green = makeColorFunc(ansi.Green)
28+
var Gray = makeColorFunc(ansi.LightBlack)
1829

1930
func Bold(arg string) string {
20-
// This is really annoying. If you just define Bold as ColorFunc("+b") it will properly bold but
21-
// will not use the default color, resulting in black and probably unreadable text. This forces
22-
// the default color before bolding.
23-
return ansi.Color(ansi.DefaultFG+arg, "+b")
31+
output := arg
32+
if isatty.IsTerminal(os.Stdout.Fd()) {
33+
// This is really annoying. If you just define Bold as ColorFunc("+b") it will properly bold but
34+
// will not use the default color, resulting in black and probably unreadable text. This forces
35+
// the default color before bolding.
36+
output = ansi.Color(ansi.DefaultFG+arg+ansi.Reset, "+b")
37+
}
38+
return output
2439
}

0 commit comments

Comments
 (0)