config

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Jul 24, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package config re-exports domain enum types for backward compatibility. The canonical definitions live in domain/ — these aliases ensure existing code using config.SortCriteria continues to work without import changes.

Index

Constants

View Source
const (
	// DetectionMethodHash uses hash-based comparison.
	DetectionMethodHash = domain.MethodHash

	// DetectionMethodArtDupl uses suffix tree detection.
	DetectionMethodArtDupl = domain.MethodArtDupl
)

Constant aliases for backward compatibility with existing config code.

View Source
const (
	DetectionModeSemantic   = domain.DetectionModeSemantic
	DetectionModeExact      = domain.DetectionModeExact
	DetectionModeStructural = domain.DetectionModeStructural
)
View Source
const (
	DiffModeDisabled   = domain.DiffModeDisabled
	DiffModeSideBySide = domain.DiffModeSideBySide
	DiffModeInline     = domain.DiffModeInline
)
View Source
const (
	OutputFormatText       = domain.OutputFormatText
	OutputFormatHTML       = domain.OutputFormatHTML
	OutputFormatJSON       = domain.OutputFormatJSON
	OutputFormatCSV        = domain.OutputFormatCSV
	OutputFormatPlumbing   = domain.OutputFormatPlumbing
	OutputFormatSimpleJSON = domain.OutputFormatSimpleJSON
	OutputFormatSARIF      = domain.OutputFormatSARIF
)
View Source
const (
	SortBySize        = domain.SortBySize
	SortByOccurrence  = domain.SortByOccurrence
	SortByHash        = domain.SortByHash
	SortByTotalTokens = domain.SortByTotalTokens
)
View Source
const DefaultThreshold = 5

DefaultThreshold is the default minimum number of duplicated statements to report. With statement-level tokenization, each Go statement produces one composite token. A threshold of 5 filters trivial patterns (single-call noise, error-check boilerplate) while still catching meaningful duplication. Users who want more sensitivity can lower to 3; users who want less noise can raise to 10+.

Variables

View Source
var (
	AllDiffModes       = domain.AllDiffModes
	DefaultDiffMode    = domain.DefaultDiffMode
	ErrInvalidDiffMode = domain.ErrInvalidDiffMode
)
View Source
var (
	// ErrInvalidDetectionMethod re-exported from domain for cross-package
	// errors.Is() compatibility.
	ErrInvalidDetectionMethod = domain.ErrInvalidDetectionMethod
	ErrInvalidType            = errors.New("invalid type")

	// ErrInvalidThreshold and ErrThresholdTooLarge are re-exported from domain
	// so that errors.Is() works across config, SDK, and domain boundaries.
	ErrInvalidThreshold  = domain.ErrInvalidThreshold
	ErrThresholdTooLarge = domain.ErrThresholdTooLarge
)

Static errors for config validation.

View Source
var (
	ErrInvalidOutputFormat = domain.ErrInvalidOutputFormat
	AllOutputFormats       = domain.AllOutputFormats
	DefaultOutputFormat    = domain.DefaultOutputFormat
	ParseOutputFormat      = domain.ParseOutputFormat
)
View Source
var (
	ErrInvalidSortCriteria = domain.ErrInvalidSortCriteria
	AllSortCriteria        = domain.AllSortCriteria
	DefaultSortCriteria    = domain.DefaultSortCriteria
	ParseSortCriteria      = domain.ParseSortCriteria
)
View Source
var ErrInvalidDetectionMode = domain.ErrInvalidDetectionMode

ErrInvalidDetectionMode aliases the domain-level sentinel.

View Source
var ErrInvalidFileType = errors.New("invalid file type")

ErrInvalidFileType is returned when a file type value is invalid.

Functions

func SaveConfig

func SaveConfig(config *Config, filename string) error

SaveConfig saves configuration to file.

func ValidateConfig

func ValidateConfig(cfg *Config) error

ValidateConfig validates the configuration.

func ValidateDetectionMethods

func ValidateDetectionMethods(methods []DetectionMethod) error

ValidateDetectionMethods validates a list of detection methods.

Types

type Config

type Config struct {
	// Threshold sets the minimum token sequence size to consider as duplicate
	Threshold int `json:"threshold,omitempty"`

	// IncludeVendor includes vendor directory in analysis
	IncludeVendor bool `json:"includeVendor,omitempty"`

	// IncludeNodeModules includes node_modules directory in hash-based analysis.
	// By default, node_modules is excluded in hash detection mode to avoid
	// processing large dependency directories. Set to true to include them.
	IncludeNodeModules bool `json:"includeNodeModules,omitempty"`

	// FilesFromStdin reads file paths from stdin when true
	FilesFromStdin bool `json:"filesFromStdin,omitempty"`

	// OutputFormat sets the output format with type safety
	OutputFormat OutputFormat `json:"outputFormat,omitzero"`

	// Verbose enables verbose output
	Verbose bool `json:"verbose,omitempty"`

	// Paths specifies the paths to analyze
	Paths []string `json:"paths,omitempty"`

	// IgnoreFiles specifies file patterns to ignore
	IgnoreFiles []string `json:"ignoreFiles,omitempty"`

	// MaxChildrenSerial sets the maximum children serial for large slices
	MaxChildrenSerial int `json:"maxChildrenSerial,omitempty"`

	// OutputFile specifies the output file (if not stdout)
	OutputFile string `json:"outputFile,omitempty"`

	// SortBy specifies sorting criteria for clone groups
	SortBy SortCriteria `json:"sortBy,omitzero"`

	// DetectionMethods specifies which detection methods to use
	DetectionMethods DetectionMethods `json:"detectionMethods,omitempty"`

	// Profile enables performance profiling output
	Profile bool `json:"profile,omitempty"`

	// Timeout specifies maximum execution time (0 = no timeout)
	Timeout time.Duration `json:"timeout,omitempty,format:nano"`

	// IncludeSQLC includes sqlc.dev generated files in analysis (default: false, filtered)
	IncludeSQLC bool `json:"includeSQLC,omitempty"`

	// IncludeTempl includes templ-generated *_templ.go files in analysis (default: false, filtered).
	// .templ source files are always included regardless of this setting.
	IncludeTempl bool `json:"includeTempl,omitempty"`

	// IncludeProtobuf includes protobuf generated files (.pb.go, _grpc.pb.go)
	IncludeProtobuf bool `json:"includeProtobuf,omitempty"`

	// IncludeMockgen includes mockgen generated files
	IncludeMockgen bool `json:"includeMockgen,omitempty"`

	// IncludeStringer includes stringer generated files
	IncludeStringer bool `json:"includeStringer,omitempty"`

	// IncludeGeneric includes files with standard "Code generated by" comments in analysis (default: false, filtered).
	// This is a catch-all that catches any tool following the Go convention from https://go.dev/s/generatedcode.
	// Includes protoc-gen-connect-go, oapi-codegen, wire, deepcopy-gen, and any other generator.
	IncludeGeneric bool `json:"includeGeneric,omitempty"`

	// Only restricts analysis to a specific file type (FileTypeGo or FileTypeTempl).
	// FileTypeAll (empty string) means analyze all file types.
	Only FileType `json:"only,omitzero"`

	// IncludePatterns specifies file patterns to always include (takes precedence over filter)
	IncludePatterns []string `json:"includePatterns,omitempty"`

	// ExcludePatterns specifies additional file patterns to exclude
	ExcludePatterns []string `json:"excludePatterns,omitempty"`

	// Incremental enables incremental analysis (only analyze changed files)
	Incremental bool `json:"incremental,omitempty"`

	// CacheDir specifies the cache directory for AST caching
	// If empty, uses default .cache/art-dupl
	CacheDir string `json:"cacheDir,omitempty"`

	// ClearCache clears the cache before running (useful for forced full rebuild)
	ClearCache bool `json:"clearCache,omitempty"`

	// MaxCacheEntries limits the number of cached AST files on disk.
	// 0 means unlimited. When exceeded, oldest entries are evicted.
	MaxCacheEntries int `json:"maxCacheEntries,omitempty"`

	// DetectionMode controls how identifier names participate in matching.
	// - "semantic" (default): alpha-normalized identifiers — detects Type 2 renamed clones.
	// - "exact": verbatim name hashing — Type 1 copy-paste only.
	// - "structural": AST shape only, ignores names entirely.
	DetectionMode DetectionMode `json:"detectionMode,omitzero"`

	// Workers specifies the number of concurrent workers for file parsing.
	// 0 or negative means use runtime.GOMAXPROCS(0).
	// 1 means sequential processing (same as Parse()).
	Workers int `json:"workers,omitempty"`

	// DiffMode enables diff visualization for HTML output.
	// When enabled, duplicate occurrences are shown with visual diff highlighting.
	DiffMode DiffMode `json:"diffMode,omitzero"`

	// RichText enables enhanced text output with classification badges,
	// priority indicators, and actionable suggestions.
	RichText bool `json:"richText,omitempty"`

	// SuppressTestLow suppresses test-file clones classified as low priority.
	// Reduces noise from test boilerplate without hiding production issues.
	SuppressTestLow bool `json:"suppressTestLow,omitempty"`

	// TestThreshold sets a separate minimum token count for test files.
	// When 0, defaults to max(30, Threshold) — test files need substantial
	// clones to be reported, filtering out common test boilerplate noise.
	TestThreshold int `json:"testThreshold,omitempty"`

	// IgnoreTests excludes all *_test.go files from analysis entirely.
	// Use --include-tests to override and analyze test files normally.
	IgnoreTests bool `json:"ignoreTests,omitempty"`

	// IncludeTests disables ALL test-specific filtering: treats *_test.go files
	// identically to production files. Overrides IgnoreTests, SuppressTestLow,
	// and TestThreshold defaults.
	IncludeTests bool `json:"includeTests,omitempty"`

	// MinLines suppresses clone groups whose clones span fewer than N source lines.
	// 0 = disabled (no line-count filtering). Useful for filtering trivial
	// one-liner clones that pass the token threshold but are too short to matter.
	MinLines int `json:"minLines,omitempty"`

	// Quiet suppresses non-essential status output (progress messages,
	// profiling notices). Clone results are still printed.
	Quiet bool `json:"quiet,omitempty"`

	// TypeAware enables go/types-based detection: encodes each local variable's
	// static type into the identifier hash so that different-typed variables with
	// the same name produce different hashes. Eliminates false positives like
	// time.Time.String matching *big.Int.String. Requires go/packages type
	// checking (10-100x slower). Only effective with semantic detection mode.
	TypeAware bool `json:"typeAware,omitempty"`
}

Config represents the dupl configuration with strong typing.

Note: Config uses primitive types (int, string, bool) for JSON marshaling compatibility. Typed enums (FileType, DetectionMethod, etc.) provide validation.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a default configuration.

func LoadConfig

func LoadConfig(filename string) (*Config, error)

LoadConfig loads configuration from file.

func LoadOptionalConfig

func LoadOptionalConfig(filename string) (*Config, error)

LoadOptionalConfig loads configuration from file if filename is not empty. Returns nil if filename is empty, allowing optional config file usage.

func MergeConfigs

func MergeConfigs(fileConfig, cliConfig *Config) *Config

MergeConfigs merges two configurations, with command line config taking precedence.

func (*Config) EffectiveSuppressTestLow added in v0.4.0

func (c *Config) EffectiveSuppressTestLow() bool

EffectiveSuppressTestLow returns whether low-priority test clones should be suppressed. When IncludeTests is true, always returns false.

func (*Config) EffectiveTestThreshold added in v0.4.0

func (c *Config) EffectiveTestThreshold() int

EffectiveTestThreshold returns the minimum token count for test-file clones. When IncludeTests is true, returns 0 (no test-specific filtering). When TestThreshold is explicitly set (>0), uses that value. Otherwise defaults to max(30, Threshold) to filter common test boilerplate.

func (*Config) UnmarshalJSON added in v0.4.0

func (c *Config) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom JSON decoding with backward-compatibility for the legacy "semantic" bool field that preceded the DetectionMode enum.

Migration rules (only when "detectionMode" is absent from the JSON):

  • "semantic": false → DetectionModeExact
  • "semantic": true → DetectionModeSemantic (already the default, no-op)

func (*Config) Validate added in v0.4.0

func (c *Config) Validate() error

Validate validates the configuration invariants in one place. It is the single entry point for all Config validation.

type DetectionMethod

type DetectionMethod = domain.DetectionMethod

DetectionMethod is an alias for domain.DetectionMethod to prevent drift across config, SDK, and detection packages.

func AllDetectionMethods

func AllDetectionMethods() []DetectionMethod

AllDetectionMethods returns all supported detection methods.

func DefaultDetectionMethod

func DefaultDetectionMethod() DetectionMethod

DefaultDetectionMethod returns the default detection method.

func ParseDetectionMethods

func ParseDetectionMethods(methodsStr string) ([]DetectionMethod, error)

ParseDetectionMethods parses comma-separated detection methods.

type DetectionMethods

type DetectionMethods []DetectionMethod

DetectionMethods is a slice of DetectionMethod for type safety.

func (DetectionMethods) Contains

func (dm DetectionMethods) Contains(method DetectionMethod) bool

Contains checks if method is in methods list.

func (DetectionMethods) IsDefault

func (dm DetectionMethods) IsDefault() bool

IsDefault checks if methods have default value.

func (DetectionMethods) IsEmpty

func (dm DetectionMethods) IsEmpty() bool

IsEmpty checks if methods list is empty.

func (DetectionMethods) IsHashOnly

func (dm DetectionMethods) IsHashOnly() bool

IsHashOnly checks if only hash detection method is selected. This is useful for optimizing the analysis pipeline - when only hash detection is used, we can skip AST parsing and work directly with file paths.

type DetectionMode added in v0.4.0

type DetectionMode = domain.DetectionMode

DetectionMode is an alias for domain.DetectionMode. It exists so callers that import config continue to write config.DetectionModeSemantic / config.IsValid etc. without an additional import.

type DiffMode

type DiffMode = domain.DiffMode

func ParseDiffMode

func ParseDiffMode(s string) (DiffMode, error)

ParseDiffMode parses a diff mode string with backwards-compatible aliases. "true"→side-by-side, "false"→disabled for legacy --diff flag compatibility.

type FileType

type FileType string

FileType represents a file type filter for analysis.

const (
	// FileTypeGo represents Go source files (.go).
	FileTypeGo FileType = "go"
	// FileTypeTempl represents Templ template files (.templ).
	FileTypeTempl FileType = "templ"
	// FileTypeAll represents all file types (no filtering).
	FileTypeAll FileType = ""
)

func ParseFileType

func ParseFileType(s string) (FileType, error)

ParseFileType parses a string into a FileType, validating the value. Returns FileTypeAll and an error if the value is invalid.

func (FileType) IsValid

func (ft FileType) IsValid() bool

IsValid validates file type.

func (FileType) MarshalJSON

func (ft FileType) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler. Returns null for empty string to allow omitempty to work.

func (FileType) Matches

func (ft FileType) Matches(path string) bool

Matches returns true if the given file path matches this file type filter. Empty string (FileTypeAll) matches all files.

func (FileType) String

func (ft FileType) String() string

String implements fmt.Stringer.

func (*FileType) UnmarshalJSON

func (ft *FileType) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type OutputFormat

type OutputFormat = domain.OutputFormat

type SortCriteria

type SortCriteria = domain.SortCriteria

Jump to

Keyboard shortcuts

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