/
buflint.go
236 lines (216 loc) · 7.98 KB
/
buflint.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
// Copyright 2020 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package buflint contains the linting functionality.
//
// The primary entry point to this package is the Handler.
package buflint
import (
"bytes"
"context"
"io"
"sort"
"strings"
"github.com/bufbuild/buf/internal/buf/bufanalysis"
"github.com/bufbuild/buf/internal/buf/bufcheck"
"github.com/bufbuild/buf/internal/buf/bufcheck/buflint/internal/buflintv1beta1"
"github.com/bufbuild/buf/internal/buf/bufcheck/internal"
"github.com/bufbuild/buf/internal/buf/bufcore/bufimage"
"go.uber.org/zap"
)
// AllFormatStrings are all format strings.
var AllFormatStrings = append(
bufanalysis.AllFormatStrings,
"config-ignore-yaml",
)
// Handler handles the main lint functionality.
type Handler interface {
// Check runs the lint checks.
//
// The image should have source code info for this to work properly.
//
// Images should be filtered with regards to imports before passing to this function.
Check(
ctx context.Context,
config *Config,
image bufimage.Image,
) ([]bufanalysis.FileAnnotation, error)
}
// NewHandler returns a new Handler.
func NewHandler(logger *zap.Logger) Handler {
return newHandler(logger)
}
// Checker is a checker.
type Checker interface {
bufcheck.Checker
internalLint() *internal.Checker
}
// Config is the check config.
type Config struct {
// Checkers are the lint checkers to run.
//
// Checkers will be sorted by first categories, then id when Configs are
// created from this package, i.e. created wth ConfigBuilder.NewConfig.
Checkers []Checker
IgnoreIDToRootPaths map[string]map[string]struct{}
IgnoreRootPaths map[string]struct{}
AllowCommentIgnores bool
}
// GetCheckers returns the checkers.
func (c *Config) GetCheckers() []bufcheck.Checker {
return checkersToBufcheckCheckers(c.Checkers)
}
// NewConfigV1Beta1 returns a new Config.
func NewConfigV1Beta1(externalConfig ExternalConfigV1Beta1) (*Config, error) {
internalConfig, err := internal.ConfigBuilder{
Use: externalConfig.Use,
Except: externalConfig.Except,
IgnoreRootPaths: externalConfig.Ignore,
IgnoreIDOrCategoryToRootPaths: externalConfig.IgnoreOnly,
AllowCommentIgnores: externalConfig.AllowCommentIgnores,
EnumZeroValueSuffix: externalConfig.EnumZeroValueSuffix,
RPCAllowSameRequestResponse: externalConfig.RPCAllowSameRequestResponse,
RPCAllowGoogleProtobufEmptyRequests: externalConfig.RPCAllowGoogleProtobufEmptyRequests,
RPCAllowGoogleProtobufEmptyResponses: externalConfig.RPCAllowGoogleProtobufEmptyResponses,
ServiceSuffix: externalConfig.ServiceSuffix,
}.NewConfig(
buflintv1beta1.VersionSpec,
)
if err != nil {
return nil, err
}
return internalConfigToConfig(internalConfig), nil
}
// GetAllCheckersV1Beta1 gets all known checkers.
//
// Should only be used for printing.
func GetAllCheckersV1Beta1() ([]bufcheck.Checker, error) {
config, err := NewConfigV1Beta1(
ExternalConfigV1Beta1{
Use: buflintv1beta1.VersionSpec.AllCategories,
},
)
if err != nil {
return nil, err
}
return checkersToBufcheckCheckers(config.Checkers), nil
}
// ExternalConfigV1Beta1 is an external config.
type ExternalConfigV1Beta1 struct {
Use []string `json:"use,omitempty" yaml:"use,omitempty"`
Except []string `json:"except,omitempty" yaml:"except,omitempty"`
// IgnoreRootPaths
Ignore []string `json:"ignore,omitempty" yaml:"ignore,omitempty"`
// IgnoreIDOrCategoryToRootPaths
IgnoreOnly map[string][]string `json:"ignore_only,omitempty" yaml:"ignore_only,omitempty"`
EnumZeroValueSuffix string `json:"enum_zero_value_suffix,omitempty" yaml:"enum_zero_value_suffix,omitempty"`
RPCAllowSameRequestResponse bool `json:"rpc_allow_same_request_response,omitempty" yaml:"rpc_allow_same_request_response,omitempty"`
RPCAllowGoogleProtobufEmptyRequests bool `json:"rpc_allow_google_protobuf_empty_requests,omitempty" yaml:"rpc_allow_google_protobuf_empty_requests,omitempty"`
RPCAllowGoogleProtobufEmptyResponses bool `json:"rpc_allow_google_protobuf_empty_responses,omitempty" yaml:"rpc_allow_google_protobuf_empty_responses,omitempty"`
ServiceSuffix string `json:"service_suffix,omitempty" yaml:"service_suffix,omitempty"`
AllowCommentIgnores bool `json:"allow_comment_ignores,omitempty" yaml:"allow_comment_ignores,omitempty"`
}
// PrintFileAnnotations prints the FileAnnotations to the Writer.
//
// Also accepts config-ignore-yaml.
func PrintFileAnnotations(
writer io.Writer,
fileAnnotations []bufanalysis.FileAnnotation,
formatString string,
) error {
switch s := strings.ToLower(strings.TrimSpace(formatString)); s {
case "config-ignore-yaml":
return printFileAnnotationsConfigIgnoreYAML(writer, fileAnnotations)
default:
return bufanalysis.PrintFileAnnotations(writer, fileAnnotations, s)
}
}
func printFileAnnotationsConfigIgnoreYAML(
writer io.Writer,
fileAnnotations []bufanalysis.FileAnnotation,
) error {
if len(fileAnnotations) == 0 {
return nil
}
ignoreIDToRootPathMap := make(map[string]map[string]struct{})
for _, fileAnnotation := range fileAnnotations {
fileInfo := fileAnnotation.FileInfo()
if fileInfo == nil || fileAnnotation.Type() == "" {
continue
}
rootPathMap, ok := ignoreIDToRootPathMap[fileAnnotation.Type()]
if !ok {
rootPathMap = make(map[string]struct{})
ignoreIDToRootPathMap[fileAnnotation.Type()] = rootPathMap
}
rootPathMap[fileInfo.Path()] = struct{}{}
}
if len(ignoreIDToRootPathMap) == 0 {
return nil
}
sortedIgnoreIDs := make([]string, 0, len(ignoreIDToRootPathMap))
ignoreIDToSortedRootPaths := make(map[string][]string, len(ignoreIDToRootPathMap))
for id, rootPathMap := range ignoreIDToRootPathMap {
sortedIgnoreIDs = append(sortedIgnoreIDs, id)
rootPaths := make([]string, 0, len(rootPathMap))
for rootPath := range rootPathMap {
rootPaths = append(rootPaths, rootPath)
}
sort.Strings(rootPaths)
ignoreIDToSortedRootPaths[id] = rootPaths
}
sort.Strings(sortedIgnoreIDs)
buffer := bytes.NewBuffer(nil)
_, _ = buffer.WriteString(`version: v1beta1
lint:
ignore_only:
`)
for _, id := range sortedIgnoreIDs {
_, _ = buffer.WriteString(" ")
_, _ = buffer.WriteString(id)
_, _ = buffer.WriteString(":\n")
for _, rootPath := range ignoreIDToSortedRootPaths[id] {
_, _ = buffer.WriteString(" - ")
_, _ = buffer.WriteString(rootPath)
_, _ = buffer.WriteString("\n")
}
}
_, err := writer.Write(buffer.Bytes())
return err
}
func internalConfigToConfig(internalConfig *internal.Config) *Config {
return &Config{
Checkers: internalCheckersToCheckers(internalConfig.Checkers),
IgnoreIDToRootPaths: internalConfig.IgnoreIDToRootPaths,
IgnoreRootPaths: internalConfig.IgnoreRootPaths,
AllowCommentIgnores: internalConfig.AllowCommentIgnores,
}
}
func configToInternalConfig(config *Config) *internal.Config {
return &internal.Config{
Checkers: checkersToInternalCheckers(config.Checkers),
IgnoreIDToRootPaths: config.IgnoreIDToRootPaths,
IgnoreRootPaths: config.IgnoreRootPaths,
AllowCommentIgnores: config.AllowCommentIgnores,
}
}
func checkersToBufcheckCheckers(checkers []Checker) []bufcheck.Checker {
if checkers == nil {
return nil
}
s := make([]bufcheck.Checker, len(checkers))
for i, e := range checkers {
s[i] = e
}
return s
}