forked from golangci/golangci-lint
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmeta_formatter.go
74 lines (58 loc) · 1.88 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
package goformatters
import (
"bytes"
"fmt"
"go/format"
"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/lint/linter"
"github.com/golangci/golangci-lint/pkg/logutils"
)
type MetaFormatter struct {
log logutils.Log
formatters []Formatter
}
func NewMetaFormatter(log logutils.Log, cfg *config.Config, enabledLinters map[string]*linter.Config) (*MetaFormatter, error) {
m := &MetaFormatter{log: log}
if _, ok := enabledLinters[gofmt.Name]; ok {
m.formatters = append(m.formatters, gofmt.New(cfg.LintersSettings.Gofmt))
}
if _, ok := enabledLinters[gofumpt.Name]; ok {
m.formatters = append(m.formatters, gofumpt.New(cfg.LintersSettings.Gofumpt, cfg.Run.Go))
}
if _, ok := enabledLinters[goimports.Name]; ok {
m.formatters = append(m.formatters, goimports.New())
}
// gci is a last because the only goal of gci is to handle imports.
if _, ok := enabledLinters[gci.Name]; ok {
formatter, err := gci.New(cfg.LintersSettings.Gci)
if err != nil {
return nil, fmt.Errorf("gci: creating formatter: %w", err)
}
m.formatters = append(m.formatters, formatter)
}
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
}