core

package
v1.4.2 Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const SupportedConfigVersion = 1

SupportedConfigVersion is the schema version this glint understands. A config written for a different one is rejected rather than half-applied.

Variables

View Source
var DefaultSkipDirs = []string{
	".git", ".svn", ".hg",
	".idea", ".vscode",
	"node_modules", "vendor",
	".next", "out", "dist", "build", "bin",
}

DefaultSkipDirs are the directory names the walker never descends into unless settings.skip_dirs says otherwise.

Functions

func CommentPart added in v1.4.2

func CommentPart(line string) string

CommentPart returns the substring of a line starting at its comment marker ("//" or "/*"), or "" when the line has no comment. A marker inside a string literal is not a comment start — this is the single implementation rules must use when they match comment text, so that a regexp source containing "//" is not mistaken for a comment.

func ExtractFullFunctionName

func ExtractFullFunctionName(call *ast.CallExpr) string

ExtractFullFunctionName extracts the full function name (package.function)

func FindConfig

func FindConfig(startDir string) (string, error)

FindConfig searches for .glint.yaml in the directory and its parents

func LineSuppresses added in v1.4.2

func LineSuppresses(line, ruleName string) bool

LineSuppresses reports whether the line's comment part carries a suppression marker for the given rule (nolint:<rule> / <rule>: safe). Single canonical implementation — rules must delegate here instead of matching suppression strings themselves.

Types

type CategoryConfig

type CategoryConfig struct {
	Enabled          bool   `yaml:"enabled"`
	SeverityOverride string `yaml:"severity_override,omitempty"`
	// Rule settings are user-authored YAML whose shape each rule defines; a
	// typed struct here would have to know all of them.
	// any-in-public-contract: safe
	Settings map[string]any        `yaml:"settings,omitempty"`
	Rules    map[string]RuleConfig `yaml:"rules,omitempty"`
}

CategoryConfig contains category-specific settings

func (*CategoryConfig) UnmarshalYAML added in v1.4.2

func (c *CategoryConfig) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML defaults Enabled to true. Without it, naming a category in order to configure its rules would switch the whole category off, because the zero value of a bool is false.

type Config

type Config struct {
	Version    int                       `yaml:"version"`
	Extends    string                    `yaml:"extends,omitempty"`
	Settings   SettingsConfig            `yaml:"settings"`
	Categories map[string]CategoryConfig `yaml:"categories"`
}

Config represents the glint configuration

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns the default configuration

func LoadConfig

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

LoadConfig loads a configuration file, resolving its `extends` chain.

func LoadConfigWithDefaults

func LoadConfigWithDefaults(projectRoot string) (*Config, error)

LoadConfigWithDefaults loads config and merges with defaults

func MergeConfigs

func MergeConfigs(base, override *Config) *Config

MergeConfigs merges two configs, with override taking precedence

func (*Config) GetMinSeverity

func (c *Config) GetMinSeverity() (Severity, error)

GetMinSeverity returns the configured minimum severity level.

func (*Config) GetRuleExceptions

func (c *Config) GetRuleExceptions(category, rule string) []Exception

GetRuleExceptions returns exceptions for a specific rule

func (*Config) IsCategoryEnabled

func (c *Config) IsCategoryEnabled(name string) bool

IsCategoryEnabled checks if a category is enabled

func (*Config) IsFileExcepted added in v1.4.2

func (c *Config) IsFileExcepted(category, rule, filePath string) bool

IsFileExcepted checks if a file should be excepted from a specific rule based on YAML exceptions. Supports ** glob patterns by converting to substring match on path segments.

func (*Config) IsRuleEnabled

func (c *Config) IsRuleEnabled(category, rule string) bool

IsRuleEnabled checks if a specific rule is enabled

func (*Config) IsViolationExcepted added in v1.4.2

func (c *Config) IsViolationExcepted(category, rule, filePath string, violation *Violation) bool

IsViolationExcepted checks whether a specific violation matches a rule exception.

func (*Config) SeverityOverrideFor added in v1.4.2

func (c *Config) SeverityOverrideFor(category, rule string) (Severity, bool, error)

SeverityOverrideFor returns the severity configured for a rule, if any. A rule-level `severity` wins over its category's `severity_override`; when neither is set the rule keeps the severity it reports itself.

func (*Config) ShouldExclude

func (c *Config) ShouldExclude(path string) bool

ShouldExclude checks if a path should be excluded based on glob patterns

func (*Config) SkipDirs added in v1.4.2

func (c *Config) SkipDirs() []string

SkipDirs returns the configured directory names to skip, or the defaults.

func (*Config) Validate added in v1.4.2

func (c *Config) Validate() error

Validate reports configuration values that glint would otherwise have to guess about: unparseable severities anywhere in the file.

type Exception

type Exception struct {
	File     string `yaml:"file,omitempty"`
	Line     int    `yaml:"line,omitempty"`
	Files    string `yaml:"files,omitempty"`    // Glob pattern
	Pattern  string `yaml:"pattern,omitempty"`  // Code pattern
	Function string `yaml:"function,omitempty"` // Function name
	Reason   string `yaml:"reason,omitempty"`
}

Exception defines when a rule should be skipped

type FileContext

type FileContext struct {
	// Path information
	Path        string // Absolute path
	RelPath     string // Relative to project root
	ProjectRoot string // Project root directory

	// File content
	Content []byte   // Raw file content
	Lines   []string // Lines for positional access

	// Go-specific (nil for non-Go files)
	GoAST     *ast.File
	GoFileSet *token.FileSet
	GoPackage string
	GoImports []string

	// Configuration
	Config *Config
}

FileContext contains all information about a file being analyzed

func NewFileContext

func NewFileContext(path, projectRoot string, content []byte, cfg *Config) *FileContext

NewFileContext creates a file context and panics on an invalid path pair. It exists for tests, which build contexts from literal paths; the analysis pipeline uses NewFileContextChecked and reports the error instead.

func NewFileContextChecked added in v1.4.2

func NewFileContextChecked(path, projectRoot string, content []byte, cfg *Config) (*FileContext, error)

NewFileContextChecked creates a file context and reports invalid path relationships.

func (*FileContext) BaseName

func (ctx *FileContext) BaseName() string

BaseName returns the base name of the file

func (*FileContext) Dir

func (ctx *FileContext) Dir() string

Dir returns the directory containing the file

func (*FileContext) Extension

func (ctx *FileContext) Extension() string

Extension returns the file extension

func (*FileContext) GetContext

func (ctx *FileContext) GetContext(lineNum, contextLines int) []string

GetContext returns lines around a specific line for context

func (*FileContext) GetLine

func (ctx *FileContext) GetLine(lineNum int) string

GetLine returns a specific line (1-based index)

func (*FileContext) GetLines

func (ctx *FileContext) GetLines(startLine, endLine int) []string

GetLines returns a range of lines (1-based, inclusive)

func (*FileContext) HasGoAST

func (ctx *FileContext) HasGoAST() bool

HasGoAST returns true if Go AST is available

func (*FileContext) IsGoFile

func (ctx *FileContext) IsGoFile() bool

IsGoFile returns true if this is a Go file

func (*FileContext) IsJavaScriptFile

func (ctx *FileContext) IsJavaScriptFile() bool

IsJavaScriptFile returns true if this is a JavaScript file

func (*FileContext) IsSuppressed added in v1.4.2

func (ctx *FileContext) IsSuppressed(line int, ruleName string) bool

IsSuppressed reports whether a violation of the given rule at the given line is suppressed by an inline comment. Two forms are recognized, on the violation line itself or on the line directly above it:

//nolint:<rule-name>
// <rule-name>: safe — <reason>

The marker must appear inside a comment ("//" or "/*"); string literals containing the same text do not suppress. Rule names match exactly: "nolint:my-rule" does not suppress rule "my-rule-extended" and vice versa.

func (*FileContext) IsTestFile

func (ctx *FileContext) IsTestFile() bool

IsTestFile returns true if this appears to be a test file

func (*FileContext) IsTypeScriptFile

func (ctx *FileContext) IsTypeScriptFile() bool

IsTypeScriptFile returns true if this is a TypeScript file

func (*FileContext) LineFor added in v1.4.2

func (ctx *FileContext) LineFor(node ast.Node) int

LineFor returns the one-based source line for an AST node.

func (*FileContext) LineForPos added in v1.4.2

func (ctx *FileContext) LineForPos(pos token.Pos) int

LineForPos returns the one-based source line for a position. Rules must use it rather than counting newlines in Content: token.Pos is an offset into the shared file set, not into a single file, so hand-rolled arithmetic silently reports the wrong line once several files share a set.

func (*FileContext) PositionFor

func (ctx *FileContext) PositionFor(node ast.Node) token.Position

PositionFor returns the position for a given ast.Node

func (*FileContext) SetGoAST

func (ctx *FileContext) SetGoAST(fset *token.FileSet, file *ast.File)

SetGoAST sets the Go AST for this file

type GoPackageContext added in v1.4.2

type GoPackageContext struct {
	Package *packages.Package
	SSA     *ssa.Package
	Files   []*FileContext
}

GoPackageContext connects a loaded typed package and its optional SSA package to the existing file contexts used by file-level rules.

type GoProjectContext added in v1.4.2

type GoProjectContext struct {
	ProjectRoot string
	FileSet     *token.FileSet
	Program     *ssa.Program
	Packages    []*GoPackageContext
	Files       []*FileContext
	// SkippedPackages lists packages excluded from typed analysis; always empty
	// unless GoProjectOptions.TolerateBrokenPackages is set.
	SkippedPackages []SkippedPackage
	// contains filtered or unexported fields
}

GoProjectContext contains the shared typed representation of the initial Go packages.

func LoadGoProject added in v1.4.2

func LoadGoProject(root string, contexts []*FileContext, opts GoProjectOptions) (*GoProjectContext, error)

LoadGoProject loads all initial packages below root from the already-read file contents.

func (*GoProjectContext) File added in v1.4.2

func (ctx *GoProjectContext) File(path string) (*FileContext, error)

File resolves an absolute or project-relative path to its existing file context.

func (*GoProjectContext) FileForPosition added in v1.4.2

func (ctx *GoProjectContext) FileForPosition(pos token.Pos) (*FileContext, error)

FileForPosition maps a position in the shared file set to its file context.

type GoProjectOptions added in v1.4.2

type GoProjectOptions struct {
	// RequireSSA builds the SSA program for rules that need it.
	RequireSSA bool
	// TolerateBrokenPackages keeps analysis running when some packages fail to
	// type-check: they are excluded from typed analysis and reported in
	// SkippedPackages instead of aborting the whole load. Needed to analyze a
	// tree that does not compile as a whole - historical commits, generated or
	// git-ignored sources, work in progress.
	TolerateBrokenPackages bool
}

GoProjectOptions controls how the typed project is loaded.

type Parser

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

Parser handles parsing of source files

func NewParser

func NewParser() *Parser

NewParser creates a new parser

func SharedParser added in v1.4.2

func SharedParser() *Parser

SharedParser returns the process-wide parser instance. Its cache keys on path and content, so sharing it never yields a stale AST.

func (*Parser) ParseGoFile

func (p *Parser) ParseGoFile(path string, content []byte) (*token.FileSet, *ast.File, error)

ParseGoFile parses a Go file and returns its AST

type RuleConfig

type RuleConfig struct {
	Enabled  bool   `yaml:"enabled"`
	Severity string `yaml:"severity,omitempty"`
	// See CategoryConfig.Settings.
	// any-in-public-contract: safe
	Settings   map[string]any `yaml:"settings,omitempty"`
	Exceptions []Exception    `yaml:"exceptions,omitempty"`
}

RuleConfig contains rule-specific settings

func (*RuleConfig) UnmarshalYAML added in v1.4.2

func (r *RuleConfig) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML defaults Enabled to true, for the same reason as CategoryConfig.UnmarshalYAML: setting a rule's severity, settings or exceptions must not disable it as a side effect.

type SettingsConfig

type SettingsConfig struct {
	Exclude     []string `yaml:"exclude"`
	SkipDirs    []string `yaml:"skip_dirs,omitempty"`
	MinSeverity string   `yaml:"min_severity"`
	Output      string   `yaml:"output"`
}

SettingsConfig contains global settings

type Severity

type Severity int

Severity represents the severity level of a violation

const (
	SeverityLow Severity = iota
	SeverityMedium
	SeverityHigh
	SeverityCritical
)

func ParseSeverity

func ParseSeverity(s string) (Severity, error)

ParseSeverity converts a string to Severity

func (Severity) IsAtLeast

func (s Severity) IsAtLeast(other Severity) bool

IsAtLeast returns true if this severity is at least as severe as other

func (Severity) Label

func (s Severity) Label() string

Label returns a formatted label for display

func (Severity) String

func (s Severity) String() string

String returns the string representation of severity

type SkippedPackage added in v1.4.2

type SkippedPackage struct {
	ID      string
	PkgPath string
	Reason  string
}

SkippedPackage describes a package excluded from typed analysis.

type Violation

type Violation struct {
	// Rule identification
	Rule     string // Rule name (e.g., "error_masking")
	Category string // Category name (e.g., "patterns")

	// Location
	File    string // Absolute or relative file path
	Line    int    // Line number (1-based)
	Column  int    // Column number (1-based, 0 = unknown)
	EndLine int    // End line for multi-line issues (0 = single line)

	// Severity
	Severity Severity

	// Description
	Message    string // What's wrong
	Suggestion string // How to fix it

	// Context
	Code string // The offending code snippet
	// Context carries rule-specific metadata consumed by config exceptions and
	// by the JSON output. Every rule attaches its own keys, so the payload has
	// no single schema to declare.
	// any-in-public-contract: safe
	Context map[string]any
}

Violation represents a single issue found by a rule

func NewViolation

func NewViolation(rule, category, file string, line int, severity Severity, message string) *Violation

NewViolation creates a new violation with required fields

func (*Violation) Location

func (v *Violation) Location() string

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

func (*Violation) String

func (v *Violation) String() string

String returns a human-readable representation

func (*Violation) WithCode

func (v *Violation) WithCode(code string) *Violation

WithCode adds the code snippet to the violation

func (*Violation) WithColumn

func (v *Violation) WithColumn(col int) *Violation

WithColumn adds column information

func (*Violation) WithContext

func (v *Violation) WithContext(key string, value any) *Violation

WithContext adds context metadata

func (*Violation) WithEndLine

func (v *Violation) WithEndLine(endLine int) *Violation

WithEndLine marks this as a multi-line violation

func (*Violation) WithSuggestion

func (v *Violation) WithSuggestion(suggestion string) *Violation

WithSuggestion adds a suggestion to the violation

type ViolationList

type ViolationList []*Violation

ViolationList is a slice of violations with helper methods

func (ViolationList) BySeverity

func (vl ViolationList) BySeverity(minSeverity Severity) ViolationList

BySeverity returns violations filtered by minimum severity

func (ViolationList) CountByCategory

func (vl ViolationList) CountByCategory() map[string]int

CountByCategory returns a map of category to count

func (ViolationList) CountByRule

func (vl ViolationList) CountByRule() map[string]int

CountByRule returns a map of rule to count

func (ViolationList) CountBySeverity

func (vl ViolationList) CountBySeverity() map[Severity]int

CountBySeverity returns a map of severity to count

type Walker

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

Walker traverses files in a project

func NewWalker

func NewWalker(projectRoot string, config *Config) *Walker

NewWalker creates a new file walker

func (*Walker) Stats

func (w *Walker) Stats() WalkerStats

Stats returns the current walker statistics

func (*Walker) WalkSync

func (w *Walker) WalkSync() ([]*FileContext, []error)

WalkSync walks files synchronously and returns all contexts

func (*Walker) WithGoParsing added in v1.4.2

func (w *Walker) WithGoParsing(enabled bool) *Walker

WithGoParsing controls whether the walker parses Go files into ASTs.

func (*Walker) WithWorkers

func (w *Walker) WithWorkers(n int) *Walker

WithWorkers sets the number of worker goroutines

type WalkerStats

type WalkerStats struct {
	TotalFiles   int
	ParsedFiles  int
	SkippedFiles int
	ErrorFiles   int
}

WalkerStats contains statistics about the walk

Jump to

Keyboard shortcuts

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