8000 fix: use ANSI colors codes instead of RGB by DanielleMaywood · Pull Request #14665 · coder/coder · GitHub
[go: up one dir, main page]

Skip to content

fix: use ANSI colors codes instead of RGB #14665

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 23 commits into from
Sep 17, 2024
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
5e308df
chore: add command for showing colors
DanielleMaywood Sep 13, 2024
86175bf
fix: use ANSI color codes instead of RGB
DanielleMaywood Sep 13, 2024
098d35d
feat: add '--no-color' flag
DanielleMaywood Sep 13, 2024
3d13060
fix: revert colors
DanielleMaywood Sep 13, 2024
5b8fa3b
chore: change colors
DanielleMaywood Sep 13, 2024
4ce84a4
fix: update golden files
DanielleMaywood Sep 13, 2024
a75dbb2
fix: replace blue with brightBlue
DanielleMaywood Sep 13, 2024
390a7ca
fix: drop '> ' for unfocused prompts
DanielleMaywood Sep 13, 2024
7e6db79
fix: run 'make fmt'
DanielleMaywood Sep 13, 2024
ce913a5
chore: allow disabling color with env flags
DanielleMaywood Sep 13, 2024
22a2d0b
fix: apply fixes from feedback
DanielleMaywood Sep 13, 2024
5e42118
fix: run 'make gen'
DanielleMaywood Sep 13, 2024
40eb24e
fix: refactor janky code
DanielleMaywood Sep 13, 2024
ccf174a
fix: re-add public function
DanielleMaywood Sep 13, 2024
1fbef1d
fix: re-add init for non-color tests
DanielleMaywood Sep 13, 2024
44c3726
fix: move styles to 'init' that can be
DanielleMaywood Sep 13, 2024
d16f625
fix: stop overwriting entire DefaultStyles
DanielleMaywood Sep 13, 2024
1babe96
fix: make code and field obey --no-color
DanielleMaywood Sep 13, 2024
ff3c392
fix: rip out '--no-color' due to race condition
DanielleMaywood Sep 13, 2024
6d93c56
fix: apply nit
DanielleMaywood Sep 13, 2024
506aa28
fix: simplify code && hide command
DanielleMaywood Sep 16, 2024
997dc43
fix: newline shouldn't be themed
DanielleMaywood Sep 16, 2024
24a838d
fix: appease the linter
DanielleMaywood Sep 16, 2024
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
66 changes: 44 additions & 22 deletions cli/cliui/cliui.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package cliui

import (
"flag"
"fmt"
"os"
"slices"
"sync"
"time"

Expand All @@ -12,6 +14,8 @@ import (
"github.com/coder/pretty"
)

const NoColorFlag = "no-color"

var Canceled = xerrors.New("canceled")

// DefaultStyles compose visual elements of the UI.
Expand All @@ -37,22 +41,37 @@ var (
)

var (
Green = Color("#04B575")
Red = Color("#ED567A")
Fuchsia = Color("#EE6FF8")
Yellow = Color("#ECFD65")
Blue = Color("#5000ff")
// ANSI color codes
red = Color("1")
green = Color("2")
yellow = Color("3")
magenta = Color("5")
white = Color("7")
brightBlue = Color("12")
brightMagenta = Color("13")
Comment on lines +41 to +47
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: indicate these are ANSI color codes

)

// Color returns a color for the given string.
func Color(s string) termenv.Color {
colorOnce.Do(func() {
color = termenv.NewOutput(os.Stdout).ColorProfile()

if flag.Lookup("test.v") != nil {
// Use a consistent colorless profile in tests so that results
// are deterministic.
color = termenv.Ascii
}

// Currently it appears there is no way to use the flag from
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Have you tried setting the option on the root command? It should then evaluate on every command.

// serpent as it isn't possible to create a root middleware that
// runs for every command. For now we just check if `os.Args`
// has the flag.
if slices.Contains(os.Args, fmt.Sprintf("--%s", NoColorFlag)) ||
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should also support --no-color=true and --no-color=true (omitting = means true) to be consistent with our CLI. Ideally we'd rely on serpent parsing here but I understand that not easily achieved.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can do!

--no-color=true and --no-color=true

Do my eyes deceive me or are these both the same?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A case of copy-pasta 😂, sorry. Meant false for the second.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Got you, just pushed a change with --no-color=true handling. It appears we already handle the --no-color=false case!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is super janky. Relying on os.Args makes it difficult to test. Also, someone could modify the option at the CLI layer and easily forget to update this. Have you considered checking the CLI option higher up in the stack?

Copy link
Contributor Author
@DanielleMaywood DanielleMaywood Sep 13, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I absolutely agree with you, however serpent doesn't (from what I can tell) have any way to support this as it lacks the ability to set a middleware that runs before any command.

To demonstrate what I mean, the code in this gist has a Middleware setup but it only runs on the root cmd and not it's children. If you know of a way to have this run before a commands handler but after options are setup I'd love to do that instead!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Scratch that: I think using rootCmd.Walk and injecting the middleware to every child should work? Will have a go at doing that.

Copy link
Contributor Author
@DanielleMaywood DanielleMaywood Sep 13, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've pushed a change that should be less janky (using the method describe in the prior message), let me know what you think!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you do the Walk approach we have the flag duplicated on every help, which is obnoxious. Can't you use an Option on the root command?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry I think I explained myself poorly, the Walk was to inject middleware onto every command. The Option was on the root command. This change was backed out anyways as mutating the DefaultStyles after func init() was causing Go's race checker to be unhappy.

slices.Contains(os.Args, fmt.Sprintf("--%s=true", NoColorFlag)) ||
os.Getenv("CODER_NO_COLOR") != "" ||
os.Getenv("NO_COLOR") != "" {
color = termenv.Ascii
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this needed? I see that the serpent options modify the global var in this package, so checking if NoColor should suffice?

That said, I really wish we could do it differently as modifying globals is a bit icky 😅

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately not as NoColor is set after our code runs. This is because there is no (apparent) way to have this initialization code ran before every command but after serpent sets up the options.

})
return color.Color(s)
}
Expand Down Expand Up @@ -109,11 +128,11 @@ func Field(s string) string {
return pretty.Sprint(DefaultStyles.Field, s)
}

func ifTerm(fmt pretty.Formatter) pretty.Formatter {
func ifTerm(f pretty.Formatter) pretty.Formatter {
if !isTerm() {
return pretty.Nop
}
return fmt
return f
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

}

func init() {
Expand All @@ -123,42 +142,45 @@ func init() {
DefaultStyles = Styles{
Code: pretty.Style{
ifTerm(pretty.XPad(1, 1)),
pretty.FgColor(Red),
pretty.BgColor(color.Color("#2c2c2c")),
pretty.FgColor(color.Color("#ED567A")),
pretty.BgColor(color.Color("#2C2C2C")),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Were there no acceptable ANSI colors to replace these? Why did we go from red to ed567a?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As we set both the foreground and background colour, we have complete control over the contrast so this looks the same regardless of the terminal theme. If we want to use an ANSI code instead we can but there isn't a need to here.

red was defined as #ED567A, and the new red didn't look as good on the background so I kept it as the old one.

},
DateTimeStamp: pretty.Style{
pretty.FgColor(color.Color("#7571F9")),
pretty.FgColor(brightBlue),
},
Error: pretty.Style{
pretty.FgColor(Red),
pretty.FgColor(red),
},
Field: pretty.Style{
pretty.XPad(1, 1),
pretty.FgColor(color.Color("#FFFFFF")),
pretty.BgColor(color.Color("#2b2a2a")),
pretty.BgColor(color.Color("#2B2A2A")),
},
Fuchsia: pretty.Style{
pretty.FgColor(brightMagenta),
},
FocusedPrompt: pretty.Style{
pretty.FgColor(white),
pretty.Wrap("> ", ""),
pretty.FgColor(brightBlue),
},
Keyword: pretty.Style{
pretty.FgColor(Green),
pretty.FgColor(green),
},
Placeholder: pretty.Style{
pretty.FgColor(color.Color("#4d46b3")),
pretty.FgColor(magenta),
},
Prompt: pretty.Style{
pretty.FgColor(color.Color("#5C5C5C")),
pretty.Wrap("> ", ""),
pretty.FgColor(white),
pretty.Wrap(" ", ""),
},
Warn: pretty.Style{
pretty.FgColor(Yellow),
pretty.FgColor(yellow),
},
Wrap: pretty.Style{
pretty.LineWrap(80),
},
}

DefaultStyles.FocusedPrompt = append(
DefaultStyles.Prompt,
pretty.FgColor(Blue),
)
}

// ValidateNotEmpty is a helper function to disallow empty inputs!
Expand Down
10 changes: 5 additions & 5 deletions cli/cliui/select.go
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ func (m selectModel) View() string {
if m.cursor == start+i {
style = pretty.Style{
pretty.Wrap("> ", ""),
pretty.FgColor(Green),
DefaultStyles.Keyword,
}
}

Expand Down Expand Up @@ -481,13 +481,13 @@ func (m multiSelectModel) View() string {
o := option.option

if m.cursor == i {
cursor = pretty.Sprint(pretty.FgColor(Green), "> ")
chosen = pretty.Sprint(pretty.FgColor(Green), "[ ]")
o = pretty.Sprint(pretty.FgColor(Green), o)
cursor = pretty.Sprint(DefaultStyles.Keyword, "> ")
chosen = pretty.Sprint(DefaultStyles.Keyword, "[ ]")
o = pretty.Sprint(DefaultStyles.Keyword, o)
}

if option.chosen {
chosen = pretty.Sprint(pretty.FgColor(Green), "[x]")
chosen = pretty.Sprint(DefaultStyles.Keyword, "[x]")
}

_, _ = s.WriteString(fmt.Sprintf(
Expand Down
15 changes: 15 additions & 0 deletions cli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,13 @@ func (r *RootCmd) Command(subcommands []*serpent.Command) (*serpent.Command, err
r.clientURL = new(url.URL)
}

// NOTE(Danielle): It appears there is no way to have a 'global' middleware in
// serpent so we manually handle the ENV/flag lookup and setup
// the option in the below OptionSet so it is documented.
// We use (and discard) this local variable to get the correct
// behavior from the CLI when the option is passed.
var noColorDiscarded bool

globalGroup := &serpent.Group{
Name: "Global",
Description: `Global options are applied to all commands. They can be set using environment variables or flags.`,
Expand Down Expand Up @@ -461,6 +468,14 @@ func (r *RootCmd) Command(subcommands []*serpent.Command) (*serpent.Command, err
Value: serpent.StringOf(&r.globalConfig),
Group: globalGroup,
},
{
Flag: cliui.NoColorFlag,
Copy link
Member
@johnstcn johnstcn Sep 13, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wonder if it would make sense to also allow setting it as an env (CODER_NO_COLOR)? Not blocking, but it would allow folks for whom our colour scheme doesn't work to simply turn it off forever by setting it in their shell profile.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes that should be a good idea. There is a 'standard' around using NO_COLOR for this https://no-color.org. We could do both NO_COLOR and CODER_NO_COLOR?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good to me!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: I think we should add the env as well here.

Env: "CODER_NO_COLOR",
Default: "false",
Description: "Disable use of color in CLI output.",
Group: globalGroup,
Value: serpent.BoolOf(&noColorDiscarded),
},
{
Flag: "version",
// This was requested by a customer to assist with their migration.
Expand Down
3 changes: 3 additions & 0 deletions cli/testdata/coder_--help.golden
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,9 @@ variables or flags.
requests. The command must output each header as `key=value` on its
own line.

--no-color bool, $CODER_NO_COLOR (default: false)
Disable use of color in CLI output.

--no-feature-warning bool, $CODER_NO_FEATURE_WARNING
Suppress warnings about unlicensed features.

Expand Down
48 changes: 48 additions & 0 deletions cmd/cliui/main.go
Use: "prompt",
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"github.com/coder/coder/v2/cli/cliui"
"github.com/coder/coder/v2/coderd/database/dbtime"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/pretty"
"github.com/coder/serpent"
)

Expand All @@ -37,6 +38,53 @@ func main() {
},
}

var noColorDiscarded bool

root.Options = []serpent.Option{
{
Default: "false",
Flag: cliui.NoColorFlag,
Value: serpent.BoolOf(&noColorDiscarded),
},
}

root.Children = append(root.Children, &serpent.Command{
Use: "colors",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 👍

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be hidden

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done!

Handler: func(inv *serpent.Invocation) error {
msg := pretty.Sprint(cliui.DefaultStyles.Code, "This is a code message")
_, _ = fmt.Fprintln(inv.Stdout, msg)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can simplify this with pretty.Fprintf

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done! I had to separate the newline from the Fprintf call though as otherwise the newline would get themed.


msg = pretty.Sprint(cliui.DefaultStyles.DateTimeStamp, "This is a datetimestamp message")
_, _ = fmt.Fprintln(inv.Stdout, msg)

msg = pretty.Sprint(cliui.DefaultStyles.Error, "This is an error message")
_, _ = fmt.Fprintln(inv.Stdout, msg)

msg = pretty.Sprint(cliui.DefaultStyles.Field, "This is a field message")
_, _ = fmt.Fprintln(inv.Stdout, msg)

msg = pretty.Sprint(cliui.DefaultStyles.Keyword, "This is a keyword message")
_, _ = fmt.Fprintln(inv.Stdout, msg)

msg = pretty.Sprint(cliui.DefaultStyles.Placeholder, "This is a placeholder message")
_, _ = fmt.Fprintln(inv.Stdout, msg)

msg = pretty.Sprint(cliui.DefaultStyles.Prompt, "This is a prompt message")
_, _ = fmt.Fprintln(inv.Stdout, msg)

msg = pretty.Sprint(cliui.DefaultStyles.FocusedPrompt, "This is a focused prompt message")
_, _ = fmt.Fprintln(inv.Stdout, msg)

msg = pretty.Sprint(cliui.DefaultStyles.Fuchsia, "This is a fuchsia message")
_, _ = fmt.Fprintln(inv.Stdout, msg)

msg = pretty.Sprint(cliui.DefaultStyles.Warn, "This is a warning message")
_, _ = fmt.Fprintln(inv.Stdout, msg)

return nil
},
})

root.Children = append(root.Children, &serpent.Command{
Handler: func(inv *serpent.Invocation) error {
Expand Down
10 changes: 10 additions & 0 deletions docs/reference/cli/README.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions enterprise/cli/testdata/coder_--help.golden
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ variables or flags.
requests. The command must output each header as `key=value` on its
own line.

--no-color bool, $CODER_NO_COLOR (default: false)
Disable use of color in CLI output.

--no-feature-warning bool, $CODER_NO_FEATURE_WARNING
Suppress warnings about unlicensed features.

Expand Down
Loading
0