github.com/elek/golangci-lint@v1.42.2-0.20211208090441-c05b7fcb3a9a/pkg/printers/checkstyle.go (about) 1 package printers 2 3 import ( 4 "context" 5 "encoding/xml" 6 "fmt" 7 8 "github.com/go-xmlfmt/xmlfmt" 9 10 "github.com/elek/golangci-lint/pkg/logutils" 11 "github.com/elek/golangci-lint/pkg/result" 12 ) 13 14 type checkstyleOutput struct { 15 XMLName xml.Name `xml:"checkstyle"` 16 Version string `xml:"version,attr"` 17 Files []*checkstyleFile `xml:"file"` 18 } 19 20 type checkstyleFile struct { 21 Name string `xml:"name,attr"` 22 Errors []*checkstyleError `xml:"error"` 23 } 24 25 type checkstyleError struct { 26 Column int `xml:"column,attr"` 27 Line int `xml:"line,attr"` 28 Message string `xml:"message,attr"` 29 Severity string `xml:"severity,attr"` 30 Source string `xml:"source,attr"` 31 } 32 33 const defaultCheckstyleSeverity = "error" 34 35 type Checkstyle struct{} 36 37 func NewCheckstyle() *Checkstyle { 38 return &Checkstyle{} 39 } 40 41 func (Checkstyle) Print(ctx context.Context, issues []result.Issue) error { 42 out := checkstyleOutput{ 43 Version: "5.0", 44 } 45 46 files := map[string]*checkstyleFile{} 47 48 for i := range issues { 49 issue := &issues[i] 50 file, ok := files[issue.FilePath()] 51 if !ok { 52 file = &checkstyleFile{ 53 Name: issue.FilePath(), 54 } 55 56 files[issue.FilePath()] = file 57 } 58 59 severity := defaultCheckstyleSeverity 60 if issue.Severity != "" { 61 severity = issue.Severity 62 } 63 64 newError := &checkstyleError{ 65 Column: issue.Column(), 66 Line: issue.Line(), 67 Message: issue.Text, 68 Source: issue.FromLinter, 69 Severity: severity, 70 } 71 72 file.Errors = append(file.Errors, newError) 73 } 74 75 out.Files = make([]*checkstyleFile, 0, len(files)) 76 for _, file := range files { 77 out.Files = append(out.Files, file) 78 } 79 80 data, err := xml.Marshal(&out) 81 if err != nil { 82 return err 83 } 84 85 fmt.Fprintf(logutils.StdOut, "%s%s\n", xml.Header, xmlfmt.FormatXML(string(data), "", " ")) 86 return nil 87 }