Debian Codegraph @

dependencies/pkg/mod/github.com/goccy/[email protected]/printer/printer.go

raw
1 package printer
2
3 import (
4 "fmt"
5 "math"
6 "strings"
7
8 "github.com/fatih/color"
9
10 "github.com/goccy/go-yaml/ast"
11 "github.com/goccy/go-yaml/token"
12 )
13
14 // Property additional property set for each the token
15 type Property struct {
16 Prefix string
17 Suffix string
18 }
19
20 // PrintFunc returns property instance
21 type PrintFunc func() *Property
22
23 // Printer create text from token collection or ast
24 type Printer struct {
25 LineNumber bool
26 LineNumberFormat func(num int) string
27 MapKey PrintFunc
28 Anchor PrintFunc
29 Alias PrintFunc
30 Bool PrintFunc
31 String PrintFunc
32 Number PrintFunc
33 Comment PrintFunc
34 }
35
36 func defaultLineNumberFormat(num int) string {
37 return fmt.Sprintf("%2d | ", num)
38 }
39
40 func (p *Printer) property(tk *token.Token) *Property {
41 prop := &Property{}
42 switch tk.PreviousType() {
43 case token.AnchorType:
44 if p.Anchor != nil {
45 return p.Anchor()
46 }
47 return prop
48 case token.AliasType:
49 if p.Alias != nil {
50 return p.Alias()
51 }
52 return prop
53 }
54 switch tk.NextType() {
55 case token.MappingValueType:
56 if p.MapKey != nil {
57 return p.MapKey()
58 }
59 return prop
60 }
61 switch tk.Type {
62 case token.BoolType:
63 if p.Bool != nil {
64 return p.Bool()
65 }
66 return prop
67 case token.AnchorType:
68 if p.Anchor != nil {
69 return p.Anchor()
70 }
71 return prop
72 case token.AliasType:
73 if p.Anchor != nil {
74 return p.Alias()
75 }
76 return prop
77 case token.StringType, token.SingleQuoteType, token.DoubleQuoteType:
78 if p.String != nil {
79 return p.String()
80 }
81 return prop
82 case token.IntegerType, token.FloatType:
83 if p.Number != nil {
84 return p.Number()
85 }
86 return prop
87 case token.CommentType:
88 if p.Comment != nil {
89 return p.Comment()
90 }
91 return prop
92 default:
93 }
94 return prop
95 }
96
97 // PrintTokens create text from token collection
98 func (p *Printer) PrintTokens(tokens token.Tokens) string {
99 if len(tokens) == 0 {
100 return ""
101 }
102 if p.LineNumber {
103 if p.LineNumberFormat == nil {
104 p.LineNumberFormat = defaultLineNumberFormat
105 }
106 }
107 texts := []string{}
108 lineNumber := tokens[0].Position.Line
109 for _, tk := range tokens {
110 lines := strings.Split(tk.Origin, "\n")
111 prop := p.property(tk)
112 header := ""
113 if p.LineNumber {
114 header = p.LineNumberFormat(lineNumber)
115 }
116 if len(lines) == 1 {
117 line := prop.Prefix + lines[0] + prop.Suffix
118 if len(texts) == 0 {
119 texts = append(texts, header+line)
120 lineNumber++
121 } else {
122 text := texts[len(texts)-1]
123 texts[len(texts)-1] = text + line
124 }
125 } else {
126 for idx, src := range lines {
127 if p.LineNumber {
128 header = p.LineNumberFormat(lineNumber)
129 }
130 line := prop.Prefix + src + prop.Suffix
131 if idx == 0 {
132 if len(texts) == 0 {
133 texts = append(texts, header+line)
134 lineNumber++
135 } else {
136 text := texts[len(texts)-1]
137 texts[len(texts)-1] = text + line
138 }
139 } else {
140 texts = append(texts, fmt.Sprintf("%s%s", header, line))
141 lineNumber++
142 }
143 }
144 }
145 }
146 return strings.Join(texts, "\n")
147 }
148
149 // PrintNode create text from ast.Node
150 func (p *Printer) PrintNode(node ast.Node) []byte {
151 return []byte(fmt.Sprintf("%+v\n", node))
152 }
153
154 const escape = "\x1b"
155
156 func format(attr color.Attribute) string {
157 return fmt.Sprintf("%s[%dm", escape, attr)
158 }
159
160 func (p *Printer) setDefaultColorSet() {
161 p.Bool = func() *Property {
162 return &Property{
163 Prefix: format(color.FgHiMagenta),
164 Suffix: format(color.Reset),
165 }
166 }
167 p.Number = func() *Property {
168 return &Property{
169 Prefix: format(color.FgHiMagenta),
170 Suffix: format(color.Reset),
171 }
172 }
173 p.MapKey = func() *Property {
174 return &Property{
175 Prefix: format(color.FgHiCyan),
176 Suffix: format(color.Reset),
177 }
178 }
179 p.Anchor = func() *Property {
180 return &Property{
181 Prefix: format(color.FgHiYellow),
182 Suffix: format(color.Reset),
183 }
184 }
185 p.Alias = func() *Property {
186 return &Property{
187 Prefix: format(color.FgHiYellow),
188 Suffix: format(color.Reset),
189 }
190 }
191 p.String = func() *Property {
192 return &Property{
193 Prefix: format(color.FgHiGreen),
194 Suffix: format(color.Reset),
195 }
196 }
197 }
198
199 func (p *Printer) PrintErrorMessage(msg string, isColored bool) string {
200 if isColored {
201 return fmt.Sprintf("%s%s%s",
202 format(color.FgHiRed),
203 msg,
204 format(color.Reset),
205 )
206 }
207 return msg
208 }
209
210 func (p *Printer) removeLeftSideNewLineChar(src string) string {
211 return strings.TrimLeft(strings.TrimLeft(strings.TrimLeft(src, "\r"), "\n"), "\r\n")
212 }
213
214 func (p *Printer) removeRightSideNewLineChar(src string) string {
215 return strings.TrimRight(strings.TrimRight(strings.TrimRight(src, "\r"), "\n"), "\r\n")
216 }
217
218 func (p *Printer) removeRightSideWhiteSpaceChar(src string) string {
219 return p.removeRightSideNewLineChar(strings.TrimRight(src, " "))
220 }
221
222 func (p *Printer) newLineCount(s string) int {
223 src := []rune(s)
224 size := len(src)
225 cnt := 0
226 for i := 0; i < size; i++ {
227 c := src[i]
228 switch c {
229 case '\r':
230 if i+1 < size && src[i+1] == '\n' {
231 i++
232 }
233 cnt++
234 case '\n':
235 cnt++
236 }
237 }
238 return cnt
239 }
240
241 func (p *Printer) isNewLineLastChar(s string) bool {
242 for i := len(s) - 1; i > 0; i-- {
243 c := s[i]
244 switch c {
245 case ' ':
246 continue
247 case '\n', '\r':
248 return true
249 }
250 break
251 }
252 return false
253 }
254
255 func (p *Printer) printBeforeTokens(tk *token.Token, minLine, extLine int) token.Tokens {
256 for {
257 if tk.Prev == nil {
258 break
259 }
260 if tk.Prev.Position.Line < minLine {
261 break
262 }
263 tk = tk.Prev
264 }
265 minTk := tk.Clone()
266 if minTk.Prev != nil {
267 // add white spaces to minTk by prev token
268 prev := minTk.Prev
269 whiteSpaceLen := len(prev.Origin) - len(strings.TrimRight(prev.Origin, " "))
270 minTk.Origin = strings.Repeat(" ", whiteSpaceLen) + minTk.Origin
271 }
272 minTk.Origin = p.removeLeftSideNewLineChar(minTk.Origin)
273 tokens := token.Tokens{minTk}
274 tk = minTk.Next
275 for tk != nil && tk.Position.Line <= extLine {
276 clonedTk := tk.Clone()
277 tokens.Add(clonedTk)
278 tk = clonedTk.Next
279 }
280 lastTk := tokens[len(tokens)-1]
281 trimmedOrigin := p.removeRightSideWhiteSpaceChar(lastTk.Origin)
282 suffix := lastTk.Origin[len(trimmedOrigin):]
283 lastTk.Origin = trimmedOrigin
284
285 if lastTk.Next != nil && len(suffix) > 1 {
286 next := lastTk.Next.Clone()
287 // add suffix to header of next token
288 if suffix[0] == '\n' || suffix[0] == '\r' {
289 suffix = suffix[1:]
290 }
291 next.Origin = suffix + next.Origin
292 lastTk.Next = next
293 }
294 return tokens
295 }
296
297 func (p *Printer) printAfterTokens(tk *token.Token, maxLine int) token.Tokens {
298 tokens := token.Tokens{}
299 if tk == nil {
300 return tokens
301 }
302 if tk.Position.Line > maxLine {
303 return tokens
304 }
305 minTk := tk.Clone()
306 minTk.Origin = p.removeLeftSideNewLineChar(minTk.Origin)
307 tokens.Add(minTk)
308 tk = minTk.Next
309 for tk != nil && tk.Position.Line <= maxLine {
310 clonedTk := tk.Clone()
311 tokens.Add(clonedTk)
312 tk = clonedTk.Next
313 }
314 return tokens
315 }
316
317 func (p *Printer) setupErrorTokenFormat(annotateLine int, isColored bool) {
318 prefix := func(annotateLine, num int) string {
319 if annotateLine == num {
320 return fmt.Sprintf("> %2d | ", num)
321 }
322 return fmt.Sprintf(" %2d | ", num)
323 }
324 p.LineNumber = true
325 p.LineNumberFormat = func(num int) string {
326 if isColored {
327 fn := color.New(color.Bold, color.FgHiWhite).SprintFunc()
328 return fn(prefix(annotateLine, num))
329 }
330 return prefix(annotateLine, num)
331 }
332 if isColored {
333 p.setDefaultColorSet()
334 }
335 }
336
337 func (p *Printer) PrintErrorToken(tk *token.Token, isColored bool) string {
338 errToken := tk
339 curLine := tk.Position.Line
340 curExtLine := curLine + p.newLineCount(p.removeLeftSideNewLineChar(tk.Origin))
341 if p.isNewLineLastChar(tk.Origin) {
342 // if last character ( exclude white space ) is new line character, ignore it.
343 curExtLine--
344 }
345
346 minLine := int(math.Max(float64(curLine-3), 1))
347 maxLine := curExtLine + 3
348 p.setupErrorTokenFormat(curLine, isColored)
349
350 beforeTokens := p.printBeforeTokens(tk, minLine, curExtLine)
351 lastTk := beforeTokens[len(beforeTokens)-1]
352 afterTokens := p.printAfterTokens(lastTk.Next, maxLine)
353
354 beforeSource := p.PrintTokens(beforeTokens)
355 prefixSpaceNum := len(fmt.Sprintf(" %2d | ", curLine))
356 annotateLine := strings.Repeat(" ", prefixSpaceNum+errToken.Position.Column-1) + "^"
357 afterSource := p.PrintTokens(afterTokens)
358 return fmt.Sprintf("%s\n%s\n%s", beforeSource, annotateLine, afterSource)
359 }