You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

checkstyle.go 1.8KB

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