...

Source file src/cdr.dev/slog/internal/entryhuman/json.go

Documentation: cdr.dev/slog/internal/entryhuman

     1  package entryhuman
     2  
     3  import (
     4  	"bytes"
     5  	"io"
     6  
     7  	"github.com/alecthomas/chroma"
     8  	"github.com/alecthomas/chroma/formatters"
     9  	jlexers "github.com/alecthomas/chroma/lexers/j"
    10  )
    11  
    12  // Adapted from https://github.com/alecthomas/chroma/blob/2f5349aa18927368dbec6f8c11608bf61c38b2dd/styles/bw.go#L7
    13  // https://github.com/alecthomas/chroma/blob/2f5349aa18927368dbec6f8c11608bf61c38b2dd/formatters/tty_indexed.go
    14  // https://github.com/alecthomas/chroma/blob/2f5349aa18927368dbec6f8c11608bf61c38b2dd/lexers/j/json.go
    15  var style = chroma.MustNewStyle("slog", chroma.StyleEntries{
    16  	// Magenta.
    17  	chroma.Keyword: "#7f007f",
    18  	// Magenta.
    19  	chroma.Number: "#7f007f",
    20  	// Magenta.
    21  	chroma.Name: "#00007f",
    22  	// Green.
    23  	chroma.String: "#007f00",
    24  })
    25  
    26  var jsonLexer = chroma.Coalesce(jlexers.JSON)
    27  
    28  func formatJSON(w io.Writer, buf []byte) []byte {
    29  	if !shouldColor(w) {
    30  		return buf
    31  	}
    32  
    33  	highlighted, _ := colorizeJSON(buf)
    34  	return highlighted
    35  }
    36  
    37  func colorizeJSON(buf []byte) ([]byte, error) {
    38  	it, _ := jsonLexer.Tokenise(nil, string(buf))
    39  	b := &bytes.Buffer{}
    40  	formatters.TTY8.Format(b, style, it)
    41  	return b.Bytes(), nil
    42  }
    43  

View as plain text