gogenfilter

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 30, 2026 License: MIT Imports: 12 Imported by: 0

README

gogenfilter

A Go library for detecting and filtering auto-generated code files. Designed for linters, static analysis tools, and code quality tools that need to skip generated output.

Supported Generators

Tool Detection
sqlc Filename patterns + content markers
templ _templ.go suffix + content
go-enum _enum.go suffix + content
protobuf .pb.go / _grpc.pb.go suffix + content
oapi-codegen Content marker oapi-codegen
deepcopy-gen zz_generated.* prefix + content
wire wire_gen.go suffix + content
moq _moq.go suffix + content
mockgen _mock.go / mock_ prefix + content
stringer Content marker
Generic fallback Any // Code generated by comment per go.dev/s/generatedcode

Features

  • Two-phase detection: Filename-based first (zero I/O), then content-based (reads file)
  • Functional options API: Clean, composable configuration
  • Custom patterns: Include/exclude patterns with ** glob support
  • Thread-safe metrics: Track what was filtered and why
  • SQLC config discovery: Parse sqlc.yaml/sqlc.yml to find output directories
  • fs.FS abstraction: Pluggable filesystem for testing

Install

go get github.com/LarsArtmann/gogenfilter

Quick Start

package main

import (
    "fmt"
    "github.com/LarsArtmann/gogenfilter"
)

func main() {
    f := gogenfilter.NewFilter(
        gogenfilter.Enabled(),
        gogenfilter.WithFilterOptions(gogenfilter.FilterAll),
    )

    filtered, err := f.ShouldFilter("db/models.go")
    if err != nil {
        panic(err)
    }

    if filtered {
        fmt.Println("skipping generated file")
    }

    stats := f.GetStats()
    fmt.Printf("Checked: %d, Filtered: %d\n",
        stats.TotalFilesChecked, stats.TotalFiltered())
}

Configuration

NewFilter accepts functional options:

// Filter all known generated code
gogenfilter.NewFilter(
    gogenfilter.Enabled(),
    gogenfilter.WithFilterOptions(gogenfilter.FilterAll),
)

// Filter specific generators only
gogenfilter.NewFilter(
    gogenfilter.Enabled(),
    gogenfilter.WithFilterOptions(gogenfilter.FilterSQLC, gogenfilter.FilterTempl),
)

// With include/exclude patterns
gogenfilter.NewFilter(
    gogenfilter.Enabled(),
    gogenfilter.WithFilterOptions(gogenfilter.FilterAll),
    gogenfilter.WithIncludePatterns("pkg/**", "internal/*.go"),
    gogenfilter.WithExcludePatterns("**/*.pb.go", "mocks/*"),
)

// With custom filesystem (for testing)
gogenfilter.NewFilter(
    gogenfilter.Enabled(),
    gogenfilter.WithFilterOptions(gogenfilter.FilterAll),
    gogenfilter.WithFS(myFS),
)

// Disabled filter (passes everything through)
gogenfilter.NewFilter(gogenfilter.Disabled())

Filter Options

Option Detection
FilterSQLC Filename patterns + "Code generated by sqlc" content
FilterTempl _templ.go suffix + templ.Component content
FilterGoEnum _enum.go suffix + "Code generated by go-enum" content
FilterProtobuf .pb.go / _grpc.pb.go suffix + content comment
FilterOapi "oapi-codegen" content marker
FilterDeepcopy zz_generated.* prefix + "Code generated by deepcopy-gen" content
FilterWire wire_gen.go suffix + "Code generated by Wire" content
FilterMoq _moq.go suffix + "Code generated by moq" content
FilterMockgen _mock.go / mock_ prefix + "Code generated by MockGen" content
FilterStringer "Code generated by \"stringer\"" content
FilterGeneric Any // Code generated by comment (fallback)
FilterAll Enables all of the above

Pattern Matching

Include and exclude patterns support two wildcards:

Pattern Meaning
* Matches any sequence of non-separator characters (within a single path segment)
** Matches zero or more complete path segments (crosses / boundaries)
Rules
  • Include patterns restrict the scope: only files matching at least one include pattern are checked for generated code. All other files are immediately filtered (skipped). If no include patterns are set, all files are considered.
  • Exclude patterns broaden the scope: files matching any exclude pattern are always filtered, regardless of generated-code detection.
  • Patterns without / match against the filename only: *.pb.go matches any/path/user.pb.go
  • Patterns with / match against the full path: internal/*.go matches internal/handler.go
  • **/ at the start matches at any depth: \*_/mocks/_.gomatchespkg/mocks/service.go
  • /** at the end matches anything under a directory: generated/\*\*matchesgenerated/a/b/c.go
  • /**/ in the middle bridges any number of segments: src/\*\*/test.gomatchessrc/pkg/test.go
Examples
gogenfilter.NewFilter(
    gogenfilter.Enabled(),
    gogenfilter.WithIncludePatterns("pkg/**"),         // everything under pkg/
    gogenfilter.WithExcludePatterns("**/*.pb.go"),      // any .pb.go at any depth
)

Detection Functions

Use low-level detection directly without the Filter struct:

// Check by filename + content (both phases)
gogenfilter.IsSQLCGenerated("db/models.go", content)
gogenfilter.IsTemplGenerated("page_templ.go", content)
gogenfilter.IsGoEnumGenerated("status_enum.go", content)
gogenfilter.IsProtobufGenerated("user.pb.go", content)
gogenfilter.IsOapiGenerated("petstore.gen.go", content)
gogenfilter.IsDeepcopyGenerated("zz_generated.deepcopy.go", content)
gogenfilter.IsWireGenerated("wire_gen.go", content)
gogenfilter.IsMoqGenerated("service_moq.go", content)
gogenfilter.IsMockgenGenerated("service_mock.go", content)
gogenfilter.IsStringerGenerated("status_string.go", content)
gogenfilter.IsGenericGenerated("any_file.go", content)

// Check by filename only (zero I/O)
gogenfilter.MatchesSQLCFilename("db/query.sql.go") // true

// Check content patterns
gogenfilter.HasSQLCContent(content)
gogenfilter.HasSQLCCodePatterns(content)

// Combined detection with variadic options
reason := gogenfilter.DetectReason("file.go", content,
    gogenfilter.FilterSQLC,
    gogenfilter.FilterTempl,
    gogenfilter.FilterGeneric,
)

SQLC Config Discovery

configs, err := gogenfilter.FindSQLCConfigs([]string{"./..."})
dirs, err := gogenfilter.GetSQLOutputDirs([]string{"."})

Metrics

f := gogenfilter.NewFilter(
    gogenfilter.Enabled(),
    gogenfilter.WithFilterOptions(gogenfilter.FilterAll),
)

filtered, _ := f.ShouldFilter("db/models.go")
filtered, _ = f.ShouldFilter("page_templ.go")
filtered, _ = f.ShouldFilter("main.go")

stats := f.GetStats()
// stats.TotalFilesChecked == 3
// stats.FilteredBy(gogenfilter.ReasonSQLC) == 1
// stats.FilteredBy(gogenfilter.ReasonTempl) == 1
// stats.TotalFiltered() == 2

License

MIT

Documentation

Overview

Package gogenfilter detects and filters auto-generated Go code files.

It identifies files generated by common tools including sqlc, templ, go-enum, protobuf, oapi-codegen, deepcopy-gen, wire, moq, mockgen, stringer, and any tool using the standard "Code generated by" comment convention per https://go.dev/s/generatedcode.

Detection is two-phase: filename-based first (zero I/O), then content-based (reads file). This optimization avoids unnecessary file reads.

Quick Start

Create a filter with functional options:

f := gogenfilter.NewFilter(
    gogenfilter.Enabled(),
    gogenfilter.WithFilterOptions(gogenfilter.FilterAll),
)

Check files — ShouldFilter returns (bool, error) to propagate I/O errors:

filtered, err := f.ShouldFilter("db/models.go")
if err != nil {
    log.Fatal(err)
}
if filtered {
    fmt.Println("skipping generated file")
}

For low-level detection without a Filter:

reason := gogenfilter.DetectReason("file.go", content,
    gogenfilter.FilterSQLC,
    gogenfilter.FilterGeneric,
)

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrProjectRootNotFound    = &ProjectRootError{Code: CodeProjectRootNotFound}
	ErrProjectRootInvalidPath = &ProjectRootError{Code: CodeProjectRootInvalidPath}
	ErrSQLCConfigRead         = &SQLCConfigError{Code: CodeSQLCConfigRead}
	ErrSQLCConfigParse        = &SQLCConfigError{Code: CodeSQLCConfigParse}
	ErrSQLCConfigWalk         = &SQLCConfigError{Code: CodeSQLCConfigWalk}
	ErrSQLCConfigCollect      = &SQLCConfigError{Code: CodeSQLCConfigCollect}
	ErrSQLCConfigFind         = &SQLCConfigError{Code: CodeSQLCConfigFind}
)

Sentinel errors for use with errors.Is. These have zero-value domain fields; matching is by ErrorCode only.

Functions

func CodeEqual

func CodeEqual[T interface{ ErrorCode() ErrorCode }](e, target T) bool

CodeEqual compares two error codes for equality.

func CodeHelp

func CodeHelp(code ErrorCode) string

CodeHelp returns the user-friendly help text for the given error code.

func HasSQLCCodePatterns

func HasSQLCCodePatterns(content string) bool

HasSQLCCodePatterns checks for sqlc-specific code patterns in content.

func HasSQLCContent

func HasSQLCContent(content string) bool

HasSQLCContent checks if content contains sqlc.dev specific markers.

func IsDeepcopyGenerated

func IsDeepcopyGenerated(_, content string) bool

IsDeepcopyGenerated checks if a file was generated by deepcopy-gen (Kubernetes).

func IsGenericGenerated

func IsGenericGenerated(_, content string) bool

IsGenericGenerated checks if a file was generated by go generate.

func IsGoEnumGenerated

func IsGoEnumGenerated(filePath, content string) bool

IsGoEnumGenerated checks if a file is generated by go-enum.

func IsMockgenGenerated

func IsMockgenGenerated(_, content string) bool

IsMockgenGenerated checks if a file was generated by mockgen.

func IsMoqGenerated

func IsMoqGenerated(_, content string) bool

IsMoqGenerated checks if a file was generated by matryer/moq.

func IsOapiGenerated

func IsOapiGenerated(_, content string) bool

IsOapiGenerated checks if a file was generated by oapi-codegen.

func IsProtobufGenerated

func IsProtobufGenerated(filePath, content string) bool

IsProtobufGenerated checks if a file is generated by protoc-gen-go.

func IsSQLCGenerated

func IsSQLCGenerated(filePath, content string) bool

IsSQLCGenerated checks if a file is generated by sqlc.dev.

func IsStringerGenerated

func IsStringerGenerated(_, content string) bool

IsStringerGenerated checks if a file was generated by the stringer tool.

func IsTemplGenerated

func IsTemplGenerated(filePath, content string) bool

IsTemplGenerated checks if a file is generated by templ.guide.

func IsWireGenerated

func IsWireGenerated(_, content string) bool

IsWireGenerated checks if a file was generated by google/wire.

func MatchPattern

func MatchPattern(path, pattern string) bool

MatchPattern checks if a path matches a pattern. Supports * (matches non-separator characters) and ** (matches any path segments). Patterns without path separators match against the filename only.

Example
package main

import (
	"fmt"

	"github.com/LarsArtmann/gogenfilter"
)

func main() {
	fmt.Println(gogenfilter.MatchPattern("db/models.go", "**/*.go"))
	fmt.Println(gogenfilter.MatchPattern("db/models.go", "**/db/*.go"))
	fmt.Println(gogenfilter.MatchPattern("main.go", "**/db/*.go"))
}
Output:
true
true
false

func MatchesSQLCFilename

func MatchesSQLCFilename(filePath string) bool

MatchesSQLCFilename checks if filename matches sqlc.dev naming patterns.

Types

type ConfigPath

type ConfigPath string

ConfigPath represents a path to a configuration file. It distinguishes config file paths from other path types.

func (ConfigPath) String

func (p ConfigPath) String() string

type ErrorCode

type ErrorCode string

ErrorCode identifies a specific error condition in the gogenfilter library. Codes use snake_case naming and can be used for programmatic error handling.

const (
	CodeProjectRootNotFound    ErrorCode = "project_root_not_found"    // project root not found from start path
	CodeProjectRootInvalidPath ErrorCode = "project_root_invalid_path" // start path could not be resolved
	CodeSQLCConfigRead         ErrorCode = "sqlc_config_read"          // sqlc config file could not be read
	CodeSQLCConfigParse        ErrorCode = "sqlc_config_parse"         // sqlc config file has invalid YAML
	CodeSQLCConfigWalk         ErrorCode = "sqlc_config_walk"          // directory walk for sqlc configs failed
	CodeSQLCConfigCollect      ErrorCode = "sqlc_config_collect"       // collecting output dirs from sqlc configs failed
	CodeSQLCConfigFind         ErrorCode = "sqlc_config_find"          // finding sqlc config files failed
)

Error codes identify specific error conditions for programmatic handling.

func AllErrorCodes

func AllErrorCodes() []ErrorCode

AllErrorCodes returns all defined error codes. Derived from errorCodeDefs — adding a new def automatically updates this list.

func (ErrorCode) String

func (c ErrorCode) String() string

type ErrorCoder

type ErrorCoder interface {
	ErrorCode() ErrorCode
}

ErrorCoder is implemented by all gogenfilter errors for programmatic code access.

type ErrorMessage

type ErrorMessage string

ErrorMessage represents error message content. It distinguishes error messages from other string values.

func (ErrorMessage) String

func (m ErrorMessage) String() string

type Filter

type Filter struct {
	// contains filtered or unexported fields
}

Filter provides smart filtering of auto-generated Go code. A Filter is immutable after construction — all configuration is applied via NewFilter.

func NewFilter

func NewFilter(configs ...FilterConfig) *Filter

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())
Example
package main

import (
	"fmt"

	"github.com/LarsArtmann/gogenfilter"
)

func main() {
	filter := gogenfilter.NewFilter(
		gogenfilter.Enabled(),
		gogenfilter.WithFilterOptions(
			gogenfilter.FilterSQLC,
			gogenfilter.FilterTempl,
			gogenfilter.FilterGeneric,
		),
	)

	fmt.Println(filter.IsEnabled())
}
Output:
true
Example (WithExcludePatterns)
package main

import (
	"fmt"

	"github.com/LarsArtmann/gogenfilter"
)

func main() {
	filter := gogenfilter.NewFilter(
		gogenfilter.Enabled(),
		gogenfilter.WithFilterOptions(gogenfilter.FilterAll),
		gogenfilter.WithExcludePatterns("**/db/*.go"),
	)

	fmt.Println(filter.IsEnabled())
}
Output:
true

func (*Filter) FilterReasons

func (f *Filter) FilterReasons() []FilterReason

FilterReasons returns the FilterReason values that this filter will detect. Each enabled FilterOption maps to its corresponding FilterReason.

func (*Filter) GetStats

func (f *Filter) GetStats() FilterStats

GetStats returns a snapshot of filter statistics.

Example
package main

import (
	"fmt"
	"testing/fstest"

	"github.com/LarsArtmann/gogenfilter"
)

// mapFSWithFiles creates a MapFS with multiple files for testing.
func mapFSWithFiles(files map[string]string) fstest.MapFS {
	mapFS := make(fstest.MapFS, len(files))
	for path, content := range files {
		mapFS[path] = &fstest.MapFile{
			Data: []byte(content),
		}
	}

	return mapFS
}

// newTestFilter creates a Filter with enabled state, filter options, and filesystem.
func newTestFilter(opts gogenfilter.FilterOption, mapFS fstest.MapFS) *gogenfilter.Filter {
	return gogenfilter.NewFilter(
		gogenfilter.Enabled(),
		gogenfilter.WithFilterOptions(opts),
		gogenfilter.WithFS(mapFS),
	)
}

func main() {
	mapFS := mapFSWithFiles(map[string]string{
		"db/models.go": "// Code generated by sqlc. DO NOT EDIT.\npackage db\n",
		"main.go":      "package main\n",
	})
	filter := newTestFilter(gogenfilter.FilterSQLC, mapFS)

	_, _ = filter.ShouldFilter("db/models.go")
	_, _ = filter.ShouldFilter("main.go")

	stats := filter.GetStats()
	fmt.Println(stats.TotalFilesChecked)
	fmt.Println(stats.FilteredBy(gogenfilter.ReasonSQLC))
	fmt.Println(stats.TotalFiltered())
}
Output:
2
1
1

func (*Filter) IsEnabled

func (f *Filter) IsEnabled() bool

IsEnabled returns whether the filter is active.

func (*Filter) MustShouldFilter

func (f *Filter) MustShouldFilter(filePath string) bool

MustShouldFilter is like ShouldFilter but panics on error. Use this in property tests and benchmarks where errors are unexpected.

Example
package main

import (
	"fmt"
	"testing/fstest"

	"github.com/LarsArtmann/gogenfilter"
)

// mapFSWithFile creates a MapFS with a single file for testing.
func mapFSWithFile(path, content string) fstest.MapFS {
	return fstest.MapFS{
		path: &fstest.MapFile{
			Data: []byte(content),
		},
	}
}

// newTestFilter creates a Filter with enabled state, filter options, and filesystem.
func newTestFilter(opts gogenfilter.FilterOption, mapFS fstest.MapFS) *gogenfilter.Filter {
	return gogenfilter.NewFilter(
		gogenfilter.Enabled(),
		gogenfilter.WithFilterOptions(opts),
		gogenfilter.WithFS(mapFS),
	)
}

func main() {
	mapFS := mapFSWithFile("db/models.go", "// Code generated by sqlc. DO NOT EDIT.\npackage db\n")
	filter := newTestFilter(gogenfilter.FilterSQLC, mapFS)

	fmt.Println(filter.MustShouldFilter("db/models.go"))
}
Output:
true

func (*Filter) ShouldFilter

func (f *Filter) ShouldFilter(filePath string) (bool, error)

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.

Example
package main

import (
	"fmt"
	"testing/fstest"

	"github.com/LarsArtmann/gogenfilter"
)

// mapFSWithFile creates a MapFS with a single file for testing.
func mapFSWithFile(path, content string) fstest.MapFS {
	return fstest.MapFS{
		path: &fstest.MapFile{
			Data: []byte(content),
		},
	}
}

// newTestFilter creates a Filter with enabled state, filter options, and filesystem.
func newTestFilter(opts gogenfilter.FilterOption, mapFS fstest.MapFS) *gogenfilter.Filter {
	return gogenfilter.NewFilter(
		gogenfilter.Enabled(),
		gogenfilter.WithFilterOptions(opts),
		gogenfilter.WithFS(mapFS),
	)
}

func main() {
	filter := newTestFilter(gogenfilter.FilterSQLC,
		mapFSWithFile("db/models.go", "// Code generated by sqlc. DO NOT EDIT.\npackage db\n"))
	filtered, _ := filter.ShouldFilter("db/models.go")
	fmt.Println(filtered)
}
Output:
true
Example (NotFiltered)
package main

import (
	"fmt"
	"testing/fstest"

	"github.com/LarsArtmann/gogenfilter"
)

// mapFSWithFile creates a MapFS with a single file for testing.
func mapFSWithFile(path, content string) fstest.MapFS {
	return fstest.MapFS{
		path: &fstest.MapFile{
			Data: []byte(content),
		},
	}
}

// newTestFilter creates a Filter with enabled state, filter options, and filesystem.
func newTestFilter(opts gogenfilter.FilterOption, mapFS fstest.MapFS) *gogenfilter.Filter {
	return gogenfilter.NewFilter(
		gogenfilter.Enabled(),
		gogenfilter.WithFilterOptions(opts),
		gogenfilter.WithFS(mapFS),
	)
}

func main() {
	filter := newTestFilter(gogenfilter.FilterSQLC,
		mapFSWithFile("main.go", "package main\n"))
	fmt.Println(filter.MustShouldFilter("main.go"))
}
Output:
false

func (*Filter) String

func (f *Filter) String() string

type FilterConfig

type FilterConfig func(*Filter)

FilterConfig is a functional option for configuring a Filter.

func Disabled

func Disabled() FilterConfig

Disabled creates a filter that does not filter any files. This is the default if neither Enabled nor Disabled is passed.

func Enabled

func Enabled() FilterConfig

Enabled enables the filter. When enabled, files matching configured generators are filtered out. Metrics collection is activated.

func WithExcludePatterns

func WithExcludePatterns(patterns ...string) FilterConfig

WithExcludePatterns adds exclude patterns. Files matching any exclude pattern are filtered regardless of generated-code detection.

func WithFS

func WithFS(fsys fs.FS) FilterConfig

WithFS sets a custom filesystem for the filter. Defaults to os.DirFS(".") if not provided.

Example
package main

import (
	"fmt"
	"testing/fstest"

	"github.com/LarsArtmann/gogenfilter"
)

// mapFSWithFile creates a MapFS with a single file for testing.
func mapFSWithFile(path, content string) fstest.MapFS {
	return fstest.MapFS{
		path: &fstest.MapFile{
			Data: []byte(content),
		},
	}
}

// newTestFilter creates a Filter with enabled state, filter options, and filesystem.
func newTestFilter(opts gogenfilter.FilterOption, mapFS fstest.MapFS) *gogenfilter.Filter {
	return gogenfilter.NewFilter(
		gogenfilter.Enabled(),
		gogenfilter.WithFilterOptions(opts),
		gogenfilter.WithFS(mapFS),
	)
}

func main() {
	mapFS := mapFSWithFile(
		"generated.go",
		"// Code generated by stringer. DO NOT EDIT.\npackage foo\n",
	)
	filter := newTestFilter(gogenfilter.FilterGeneric, mapFS)

	filtered, _ := filter.ShouldFilter("generated.go")
	fmt.Println(filtered)
}
Output:
true

func WithFilterOptions

func WithFilterOptions(opts ...FilterOption) FilterConfig

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 WithIncludePatterns

func WithIncludePatterns(patterns ...string) FilterConfig

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.

Example
package main

import (
	"fmt"
	"testing/fstest"

	"github.com/LarsArtmann/gogenfilter"
)

// mapFSWithFiles creates a MapFS with multiple files for testing.
func mapFSWithFiles(files map[string]string) fstest.MapFS {
	mapFS := make(fstest.MapFS, len(files))
	for path, content := range files {
		mapFS[path] = &fstest.MapFile{
			Data: []byte(content),
		}
	}

	return mapFS
}

// newTestFilterWithInclude creates a Filter with include patterns.
func newTestFilterWithInclude(
	opts gogenfilter.FilterOption,
	include string,
	mapFS fstest.MapFS,
) *gogenfilter.Filter {
	return gogenfilter.NewFilter(
		gogenfilter.Enabled(),
		gogenfilter.WithFilterOptions(opts),
		gogenfilter.WithIncludePatterns(include),
		gogenfilter.WithFS(mapFS),
	)
}

func main() {
	mapFS := mapFSWithFiles(map[string]string{
		"db/models.go":  "// Code generated by sqlc. DO NOT EDIT.\npackage db\n",
		"other/file.go": "// Code generated by sqlc. DO NOT EDIT.\npackage other\n",
	})

	filter := newTestFilterWithInclude(gogenfilter.FilterSQLC, "db/**", mapFS)

	dbFiltered, _ := filter.ShouldFilter("db/models.go")
	otherFiltered, _ := filter.ShouldFilter("other/file.go")
	fmt.Println(dbFiltered, otherFiltered)
}
Output:
true true

type FilterOption

type FilterOption string

FilterOption represents a type of generated code to filter.

const (
	// FilterSQLC filters sqlc.dev generated files.
	FilterSQLC FilterOption = "sqlc"

	// FilterTempl filters templ.guide generated files.
	FilterTempl FilterOption = "templ"

	// FilterGoEnum filters go-enum generated files.
	FilterGoEnum FilterOption = "go-enum"

	// FilterProtobuf filters protoc-gen-go generated files (.pb.go, _grpc.pb.go).
	FilterProtobuf FilterOption = "protobuf"

	// FilterOapi filters oapi-codegen generated files (*.gen.go with oapi-codegen markers).
	FilterOapi FilterOption = "oapi-codegen"

	// FilterDeepcopy filters deepcopy-gen generated files (Kubernetes ecosystem).
	FilterDeepcopy FilterOption = "deepcopy-gen"

	// FilterWire filters google/wire generated dependency injection files.
	FilterWire FilterOption = "wire"

	// FilterMoq filters matryer/moq generated mock files.
	FilterMoq FilterOption = "moq"

	// FilterMockgen filters mockgen generated files.
	FilterMockgen FilterOption = "mockgen"

	// FilterStringer filters stringer generated files.
	FilterStringer FilterOption = "stringer"

	// FilterGeneric filters any file with the standard "Code generated by" comment.
	// This catches all Go generators that follow the convention from https://go.dev/s/generatedcode.
	// It acts as a fallback after specific detectors have been checked.
	FilterGeneric FilterOption = "generic"

	// FilterAll filters all auto-generated code.
	FilterAll FilterOption = "all"
)

func AllFilterOptions

func AllFilterOptions() []FilterOption

AllFilterOptions returns all valid FilterOption values. Derived from the detectors table plus FilterAll, so adding a new detector automatically updates this list.

Example
package main

import (
	"fmt"

	"github.com/LarsArtmann/gogenfilter"
)

func main() {
	opts := gogenfilter.AllFilterOptions()

	fmt.Println(len(opts))
}
Output:
12

func (FilterOption) IsValid

func (o FilterOption) IsValid() bool

IsValid reports whether the FilterOption is a recognized value.

Example
package main

import (
	"fmt"

	"github.com/LarsArtmann/gogenfilter"
)

func main() {
	fmt.Println(gogenfilter.FilterSQLC.IsValid())
	fmt.Println(gogenfilter.FilterOption("unknown").IsValid())
}
Output:
true
false

func (FilterOption) Reason

func (o FilterOption) Reason() FilterReason

Reason returns the FilterReason corresponding to this FilterOption. This relies on the invariant that each FilterOption constant and its matching FilterReason constant share the same underlying string value (e.g., FilterSQLC == "sqlc" == ReasonSQLC). The detectors table enforces this pairing via explicit (option, reason) fields. When adding a new detector, both a FilterOption and FilterReason const with identical values must be defined.

func (FilterOption) String

func (o FilterOption) String() string

type FilterReason

type FilterReason string

FilterReason represents the reason a file was filtered.

const (
	ReasonSQLC           FilterReason = "sqlc"
	ReasonTempl          FilterReason = "templ"
	ReasonGoEnum         FilterReason = "go-enum"
	ReasonProtobuf       FilterReason = "protobuf"
	ReasonOapi           FilterReason = "oapi-codegen"
	ReasonDeepcopy       FilterReason = "deepcopy-gen"
	ReasonWire           FilterReason = "wire"
	ReasonMoq            FilterReason = "moq"
	ReasonMockgen        FilterReason = "mockgen"
	ReasonStringer       FilterReason = "stringer"
	ReasonGeneric        FilterReason = "generic"
	ReasonIncludePattern FilterReason = "include-pattern"
	ReasonExcludePattern FilterReason = "exclude-pattern"
	ReasonNotFiltered    FilterReason = "not-filtered"
)

FilterReason values for each supported generator and special filter outcomes.

func AllFilterReasons

func AllFilterReasons() []FilterReason

AllFilterReasons returns all valid FilterReason values. Derived from the detectors table plus special reasons (include/exclude/not-filtered), so adding a new detector automatically updates this list.

Example
package main

import (
	"fmt"

	"github.com/LarsArtmann/gogenfilter"
)

func main() {
	reasons := gogenfilter.AllFilterReasons()

	fmt.Println(len(reasons))
}
Output:
14

func DetectReason

func DetectReason(filePath, content string, opts ...FilterOption) FilterReason

DetectReason checks if a file is auto-generated based on filename and content. No I/O is performed — the caller provides the file content. Returns the reason for filtering, or ReasonNotFiltered if the file is not generated.

Example
package main

import (
	"fmt"

	"github.com/LarsArtmann/gogenfilter"
)

func main() {
	sqlcContent := `// Code generated by sqlc. DO NOT EDIT.
// versions:
package db
`
	reason := gogenfilter.DetectReason(
		"db/models.go",
		sqlcContent,
		gogenfilter.FilterSQLC,
	)

	fmt.Println(reason)
}
Output:
sqlc
Example (NotFiltered)
package main

import (
	"fmt"

	"github.com/LarsArtmann/gogenfilter"
)

func main() {
	reason := gogenfilter.DetectReason(
		"main.go",
		"package main\n",
		gogenfilter.FilterSQLC,
	)

	fmt.Println(reason)
}
Output:
not-filtered

func DetectReasonReader

func DetectReasonReader(filePath string, r io.Reader, opts ...FilterOption) (FilterReason, error)

DetectReasonReader checks if a file is auto-generated by reading content from an io.Reader. Useful when the caller already has the file content in a stream (e.g., from an HTTP handler or a processing pipeline) and wants to avoid reading it into a string first. Returns the reason for filtering, or ReasonNotFiltered if the file is not generated.

Example
package main

import (
	"bytes"
	"fmt"

	"github.com/LarsArtmann/gogenfilter"
)

func main() {
	content := "// Code generated by sqlc. DO NOT EDIT.\npackage db\n"
	r := bytes.NewBufferString(content)

	reason, _ := gogenfilter.DetectReasonReader(
		"db/models.go",
		r,
		gogenfilter.FilterSQLC,
	)
	fmt.Println(reason)
}
Output:
sqlc

func (FilterReason) IsValid

func (r FilterReason) IsValid() bool

IsValid reports whether the FilterReason is a recognized value.

Example
package main

import (
	"fmt"

	"github.com/LarsArtmann/gogenfilter"
)

func main() {
	fmt.Println(gogenfilter.ReasonSQLC.IsValid())
	fmt.Println(gogenfilter.FilterReason("unknown").IsValid())
}
Output:
true
false

func (FilterReason) String

func (r FilterReason) String() string

type FilterStats

type FilterStats struct {
	MetricsMixin
}

FilterStats represents a snapshot of filter statistics.

func (FilterStats) FilteredBy

func (fs FilterStats) FilteredBy(reason FilterReason) int

FilteredBy returns the count of files filtered for a specific reason. Returns 0 if no files were filtered for that reason.

func (FilterStats) String

func (fs FilterStats) String() string

func (FilterStats) TotalFiltered

func (fs FilterStats) TotalFiltered() int

TotalFiltered returns the total number of filtered files across all reasons.

type Helper

type Helper interface {
	Help() string
}

Helper is implemented by errors that provide user-friendly guidance.

type Metrics

type Metrics struct {
	MetricsMixin
	// contains filtered or unexported fields
}

Metrics tracks filter statistics for analysis and debugging.

func NewMetrics

func NewMetrics() *Metrics

NewMetrics creates a new filter metrics tracker.

func (*Metrics) GetStats

func (m *Metrics) GetStats() FilterStats

GetStats returns the current filter statistics.

func (*Metrics) RecordChecked

func (m *Metrics) RecordChecked(filePath string)

RecordChecked records that a file was checked but not filtered.

func (*Metrics) RecordFiltered

func (m *Metrics) RecordFiltered(filePath string, reason FilterReason)

RecordFiltered records that a file was filtered for a given reason.

type MetricsMixin

type MetricsMixin struct {
	TotalFilesChecked TotalFilesChecked
	// contains filtered or unexported fields
}

MetricsMixin provides common fields for filter metrics. It is embedded in FilterStats to provide read-only access to metrics data.

The filteredByReason field is intentionally unexported to enforce encapsulation: callers must use the FilteredBy() and TotalFiltered() methods rather than reading or mutating the map directly. This prevents external code from breaking the invariant that counts are non-negative and consistent with the total.

type Operation

type Operation string

Operation represents an operation name (e.g., "read", "parse", "walk"). It provides type safety for operation identifiers.

func (Operation) String

func (o Operation) String() string

type ProjectRootError

type ProjectRootError struct {
	Code      ErrorCode
	StartPath StartPath
	Markers   []string
	Cause     error
}

ProjectRootError is returned when the project root cannot be found.

func FindProjectRoot

func FindProjectRoot(startPath StartPath, markers []string) (string, *ProjectRootError)

FindProjectRoot searches parent directories for project marker files. Returns empty string if no marker is found after searching up to maxProjectRootDepth levels.

func (*ProjectRootError) Error

func (e *ProjectRootError) Error() string

func (*ProjectRootError) ErrorCode

func (e *ProjectRootError) ErrorCode() ErrorCode

ErrorCode returns the error code for programmatic matching.

func (*ProjectRootError) Help

func (e *ProjectRootError) Help() string

Help returns user-friendly guidance for resolving the error.

func (*ProjectRootError) Is

func (e *ProjectRootError) Is(target error) bool

Is supports errors.Is by comparing error codes with sentinel errors.

func (*ProjectRootError) Unwrap

func (e *ProjectRootError) Unwrap() error

type SQLCConfigError

type SQLCConfigError struct {
	Code       ErrorCode
	ConfigPath ConfigPath
	Operation  Operation
	Message    ErrorMessage
	Cause      error
}

SQLCConfigError is returned when a sqlc configuration file cannot be processed.

func FindSQLCConfigs

func FindSQLCConfigs(paths []string) (map[string]string, *SQLCConfigError)

FindSQLCConfigs searches for sqlc.yaml or sqlc.yml files in the given paths. Searches both the provided paths and their parent directories (up to 3 levels up). Returns a map of config file path to project root directory.

func FindSQLCConfigsFS

func FindSQLCConfigsFS(fsys fs.FS, paths []string) (map[string]string, *SQLCConfigError)

FindSQLCConfigsFS searches for sqlc.yaml or sqlc.yml files using the provided filesystem. Paths must be valid within fsys (relative to the FS root). Unlike FindSQLCConfigs, this does not search parent directories.

func GetSQLOutputDirs

func GetSQLOutputDirs(paths []string) ([]string, *SQLCConfigError)

GetSQLOutputDirs returns a list of output directories from sqlc configuration files.

func GetSQLOutputDirsFS

func GetSQLOutputDirsFS(fsys fs.FS, paths []string) ([]string, *SQLCConfigError)

GetSQLOutputDirsFS returns output directories from sqlc configs using the provided filesystem. Paths must be valid within fsys (relative to the FS root).

func (*SQLCConfigError) Error

func (e *SQLCConfigError) Error() string

func (*SQLCConfigError) ErrorCode

func (e *SQLCConfigError) ErrorCode() ErrorCode

ErrorCode returns the error code for programmatic matching.

func (*SQLCConfigError) Help

func (e *SQLCConfigError) Help() string

Help returns user-friendly guidance for resolving the error.

func (*SQLCConfigError) Is

func (e *SQLCConfigError) Is(target error) bool

Is supports errors.Is by comparing error codes with sentinel errors.

func (*SQLCConfigError) Unwrap

func (e *SQLCConfigError) Unwrap() error

type StartPath

type StartPath string

StartPath represents a directory path used as a starting point for traversal. It ensures path values are not confused with other string types.

func (StartPath) String

func (p StartPath) String() string

type TotalFilesChecked

type TotalFilesChecked int

TotalFilesChecked represents a count of files that have been checked. It provides type safety for metrics counting.

func (TotalFilesChecked) String

func (c TotalFilesChecked) String() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL