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