forked from golangci/golangci-lint
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmeta_formatter.go
90 lines (71 loc) · 2.36 KB
/
meta_formatter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package goformatters
import (
"bytes"
"fmt"
"go/format"
"slices"
"github.com/golangci/golangci-lint/pkg/config"
"github.com/golangci/golangci-lint/pkg/goformatters/gci"
"github.com/golangci/golangci-lint/pkg/goformatters/gofmt"
"github.com/golangci/golangci-lint/pkg/goformatters/gofumpt"
"github.com/golangci/golangci-lint/pkg/goformatters/goimports"
"github.com/golangci/golangci-lint/pkg/goformatters/golines"
"github.com/golangci/golangci-lint/pkg/logutils"
)
type MetaFormatter struct {
log logutils.Log
formatters []Formatter
}
func NewMetaFormatter(log logutils.Log, cfg *config.Formatters, runCfg *config.Run) (*MetaFormatter, error) {
for _, formatter := range cfg.Enable {
if !IsFormatter(formatter) {
return nil, fmt.Errorf("invalid formatter %q", formatter)
}
}
m := &MetaFormatter{log: log}
if slices.Contains(cfg.Enable, gofmt.Name) {
m.formatters = append(m.formatters, gofmt.New(&cfg.Settings.GoFmt))
}
if slices.Contains(cfg.Enable, gofumpt.Name) {
m.formatters = append(m.formatters, gofumpt.New(&cfg.Settings.GoFumpt, runCfg.Go))
}
if slices.Contains(cfg.Enable, goimports.Name) {
m.formatters = append(m.formatters, goimports.New(&cfg.Settings.GoImports))
}
// gci is a last because the only goal of gci is to handle imports.
if slices.Contains(cfg.Enable, gci.Name) {
formatter, err := gci.New(&cfg.Settings.Gci)
if err != nil {
return nil, fmt.Errorf("gci: creating formatter: %w", err)
}
m.formatters = append(m.formatters, formatter)
}
// golines calls `format.Source()` internally so no need to format after it.
if slices.Contains(cfg.Enable, golines.Name) {
m.formatters = append(m.formatters, golines.New(&cfg.Settings.GoLines))
}
return m, nil
}
func (m *MetaFormatter) Format(filename string, src []byte) []byte {
if len(m.formatters) == 0 {
data, err := format.Source(src)
if err != nil {
m.log.Warnf("(fmt) formatting file %s: %v", filename, err)
return src
}
return data
}
data := bytes.Clone(src)
for _, formatter := range m.formatters {
formatted, err := formatter.Format(filename, data)
if err != nil {
m.log.Warnf("(%s) formatting file %s: %v", formatter.Name(), filename, err)
continue
}
data = formatted
}
return data
}
func IsFormatter(name string) bool {
return slices.Contains([]string{gofmt.Name, gofumpt.Name, goimports.Name, gci.Name, golines.Name}, name)
}