Help us shape the future of Go! Take the 2026 Go Developer Survey

config

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package config handles configuration management for the code review assistant.

Configuration is loaded with the following priority (highest to lowest): 1. CLI flags (passed via command-line arguments) 2. Environment variables 3. Configuration file (YAML format) 4. Default values

Configuration File

The configuration file uses YAML format and supports the following sections:

analysis:
  large_file_threshold: 500
  long_function_threshold: 50
  complexity_threshold: 10
  max_parameters: 5
  enable_coverage: true
  min_coverage_threshold: 50.0

output:
  format: console
  verbose: false

Usage

Load configuration from file:

cfg, err := config.LoadConfig("config.yaml")
if err != nil {
    log.Fatal(err)
}

Apply CLI flag overrides:

overrides := map[string]interface{}{
    "complexity_threshold": 15,
    "verbose": true,
}
cfg.Merge(overrides)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuiltinPresetYAML added in v1.6.0

func BuiltinPresetYAML(name string) ([]byte, error)

BuiltinPresetYAML returns the embedded YAML of a built-in preset.

func IsPresetPath added in v1.6.0

func IsPresetPath(value string) bool

IsPresetPath reports whether value names a preset file rather than a built-in preset: it contains a path separator or has a YAML extension.

Types

type AnalysisConfig

type AnalysisConfig struct {
	ExcludePatterns       []string `mapstructure:"exclude_patterns"`
	LargeFileThreshold    int      `mapstructure:"large_file_threshold"`
	LongFunctionThreshold int      `mapstructure:"long_function_threshold"`
	MinCommentRatio       float64  `mapstructure:"min_comment_ratio"`
	ComplexityThreshold   int      `mapstructure:"complexity_threshold"`

	// Anti-pattern detection
	MaxParameters           int  `mapstructure:"max_parameters"`
	MaxNestingDepth         int  `mapstructure:"max_nesting_depth"`
	MaxReturnStatements     int  `mapstructure:"max_return_statements"`
	DetectMagicNumbers      bool `mapstructure:"detect_magic_numbers"`
	DetectDuplicateErrors   bool `mapstructure:"detect_duplicate_errors"`
	DetectNonNullAssertions bool `mapstructure:"detect_non_null_assertions"` // Kotlin: flag !! usage
	DetectRunBlocking       bool `mapstructure:"detect_run_blocking"`        // Kotlin: flag runBlocking outside main

	// Test coverage
	EnableCoverage       bool    `mapstructure:"enable_coverage"`
	MinCoverageThreshold float64 `mapstructure:"min_coverage_threshold"`
	CoverageTimeout      int     `mapstructure:"coverage_timeout_seconds"`

	// Dependency analysis
	MaxImports              int  `mapstructure:"max_imports"`
	MaxExternalDependencies int  `mapstructure:"max_external_dependencies"`
	DetectCircularDeps      bool `mapstructure:"detect_circular_deps"`

	// Parallel processing
	Workers int `mapstructure:"workers"` // 0=auto (runtime.NumCPU), 1=sequential, N=parallel

	// Diff-based analysis (CLI-only; never read from config files)
	Diff DiffConfig `mapstructure:"-"`
}

AnalysisConfig contains all settings that control code analysis behavior.

This includes:

  • File and function size thresholds
  • Complexity thresholds
  • Anti-pattern detection settings
  • Test coverage configuration
  • Dependency analysis settings

All threshold values can be overridden via CLI flags, environment variables, or configuration files.

type ComparisonConfig added in v0.3.0

type ComparisonConfig struct {
	Enabled         bool    `mapstructure:"enabled"`          // Enable comparison
	AutoCompare     bool    `mapstructure:"auto_compare"`     // Auto-compare with latest
	StableThreshold float64 `mapstructure:"stable_threshold"` // % change for "stable" (default: 5.0)
}

ComparisonConfig contains settings for historical comparison.

Phase 3: Enables comparison with previous analysis runs.

type Config

type Config struct {
	Language   string           `mapstructure:"language"` // Language to analyze: "auto", "go", "python", etc.
	Preset     string           `mapstructure:"preset"`   // Effective preset label ("" when none), set by LoadConfigWithPreset
	Analysis   AnalysisConfig   `mapstructure:"analysis"`
	Output     OutputConfig     `mapstructure:"output"`
	Storage    StorageConfig    `mapstructure:"storage"`    // Phase 3: Persistent storage
	Comparison ComparisonConfig `mapstructure:"comparison"` // Phase 3: Historical comparison
}

Config represents the complete application configuration.

Configuration can be loaded from multiple sources with the following priority (highest to lowest):

  1. CLI flags (set via Merge())
  2. Environment variables (prefixed with CRA_)
  3. Configuration file (YAML format)
  4. Default values (from Default())

This layered approach allows flexible configuration for different environments while maintaining sensible defaults.

func Default

func Default() *Config

Default returns a Config with sensible default values for all settings.

These defaults are based on industry best practices and common code quality standards:

  • Large file threshold: 500 lines
  • Long function threshold: 50 lines
  • Cyclomatic complexity threshold: 10
  • Minimum comment ratio: 15%
  • Test coverage threshold: 50%

All anti-pattern detectors are enabled by default. Files matching common patterns (vendor/, testdata/, *_test.go, *.pb.go) are excluded from analysis.

func LoadConfig

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

LoadConfig loads configuration from multiple sources and merges them.

Configuration is loaded in the following order (later sources override earlier):

  1. Default values (from Default())
  2. Configuration file (YAML format)
  3. Environment variables (prefixed with CRA_)

Configuration File Search: If configPath is provided, only that file is loaded. Otherwise, the loader searches for "config.yaml" in:

  • Current directory
  • User's home directory (~/.cra/)

Environment Variables: All settings can be overridden via environment variables with the CRA_ prefix. For example: CRA_ANALYSIS_COMPLEXITY_THRESHOLD=15

Returns the merged configuration or an error if the config file exists but cannot be read. Missing config files are acceptable and will use defaults.

LoadConfig applies only a preset named by "preset:" in the config file or by CRA_PRESET; use LoadConfigWithPreset to pass one explicitly.

func LoadConfigWithPreset added in v1.6.0

func LoadConfigWithPreset(configPath, explicitPreset string) (*Config, error)

LoadConfigWithPreset loads configuration like LoadConfig and applies a preset.

explicitPreset (from --preset), or else the CRA_PRESET environment variable, is an explicit per-run choice and ranks above the config file and env:

defaults < config file < env < preset < CLI flags (applied later via Merge)

Without an explicit preset, a "preset:" key in the config file applies, and that file's own keys override it:

defaults < preset < config file < env < CLI flags

Either way a preset only sets the keys in PresetAnalysis. Relative preset paths resolve against the config file's directory for "preset:", and against the working directory otherwise.

func (*Config) Merge

func (c *Config) Merge(overrides map[string]interface{})

Merge merges CLI flag overrides into the configuration.

This method applies command-line flag overrides with the highest priority, allowing users to override config file and environment settings on a per-invocation basis.

The overrides map should contain flag names as keys and their values. Only non-zero/non-empty values are applied to avoid overwriting valid config with flag defaults.

Example:

overrides := map[string]interface{}{
    "complexity_threshold": 15,
    "verbose": true,
}
config.Merge(overrides)

type DiffConfig added in v1.5.0

type DiffConfig struct {
	Mode         string // "", "staged", "since" or "branch"
	Ref          string // Ref for "since" / "branch"
	WithCoverage bool   // Run coverage in diff mode
	WithDeps     bool   // Run dependency analysis (over the full project) in diff mode
}

DiffConfig holds diff-based analysis settings. They come only from CLI flags (--staged, --since, --branch, --with-coverage, --with-deps).

func (DiffConfig) Enabled added in v1.5.0

func (d DiffConfig) Enabled() bool

Enabled reports whether a diff mode was selected.

type OutputConfig

type OutputConfig struct {
	Format     string `mapstructure:"format"`
	Verbose    bool   `mapstructure:"verbose"`
	OutputFile string `mapstructure:"output_file"` // Phase 3: File output path
	JSONPretty bool   `mapstructure:"json_pretty"` // Phase 3: Pretty-print JSON
	QuietMode  bool   `mapstructure:"quiet"`       // Disable live status reporting
	ShowStatus bool   `mapstructure:"show_status"` // Force enable status reporting

	// ToolVersion is the CLI version, set by cmd (never read from config files).
	ToolVersion string `mapstructure:"-"`
}

OutputConfig contains settings that control report formatting and output.

Format determines the output style: console, markdown, json. Verbose enables detailed per-file and per-package reporting. OutputFile specifies a file path for output (empty means stdout). JSONPretty controls JSON formatting (pretty vs compact). QuietMode disables live status reporting. ShowStatus forces status reporting even when output is piped.

type Preset added in v1.6.0

type Preset struct {
	Name        string         `yaml:"name"`
	Description string         `yaml:"description"`
	Analysis    PresetAnalysis `yaml:"analysis"`

	// Label identifies the preset in reports: the built-in name, or the
	// file path exactly as given.
	Label string `yaml:"-"`
}

Preset is a named set of analysis thresholds and detector switches.

A preset only covers the keys in PresetAnalysis. It never changes whether coverage runs, output, storage, workers or exclude patterns.

func BuiltinPresets added in v1.6.0

func BuiltinPresets() []*Preset

BuiltinPresets returns the built-in presets in display order.

func LoadPreset added in v1.6.0

func LoadPreset(value, baseDir string) (*Preset, error)

LoadPreset loads a built-in preset by name (case-insensitive) or a preset file by path. Relative paths resolve against baseDir (the working directory when baseDir is empty).

func (*Preset) ApplyTo added in v1.6.0

func (p *Preset) ApplyTo(a *AnalysisConfig)

ApplyTo copies the preset's set values onto a, leaving the rest unchanged.

func (*Preset) SetViperDefaults added in v1.6.0

func (p *Preset) SetViperDefaults(v *viper.Viper)

SetViperDefaults registers the preset's set values as viper defaults, so values from a config file still override them.

type PresetAnalysis added in v1.6.0

type PresetAnalysis struct {
	LargeFileThreshold      *int     `yaml:"large_file_threshold"`
	LongFunctionThreshold   *int     `yaml:"long_function_threshold"`
	MinCommentRatio         *float64 `yaml:"min_comment_ratio"`
	ComplexityThreshold     *int     `yaml:"complexity_threshold"`
	MaxParameters           *int     `yaml:"max_parameters"`
	MaxNestingDepth         *int     `yaml:"max_nesting_depth"`
	MaxReturnStatements     *int     `yaml:"max_return_statements"`
	DetectMagicNumbers      *bool    `yaml:"detect_magic_numbers"`
	DetectDuplicateErrors   *bool    `yaml:"detect_duplicate_errors"`
	DetectNonNullAssertions *bool    `yaml:"detect_non_null_assertions"`
	DetectRunBlocking       *bool    `yaml:"detect_run_blocking"`
	MinCoverageThreshold    *float64 `yaml:"min_coverage_threshold"`
	MaxImports              *int     `yaml:"max_imports"`
	MaxExternalDependencies *int     `yaml:"max_external_dependencies"`
	DetectCircularDeps      *bool    `yaml:"detect_circular_deps"`
}

PresetAnalysis holds the analysis settings a preset may set. Nil fields are left unchanged when the preset is applied.

type StorageConfig added in v0.3.0

type StorageConfig struct {
	Enabled     bool   `mapstructure:"enabled"`      // Enable storage
	Backend     string `mapstructure:"backend"`      // "file" or "sqlite"
	Path        string `mapstructure:"path"`         // Custom storage path (empty = default)
	AutoSave    bool   `mapstructure:"auto_save"`    // Automatically save after analysis
	ProjectMode bool   `mapstructure:"project_mode"` // Use ./.cra instead of ~/.cra
}

StorageConfig contains settings for persistent storage of analysis reports.

Phase 3: Enables saving reports for historical tracking and comparison.

Jump to

Keyboard shortcuts

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