github.com/songshiyun/revive@v1.1.5-0.20220323112655-f8433a19b3c5/formatter/checkstyle.go (about) 1 package formatter 2 3 import ( 4 "bytes" 5 "encoding/xml" 6 plainTemplate "text/template" 7 8 "github.com/songshiyun/revive/lint" 9 ) 10 11 // Checkstyle is an implementation of the Formatter interface 12 // which formats the errors to Checkstyle-like format. 13 type Checkstyle struct { 14 Metadata lint.FormatterMetadata 15 } 16 17 // Name returns the name of the formatter 18 func (f *Checkstyle) Name() string { 19 return "checkstyle" 20 } 21 22 type issue struct { 23 Line int 24 Col int 25 What string 26 Confidence float64 27 Severity lint.Severity 28 RuleName string 29 } 30 31 // Format formats the failures gotten from the lint. 32 func (f *Checkstyle) Format(failures <-chan lint.Failure, config lint.Config) (string, error) { 33 issues := map[string][]issue{} 34 for failure := range failures { 35 buf := new(bytes.Buffer) 36 xml.Escape(buf, []byte(failure.Failure)) 37 what := buf.String() 38 iss := issue{ 39 Line: failure.Position.Start.Line, 40 Col: failure.Position.Start.Column, 41 What: what, 42 Confidence: failure.Confidence, 43 Severity: severity(config, failure), 44 RuleName: failure.RuleName, 45 } 46 fn := failure.GetFilename() 47 if issues[fn] == nil { 48 issues[fn] = make([]issue, 0) 49 } 50 issues[fn] = append(issues[fn], iss) 51 } 52 53 t, err := plainTemplate.New("revive").Parse(checkstyleTemplate) 54 if err != nil { 55 return "", err 56 } 57 58 buf := new(bytes.Buffer) 59 60 err = t.Execute(buf, issues) 61 if err != nil { 62 return "", err 63 } 64 65 return buf.String(), nil 66 } 67 68 const checkstyleTemplate = `<?xml version='1.0' encoding='UTF-8'?> 69 <checkstyle version="5.0"> 70 {{- range $k, $v := . }} 71 <file name="{{ $k }}"> 72 {{- range $i, $issue := $v }} 73 <error line="{{ $issue.Line }}" column="{{ $issue.Col }}" message="{{ $issue.What }} (confidence {{ $issue.Confidence}})" severity="{{ $issue.Severity }}" source="revive/{{ $issue.RuleName }}"/> 74 {{- end }} 75 </file> 76 {{- end }} 77 </checkstyle>`