Skip to content

Commit fd90c81

Browse files
authored
Merge pull request #20 from mittwald/feat/notice
feat(notice): add error, warning, info, OK and debug lines
2 parents b52ec1f + 8116159 commit fd90c81

11 files changed

Lines changed: 1579 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ compiled into your binary.
4141
| [`cobrax`](https://pkg.go.dev/github.com/mittwald/cli-kit/cobrax) | Cobra helpers: `--color` and other auto/always/never flags, enum flags, deprecated flag spellings as hidden aliases, hardened, cached and prefix-filtered shell completion with an optional `--install` or a script written to a path, version command |
4242
| [`fsx`](https://pkg.go.dev/github.com/mittwald/cli-kit/fsx) | Files replaced atomically with a chosen mode, refusing a symbolic link in their place |
4343
| [`browser`](https://pkg.go.dev/github.com/mittwald/cli-kit/browser) | A web page opened in the user's browser, http and https URLs only, without a shell |
44+
| [`notice`](https://pkg.go.dev/github.com/mittwald/cli-kit/notice) | Error, warning, info, OK and debug lines in line, badge, bar or block themes, with colors for dark and light terminals, colored values and patterns, made plain and redacted |
4445
| [`logx`](https://pkg.go.dev/github.com/mittwald/cli-kit/logx) | A `log/slog` handler writing plain, redacted lines for `--verbose` |
4546
| [`clipboard`](https://pkg.go.dev/github.com/mittwald/cli-kit/clipboard) | Text copied to the system clipboard through the platform's helper commands, without cgo |
4647
| [`buildinfo`](https://pkg.go.dev/github.com/mittwald/cli-kit/buildinfo) | Version, commit and date from `-ldflags` or the Go build information |
@@ -208,6 +209,23 @@ logger.Debug("sent a request", "path", path, "status", status) // plain, credent
208209
logger.Debug("response", "body", redact.Values(body, token)) // the token the program sent, in any escaped form
209210
```
210211

212+
### Notices
213+
214+
```go
215+
notice.Use(notice.New(notice.Options{
216+
Theme: notice.Badge.WithColors(notice.Deep), // or Line, Bar, Block; Default, Muted, Pastel
217+
Debug: verbose,
218+
Around: bar.WithCleared, // a progress bar steps aside for each notice
219+
}))
220+
221+
notice.Warnf("Booking day %s was never left: the start at %s has no Gehen",
222+
notice.Date(day), notice.Time(start)) // values in their role's color
223+
notice.Error(err) // plain and redacted, like every argument
224+
225+
mr := notice.NewRole("merge request", notice.RoleColors{Dark: theme.Fg256(218), Light: theme.Fg256(125)})
226+
th := notice.Block.WithPatterns(notice.Pattern{Match: regexp.MustCompile(`[\w./-]+![0-9]+`), Role: mr})
227+
```
228+
211229
### Shell completion and version
212230

213231
```go

‎examples/demo/main.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ func run() int {
6262
newLiveCommand(),
6363
newTableCommand(),
6464
newThemeCommand(),
65+
newNoticeCommand(),
6566
newTermCommand(links),
6667
cobrax.NewVersionCommand(info),
6768
)

‎examples/demo/notice.go‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
package main
2+
3+
import (
4+
"errors"
5+
"fmt"
6+
"os"
7+
"regexp"
8+
"slices"
9+
"sort"
10+
11+
"github.com/spf13/cobra"
12+
13+
"github.com/mittwald/cli-kit/notice"
14+
"github.com/mittwald/cli-kit/theme"
15+
)
16+
17+
// newNoticeCommand returns the notice command: every theme in every set of
18+
// colors, on a dark or a light background.
19+
func newNoticeCommand() *cobra.Command {
20+
var themeName, colorsName, background string
21+
cmd := &cobra.Command{
22+
Use: "notice",
23+
Short: "Show the notice themes and colors: error, warning, info, OK and debug lines",
24+
Args: cobra.NoArgs,
25+
RunE: func(*cobra.Command, []string) error {
26+
return runNotice(themeName, colorsName, background)
27+
},
28+
}
29+
cmd.Flags().StringVar(&themeName, "theme", "", "show only this theme: line, badge, bar or block")
30+
cmd.Flags().StringVar(&colorsName, "colors", "", "show only these colors: default, muted, deep or pastel")
31+
cmd.Flags().StringVar(&background, "background", "auto", "the terminal's background: auto, dark or light")
32+
return cmd
33+
}
34+
35+
func runNotice(themeName, colorsName, background string) error {
36+
bg, ok := map[string]notice.Background{
37+
"auto": notice.BackgroundAuto, "dark": notice.BackgroundDark, "light": notice.BackgroundLight,
38+
}[background]
39+
if !ok {
40+
return fmt.Errorf("--background %q is not auto, dark or light", background)
41+
}
42+
names := make([]string, 0, len(notice.AllColors))
43+
for name := range notice.AllColors {
44+
names = append(names, name)
45+
}
46+
sort.Strings(names)
47+
// default first, the rest by name
48+
names = append([]string{"default"}, slices.DeleteFunc(names, func(n string) bool { return n == "default" })...)
49+
if colorsName != "" {
50+
if _, ok := notice.AllColors[colorsName]; !ok {
51+
return fmt.Errorf("--colors %q is not one of %v", colorsName, names)
52+
}
53+
names = []string{colorsName}
54+
}
55+
themes := notice.Themes
56+
if themeName != "" {
57+
i := slices.IndexFunc(themes, func(t notice.Theme) bool { return t.Name == themeName })
58+
if i < 0 {
59+
return fmt.Errorf("--theme %q is not line, badge, bar or block", themeName)
60+
}
61+
themes = themes[i : i+1]
62+
}
63+
64+
// A tool's own role, picked out of messages by a pattern.
65+
mr := notice.NewRole("merge request", notice.RoleColors{Dark: theme.Fg256(218), Light: theme.RGB(0xA0, 0x30, 0x6E)})
66+
mrPattern := notice.Pattern{Match: regexp.MustCompile(`[\w./-]+![0-9]+`), Role: mr}
67+
68+
title := theme.Bold.For(os.Stdout)
69+
for _, name := range names {
70+
for _, t := range themes {
71+
fmt.Println(title.Paint(fmt.Sprintf("── %s · %s ──", t.Name, name)))
72+
p := notice.New(notice.Options{
73+
Theme: t.WithColors(notice.AllColors[name]).WithPatterns(mrPattern),
74+
Background: bg,
75+
Writer: os.Stdout,
76+
Debug: true,
77+
})
78+
p.Error(fmt.Errorf("could not read the replies on tools/nickpit!123: %w", errors.New("request timed out")))
79+
p.Warnf("Booking day %s was never left: the start at %s %s has no Gehen",
80+
notice.Date("19.11.2026"), notice.Date("19.11.2026"), notice.Time("08:40"))
81+
p.Infof("session %s saved to %s", notice.Ref("7f3a2c"), notice.Path("~/.local/state/nickpit/7f3a2c.json"))
82+
p.Successf("Booked Kommen at %s on %s", notice.Time("08:40"), notice.Date("25.11.2026"))
83+
p.Debugf("GET %s, %d retries left", notice.Path("https://gitlab.example/api/v4/projects/42"), notice.Detail(3))
84+
fmt.Println()
85+
}
86+
}
87+
return nil
88+
}

‎notice/doc.go‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// Package notice writes the error, warning, info, OK and debug lines of a
2+
// command-line tool: one line per notice on the error stream, labeled
3+
// ERROR, WARN, INFO, OK or DEBUG.
4+
//
5+
// A [Theme] sets how a notice looks. [Line] writes the label in its level's
6+
// color and a colon ("WARN: …"); [Badge] writes the label on its level's
7+
// background, padded so the messages line up; [Bar] adds a tint of the
8+
// level's color behind the message, and [Block] puts the whole line on the
9+
// level's background. Bar and Block fill the line to the right edge of the
10+
// terminal unless the theme says otherwise.
11+
//
12+
// The colors of a theme are [Colors]: a [Palette] for dark terminals and
13+
// one for light ones, picked by [Options] Background, which reads
14+
// COLORFGBG by default. [Default], [Muted], [Deep] and [Pastel] are the
15+
// built-in colors; [Theme.WithColors] puts any of them on any theme, and
16+
// [Options] Colors change single colors over them.
17+
//
18+
// Values in a message are marked with a [Role], so they stand out in a
19+
// color of their own: [Date], [Time], [Detail], [Ref] and [Path] mark the
20+
// built-in roles, and [NewRole] makes one of a tool's own, with colors for
21+
// both backgrounds. A [Pattern] gives a role to whatever a regular
22+
// expression matches in the message's own text, such as a merge request
23+
// reference.
24+
//
25+
// Every notice is made safe before it is written: escape sequences and
26+
// control characters are taken out (term.Plain) and recognizable
27+
// credentials replaced (redact.Patterns), in the message and in its values.
28+
// Credentials are looked for in the message as it reads, values in place;
29+
// a notice in which one is found is written without colored values.
30+
// Where the writer takes no color, as term.Colored decides, a notice is
31+
// plain text in every theme: "WARN: …".
32+
//
33+
// A [Printer] writes notices with its [Options]. The package-level
34+
// functions, such as [Warnf], use the Printer that [Use] installed for the
35+
// whole process, or a [Line] Printer on os.Stderr.
36+
package notice

‎notice/example_test.go‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package notice_test
2+
3+
import (
4+
"errors"
5+
"os"
6+
7+
"github.com/mittwald/cli-kit/notice"
8+
)
9+
10+
func Example() {
11+
// os.Stdout is no terminal in a test, so the notices come out plain.
12+
p := notice.New(notice.Options{Theme: notice.Badge, Writer: os.Stdout})
13+
p.Warnf("Booking day %s was never left: the start at %s has no Gehen", notice.Date("19.11.2026"), notice.Time("08:40"))
14+
p.Error(errors.New("request timed out: password=hunter2"))
15+
p.Debugf("not shown without Options.Debug")
16+
// Output:
17+
// WARN: Booking day 19.11.2026 was never left: the start at 08:40 has no Gehen
18+
// ERROR: request timed out: password=[REDACTED]
19+
}

‎notice/notice.go‎

Lines changed: 199 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,199 @@
1+
package notice
2+
3+
import (
4+
"io"
5+
"os"
6+
"strconv"
7+
"strings"
8+
"sync"
9+
"sync/atomic"
10+
11+
"github.com/mittwald/cli-kit/term"
12+
)
13+
14+
// Background is the background of the terminal a notice goes to, which
15+
// picks between a theme's Dark and Light colors.
16+
type Background int
17+
18+
// The backgrounds.
19+
const (
20+
// BackgroundAuto reads COLORFGBG, which some terminals set, and takes
21+
// the dark colors when it does not tell.
22+
BackgroundAuto Background = iota
23+
// BackgroundDark takes the dark colors.
24+
BackgroundDark
25+
// BackgroundLight takes the light colors.
26+
BackgroundLight
27+
)
28+
29+
// Options configure a [Printer]. The zero Options print the [Line] theme to
30+
// os.Stderr.
31+
type Options struct {
32+
// Theme is how notices look. The zero Theme is [Line]; a Theme without
33+
// dark colors of its own takes [Default].
34+
Theme Theme
35+
// Background picks the theme's dark or light colors.
36+
Background Background
37+
// Colors are set over the theme's colors, one color at a time: a color
38+
// they leave empty keeps the theme's. As in a theme, a color Light
39+
// leaves empty is taken from Dark.
40+
Colors Colors
41+
// Writer is where notices go; os.Stderr when nil. Whether they are
42+
// painted is decided for it by term.Colored.
43+
Writer io.Writer
44+
// Debug turns on the debug notices, usually with a --verbose flag.
45+
Debug bool
46+
// Around, when set, writes each notice: it gets a function that writes
47+
// it and calls that function, so a progress bar or a live display can
48+
// step aside first, as progress.Bar.WithCleared does.
49+
Around func(write func())
50+
// KeepEscapes leaves escape sequences and control characters in the
51+
// text of a message and its arguments instead of making it plain with
52+
// term.Plain.
53+
//
54+
// Use it only for text the program wrote itself. Text from a server, a
55+
// file or an error can then move the cursor, rewrite earlier lines or
56+
// change the terminal's title.
57+
KeepEscapes bool
58+
// NoRedact leaves recognizable credentials, such as password=… or a
59+
// Bearer token, in the text instead of replacing them with
60+
// redact.Patterns.
61+
//
62+
// Use it only for text that cannot carry a credential; otherwise a
63+
// notice can put a secret on the screen and into a terminal's
64+
// scrollback or a CI log.
65+
NoRedact bool
66+
}
67+
68+
// Printer writes notices. It is safe for concurrent use; notices from
69+
// several goroutines never interleave.
70+
type Printer struct {
71+
options Options
72+
mu sync.Mutex
73+
}
74+
75+
// New returns a Printer with options.
76+
func New(options Options) *Printer {
77+
if options.Writer == nil {
78+
options.Writer = os.Stderr
79+
}
80+
switch t := options.Theme; {
81+
case t.Name == "" && t.Layout == LayoutLine && t.Colors.Dark.Levels == nil && t.Colors.Light.Levels == nil &&
82+
t.Padding == (Padding{}) && !t.NoFill && len(t.Patterns) == 0:
83+
options.Theme = Line // the zero Theme
84+
case t.Colors.Dark.Levels == nil:
85+
options.Theme.Colors = Default // a theme that sets no colors of its own
86+
}
87+
return &Printer{options: options}
88+
}
89+
90+
var active atomic.Pointer[Printer]
91+
92+
// Use installs p as the Printer of the package-level functions, [Errorf]
93+
// and the rest, for the whole process. Call it once at start-up.
94+
func Use(p *Printer) { active.Store(p) }
95+
96+
// Active returns the Printer [Use] installed, or one with the zero
97+
// [Options].
98+
func Active() *Printer {
99+
if p := active.Load(); p != nil {
100+
return p
101+
}
102+
p := New(Options{})
103+
if active.CompareAndSwap(nil, p) {
104+
return p
105+
}
106+
return active.Load()
107+
}
108+
109+
// Errorf writes an error notice. Arguments are formatted as fmt.Sprintf
110+
// formats them; mark the values the message carries with [Value] or its
111+
// shorthands, such as [Date] and [Path], to color them.
112+
func (p *Printer) Errorf(format string, args ...any) { p.Notify(LevelError, format, args...) }
113+
114+
// Warnf writes a warning notice; see [Printer.Errorf].
115+
func (p *Printer) Warnf(format string, args ...any) { p.Notify(LevelWarn, format, args...) }
116+
117+
// Infof writes an informational notice; see [Printer.Errorf].
118+
func (p *Printer) Infof(format string, args ...any) { p.Notify(LevelInfo, format, args...) }
119+
120+
// Successf writes an OK notice; see [Printer.Errorf].
121+
func (p *Printer) Successf(format string, args ...any) { p.Notify(LevelOK, format, args...) }
122+
123+
// Debugf writes a debug notice when [Options] Debug is set; see
124+
// [Printer.Errorf].
125+
func (p *Printer) Debugf(format string, args ...any) { p.Notify(LevelDebug, format, args...) }
126+
127+
// Error writes err as an error notice. A nil err writes nothing.
128+
func (p *Printer) Error(err error) {
129+
if err != nil {
130+
p.Notify(LevelError, "%v", err)
131+
}
132+
}
133+
134+
// Warn writes err as a warning notice. A nil err writes nothing.
135+
func (p *Printer) Warn(err error) {
136+
if err != nil {
137+
p.Notify(LevelWarn, "%v", err)
138+
}
139+
}
140+
141+
// Notify writes a notice of level; see [Printer.Errorf].
142+
func (p *Printer) Notify(level Level, format string, args ...any) {
143+
if level == LevelDebug && !p.options.Debug {
144+
return
145+
}
146+
colored := term.Colored(p.options.Writer)
147+
text := p.render(level, format, args, colored)
148+
write := func() {
149+
p.mu.Lock()
150+
defer p.mu.Unlock()
151+
_, _ = io.WriteString(p.options.Writer, text)
152+
}
153+
if p.options.Around != nil {
154+
p.options.Around(write)
155+
return
156+
}
157+
write()
158+
}
159+
160+
// Errorf writes an error notice with the [Active] Printer.
161+
func Errorf(format string, args ...any) { Active().Errorf(format, args...) }
162+
163+
// Warnf writes a warning notice with the [Active] Printer.
164+
func Warnf(format string, args ...any) { Active().Warnf(format, args...) }
165+
166+
// Infof writes an informational notice with the [Active] Printer.
167+
func Infof(format string, args ...any) { Active().Infof(format, args...) }
168+
169+
// Successf writes an OK notice with the [Active] Printer.
170+
func Successf(format string, args ...any) { Active().Successf(format, args...) }
171+
172+
// Debugf writes a debug notice with the [Active] Printer.
173+
func Debugf(format string, args ...any) { Active().Debugf(format, args...) }
174+
175+
// Error writes err as an error notice with the [Active] Printer.
176+
func Error(err error) { Active().Error(err) }
177+
178+
// Warn writes err as a warning notice with the [Active] Printer.
179+
func Warn(err error) { Active().Warn(err) }
180+
181+
// lightBackground reports what COLORFGBG says of the background: its last
182+
// field is the background's color number, and 7 and 15 (white) are the
183+
// light ones, as the terminals that set it use them.
184+
func lightBackground(colorfgbg string) bool {
185+
fields := strings.Split(colorfgbg, ";")
186+
n, err := strconv.Atoi(strings.TrimSpace(fields[len(fields)-1]))
187+
return err == nil && (n == 7 || n == 15)
188+
}
189+
190+
// light reports whether the light colors apply.
191+
func (p *Printer) light() bool {
192+
switch p.options.Background {
193+
case BackgroundLight:
194+
return true
195+
case BackgroundDark:
196+
return false
197+
}
198+
return lightBackground(os.Getenv("COLORFGBG"))
199+
}

0 commit comments

Comments
 (0)