Skip to content

Commit

Permalink
add colorize writer
Browse files Browse the repository at this point in the history
  • Loading branch information
mkideal committed Aug 23, 2024
1 parent 9de4466 commit 97b8297
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions term/term.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,23 @@ func IsSupports256Colors() bool {
return isSupports256Colors
}

func ColorizeWriter(w io.Writer, c Color) io.Writer {
return &colorizeWriter{w: w, color: c, isTerminal: IsTerminal(w)}
}

type colorizeWriter struct {
w io.Writer
color Color
isTerminal bool
}

func (w *colorizeWriter) Write(p []byte) (n int, err error) {
if w.isTerminal && isSupportsAnsi && (!w.color.Is256() || isSupports256Colors) {
return w.w.Write([]byte(w.color.Format(string(p))))
}
return w.w.Write(p)
}

// Reset is the ANSI escape code to reset all attributes.
const Reset = "\033[0m"

Expand Down

0 comments on commit 97b8297

Please sign in to comment.