github.com/tinygo-org/tinygo@v0.31.3-0.20240404173401-90b0bf646c27/colorwriter.go (about)

     1  package main
     2  
     3  import (
     4  	"io"
     5  )
     6  
     7  // ANSI escape codes for terminal colors.
     8  const (
     9  	TermColorReset  = "\x1b[0m"
    10  	TermColorYellow = "\x1b[93m"
    11  )
    12  
    13  // ColorWriter wraps an io.Writer but adds a prefix and a terminal color.
    14  type ColorWriter struct {
    15  	Out    io.Writer
    16  	Color  string
    17  	Prefix string
    18  	line   []byte
    19  }
    20  
    21  // Write implements io.Writer, but with an added prefix and terminal color.
    22  func (w *ColorWriter) Write(p []byte) (n int, err error) {
    23  	for _, c := range p {
    24  		if c == '\n' {
    25  			w.line = append(w.line, []byte(TermColorReset)...)
    26  			w.line = append(w.line, '\n')
    27  			// Write this line.
    28  			_, err := w.Out.Write(w.line)
    29  			w.line = w.line[:0]
    30  			w.line = append(w.line, []byte(w.Color+w.Prefix)...)
    31  			if err != nil {
    32  				return 0, err
    33  			}
    34  		} else {
    35  			w.line = append(w.line, c)
    36  		}
    37  	}
    38  	return len(p), nil
    39  }