lint.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package lint
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "strings"
  7. )
  8. var linterMap map[string]Linter
  9. // ErrLintNotExists .
  10. var ErrLintNotExists = errors.New("linter not exists")
  11. func init() {
  12. linterMap = make(map[string]Linter)
  13. }
  14. // RegisterLinter register linter for a kind of file
  15. func RegisterLinter(filetype string, linter Linter) {
  16. if _, ok := linterMap[filetype]; ok {
  17. panic("linter for filetype " + filetype + " already exists")
  18. }
  19. linterMap[filetype] = linter
  20. }
  21. // LineErr error contains line number
  22. type LineErr struct {
  23. Line int `json:"line"`
  24. Message string `json:"message"`
  25. }
  26. // Error lint error
  27. type Error []LineErr
  28. func (errs Error) Error() string {
  29. messages := make([]string, 0, len(errs))
  30. for _, err := range errs {
  31. messages = append(messages, fmt.Sprintf("%d:%s", err.Line, err.Message))
  32. }
  33. return strings.Join(messages, "\n")
  34. }
  35. func (errs Error) String() string {
  36. return errs.Error()
  37. }
  38. // Linter lint config file
  39. type Linter interface {
  40. Lint(r io.Reader) Error
  41. }
  42. // Lint config file,
  43. func Lint(filetype string, r io.Reader) error {
  44. lint, ok := linterMap[filetype]
  45. if !ok {
  46. return ErrLintNotExists
  47. }
  48. if lintErr := lint.Lint(r); lintErr != nil {
  49. return lintErr
  50. }
  51. return nil
  52. }