// SPDX-License-Identifier: GPL-3.0-or-later package main import ( "fmt" "io" "strings" "git.labunix.xyz/krino/internal/tui" ) // palette styles text for a terminal (spec §8.2) with SGR codes from the // 16-colour ANSI palette plus bold and faint only, so the terminal's own // theme decides what they look like. The zero value is plain: every method // returns its text unchanged, which keeps output with colour off // byte-identical to what krino printed before colour existed. type palette struct{ on bool } func (p palette) style(code, s string) string { if !p.on || s == "" { return s } return "\x1b[" + code + "m" + s + "\x1b[0m" } func (p palette) bold(s string) string { return p.style("1", s) } func (p palette) faint(s string) string { return p.style("2", s) } func (p palette) bad(s string) string { return p.style("31", s) } func (p palette) good(s string) string { return p.style("32", s) } func (p palette) warn(s string) string { return p.style("33", s) } func (p palette) rule(s string) string { return p.style("34", s) } func (p palette) alarm(s string) string { return p.style("1;31", s) } // keys bolds every one-character [x] key in a prompt line. func (p palette) keys(menu string) string { if !p.on { return menu } var b strings.Builder for i := 0; i < len(menu); { if menu[i] == '[' && i+2 < len(menu) && menu[i+2] == ']' { b.WriteString(p.bold(menu[i : i+3])) i += 3 continue } b.WriteByte(menu[i]) i++ } return b.String() } // outcome renders the "N applied · N failed · N declined" line: the applied // count green and the failed count red, each only when above 0. func outcome(p palette, applied, failed, declined int) string { a, f := fmt.Sprint(applied), fmt.Sprint(failed) if applied > 0 { a = p.good(a) } if failed > 0 { f = p.bad(f) } return fmt.Sprintf("%s applied · %s failed · %d declined", a, f, declined) } // colourPolicy is tui.Colour (terminal, and NO_COLOR unset); tests replace // it, since no test runs on a terminal. var colourPolicy = tui.Colour // widthPolicy is tui.Width, the terminal's columns (0: never wrap); pager // is tui.Page. Tests replace both, for the same reason. var ( widthPolicy = tui.Width pager = tui.Page ) // show writes text to w: straight out with -P (--no-pager), otherwise // through the pager, which only engages when text is taller than the // terminal. func show(g *globals, w io.Writer, text string) error { if g.noPager { _, err := io.WriteString(w, text) return err } return pager(w, text) } // colourOn reports whether output to w is coloured: never with --no-color, // otherwise as colourPolicy decides. func colourOn(g *globals, w io.Writer) bool { return !g.noColor && colourPolicy(w) }