Documentation
¶
Overview ¶
Package goconst finds repeated strings that could be replaced by a constant.
There are obvious benefits to using constants instead of repeating strings, mostly to ease maintenance. Cannot argue against changing a single constant versus many strings. While this could be considered a beginner mistake, across time, multiple packages and large codebases, some repetition could have slipped in.
Index ¶
- Variables
- func GetByteBuffer() []byte
- func GetStringBuilder() *strings.Builder
- func InternString(s string) string
- func PutByteBuffer(buf []byte)
- func PutExtendedPosBuffer(slice []ExtendedPos)
- func PutStringBuilder(sb *strings.Builder)
- type Config
- type ConstType
- type Constants
- type ExtendedPos
- type Issue
- type Parser
- func (p *Parser) EnableBatchProcessing(batchSize int)
- func (p *Parser) GetStringCount(str string) int
- func (p *Parser) IncrementStringCount(str string) int
- func (p *Parser) ParseTree() (Strings, Constants, error)
- func (p *Parser) ProcessResults()
- func (p *Parser) SetConcurrency(max int)
- func (p *Parser) SetIgnoreFunctions(names []string)
- type Strings
- type Type
Constants ¶
This section is empty.
Variables ¶
var ByteBufferPool = sync.Pool{ New: func() interface{} { slice := make([]byte, 0, 8*1024) return &slice }, }
ByteBufferPool is a pool for temporary byte slices
var ExtendedPosPool = sync.Pool{ New: func() interface{} { slice := make([]ExtendedPos, 0, 8) return &slice }, }
ExtendedPosPool is a pool for slices of ExtendedPos
var FileReaderPool = sync.Pool{ New: func() interface{} { return make([]byte, 32*1024) }, }
FileReaderPool is a pool of byte buffers used for reading files
var StringBuilderPool = sync.Pool{ New: func() interface{} { return new(strings.Builder) }, }
StringBuilderPool is a pool of string builders to reduce memory allocations
var StringInternPool = sync.Map{}
StringInternPool is a pool for deduplicating strings to reduce memory usage
Functions ¶
func GetByteBuffer ¶ added in v1.8.0
func GetByteBuffer() []byte
GetByteBuffer retrieves a byte buffer from the pool
func GetStringBuilder ¶ added in v1.8.0
GetStringBuilder retrieves a string builder from the pool
func InternString ¶ added in v1.8.0
InternString returns a deduplicated reference to the given string to reduce memory usage when the same string appears multiple times
func PutByteBuffer ¶ added in v1.8.0
func PutByteBuffer(buf []byte)
PutByteBuffer returns a byte buffer to the pool
func PutExtendedPosBuffer ¶ added in v1.8.0
func PutExtendedPosBuffer(slice []ExtendedPos)
PutExtendedPosBuffer returns an ExtendedPos slice to the pool
func PutStringBuilder ¶ added in v1.8.0
PutStringBuilder returns a string builder to the pool after resetting it
Types ¶
type Config ¶
type Config struct {
// IgnoreStrings is a list of regular expressions to filter strings
IgnoreStrings []string
// IgnoreTests indicates whether test files should be excluded
IgnoreTests bool
// MatchWithConstants enables matching strings with existing constants
MatchWithConstants bool
// MinStringLength is the minimum length a string must have to be reported
MinStringLength int
// MinOccurrences is the minimum number of occurrences required to report a string
MinOccurrences int
// ParseNumbers enables detection of duplicated numbers
ParseNumbers bool
// NumberMin sets the minimum value for reported number matches
NumberMin int
// NumberMax sets the maximum value for reported number matches
NumberMax int
// ExcludeTypes allows excluding specific types of contexts
ExcludeTypes map[Type]bool
// FindDuplicates enables finding constants whose values match existing constants in other packages.
FindDuplicates bool
// EvalConstExpressions enables evaluation of constant expressions like Prefix + "suffix"
EvalConstExpressions bool
// IgnoreFunctions is a list of function names whose string arguments should be ignored.
// Supports direct calls (e.g., "println") and one-level qualified calls (e.g., "slog.Info").
IgnoreFunctions []string
}
Config contains all configuration options for the goconst analyzer.
type ConstType ¶
type ConstType struct {
// Using embedded Position to save memory vs. a separate field
token.Position
// Interned strings to reduce memory usage
Name string
// contains filtered or unexported fields
}
ConstType holds information about a constant declaration.
type ExtendedPos ¶
type ExtendedPos struct {
// Using embedded Position to save memory vs. a separate field
token.Position
// contains filtered or unexported fields
}
ExtendedPos extends token.Position with package information. This structure is optimized for memory usage in large codebases.
func GetExtendedPosBuffer ¶ added in v1.8.0
func GetExtendedPosBuffer() []ExtendedPos
GetExtendedPosBuffer retrieves an ExtendedPos slice from the pool
type Issue ¶
type Issue struct {
Pos token.Position
OccurrencesCount int
Str string
MatchingConst string
DuplicateConst string
DuplicatePos token.Position
}
Issue represents a finding of duplicated strings, numbers, or constants. Each Issue includes the position where it was found, how many times it occurs, the string itself, and any matching constant name. When both test and non-test files are analyzed, OccurrencesCount reflects the count within the issue's scope (test or non-test) rather than the global total.
type Parser ¶
type Parser struct {
// contains filtered or unexported fields
}
Parser represents the core analysis engine for finding repeated strings and constants. It holds both configuration options and the internal state during analysis.
func New ¶
func New(path, ignore, ignoreStrings string, ignoreTests, matchConstant, numbers, findDuplicates, evalConstExpressions bool, numberMin, numberMax, minLength, minOccurrences int, excludeTypes map[Type]bool) *Parser
New creates a new instance of the parser. This is your entry point if you'd like to use goconst as an API.
Parameters:
- path: the file or directory path to analyze
- ignore: regex pattern to ignore files
- ignoreStrings: regex pattern to ignore strings
- ignoreTests: whether to ignore test files
- matchConstant: whether to match strings with existing constants
- numbers: whether to analyze number literals
- findDuplicates: whether to find consts with duplicate values
- evalConstExpressions: whether to evaluate constant expressions
- numberMin/numberMax: range limits for number analysis
- minLength: minimum string length to consider
- minOccurrences: minimum occurrences to report
- excludeTypes: map of context types to exclude
func NewWithIgnorePatterns ¶ added in v1.8.0
func NewWithIgnorePatterns( path, ignore string, ignoreStrings []string, ignoreTests, matchConstant, numbers, findDuplicates, evalConstExpressions bool, numberMin, numberMax, minLength, minOccurrences int, excludeTypes map[Type]bool) *Parser
NewWithIgnorePatterns creates a new instance of the parser with support for multiple ignore patterns. This is an alternative constructor that takes a slice of ignore string patterns.
func (*Parser) EnableBatchProcessing ¶ added in v1.8.0
EnableBatchProcessing activates batch processing mode for very large codebases. This mode collects files in batches before processing them to reduce memory usage. The batchSize parameter controls how many files to process in each batch.
func (*Parser) GetStringCount ¶ added in v1.8.0
GetStringCount safely gets the count for a string
func (*Parser) IncrementStringCount ¶ added in v1.8.0
IncrementStringCount safely increments the count for a string and returns the new count
func (*Parser) ParseTree ¶
ParseTree will search the given path for occurrences that could be moved into constants. If "..." is appended, the search will be recursive.
It returns maps of strings and constants found during the analysis, and any error encountered. Use ProcessResults to filter the results based on configuration before retrieving them.
func (*Parser) ProcessResults ¶
func (p *Parser) ProcessResults()
ProcessResults post-processes the raw results. It filters the discovered strings based on the parser's configuration: - Removes strings that don't meet the minimum occurrences threshold - Filters out strings matching the ignore pattern - Applies number range filtering if min/max values are set
func (*Parser) SetConcurrency ¶ added in v1.8.0
SetConcurrency allows setting the maximum number of goroutines to use for parallel file processing. Default is the number of CPUs.
func (*Parser) SetIgnoreFunctions ¶ added in v1.10.0
SetIgnoreFunctions configures which function calls should have their string arguments ignored. Supports direct calls (e.g., "println") and one-level qualified calls (e.g., "slog.Info", "fmt.Errorf").
type Strings ¶
type Strings map[string][]ExtendedPos
Strings maps string literals to their positions in the code.
type Type ¶
type Type int
Type represents the context in which a string literal appears.
const ( // Assignment represents a string in an assignment context (e.g., x := "foo") Assignment Type = iota // Binary represents a string in a binary expression (e.g., x == "foo") Binary // Case represents a string in a case clause (e.g., case "foo":) Case // Return represents a string in a return statement (e.g., return "foo") Return // Call represents a string passed as an argument to a function call (e.g., f("foo")) Call // CompositeLit represents a string inside a composite literal // (e.g., []string{"foo"}, map[string]string{"k": "v"}, MyStruct{Field: "foo"}) CompositeLit )