/
highlight.go
58 lines (48 loc) 路 1.05 KB
/
highlight.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
54
55
56
57
58
package templates
import (
"go/format"
"io"
"github.com/alecthomas/chroma/quick"
"github.com/hashicorp/hcl/v2/hclwrite"
"github.com/pkg/errors"
)
var (
ErrNoColor = "failed to print output with NO_COLOR"
ErrHighlight = "failed to highlight %s source"
ErrFmt = "failed to format %s source"
)
type Language int
const (
GO Language = iota
HCL
PLAINTEXT
)
func (l Language) string() string {
return [...]string{"go", "hcl", "plaintext"}[l]
}
// Highlight and format text
func Highlight(w io.Writer, text string, lang Language, skipColor bool) error {
formatter := "terminal"
if skipColor {
formatter = "noop"
}
switch lang {
case HCL:
fmt := hclwrite.Format([]byte(text))
if fmt == nil {
return nil
}
text = string(fmt)
case GO:
fmt, err := format.Source([]byte(text))
if err != nil {
return errors.Wrapf(err, ErrFmt, lang.string())
}
text = string(fmt)
}
err := quick.Highlight(w, text, lang.string(), formatter, "fallback")
if err != nil {
return errors.Wrapf(err, ErrHighlight, lang.string())
}
return nil
}