Skip to content

Commit 098d35d

Browse files
feat: add '--no-color' flag
1 parent 86175bf commit 098d35d

File tree

3 files changed

+33
-4
lines changed

3 files changed

+33
-4
lines changed

cli/cliui/cliui.go

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@ package cliui
22

33
import (
44
"flag"
5+
"fmt"
56
"os"
7+
"slices"
68
"sync"
79
"time"
810

@@ -12,6 +14,10 @@ import (
1214
"github.com/coder/pretty"
1315
)
1416

17+
const NoColorFlag = "no-color"
18+
19+
var NoColor = false
20+
1521
var Canceled = xerrors.New("canceled")
1622

1723
// DefaultStyles compose visual elements of the UI.
@@ -37,21 +43,30 @@ var (
3743
)
3844

3945
var (
40-
Green = Color("2")
41-
Red = Color("1")
42-
Yellow = Color("3")
43-
Blue = Color("6")
46+
Green = Color("10")
47+
Red = Color("9")
48+
Yellow = Color("11")
49+
Blue = Color("12")
4450
)
4551

4652
// Color returns a color for the given string.
4753
func Color(s string) termenv.Color {
4854
colorOnce.Do(func() {
4955
color = termenv.NewOutput(os.Stdout).ColorProfile()
56+
5057
if flag.Lookup("test.v") != nil {
5158
// Use a consistent colorless profile in tests so that results
5259
// are deterministic.
5360
color = termenv.Ascii
5461
}
62+
63+
// Currently it appears there is no way to use the flag from
64+
// serpent as it isn't possible to create a root middleware that
65+
// runs for every command. For now we just check if `os.Args`
66+
// has the flag.
67+
if slices.Contains(os.Args, fmt.Sprintf("--%s", NoColorFlag)) {
68+
color = termenv.Ascii
69+
}
5570
})
5671
return color.Color(s)
5772
}

cli/root.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -461,6 +461,12 @@ func (r *RootCmd) Command(subcommands []*serpent.Command) (*serpent.Command, err
461461
Value: serpent.StringOf(&r.globalConfig),
462462
Group: globalGroup,
463463
},
464+
{
465+
Flag: cliui.NoColorFlag,
466+
Description: "Disable use of color in CLI output.",
467+
Value: serpent.BoolOf(&cliui.NoColor),
468+
Group: globalGroup,
469+
},
464470
{
465471
Flag: "version",
466472
// This was requested by a customer to assist with their migration.

cmd/cliui/main.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,14 @@ func main() {
3838
},
3939
}
4040

41+
root.Options = []serpent.Option{
42+
{
43+
Default: "false",
44+
Flag: cliui.NoColorFlag,
45+
Value: serpent.BoolOf(&cliui.NoColor),
46+
},
47+
}
48+
4149
root.Children = append(root.Children, &serpent.Command{
4250
Use: "colors",
4351
Handler: func(inv *serpent.Invocation) error {

0 commit comments

Comments
 (0)