Repository navigation
Expand file tree
/
Copy pathfilter.go
More file actions
267 lines (217 loc) · 7.07 KB
/
Copy pathfilter.go
File metadata and controls
267 lines (217 loc) · 7.07 KB
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
package gogenfilter
import (
"fmt"
"io/fs"
"os"
"sort"
"strings"
)
// FilterConfig is a functional option for configuring a Filter.
type FilterConfig func(*Filter)
// Enabled enables the filter. When enabled, files matching configured generators
// are filtered out. Metrics collection is activated.
func Enabled() FilterConfig {
return func(filter *Filter) { filter.enabled = true }
}
// Disabled creates a filter that does not filter any files.
// This is the default if neither Enabled nor Disabled is passed.
func Disabled() FilterConfig {
return func(f *Filter) { f.enabled = false }
}
// WithFilterOptions specifies which generated code types to filter.
// FilterAll expands to all specific detectors plus FilterGeneric.
// Panics if any option is not a valid FilterOption.
func WithFilterOptions(opts ...FilterOption) FilterConfig {
for _, opt := range opts {
if !opt.IsValid() {
panic("gogenfilter: invalid FilterOption: " + opt.String())
}
}
return func(filter *Filter) {
expanded := optionsMap(opts...)
for opt := range expanded {
filter.options[opt] = struct{}{}
}
}
}
// WithFS sets a custom filesystem for the filter.
// Defaults to os.DirFS(".") if not provided.
func WithFS(fsys fs.FS) FilterConfig {
return func(filter *Filter) {
if fsys != nil {
filter.fsys = fsys
}
}
}
// WithIncludePatterns restricts filtering scope to files matching at least one
// of the given patterns. Files that do NOT match any include pattern are
// immediately filtered (excluded from analysis) with reason ReasonIncludePattern.
//
// This "restrict scope" behavior means include patterns act as a whitelist for
// which files are worth inspecting — all other files are skipped.
// Use this to focus filtering on specific directories (e.g., "**/generated/*.go").
//
// Patterns use the ** glob syntax supported by MatchPattern.
// If no include patterns are set, all files are considered.
func WithIncludePatterns(patterns ...string) FilterConfig {
return func(filter *Filter) {
filter.includePatterns = append(filter.includePatterns, patterns...)
}
}
// WithExcludePatterns adds exclude patterns. Files matching any exclude pattern
// are filtered regardless of generated-code detection.
func WithExcludePatterns(patterns ...string) FilterConfig {
return func(filter *Filter) {
filter.excludePatterns = append(filter.excludePatterns, patterns...)
}
}
// Filter provides smart filtering of auto-generated Go code.
// A Filter is immutable after construction — all configuration is applied via NewFilter.
type Filter struct {
options map[FilterOption]struct{}
enabled bool
includePatterns []string
excludePatterns []string
metrics *Metrics
fsys fs.FS
}
// NewFilter creates a new filter configured with the given functional options.
// By default, the filter is disabled with no filter options.
//
// Examples:
//
// NewFilter(Enabled(), WithFilterOptions(FilterAll))
// NewFilter(Enabled(), WithFilterOptions(FilterSQLC, FilterTempl), WithExcludePatterns("**/db/*.go"))
// NewFilter(Disabled())
func NewFilter(configs ...FilterConfig) *Filter {
filter := &Filter{
options: make(map[FilterOption]struct{}),
enabled: false,
includePatterns: make([]string, 0),
excludePatterns: make([]string, 0),
metrics: nil,
fsys: os.DirFS("."),
}
for _, cfg := range configs {
cfg(filter)
}
if filter.enabled {
filter.metrics = NewMetrics()
}
return filter
}
// IsEnabled returns whether the filter is active.
func (f *Filter) IsEnabled() bool {
return f.enabled
}
// FilterReasons returns the FilterReason values that this filter will detect.
// Each enabled FilterOption maps to its corresponding FilterReason.
func (f *Filter) FilterReasons() []FilterReason {
reasons := make([]FilterReason, 0, len(f.options))
for opt := range f.options {
reasons = append(reasons, opt.Reason())
}
return reasons
}
// ShouldFilter determines if a file should be filtered out (excluded from analysis).
// Returns an error if the file could not be read for content-based detection.
func (f *Filter) ShouldFilter(filePath string) (bool, error) {
if !f.enabled {
f.recordChecked(filePath)
return false, nil
}
if len(f.includePatterns) > 0 {
return f.shouldFilterWithIncludes(filePath)
}
return f.shouldFilterWithExcludes(filePath)
}
// MustShouldFilter is like ShouldFilter but panics on error.
// Use this in property tests and benchmarks where errors are unexpected.
func (f *Filter) MustShouldFilter(filePath string) bool {
filtered, err := f.ShouldFilter(filePath)
if err != nil {
panic("gogenfilter: ShouldFilter error: " + err.Error())
}
return filtered
}
// GetStats returns a snapshot of filter statistics.
func (f *Filter) GetStats() FilterStats {
if f.metrics == nil {
return FilterStats{
MetricsMixin: MetricsMixin{
TotalFilesChecked: 0,
filteredByReason: nil,
},
}
}
return f.metrics.GetStats()
}
func (f *Filter) recordChecked(filePath string) {
if f.metrics != nil {
f.metrics.RecordChecked(filePath)
}
}
func (f *Filter) recordFiltered(filePath string, reason FilterReason) {
if f.metrics != nil {
f.metrics.RecordFiltered(filePath, reason)
}
}
func (f *Filter) matchesAnyPattern(filePath string, patterns []string) bool {
return anyMatch(filePath, patterns, MatchPattern)
}
func (f *Filter) shouldFilterWithIncludes(filePath string) (bool, error) {
return f.shouldFilterByPattern(filePath, !f.matchesAnyPattern(filePath, f.includePatterns), ReasonIncludePattern)
}
func (f *Filter) shouldFilterWithExcludes(filePath string) (bool, error) {
return f.shouldFilterByPattern(filePath, f.matchesAnyPattern(filePath, f.excludePatterns), ReasonExcludePattern)
}
func (f *Filter) shouldFilterByPattern(filePath string, patternMatched bool, reason FilterReason) (bool, error) {
if patternMatched {
f.recordFiltered(filePath, reason)
return true, nil
}
filtered, err := f.shouldFilterByDetection(filePath)
if err != nil {
return false, err
}
if filtered {
return true, nil
}
f.recordChecked(filePath)
return false, nil
}
func (f *Filter) shouldFilterByDetection(filePath string) (bool, error) {
reason, err := detectReasonFS(f.fsys, filePath, f.options)
if err != nil {
return false, err
}
if reason != ReasonNotFiltered {
f.recordFiltered(filePath, reason)
return true, nil
}
return false, nil
}
func (f *Filter) appendPatternPart(parts []string, label string, patterns []string) []string {
if len(patterns) > 0 {
return append(parts, fmt.Sprintf("%s=%v", label, patterns))
}
return parts
}
func (f *Filter) String() string {
if !f.enabled {
return "Filter(disabled)"
}
opts := make([]string, 0, len(f.options))
for opt := range f.options {
opts = append(opts, string(opt))
}
sort.Strings(opts)
parts := []string{fmt.Sprintf("options=[%s]", strings.Join(opts, ","))}
parts = f.appendPatternPart(parts, "includes", f.includePatterns)
parts = f.appendPatternPart(parts, "excludes", f.excludePatterns)
if f.metrics != nil {
stats := f.metrics.GetStats()
parts = append(parts, "stats="+stats.String())
}
return fmt.Sprintf("Filter(%s)", strings.Join(parts, ", "))
}