From b94c99e226a9280bb3cbce444ed67abcbe21a042 Mon Sep 17 00:00:00 2001 From: w3cj Date: Sat, 31 Oct 2026 15:36:13 -0700 Subject: [PATCH] feat(ui): color errors, warnings, doc links and log text in a terminal devvm colors the labels and links around its messages with the terminal's 16 base colors, so the theme picks shades that read on its background; a message's own text stays in the default foreground. - Die's devvm: label bold red (1;31), Warn's bold yellow (1;33) - doc links underlined blue (4;34) - Info's ==> bold (1) - DieLogged's log end and its --- lines, and the status line's log text, dim (2), each line painted apart - the done mark green (32) No bright colors, backgrounds, 256 colors or truecolor, and no background detection. Each stream decides apart (colorOn): NO_COLOR or DEVVM_MESSAGES=names off, then FORCE_COLOR or CLICOLOR_FORCE (but 0) on, then TERM=dumb off, else only when that stream is a terminal. Names mode stays plain in a terminal too, so e2e's checks under script read the names unchanged. The run log and Stdout() data are never colored; no --color flag and no message text changes. internal/ui: a style per stream (style.go: paint, paintLines, message, labelled, fit), made in onTerminal; Die and Warn share labelled. The status line cuts and counts its plain text (style.fit) before painting, so it fits and clears at the right width; statusText returns the log part apart. Codes are added after printable() and msg.Shown. internal/msg: M.Parts returns the text and the doc link apart, names and no link in names mode; String joins them as before. mise run test unsets NO_COLOR, FORCE_COLOR and CLICOLOR_FORCE, and tests/e2e.sh unsets FORCE_COLOR and CLICOLOR_FORCE, so a user's own settings don't change what they check. Tests: TestColorOn (env x terminal), TestMessagesColored (Say, Info, Note, Warn, Die colored and plain, the link apart), TestNamesModeStaysPlain, TestDieLoggedColored, TestColoredStatusLineFits, TestDoneMarkGreen; msg's TestStringAddsDocLink checks Parts. Docs: using/settings (Colors, the environment table); contributing (Messages: Colors). Co-Authored-By: Claude Opus 5.5 --- docs/content/docs/contributing/_index.md | 16 +++ docs/content/docs/using/settings.md | 13 ++ internal/msg/msg.go | 18 ++- internal/msg/msg_test.go | 7 ++ internal/ui/pick.go | 2 +- internal/ui/runlog.go | 2 +- internal/ui/status.go | 30 ++--- internal/ui/status_test.go | 3 +- internal/ui/style.go | 96 +++++++++++++++ internal/ui/style_test.go | 147 +++++++++++++++++++++++ internal/ui/ui.go | 42 ++++--- mise.toml | 4 +- tests/e2e.sh | 1 + 13 files changed, 341 insertions(+), 40 deletions(-) create mode 100644 internal/ui/style.go create mode 100644 internal/ui/style_test.go diff --git a/docs/content/docs/contributing/_index.md b/docs/content/docs/contributing/_index.md index 8e816d3c..decbe544 100644 --- a/docs/content/docs/contributing/_index.md +++ b/docs/content/docs/contributing/_index.md @@ -266,6 +266,22 @@ stderr 'msg_unknown name=nope$' `devvm _msg NAME key=value…` prints a message's text (never its names), for end-to-end tests that look for it in a VM's output. It's hidden from the help. +### Colors + +Only `internal/ui` adds color, through a `style` for each stream that `onTerminal` makes, and `colorOn` decides each one: `NO_COLOR` or `DEVVM_MESSAGES=names` turns it off, then `FORCE_COLOR` or `CLICOLOR_FORCE` (but `0`) turns it on, then `TERM=dumb` turns it off, and otherwise the stream gets color only when it's a terminal. Names mode stays plain in a terminal too, so end-to-end checks that run devvm under `script` read the names as they are. A `UI` from `New`, as tests make, is plain. + +The colors are SGR codes from the 16 base colors only, which the theme maps to its own shades. devvm uses no bright colors (90–97), because Solarized maps them to greys and bright black is Solarized Dark's background, and it uses no backgrounds, 256 colors or truecolor. The codes go on labels, links and log text, never on a message's own text: + +- `Die`'s `devvm:` label is bold red (`1;31`), and `Warn`'s is bold yellow (`1;33`). +- A doc link is underlined blue (`4;34`). `msg.M.Parts` gives a message's text and its doc link apart, so `ui` colors the link alone. +- `Info`'s `==>` is bold (`1`). +- The run log's end that `DieLogged` prints, with its `---` lines, and the log text on the status line are dim (`2`). +- The done mark that a slow step leaves is green (`32`). + +The codes are added after `printable` and `msg.Shown`, so they're the only ones devvm prints. The status line cuts and counts its plain text with `style.fit` before painting it, so it still fits the terminal's width and clears the right number of rows. The run log is never colored. + +`mise run test` unsets `NO_COLOR`, `FORCE_COLOR` and `CLICOLOR_FORCE`, and `tests/e2e.sh` unsets the last two, so your own settings never change what they check. + ### Translations A translation is `locales/.toml` (`de.toml`) with the same tables, `one` and `other` translated (and the language's other plural forms, such as `few`), loaded by go-i18n the same way. Doc links are the same in every language: the docs site is English. devvm picks the language from the first of `LC_ALL`, `LC_MESSAGES` and `LANG` that is set (`de_DE.UTF-8` is German); `C` and `POSIX` are English. A message missing from a translation is shown in English. diff --git a/docs/content/docs/using/settings.md b/docs/content/docs/using/settings.md index fda979bf..54a42659 100644 --- a/docs/content/docs/using/settings.md +++ b/docs/content/docs/using/settings.md @@ -92,10 +92,23 @@ When devvm refuses a folder, make the VM in a project folder inside it, or keep > [!WARNING] > If you mean to give the VM the whole folder, pass `--unsafe-folder` when you make the VM, and devvm warns you that the VM gets read-write access to it ([only the project folder](../internals/security.md#only-the-project-folder)). +## Colors + +In a terminal, devvm colors the labels and links around its messages, while the messages' own text stays in your terminal's usual color. An error's `devvm:` label is red and a warning's is yellow, a doc link is blue and underlined, and the `==>` before what devvm did is bold. When a step fails, the end of the run log that devvm prints is dim, and so is the log's latest line on the status line. The mark a slow step leaves when it's done is green. + +devvm uses only your terminal's 16 base colors, so your theme picks shades that read well on its background, light or dark. It never sets a background color. + +devvm decides for standard output and standard error apart, and colors one only when it's a terminal, so output you pipe or redirect to a file stays plain. The run log is never colored. You can change that with these environment variables, the first that applies deciding: + +- `NO_COLOR`, set to anything, turns colors off. +- `FORCE_COLOR` or `CLICOLOR_FORCE`, set to anything but `0`, turns them on even when the output isn't a terminal. +- `TERM=dumb` turns them off. + ## Environment | | | | --- | --- | +| `NO_COLOR`, `FORCE_COLOR`, `CLICOLOR_FORCE` | turn devvm's colors off, or on when the output isn't a terminal ([details](#colors)) | | `DEVVM_VERBOSE=1` | print the output of the commands devvm runs, instead of logging it ([details](troubleshooting.md#a-command-fails)) | | `DEVVM_LIMA_HOME` | move devvm's own Lima home ([details](../internals/lima.md#a-lima-home-of-its-own)) | | `DEVVM_FROM` | the container image that the base of new VMs and builds starts from when there's no `--from` ([details](from.md)) | diff --git a/internal/msg/msg.go b/internal/msg/msg.go index 23cadc84..f8f4404b 100644 --- a/internal/msg/msg.go +++ b/internal/msg/msg.go @@ -64,13 +64,21 @@ func (m M) ID() string { return m.id } // String returns the message as devvm prints it: its text, then its doc // link on a line of its own. With DEVVM_MESSAGES=names, its names instead. func (m M) String() string { + text, link := m.Parts() + if link != "" { + return text + "\n" + link + } + return text +} + +// Parts returns what String joins, apart, so a terminal can color the +// link: the message's text and its doc link ("" when it has none). With +// DEVVM_MESSAGES=names, its names and no link. +func (m M) Parts() (text, link string) { if namesMode() { - return m.Names() + return m.Names(), "" } - if u := m.DocURL(); u != "" { - return m.Text() + "\n" + u - } - return m.Text() + return m.Text(), m.DocURL() } // Line returns the message on one line, without its doc link: its text, or diff --git a/internal/msg/msg_test.go b/internal/msg/msg_test.go index 66fb195a..b418a727 100644 --- a/internal/msg/msg_test.go +++ b/internal/msg/msg_test.go @@ -166,6 +166,13 @@ func TestStringAddsDocLink(t *testing.T) { if got := m.Line(); got != m.Text() { t.Errorf("Line: got %q, want the text without the link", got) } + if text, link := m.Parts(); text != m.Text() || link != m.DocURL() { + t.Errorf("Parts: got %q, %q, want the text and the link apart", text, link) + } + t.Setenv("DEVVM_MESSAGES", "names") + if text, link := m.Parts(); text != m.Names() || link != "" { + t.Errorf("Parts in names mode: got %q, %q, want the names and no link", text, link) + } } func TestDocURL(t *testing.T) { diff --git a/internal/ui/pick.go b/internal/ui/pick.go index 67199b83..ca0a3a77 100644 --- a/internal/ui/pick.go +++ b/internal/ui/pick.go @@ -65,7 +65,7 @@ func (u *UI) pick(help msg.M, choices []Choice, one bool) { return } // In raw mode a line ends with \r\n; the cursor is hidden meanwhile. - u.write(u.stdout, strings.ReplaceAll(help.String(), "\n", "\r\n")+"\r\n\033[?25l") + u.write(u.stdout, strings.ReplaceAll(u.outStyle.message(help), "\n", "\r\n")+"\r\n\033[?25l") ok := u.pickLoop(u.stdin, choices, one) u.write(u.stdout, "\033[?25h") restore() diff --git a/internal/ui/runlog.go b/internal/ui/runlog.go index be2041ad..0c4870a9 100644 --- a/internal/ui/runlog.go +++ b/internal/ui/runlog.go @@ -111,7 +111,7 @@ func (u *UI) LogNote() { u.log.noted = true u.log.Unlock() if !noted { - u.write(u.stdout, " "+msg.LogDetails(path).String()+"\n") + u.write(u.stdout, " "+u.outStyle.message(msg.LogDetails(path))+"\n") } } diff --git a/internal/ui/status.go b/internal/ui/status.go index aa4e1791..55dd77c1 100644 --- a/internal/ui/status.go +++ b/internal/ui/status.go @@ -83,14 +83,15 @@ func (s *statusLine) run() { func (s *statusLine) draw() { frames := glyphs(s.u.getenv)[1:] s.cols = s.u.width() - text := " " + frames[s.frame%len(frames)] + " " + - statusText(s.label, int(time.Since(s.start).Seconds()), lastLine(s.u.logPath()), s.cols) - text = truncate(text, s.cols-1) + text, log := statusText(s.label, int(time.Since(s.start).Seconds()), lastLine(s.u.logPath()), s.cols) + line, drawn := s.u.errStyle.fit([]part{ + {" " + frames[s.frame%len(frames)] + " " + text, ""}, {log, sgrDim}, + }, s.cols-1) s.frame++ // No line wrapping while it draws: a resize between reading the width // and drawing would wrap. - s.u.write(s.u.stderr, clearLine(s.drawn, s.cols)+"\033[?7l"+text+"\033[?7h") - s.drawn = utf8.RuneCountInString(text) + s.u.write(s.u.stderr, clearLine(s.drawn, s.cols)+"\033[?7l"+line+"\033[?7h") + s.drawn = drawn } func (s *statusLine) stop() { @@ -129,9 +130,10 @@ func glyphs(getenv func(string) string) []string { return []string{"ok", "|", "/", "-", `\`} } -// doneLine is what a step that took a while leaves behind. +// doneLine is what a step that took a while leaves behind, its mark green +// in a terminal. func (u *UI) doneLine(label string, secs int) string { - return " " + glyphs(u.getenv)[0] + " " + label + " (" + duration(secs) + ")\n" + return " " + u.errStyle.paint(sgrDone, glyphs(u.getenv)[0]) + " " + label + " (" + duration(secs) + ")\n" } // duration is 5s, or 2m05s from a minute. @@ -142,20 +144,20 @@ func duration(secs int) string { return fmt.Sprintf("%dm%02ds", secs/60, secs%60) } -// statusText is the label and time, then as much of the log's latest line -// (its last carriage-return segment, without control characters) as fits in -// cols. -func statusText(label string, secs int, logLine string, cols int) string { - text := label + " " + duration(secs) +// statusText is the label and time, then apart, so it can be dimmed, as +// much of the log's latest line (its last carriage-return segment, without +// control characters) as fits in cols, after two spaces. +func statusText(label string, secs int, logLine string, cols int) (text, log string) { + text = label + " " + duration(secs) if i := strings.LastIndexByte(logLine, '\r'); i >= 0 { logLine = logLine[i+1:] } logLine = oneLine(logLine) room := cols - utf8.RuneCountInString(text) - 9 if room >= 10 && logLine != "" { - text += " " + truncate(logLine, room) + log = " " + truncate(logLine, room) } - return text + return text, log } func truncate(s string, n int) string { diff --git a/internal/ui/status_test.go b/internal/ui/status_test.go index 63d12cea..7cdd188d 100644 --- a/internal/ui/status_test.go +++ b/internal/ui/status_test.go @@ -35,7 +35,8 @@ func TestStatusText(t *testing.T) { // No control characters from the log, C1 in UTF-8 included. {"x", 1, "a\033[2Jb\302\233c", 80, "x 1s a[2Jbc"}, } { - if got := statusText(tc.label, tc.secs, tc.logLine, tc.cols); got != tc.want { + if text, log := statusText(tc.label, tc.secs, tc.logLine, tc.cols); text+log != tc.want { + got := text + log t.Errorf("statusText(%q, %d, %q, %d) = %q, want %q", tc.label, tc.secs, tc.logLine, tc.cols, got, tc.want) } } diff --git a/internal/ui/style.go b/internal/ui/style.go new file mode 100644 index 00000000..c281b49e --- /dev/null +++ b/internal/ui/style.go @@ -0,0 +1,96 @@ +package ui + +import ( + "strings" + "unicode/utf8" + + "github.com/w3cj/devvm/internal/msg" +) + +// The SGR codes devvm colors with: only the terminal's 16 base colors, which +// its theme maps to colors that read well on its background, and bold, dim +// and underline. No bright colors (Solarized maps them to greys, and bright +// black is Solarized Dark's background), no backgrounds, no 256 or truecolor. +const ( + sgrBold = "1" + sgrDim = "2" + sgrError = "1;31" // Die's devvm: label, bold red + sgrWarn = "1;33" // Warn's devvm: label, bold yellow + sgrLink = "4;34" // doc links, underlined blue + sgrDone = "32" // the done mark, green +) + +// A style colors what devvm prints on one stream: labels, doc links and +// log text, never a message's own text. The zero style is plain. +type style struct{ on bool } + +// colorOn reports whether a stream gets color: never with NO_COLOR or +// DEVVM_MESSAGES=names, always with FORCE_COLOR or CLICOLOR_FORCE (but 0), +// never with TERM=dumb, else only when the stream is a terminal. +func colorOn(getenv func(string) string, terminal bool) bool { + switch { + case getenv("NO_COLOR") != "", getenv("DEVVM_MESSAGES") == "names": + return false + case forced(getenv("FORCE_COLOR")), forced(getenv("CLICOLOR_FORCE")): + return true + case getenv("TERM") == "dumb": + return false + } + return terminal +} + +func forced(v string) bool { return v != "" && v != "0" } + +// paint wraps text in the SGR code, then a reset, when the style is on. +func (s style) paint(code, text string) string { + if !s.on || code == "" || text == "" { + return text + } + return "\033[" + code + "m" + text + "\033[0m" +} + +// paintLines paints each line of text apart, so a line shown on its own +// (scrolled, or copied) carries its code and its reset. +func (s style) paintLines(code, text string) string { + if !s.on { + return text + } + var b strings.Builder + for line := range strings.SplitAfterSeq(text, "\n") { + body := strings.TrimSuffix(line, "\n") + b.WriteString(s.paint(code, body) + line[len(body):]) + } + return b.String() +} + +// message renders m as devvm prints it: its text, then its doc link, +// colored, on a line of its own. +func (s style) message(m msg.M) string { + text, link := m.Parts() + if link == "" { + return text + } + return text + "\n" + s.paint(sgrLink, link) +} + +// labelled renders m with a "devvm: " label, painted with code, before +// each line: Warn's and Die's. +func (s style) labelled(code string, m msg.M) string { + return prefixLines(s.paint(code, "devvm:")+" ", s.message(m)) +} + +// A part is some of a line to paint with code ("" for none). +type part struct{ text, code string } + +// fit renders as much of the parts as fits in n runes, each painted, and +// how many runes it shows: it counts and cuts the plain text only. +func (s style) fit(parts []part, n int) (string, int) { + var b strings.Builder + shown := 0 + for _, p := range parts { + t := truncate(p.text, n-shown) + shown += utf8.RuneCountInString(t) + b.WriteString(s.paint(p.code, t)) + } + return b.String(), shown +} diff --git a/internal/ui/style_test.go b/internal/ui/style_test.go new file mode 100644 index 00000000..1cedf201 --- /dev/null +++ b/internal/ui/style_test.go @@ -0,0 +1,147 @@ +package ui + +import ( + "regexp" + "strings" + "testing" + "unicode/utf8" + + "github.com/w3cj/devvm/internal/msg" +) + +// sgr matches the SGR codes devvm prints. +var sgr = regexp.MustCompile("\033\\[[0-9;]*m") + +func plain(s string) string { return sgr.ReplaceAllString(s, "") } + +func TestColorOn(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + env env + terminal bool + want bool + }{ + {env{}, true, true}, + {env{}, false, false}, + {env{"TERM": "xterm-256color"}, true, true}, + {env{"TERM": "dumb"}, true, false}, + {env{"NO_COLOR": "1"}, true, false}, + {env{"NO_COLOR": ""}, true, true}, // set but empty: not set + {env{"FORCE_COLOR": "1"}, false, true}, + {env{"CLICOLOR_FORCE": "1"}, false, true}, + {env{"FORCE_COLOR": "1", "TERM": "dumb"}, false, true}, + {env{"FORCE_COLOR": "0"}, false, false}, + {env{"CLICOLOR_FORCE": "0"}, true, true}, + {env{"FORCE_COLOR": "1", "NO_COLOR": "1"}, true, false}, + {env{"DEVVM_MESSAGES": "names"}, true, false}, + {env{"DEVVM_MESSAGES": "names", "FORCE_COLOR": "1"}, true, false}, + } { + if got := colorOn(tc.env.get, tc.terminal); got != tc.want { + t.Errorf("colorOn(%v, terminal %v) = %v, want %v", tc.env, tc.terminal, got, tc.want) + } + } +} + +func TestMessagesColored(t *testing.T) { + t.Setenv("DEVVM_MESSAGES", "") + linked := msg.PortsNoSSH("v") + text, link := linked.Parts() + if link == "" || strings.Contains(text, link) { + t.Fatalf("ports_no_ssh: want a doc link apart from the text, got %q, %q", text, link) + } + for _, tc := range []struct { + name string + print func(*UI, msg.M) + stdout, stder string + }{ + {"say", (*UI).Say, text + "\n\033[4;34m" + link + "\033[0m\n", ""}, + {"info", (*UI).Info, "\033[1m==>\033[0m " + text + "\n\033[4;34m" + link + "\033[0m\n", ""}, + {"note", (*UI).Note, "", text + "\n\033[4;34m" + link + "\033[0m\n"}, + {"warn", (*UI).Warn, "", "\033[1;33mdevvm:\033[0m " + text + "\n\033[1;33mdevvm:\033[0m \033[4;34m" + link + "\033[0m\n"}, + {"die", func(u *UI, m msg.M) { exitCode(func() { u.Die(m) }) }, "", "\033[1;31mdevvm:\033[0m " + text + "\n\033[1;31mdevvm:\033[0m \033[4;34m" + link + "\033[0m\n"}, + } { + u, out, errOut := testUI(t, "") + u.outStyle, u.errStyle = style{true}, style{true} + tc.print(u, linked) + if out.String() != tc.stdout || errOut.String() != tc.stder { + t.Errorf("%s colored: stdout %q, stderr %q; want %q, %q", tc.name, out, errOut, tc.stdout, tc.stder) + } + // Plain, it's the same text without the codes. + u, out, errOut = testUI(t, "") + tc.print(u, linked) + if got := out.String() + errOut.String(); got != plain(tc.stdout+tc.stder) { + t.Errorf("%s plain: %q", tc.name, got) + } + } + if plain(text+"\n\033[4;34m"+link+"\033[0m") != linked.String() { + t.Errorf("String: %q", linked.String()) + } +} + +func TestNamesModeStaysPlain(t *testing.T) { + t.Setenv("DEVVM_MESSAGES", "names") + m := msg.PortsNoSSH("v") + if text, link := m.Parts(); text != m.Names() || link != "" || m.String() != m.Names() { + t.Errorf("names mode: Parts %q, %q, String %q", text, link, m.String()) + } + // A terminal in names mode gets no color, so e2e's checks of a terminal + // read the names as they are. + if colorOn(env{"DEVVM_MESSAGES": "names"}.get, true) { + t.Error("names mode in a terminal: want no color") + } +} + +func TestDieLoggedColored(t *testing.T) { + u, _, errOut := testUI(t, "") + u.errStyle = style{true} + if err := u.logged(t.Context(), msg.M{}, "sh", "-c", "printf 'one\\n\\033[31mtwo\\n'"); err != nil { + t.Fatal(err) + } + exitCode(func() { u.DieLogged(msg.MsgUnknown("x")) }) + got := errOut.String() + // Each line of the log's end dim, the log's own codes dropped; then the + // message, its label red. + head := "\033[2m--- " + msg.LogEnd(u.logPath()).Line() + "\033[0m\n" + want := "\033[2mone\033[0m\n\033[2m[31mtwo\033[0m\n\033[2m---\033[0m\n" + + "\033[1;31mdevvm:\033[0m msg_unknown name=x\n" + if !strings.HasPrefix(got, head) || !strings.HasSuffix(got, want) { + t.Errorf("DieLogged colored:\n%q\nwant it to end\n%q", got, want) + } +} + +func TestColoredStatusLineFits(t *testing.T) { + t.Parallel() + u, _, errOut := testUI(t, "") + u.stderrTTY, u.errStyle = true, style{true} + u.termWidth = func() int { return 40 } + u.getenv = env{"LC_ALL": "C"}.get + if err := u.logged(t.Context(), msg.MsgUnknown("x"), "sh", "-c", "echo "+strings.Repeat("progress", 10)+"; sleep 0.5"); err != nil { + t.Fatal(err) + } + got := errOut.String() + if !strings.Contains(got, "\033[2m progress") { + t.Errorf("status line: want the log's line dim: %q", got) + } + // The plain text fits in the width, whatever the codes add. + for line := range strings.SplitSeq(got, "\033[?7l") { + text, _, _ := strings.Cut(line, "\033[?7h") + if n := utf8.RuneCountInString(plain(text)); n > 39 { + t.Errorf("wider than the terminal: %d runes: %q", n, text) + } + } + // What fit counts the plain text, so clearing covers the line drawn. + line, n := u.errStyle.fit([]part{{strings.Repeat("a", 30), ""}, {strings.Repeat("b", 30), sgrDim}}, 39) + if n != 39 || plain(line) != strings.Repeat("a", 30)+strings.Repeat("b", 9) || clearLine(n, 40) != "\r\033[K" { + t.Errorf("fit: %q, %d", line, n) + } +} + +func TestDoneMarkGreen(t *testing.T) { + t.Parallel() + u, _, _ := testUI(t, "") + u.getenv = env{"LC_ALL": "C"}.get + u.errStyle = style{true} + if got, want := u.doneLine("starting x", 5), " \033[32mok\033[0m starting x (5s)\n"; got != want { + t.Errorf("doneLine: got %q, want %q", got, want) + } +} diff --git a/internal/ui/ui.go b/internal/ui/ui.go index ef22dbf5..9b2e3e70 100644 --- a/internal/ui/ui.go +++ b/internal/ui/ui.go @@ -32,6 +32,9 @@ type UI struct { stdin *bufio.Reader stdinTTY, stdoutTTY, stderrTTY bool + // outStyle and errStyle color what goes to stdout and stderr, each on + // only as colorOn decides for that stream. + outStyle, errStyle style // termWidth is the terminal's width in columns, 0 when unknown. termWidth func() int // readPassword reads a line from the terminal without echoing it. @@ -85,6 +88,7 @@ func New(stdin io.Reader, stdout, stderr io.Writer) *UI { func onTerminal() *UI { u := New(os.Stdin, os.Stdout, os.Stderr) u.stdinTTY, u.stdoutTTY, u.stderrTTY = isTerminal(os.Stdin), isTerminal(os.Stdout), isTerminal(os.Stderr) + u.outStyle, u.errStyle = style{colorOn(u.getenv, u.stdoutTTY)}, style{colorOn(u.getenv, u.stderrTTY)} u.termWidth = func() int { w, _, err := term.GetSize(fd(os.Stderr)) if err != nil { @@ -142,16 +146,20 @@ func (u *UI) write(w io.Writer, s string) { } // Say prints the message to stdout. -func (u *UI) Say(m msg.M) { u.write(u.stdout, m.String()+"\n") } +func (u *UI) Say(m msg.M) { u.write(u.stdout, u.outStyle.message(m)+"\n") } -// Info prints "==> " and the message to stdout: what devvm did. -func (u *UI) Info(m msg.M) { u.write(u.stdout, "==> "+m.String()+"\n") } +// Info prints "==> " (bold in a terminal) and the message to stdout: what +// devvm did. +func (u *UI) Info(m msg.M) { + u.write(u.stdout, u.outStyle.paint(sgrBold, "==>")+" "+u.outStyle.message(m)+"\n") +} // Note prints the message to stderr. -func (u *UI) Note(m msg.M) { u.write(u.stderr, m.String()+"\n") } +func (u *UI) Note(m msg.M) { u.write(u.stderr, u.errStyle.message(m)+"\n") } -// Warn prints the message to stderr, with "devvm: " before each line. -func (u *UI) Warn(m msg.M) { u.write(u.stderr, prefixLines("devvm: ", m.String())) } +// Warn prints the message to stderr, with "devvm: " before each line, +// yellow in a terminal. +func (u *UI) Warn(m msg.M) { u.write(u.stderr, u.errStyle.labelled(sgrWarn, m)) } func prefixLines(prefix, s string) string { var b strings.Builder @@ -161,21 +169,23 @@ func prefixLines(prefix, s string) string { return b.String() } -// Die prints the message like Warn and ends the run with exit code 1: it -// panics, and Main runs the cleanups and returns 1. Once the run is -// interrupted it prints nothing, as the failure is the interrupt's. +// Die prints the message like Warn, its label red in a terminal, and ends +// the run with exit code 1: it panics, and Main runs the cleanups and +// returns 1. Once the run is interrupted it prints nothing, as the failure +// is the interrupt's. func (u *UI) Die(m msg.M) { if !u.Interrupted() { - u.Warn(m) + u.write(u.stderr, u.errStyle.labelled(sgrError, m)) } exit(1) } // DieLogged is Die after printing the last 25 lines of the run's log, if it -// has one, without control characters. +// has one, without control characters, dim in a terminal. func (u *UI) DieLogged(m msg.M) { if path := u.logPath(); path != "" && !u.Interrupted() { - u.write(u.stderr, "--- "+msg.LogEnd(path).Line()+"\n"+printable(tailLines(path, 25))+"---\n") + tail := "--- " + msg.LogEnd(path).Line() + "\n" + printable(tailLines(path, 25)) + "---\n" + u.write(u.stderr, u.errStyle.paintLines(sgrDim, tail)) } u.Die(m) } @@ -184,7 +194,7 @@ func (u *UI) DieLogged(m msg.M) { // starting with y. No answer at all (the end of input) ends the run with // exit code 1, so nothing goes ahead unanswered. func (u *UI) Ask(m msg.M) bool { - a := u.answer(m.String() + " [y/N] ") + a := u.answer(u.errStyle.message(m) + " [y/N] ") return strings.HasPrefix(a, "y") || strings.HasPrefix(a, "Y") } @@ -194,7 +204,7 @@ func (u *UI) Ask(m msg.M) bool { func (u *UI) Confirm(q ...msg.M) bool { prompt := "[Y/n] " if len(q) > 0 { - prompt = q[0].String() + " " + prompt + prompt = u.errStyle.message(q[0]) + " " + prompt } a := u.answer(prompt) return !strings.HasPrefix(a, "n") && !strings.HasPrefix(a, "N") @@ -204,7 +214,7 @@ func (u *UI) Confirm(q ...msg.M) bool { // the spaces around it, "" for Enter. No answer at all ends the run like // Ask. func (u *UI) Answer(prompt msg.M) string { - return strings.TrimSpace(u.answer(prompt.String() + " ")) + return strings.TrimSpace(u.answer(u.errStyle.message(prompt) + " ")) } // readTerminal reads a line from the terminal without echoing it. A @@ -227,7 +237,7 @@ func (u *UI) Secret(prompt msg.M) string { if !u.stdinTTY { return u.Line() } - u.write(u.stderr, prompt.String()+" ") + u.write(u.stderr, u.errStyle.message(prompt)+" ") v, err := u.readPassword() u.write(u.stderr, "\n") if err != nil { diff --git a/mise.toml b/mise.toml index dc766d7a..02d28eae 100644 --- a/mise.toml +++ b/mise.toml @@ -64,13 +64,13 @@ run = [ description = "Run the unit and CLI tests" env = { CGO_ENABLED = "1" } # Tests get a throwaway HOME and XDG folders, so none can reach the real ones, -# and no SSH agent. +# no SSH agent, and no color settings of your own. run = ''' GOCACHE="$(go env GOCACHE)" GOMODCACHE="$(go env GOMODCACHE)" GOPATH="$(go env GOPATH)" export GOCACHE GOMODCACHE GOPATH home="$(mktemp -d "${TMPDIR:-/tmp}/devvm-test.XXXXXX")" trap 'rm -rf "$home"' EXIT -unset SSH_AUTH_SOCK +unset SSH_AUTH_SOCK NO_COLOR FORCE_COLOR CLICOLOR_FORCE HOME="$home" XDG_DATA_HOME="$home/.local/share" XDG_CONFIG_HOME="$home/.config" XDG_CACHE_HOME="$home/.cache" \ gotestsum -- -race -cover ./... ''' diff --git a/tests/e2e.sh b/tests/e2e.sh index 118eb317..33c92998 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -139,6 +139,7 @@ export XDG_DATA_HOME=$work/data XDG_CONFIG_HOME=$work/config export DEVVM_SECRET_SERVICE=devvm-go-e2e # its Keychain items: fake tokens only, deleted at the end unset DEVVM_MESSAGES DEVVM_VERBOSE DEVVM_UBUNTU_URL DEVVM_HOST_MISE CLAUDE_CODE_OAUTH_TOKEN DEVVM_FROM unset SSH_AUTH_SOCK # your SSH agent is never reached: checks that need one start their own +unset FORCE_COLOR CLICOLOR_FORCE # devvm's output stays plain where the checks read it mkdir -p "$LIMA_HOME" for real in "$HOME/.lima" "$HOME/.local/share/devvm/lima"; do real=$(cd "$real" 2>/dev/null && pwd -P || echo "$real")