-
Notifications
You must be signed in to change notification settings - Fork 0
/
coloryaml.go
53 lines (47 loc) · 902 Bytes
/
coloryaml.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package coloryaml
import (
"bytes"
"io"
"os"
"strings"
"github.com/goccy/go-yaml/lexer"
"gopkg.in/yaml.v3"
)
func Colorize(s string) string {
// https://github.com/mikefarah/yq/blob/v4.43.1/pkg/yqlib/color_print.go
tokens := lexer.Tokenize(s)
return Printer().PrintTokens(tokens)
}
func Sprintln(obj any) (string, error) {
b, err := yaml.Marshal(obj)
if err != nil {
return "", err
}
s := Colorize(string(b))
if !strings.HasSuffix(s, "\n") {
s += "\n"
}
return s, nil
}
func Fprintln(w io.Writer, obj any) error {
if !shouldColor(w) {
b, err := yaml.Marshal(obj)
if err != nil {
return err
}
if !bytes.HasSuffix(b, []byte{'\n'}) {
b = append(b, '\n')
}
_, err = w.Write(b)
return err
}
s, err := Sprintln(obj)
if err != nil {
return err
}
_, err = io.WriteString(w, s)
return err
}
func Println(obj any) error {
return Fprintln(os.Stdout, obj)
}