Diagnostics are printed as "prog: message" on stderr, at three levels: quiet (errors only), normal and verbose. Warnings and errors are colored only when stderr is a terminal, NO_COLOR is unset and TERM is not "dumb"; the terminal check uses the TCGETS ioctl instead of guessing from the file mode.
89 lines
2.0 KiB
Go
89 lines
2.0 KiB
Go
package cli
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
|
|
"golang.org/x/sys/unix"
|
|
)
|
|
|
|
// Verbosity selects which messages a Logger prints.
|
|
type Verbosity int
|
|
|
|
const (
|
|
Quiet Verbosity = iota // errors only
|
|
Normal // plus status and warnings
|
|
Verbose // plus details and backend listings
|
|
)
|
|
|
|
// Logger writes "prog: message" diagnostics, normally to stderr.
|
|
type Logger struct {
|
|
Level Verbosity
|
|
prog string
|
|
w io.Writer
|
|
color bool
|
|
}
|
|
|
|
// NewLogger returns a Logger writing to f. Color is used only when f is a
|
|
// terminal, NO_COLOR is unset or empty, and TERM is set and not "dumb".
|
|
func NewLogger(prog string, f *os.File) *Logger {
|
|
return &Logger{Level: Normal, prog: prog, w: f, color: wantColor(f)}
|
|
}
|
|
|
|
func wantColor(f *os.File) bool {
|
|
if os.Getenv("NO_COLOR") != "" {
|
|
return false
|
|
}
|
|
if term := os.Getenv("TERM"); term == "" || term == "dumb" {
|
|
return false
|
|
}
|
|
_, err := unix.IoctlGetTermios(int(f.Fd()), unix.TCGETS)
|
|
return err == nil
|
|
}
|
|
|
|
// Color reports whether diagnostics use color.
|
|
func (l *Logger) Color() bool { return l.color }
|
|
|
|
// Info prints a status message unless quiet.
|
|
func (l *Logger) Info(format string, a ...any) {
|
|
if l.Level >= Normal {
|
|
l.print("", format, a...)
|
|
}
|
|
}
|
|
|
|
// Detail prints a message only when verbose.
|
|
func (l *Logger) Detail(format string, a ...any) {
|
|
if l.Level >= Verbose {
|
|
l.print("", format, a...)
|
|
}
|
|
}
|
|
|
|
// Warn prints a warning unless quiet.
|
|
func (l *Logger) Warn(format string, a ...any) {
|
|
if l.Level >= Normal {
|
|
l.print(l.paint("33", "warning:")+" ", format, a...)
|
|
}
|
|
}
|
|
|
|
// Error always prints.
|
|
func (l *Logger) Error(format string, a ...any) {
|
|
l.print(l.paint("31", "error:")+" ", format, a...)
|
|
}
|
|
|
|
// Plain prints a line without the program prefix.
|
|
func (l *Logger) Plain(format string, a ...any) {
|
|
fmt.Fprintf(l.w, format+"\n", a...)
|
|
}
|
|
|
|
func (l *Logger) print(prefix, format string, a ...any) {
|
|
fmt.Fprintf(l.w, "%s: %s%s\n", l.prog, prefix, fmt.Sprintf(format, a...))
|
|
}
|
|
|
|
func (l *Logger) paint(code, s string) string {
|
|
if !l.color {
|
|
return s
|
|
}
|
|
return "\x1b[1;" + code + "m" + s + "\x1b[0m"
|
|
}
|