lint

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 11, 2026 License: AGPL-3.0 Imports: 16 Imported by: 0

Documentation

Overview

Package lint provides integration with external linters for code validation.

The lint package executes established linters (golangci-lint, ruff, eslint) as a validation layer for LLM-generated code. This provides:

  • 500+ rules from community-maintained linters
  • Fast execution (10-200ms depending on linter)
  • Accurate detection of common LLM mistakes (unused vars, unchecked errors)
  • Graceful degradation when linters are not installed

Architecture

The package integrates into the validation pipeline:

Patch → Size Check → Syntax Check → LINTER CHECK → Pattern Scan → Result

Linters run on the full file after applying a patch, catching issues that regex patterns would miss (type errors, import cycles, etc.).

Supported Linters

| Language   | Linter         | Command             |
|------------|----------------|---------------------|
| Go         | golangci-lint  | golangci-lint run   |
| Python     | Ruff           | ruff check          |
| TypeScript | ESLint         | eslint              |
| JavaScript | ESLint         | eslint              |

Severity Mapping

Each linter's output is mapped to a standard severity:

| Linter Severity | Our Severity | Action      |
|-----------------|--------------|-------------|
| error           | Error        | Block patch |
| warning         | Warning      | Allow, warn |
| info/style      | Info         | Log only    |

Usage

runner := lint.NewLintRunner()

// Lint a file
result, err := runner.Lint(ctx, "path/to/file.go")
if err != nil {
    // Linter failed or unavailable
}
if !result.Valid {
    // File has blocking issues
}

// Lint content directly
result, err := runner.LintContent(ctx, []byte("package main..."), "go")

Thread Safety

All exported types are safe for concurrent use.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrLinterNotInstalled indicates the linter binary was not found in PATH.
	ErrLinterNotInstalled = errors.New("linter not installed")

	// ErrLinterTimeout indicates the linter exceeded its configured timeout.
	ErrLinterTimeout = errors.New("linter timeout")

	// ErrLinterFailed indicates the linter process failed to execute.
	ErrLinterFailed = errors.New("linter execution failed")

	// ErrUnsupportedLanguage indicates no linter configuration exists for the language.
	ErrUnsupportedLanguage = errors.New("unsupported language")

	// ErrParseOutput indicates failure to parse the linter's JSON output.
	ErrParseOutput = errors.New("failed to parse linter output")

	// ErrInvalidInput indicates invalid input to a lint function.
	ErrInvalidInput = errors.New("invalid input")
)

Sentinel errors for the lint package.

View Source
var DefaultGoConfig = LinterConfig{
	Language: "go",
	Command:  "golangci-lint",
	Args: []string{
		"run",
		"--out-format=json",
		"--issues-exit-code=0",
		"--timeout=30s",
	},
	Extensions: []string{".go"},
	Timeout:    30 * time.Second,
	FixArgs: []string{
		"run",
		"--fix",
		"--out-format=json",
		"--issues-exit-code=0",
		"--timeout=30s",
	},
}

DefaultGoConfig is the configuration for golangci-lint.

Description:

golangci-lint is the standard Go linter aggregator.
It runs multiple linters in parallel and provides unified JSON output.
View Source
var DefaultGoPolicy = RulePolicy{
	BlockOn: []string{

		"errcheck",

		"typecheck",

		"staticcheck",
		"SA",

		"gosec",
		"G",

		"nilness",
		"nilerr",

		"datarace",
	},
	WarnOn: []string{

		"ineffassign",
		"unused",
		"deadcode",
		"govet",
		"shadow",

		"prealloc",
		"copylock",

		"unconvert",
		"unparam",
	},
	Ignore: []string{

		"lll",
		"gofmt",
		"goimports",
		"whitespace",
		"wsl",

		"gocyclo",
		"gocognit",
		"funlen",

		"revive/var-naming",
		"stylecheck/ST1003",
	},
}

DefaultGoPolicy is the default policy for Go linting.

Description:

Blocks on correctness and security issues that indicate bugs.
Warns on code quality issues that don't affect correctness.
Ignores pure style issues that are subjective.
View Source
var DefaultJSConfig = LinterConfig{
	Language: "javascript",
	Command:  "eslint",
	Args: []string{
		"--format=json",
		"--no-error-on-unmatched-pattern",
	},
	Extensions: []string{".js", ".jsx", ".mjs", ".cjs"},
	Timeout:    30 * time.Second,
	FixArgs: []string{
		"--fix",
		"--format=json",
		"--no-error-on-unmatched-pattern",
	},
}

DefaultJSConfig is an alias for TypeScript config (same linter).

View Source
var DefaultPythonConfig = LinterConfig{
	Language: "python",
	Command:  "ruff",
	Args: []string{
		"check",
		"--output-format=json",
		"--exit-zero",
	},
	Extensions:    []string{".py", ".pyi"},
	Timeout:       10 * time.Second,
	SupportsStdin: true,
	FixArgs: []string{
		"check",
		"--fix",
		"--output-format=json",
		"--exit-zero",
	},
}

DefaultPythonConfig is the configuration for Ruff.

Description:

Ruff is an extremely fast Python linter written in Rust.
It provides pyflakes, pycodestyle, and more in one tool.
View Source
var DefaultPythonPolicy = RulePolicy{
	BlockOn: []string{

		"F",

		"S",

		"PGH",
	},
	WarnOn: []string{

		"E",

		"W",

		"C90",

		"I",
	},
	Ignore: []string{

		"E501",

		"W291",
		"W293",

		"E302",
		"E303",

		"D",
	},
}

DefaultPythonPolicy is the default policy for Python linting (Ruff).

Description:

Ruff uses rule codes like E501, F401, etc.
E = pycodestyle errors
W = pycodestyle warnings
F = Pyflakes (unused imports, undefined names)
C = complexity
S = security (bandit)
View Source
var DefaultTSConfig = LinterConfig{
	Language: "typescript",
	Command:  "eslint",
	Args: []string{
		"--format=json",
		"--no-error-on-unmatched-pattern",
	},
	Extensions: []string{".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"},
	Timeout:    30 * time.Second,
	FixArgs: []string{
		"--fix",
		"--format=json",
		"--no-error-on-unmatched-pattern",
	},
}

DefaultTSConfig is the configuration for ESLint (TypeScript/JavaScript).

Description:

ESLint is the standard linter for JavaScript and TypeScript.
Note: ESLint requires a project config (.eslintrc) to work properly.
View Source
var DefaultTSPolicy = RulePolicy{
	BlockOn: []string{

		"@typescript-eslint/no-unsafe",
		"@typescript-eslint/no-explicit-any",

		"no-undef",
		"no-unused-vars",

		"no-eval",
		"no-implied-eval",
	},
	WarnOn: []string{

		"eqeqeq",
		"no-console",
		"prefer-const",

		"complexity",
	},
	Ignore: []string{

		"indent",
		"semi",
		"quotes",
		"comma-dangle",

		"max-len",
	},
}

DefaultTSPolicy is the default policy for TypeScript/JavaScript linting.

Description:

ESLint uses severity levels (0=off, 1=warn, 2=error).
We map ESLint severity directly, with overrides for specific rules.

Functions

func ExtensionForLanguage

func ExtensionForLanguage(language string) string

ExtensionForLanguage returns the primary file extension for a language.

Description:

Returns the most common file extension for the language.
Used when creating temp files for content linting.

Inputs:

language - The language identifier

Outputs:

string - File extension with dot (e.g., ".go") or empty string

func LanguageFromPath

func LanguageFromPath(filePath string) string

LanguageFromPath detects the language from a file path.

Description:

Determines the programming language based on file extension.
Returns empty string for unknown extensions.

Inputs:

filePath - Path to the file (can be relative or absolute)

Outputs:

string - Language identifier (e.g., "go", "python") or empty string

func RegisterParser

func RegisterParser(language string, parser ParserFunc)

RegisterParser adds or replaces a parser for a language.

Description:

Allows custom parsers to be registered for additional linters
or to override default behavior.

Inputs:

language - The language identifier
parser - The parser function

Types

type ConfigRegistry

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

ConfigRegistry manages linter configurations for different languages.

Thread Safety: Safe for concurrent use after initialization.

func NewConfigRegistry

func NewConfigRegistry() *ConfigRegistry

NewConfigRegistry creates a new registry with default configurations.

func (*ConfigRegistry) Get

func (r *ConfigRegistry) Get(language string) *LinterConfig

Get returns the configuration for a language.

Description:

Returns a clone of the configuration for thread safety.
Returns nil if no configuration exists for the language.

Inputs:

language - The language identifier (e.g., "go", "python")

Outputs:

*LinterConfig - The configuration, or nil if not found

Thread Safety: Safe for concurrent use.

func (*ConfigRegistry) GetByExtension

func (r *ConfigRegistry) GetByExtension(ext string) *LinterConfig

GetByExtension returns the configuration for a file extension.

Description:

Looks up the language from the extension and returns the config.
Returns nil if no linter handles the extension.

Inputs:

ext - File extension including dot (e.g., ".go", ".py")

Outputs:

*LinterConfig - The configuration, or nil if not found

Thread Safety: Safe for concurrent use.

func (*ConfigRegistry) Languages

func (r *ConfigRegistry) Languages() []string

Languages returns all registered language names.

Thread Safety: Safe for concurrent use.

func (*ConfigRegistry) Register

func (r *ConfigRegistry) Register(config *LinterConfig)

Register adds or updates a linter configuration.

Description:

Registers a linter configuration for a language.
Also updates the extension map for language detection.

Inputs:

config - The linter configuration to register

Thread Safety: Safe for concurrent use.

func (*ConfigRegistry) SetAvailable

func (r *ConfigRegistry) SetAvailable(language string, available bool)

SetAvailable marks a linter as available or unavailable.

Description:

Updates the Available flag for a linter configuration.
Called by the runner after detecting installed linters.

Inputs:

language - The language identifier
available - Whether the linter is available

Thread Safety: Safe for concurrent use.

type FeedbackIssue

type FeedbackIssue struct {
	Rule    string `json:"rule"`
	Message string `json:"message"`
	Line    int    `json:"line"`
	Fix     string `json:"fix,omitempty"`
}

FeedbackIssue is a single issue in the feedback.

type LintFeedback

type LintFeedback struct {
	// Rejected is true if the patch should be rejected.
	Rejected bool `json:"rejected"`

	// Reason is a human-readable summary of why.
	Reason string `json:"reason"`

	// Issues are the individual problems found.
	Issues []FeedbackIssue `json:"issues"`

	// AutoFixable is the count of issues that can be auto-fixed.
	AutoFixable int `json:"auto_fixable"`

	// Action is suggested action for the agent.
	Action string `json:"action"`
}

LintFeedback is agent-friendly feedback about lint issues.

Description:

Provides structured feedback that an LLM agent can use to
understand what went wrong and how to fix it.

func FormatFeedback

func FormatFeedback(result *LintResult) *LintFeedback

FormatFeedback creates agent-friendly feedback from a lint result.

Description:

Converts a LintResult into structured feedback suitable for
an LLM agent to understand and act upon.

Inputs:

result - The lint result to format

Outputs:

*LintFeedback - Structured feedback for the agent

func (*LintFeedback) String

func (f *LintFeedback) String() string

String returns a human-readable string representation of the feedback.

Description:

Formats the feedback as a multi-line string suitable for
logging or displaying to users. Uses strings.Builder for
efficient string construction.

Thread Safety: Safe for concurrent use.

type LintIssue

type LintIssue struct {
	// File is the path to the file containing the issue.
	File string `json:"file"`

	// Line is the 1-indexed line number where the issue occurs.
	Line int `json:"line"`

	// Column is the 1-indexed column number where the issue occurs.
	// May be 0 if the linter doesn't provide column info.
	Column int `json:"column,omitempty"`

	// EndLine is the ending line for multi-line issues.
	// May be 0 if the linter doesn't provide end position.
	EndLine int `json:"end_line,omitempty"`

	// EndColumn is the ending column for the issue.
	EndColumn int `json:"end_column,omitempty"`

	// Rule is the linter rule that triggered (e.g., "errcheck", "E501").
	Rule string `json:"rule"`

	// RuleURL is a link to documentation for the rule.
	RuleURL string `json:"rule_url,omitempty"`

	// Severity is the severity level of the issue.
	Severity Severity `json:"severity"`

	// Message is the human-readable description of the issue.
	Message string `json:"message"`

	// Suggestion is a suggested fix if available.
	Suggestion string `json:"suggestion,omitempty"`

	// CanAutoFix indicates whether this issue can be automatically fixed.
	CanAutoFix bool `json:"can_auto_fix"`

	// Replacement is the suggested replacement text for auto-fix.
	Replacement string `json:"replacement,omitempty"`

	// Linter is the name of the linter that found this issue.
	Linter string `json:"linter,omitempty"`
}

LintIssue represents a single issue found by a linter.

Thread Safety: Immutable after creation.

func ApplyPolicy

func ApplyPolicy(issues []LintIssue, policy *RulePolicy) (errors, warnings, infos []LintIssue)

ApplyPolicy applies a policy to lint issues, setting appropriate severities.

Description:

Takes raw lint issues from a linter and categorizes them based
on the policy into errors, warnings, and infos.

Inputs:

issues - Raw issues from the linter
policy - The policy to apply

Outputs:

errors - Issues that should block
warnings - Issues that should warn
infos - Issues that are informational

func (*LintIssue) Location

func (i *LintIssue) Location() string

Location returns a formatted location string (file:line:col).

type LintOptions

type LintOptions struct {
	// Timeout overrides the default timeout for this operation.
	Timeout time.Duration

	// Rules limits linting to specific rules. Empty means all rules.
	Rules []string

	// ExcludeRules excludes specific rules from linting.
	ExcludeRules []string

	// IncludeFixes includes fix suggestions when available.
	IncludeFixes bool
}

LintOptions configures a single lint operation.

func DefaultLintOptions

func DefaultLintOptions() LintOptions

DefaultLintOptions returns the default options.

type LintResult

type LintResult struct {
	// Valid is true if no blocking errors were found.
	Valid bool `json:"valid"`

	// Errors are issues with SeverityError that block the patch.
	Errors []LintIssue `json:"errors"`

	// Warnings are issues with SeverityWarning that don't block.
	Warnings []LintIssue `json:"warnings"`

	// Infos are informational issues (style, hints).
	Infos []LintIssue `json:"infos,omitempty"`

	// Duration is how long the linter took to run.
	Duration time.Duration `json:"duration"`

	// Linter is which linter produced this result.
	Linter string `json:"linter"`

	// Language is the language that was linted.
	Language string `json:"language"`

	// FilePath is the file that was linted (may be temp file for content lint).
	FilePath string `json:"file_path,omitempty"`

	// LinterAvailable indicates whether the linter was found.
	// When false, the result may be empty due to unavailable linter.
	LinterAvailable bool `json:"linter_available"`
}

LintResult contains the result of running a linter.

Thread Safety: Immutable after creation by the runner.

func (*LintResult) AllIssues

func (r *LintResult) AllIssues() []LintIssue

AllIssues returns all issues combined.

func (*LintResult) AutoFixableCount

func (r *LintResult) AutoFixableCount() int

AutoFixableCount returns the count of issues that can be auto-fixed.

func (*LintResult) HasErrors

func (r *LintResult) HasErrors() bool

HasErrors returns true if there are any blocking errors.

func (*LintResult) HasIssues

func (r *LintResult) HasIssues() bool

HasIssues returns true if there are any issues of any severity.

func (*LintResult) HasWarnings

func (r *LintResult) HasWarnings() bool

HasWarnings returns true if there are any warnings.

func (*LintResult) IssueCount

func (r *LintResult) IssueCount() int

IssueCount returns the total number of issues.

type LintRunner

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

LintRunner executes linters and processes their output.

Description:

Manages linter execution, output parsing, and policy application.
Detects available linters at startup and provides graceful fallback
when linters are not installed.

Thread Safety: Safe for concurrent use.

func NewLintRunner

func NewLintRunner(opts ...Option) *LintRunner

NewLintRunner creates a new lint runner.

Description:

Creates a runner with default or custom configurations.
Call DetectAvailableLinters to check which linters are installed.

Inputs:

opts - Optional configuration options

Outputs:

*LintRunner - The configured runner

func (*LintRunner) AutoFix

func (r *LintRunner) AutoFix(ctx context.Context, filePath string) (*LintResult, error)

AutoFix runs the linter in fix mode on a file.

Description:

Executes the linter with --fix flag to automatically fix issues.
The file is modified in place. Returns the list of remaining issues
that could not be fixed.

Inputs:

ctx - Context for cancellation and timeout
filePath - Path to the file to fix

Outputs:

*LintResult - Result after fixes applied (remaining issues)
error - Non-nil if the linter failed

Example:

result, err := runner.AutoFix(ctx, "path/to/file.go")
if err != nil {
    return err
}
if result.HasErrors() {
    // Some issues couldn't be fixed automatically
}

Thread Safety: Safe for concurrent use on different files. NOT safe to run on the same file concurrently.

func (*LintRunner) AutoFixContent

func (r *LintRunner) AutoFixContent(ctx context.Context, content []byte, language string) ([]byte, *LintResult, error)

AutoFixContent fixes content and returns both the fixed content and edit list.

Description:

Writes content to a temp file, runs the linter with --fix,
then reads back the fixed content. Also returns a lint result
with any remaining issues.

Inputs:

ctx - Context for cancellation and timeout
content - The source code to fix
language - The language identifier

Outputs:

[]byte - The fixed content
*LintResult - Remaining issues after fixes
error - Non-nil if the linter failed

Thread Safety: Safe for concurrent use.

func (*LintRunner) AutoFixWithLanguage

func (r *LintRunner) AutoFixWithLanguage(ctx context.Context, filePath, language string) (*LintResult, error)

AutoFixWithLanguage runs the linter in fix mode for a specific language.

Description:

Like AutoFix, but with explicit language specification.

Inputs:

ctx - Context for cancellation and timeout
filePath - Path to the file to fix
language - The language identifier

Outputs:

*LintResult - Result after fixes applied (remaining issues)
error - Non-nil if the linter failed

Thread Safety: Safe for concurrent use on different files.

func (*LintRunner) Configs

func (r *LintRunner) Configs() *ConfigRegistry

Configs returns the config registry for customization.

func (*LintRunner) DetectAvailableLinters

func (r *LintRunner) DetectAvailableLinters() map[string]bool

DetectAvailableLinters checks which linters are installed.

Description:

Probes the system PATH for each configured linter binary.
Updates the Available flag in configurations and returns
a map of language to availability.

Outputs:

map[string]bool - Map of language to whether linter is available

Thread Safety: Safe for concurrent use.

func (*LintRunner) IsAvailable

func (r *LintRunner) IsAvailable(language string) bool

IsAvailable returns whether a linter is available for a language.

Description:

Checks if the linter for the given language has been detected
as available. Returns false if language is unknown or linter
is not installed.

Inputs:

language - The language identifier

Outputs:

bool - True if linter is available

Thread Safety: Safe for concurrent use.

func (*LintRunner) Lint

func (r *LintRunner) Lint(ctx context.Context, filePath string) (*LintResult, error)

Lint runs the linter on a file.

Description:

Detects the language from the file path, runs the appropriate
linter, parses output, and applies policy to categorize issues.

Inputs:

ctx - Context for cancellation and timeout
filePath - Path to the file to lint (absolute or relative to workingDir)

Outputs:

*LintResult - The lint result with categorized issues
error - Non-nil if the linter failed to execute

Errors:

ErrUnsupportedLanguage - No linter for the file type
ErrLinterNotInstalled - Linter not found in PATH
ErrLinterTimeout - Linter exceeded timeout
ErrLinterFailed - Linter process failed

Thread Safety: Safe for concurrent use.

func (*LintRunner) LintContent

func (r *LintRunner) LintContent(ctx context.Context, content []byte, language string) (*LintResult, error)

LintContent runs the linter on content directly.

Description:

Writes content to a temp file, runs the linter, then cleans up.
File paths in results are remapped to indicate temp file origin.

Inputs:

ctx - Context for cancellation and timeout
content - The source code to lint
language - The language identifier (e.g., "go", "python")

Outputs:

*LintResult - The lint result with categorized issues
error - Non-nil if the linter failed

Thread Safety: Safe for concurrent use.

func (*LintRunner) LintDirectory

func (r *LintRunner) LintDirectory(ctx context.Context, dirPath string) ([]*LintResult, error)

LintDirectory runs the linter on all supported files in a directory.

Description:

Recursively finds all files with supported extensions and lints them.
Skips vendor, node_modules, and hidden directories.

Inputs:

ctx - Context for cancellation
dirPath - Path to directory to lint

Outputs:

[]*LintResult - Results for each file
error - Non-nil if directory walk or linting failed

Thread Safety: Safe for concurrent use.

func (*LintRunner) LintFiles

func (r *LintRunner) LintFiles(ctx context.Context, filePaths []string) ([]*LintResult, error)

LintFiles runs the linter on multiple files concurrently.

Description:

Lints multiple files in parallel using goroutines.
Results are returned in the same order as input files.

Inputs:

ctx - Context for cancellation
filePaths - Paths to files to lint

Outputs:

[]*LintResult - Results in same order as input
error - Non-nil if any file failed to lint

Thread Safety: Safe for concurrent use.

func (*LintRunner) LintWithLanguage

func (r *LintRunner) LintWithLanguage(ctx context.Context, filePath, language string) (*LintResult, error)

LintWithLanguage runs the linter for a specific language on a file.

Description:

Like Lint, but with explicit language specification.
Useful when the file extension doesn't match the language.

Inputs:

ctx - Context for cancellation and timeout
filePath - Path to the file to lint
language - The language identifier

Outputs:

*LintResult - The lint result with categorized issues
error - Non-nil if the linter failed to execute

Thread Safety: Safe for concurrent use.

func (*LintRunner) Policies

func (r *LintRunner) Policies() *PolicyRegistry

Policies returns the policy registry for customization.

type LinterConfig

type LinterConfig struct {
	// Language is the language this linter handles (e.g., "go", "python").
	Language string

	// Command is the linter executable name (e.g., "golangci-lint").
	Command string

	// Args are the arguments to pass to the linter.
	// Should include flags for JSON output.
	Args []string

	// Extensions are file extensions this linter handles (e.g., []string{".go"}).
	Extensions []string

	// Timeout is the maximum time to wait for the linter.
	Timeout time.Duration

	// Available indicates whether the linter binary was found in PATH.
	// Set by DetectAvailableLinters.
	Available bool

	// SupportsStdin indicates whether the linter can read from stdin.
	SupportsStdin bool

	// FixArgs are arguments for running the linter in fix mode.
	// Empty if the linter doesn't support auto-fix.
	FixArgs []string
}

LinterConfig configures how to run a specific linter.

Thread Safety: Treat as immutable after creation.

func (*LinterConfig) Clone

func (c *LinterConfig) Clone() *LinterConfig

Clone returns a deep copy of the config.

type LinterError

type LinterError struct {
	// Linter is the name of the linter that failed (e.g., "golangci-lint").
	Linter string

	// Language is the language being linted (e.g., "go").
	Language string

	// Err is the underlying error.
	Err error

	// Output contains any stderr output from the linter.
	Output string
}

LinterError wraps errors from a specific linter with context.

Thread Safety: Immutable after creation.

func NewLinterError

func NewLinterError(linter, language string, err error) *LinterError

NewLinterError creates a new LinterError.

Description:

Creates an error with context about which linter failed.

Inputs:

linter - Name of the linter (e.g., "golangci-lint")
language - Language being linted (e.g., "go")
err - The underlying error

Outputs:

*LinterError - The wrapped error

func (*LinterError) Error

func (e *LinterError) Error() string

Error implements the error interface.

func (*LinterError) Unwrap

func (e *LinterError) Unwrap() error

Unwrap returns the underlying error for errors.Is/As support.

func (*LinterError) WithOutput

func (e *LinterError) WithOutput(output string) *LinterError

WithOutput adds stderr output to the error.

Description:

Returns a copy of the error with the output field set.
Useful for capturing linter stderr for debugging.

Inputs:

output - The stderr output from the linter

Outputs:

*LinterError - A new error with output set

type Option

type Option func(*LintRunner)

Option configures the LintRunner.

func WithConfigs

func WithConfigs(configs *ConfigRegistry) Option

WithConfigs sets a custom config registry.

func WithPolicies

func WithPolicies(policies *PolicyRegistry) Option

WithPolicies sets a custom policy registry.

func WithWorkingDir

func WithWorkingDir(dir string) Option

WithWorkingDir sets the working directory for linter execution.

type ParserFunc

type ParserFunc func(data []byte) ([]LintIssue, error)

ParserFunc is a function that parses linter output into issues.

func GetParser

func GetParser(language string) ParserFunc

GetParser returns the parser function for a language.

Description:

Returns the registered parser for the given language, or nil if
no parser is registered.

Inputs:

language - The language identifier

Outputs:

ParserFunc - The parser function, or nil if not found

type PolicyRegistry

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

PolicyRegistry manages policies for different languages.

Thread Safety: Safe for concurrent use after initialization.

func NewPolicyRegistry

func NewPolicyRegistry() *PolicyRegistry

NewPolicyRegistry creates a new registry with default policies.

func (*PolicyRegistry) Get

func (r *PolicyRegistry) Get(language string) *RulePolicy

Get returns the policy for a language.

Description:

Returns the policy for the given language.
Returns nil if no policy is registered for the language.

Inputs:

language - The language identifier (e.g., "go", "python")

Outputs:

*RulePolicy - The policy, or nil if not found

Thread Safety: Safe for concurrent use.

func (*PolicyRegistry) Languages

func (r *PolicyRegistry) Languages() []string

Languages returns all registered language names.

Thread Safety: Safe for concurrent use.

func (*PolicyRegistry) Register

func (r *PolicyRegistry) Register(language string, policy *RulePolicy)

Register adds or updates a policy for a language.

Description:

Registers a custom policy for a language, overwriting any existing policy.

Inputs:

language - The language identifier
policy - The policy to register

Thread Safety: Safe for concurrent use.

type RulePolicy

type RulePolicy struct {
	// BlockOn are rules that block patches (treat as errors).
	BlockOn []string

	// WarnOn are rules that warn but allow patches.
	WarnOn []string

	// Ignore are rules to completely ignore.
	Ignore []string
}

RulePolicy defines how to handle specific linter rules.

Description:

Rules are matched by prefix. For example, "errcheck" matches
"errcheck", "errcheck/assert", etc.

Thread Safety: Treat as immutable after creation.

func (*RulePolicy) GetSeverity

func (p *RulePolicy) GetSeverity(rule string) Severity

GetSeverity returns the severity for a rule based on policy.

Description:

Determines the severity based on which policy list the rule matches.
Ignore takes precedence, then BlockOn, then WarnOn.
Default is SeverityWarning.

Inputs:

rule - The rule identifier from the linter

Outputs:

Severity - The severity level for the rule

func (*RulePolicy) ShouldBlock

func (p *RulePolicy) ShouldBlock(rule string) bool

ShouldBlock returns true if the rule should block patches.

Description:

Checks if the rule matches any BlockOn patterns.
Matching is done by prefix.

Inputs:

rule - The rule identifier from the linter

Outputs:

bool - True if the rule should block

func (*RulePolicy) ShouldIgnore

func (p *RulePolicy) ShouldIgnore(rule string) bool

ShouldIgnore returns true if the rule should be ignored.

Description:

Checks if the rule matches any Ignore patterns.
Matching is done by prefix.

Inputs:

rule - The rule identifier from the linter

Outputs:

bool - True if the rule should be ignored

func (*RulePolicy) ShouldWarn

func (p *RulePolicy) ShouldWarn(rule string) bool

ShouldWarn returns true if the rule should produce a warning.

Description:

Checks if the rule matches any WarnOn patterns.
Matching is done by prefix.

Inputs:

rule - The rule identifier from the linter

Outputs:

bool - True if the rule should warn

type Severity

type Severity int

Severity represents the severity level of a lint issue.

const (
	// SeverityInfo represents informational/style issues that don't block patches.
	SeverityInfo Severity = iota

	// SeverityWarning represents issues that should be noted but don't block patches.
	SeverityWarning

	// SeverityError represents issues that block patches from being applied.
	SeverityError
)

func SeverityFromString

func SeverityFromString(s string) Severity

SeverityFromString parses a severity string.

Description:

Parses common severity strings from different linters.
Unknown values default to SeverityWarning.

Inputs:

s - Severity string (e.g., "error", "warning", "info")

Outputs:

Severity - The parsed severity level

func (Severity) String

func (s Severity) String() string

String returns the string representation of the severity.

type TextEdit

type TextEdit struct {
	// StartLine is the 1-indexed starting line.
	StartLine int `json:"start_line"`

	// StartColumn is the 1-indexed starting column.
	StartColumn int `json:"start_column"`

	// EndLine is the 1-indexed ending line.
	EndLine int `json:"end_line"`

	// EndColumn is the 1-indexed ending column.
	EndColumn int `json:"end_column"`

	// NewText is the replacement text.
	NewText string `json:"new_text"`
}

TextEdit represents a text change for auto-fix.

Thread Safety: Immutable after creation.

Jump to

Keyboard shortcuts

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