Documentation
¶
Overview ¶
Package rubocop is a pure-Go (no cgo) reimplementation of the core of Ruby's RuboCop linter — the offense/cop framework, a faithful core cop set, the .rubocop.yml configuration model and the default formatters — built on the go-ruby-parser Ruby AST and lexer.
It is interpreter-independent: cops inspect a Ruby source string (its lines, its token stream and its abstract syntax tree) and emit Offenses whose cop name, location and message byte-match those the `rubocop` gem produces. The file-walking that the gem performs is a thin host seam; this library runs on source strings, which is the shape [go-embedded-ruby] binds into `rbgo`.
It is a sibling of the other go-ruby-* front-end libraries (go-ruby-parser, go-ruby-regexp, go-ruby-erb, go-ruby-yaml) and, like them, hands the host an explicit value model rather than driving a live interpreter.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
// contains filtered or unexported fields
}
Config is a whole-run configuration: the AllCops defaults plus per-cop overrides parsed from a .rubocop.yml document. A cop's effective CopConfig is its built-in defaults merged with any overrides here (overrides win).
func NewConfig ¶
func NewConfig() *Config
NewConfig returns an empty Config: every cop takes its built-in default (enabled, default params). This is the "no .rubocop.yml present" case.
func ParseConfig ¶
ParseConfig parses a .rubocop.yml document into a Config. It understands the subset RuboCop configs use in practice: an AllCops section (DisabledByDefault) and per-cop sections carrying Enabled plus arbitrary scalar/param keys. Unknown keys are preserved as params so parameterised cops can read them. A YAML syntax error is returned; an empty document yields the empty (all-default) Config.
func (*Config) For ¶
For resolves the effective CopConfig for cop name, merging def (the cop's built-in defaults) with any override from the parsed config. Enabled follows RuboCop's precedence: an explicit per-cop Enabled always wins; otherwise the cop is on unless AllCops.DisabledByDefault turned everything off. Params from the override are layered over the defaults key-by-key.
type Cop ¶
type Cop interface {
// Name is the department-qualified cop name, e.g. "Style/StringLiterals".
Name() string
// Inspect returns the offenses this cop finds in src, in source order.
Inspect(src *Source, cfg CopConfig) []Offense
}
Cop is a single lint rule. Inspect examines a Source and returns the offenses it finds, in source order. It receives its resolved per-cop configuration (the merged params from .rubocop.yml plus the cop's own defaults) so parameterised cops (Metrics/*, Layout/LineLength, …) read their Max and friends from it.
This mirrors RuboCop's cop protocol: the gem's cops implement on_<node> callbacks the commissioner dispatches while walking the AST, but the contract that matters to a consumer is the same — given a source, yield offenses. A cop here walks whichever view (lines, tokens, AST) it needs itself; the Runner is the commissioner that invokes each enabled cop once per source.
type CopConfig ¶
CopConfig is the resolved configuration for a single cop: whether it is enabled and its parameter map (Max, EnforcedStyle, …). Params values are the Go shapes go-ruby-yaml decodes YAML scalars to (int, float64, bool, string, []any).
type Correction ¶
Correction is a single source edit an autocorrecting cop proposes: replace the half-open byte range [Begin, End) of the original source with Replacement. Applying corrections is the host's job (see Runner.Autocorrect for a reference applier); the cop only computes them.
type FileResult ¶
FileResult pairs a file path with the offenses found in it (in report order).
type Formatter ¶
type Formatter interface {
// Format renders the offenses for the files in results (in the given order)
// plus the trailing summary, returning the complete report text.
Format(results []FileResult) string
}
Formatter renders a run's offenses to text. The two built-ins reproduce RuboCop's `--format simple` (SimpleTextFormatter) and `--format progress` (ProgressFormatter) output byte-for-byte, including the summary line.
type Location ¶
Location is a 1-based line/column span within the inspected source, exactly as RuboCop reports it: Line and Column point at the first offending character and Length is the number of columns the caret underline spans in the clang-style formatter (0 when the cop does not define a precise span).
type Offense ¶
type Offense struct {
CopName string
Location Location
Message string
Severity Severity
Correctable bool
// Correction, when non-nil, is the autocorrection the cop would apply. It is
// advisory: this library computes the edit but leaves applying it to the host.
Correction *Correction
}
Offense is a single reported violation. CopName is the department-qualified cop name (e.g. "Layout/TrailingWhitespace"); Message is the human-readable text the cop emits (byte-identical to the gem's); Severity is its level; Correctable records whether the cop offers an autocorrection (the "[Correctable]" marker).
type ProgressFormatter ¶
type ProgressFormatter struct{}
ProgressFormatter reproduces `rubocop --format progress`: a run of per-file status dots/letters (`.` clean, or the offenses' severity codes), a blank line, an "Offenses:" listing in clang style, a blank line, then the summary.
func (ProgressFormatter) Format ¶
func (ProgressFormatter) Format(results []FileResult) string
Format renders results in the progress style.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry is an ordered, name-indexed set of cops. The zero Registry is not usable; construct one with NewRegistry (empty) or DefaultRegistry (the built-in core cop set). Registration is idempotent-by-replacement: registering a cop whose name already exists replaces it, so a host can override a built-in.
func DefaultRegistry ¶
func DefaultRegistry() *Registry
DefaultRegistry returns a Registry populated with the built-in core cop set.
type Runner ¶
type Runner struct {
// contains filtered or unexported fields
}
Runner drives a registry of cops over a source with a configuration — the counterpart of RuboCop's Commissioner + team. Construct one with NewRunner; Inspect and InspectSource return the offenses in RuboCop's report order.
func NewRunner ¶
NewRunner returns a Runner over reg and cfg. A nil registry defaults to the built-in core cop set (DefaultRegistry); a nil config to the all-defaults Config (NewConfig).
func (*Runner) Autocorrect ¶
Autocorrect applies, to source, the corrections of every offense that carries one, returning the rewritten source. Non-overlapping corrections are applied right-to-left so earlier byte offsets stay valid; overlapping corrections keep the first (lowest-offset) and skip the rest, mirroring how RuboCop's corrector refuses to clobber an already-edited range in a single pass. It is a reference applier for hosts that want the whole edit in one call.
func (*Runner) Inspect ¶
Inspect lexes/parses source (named path for file-naming cops) and runs every enabled cop, returning the offenses sorted the way RuboCop reports them.
func (*Runner) InspectSource ¶
InspectSource runs every enabled cop over an already-built Source. Splitting this out lets a host lex/parse once and reuse the Source.
type Severity ¶
type Severity int
Severity is an offense severity level, matching RuboCop's five-level scale. Its single-letter code is what the formatters print (I/R/C/W/E/F).
const ( Convention Severity = iota // C — a style/convention offense (the common case) Warning // W — a Lint warning (a probable mistake) Error // E — a definite problem Fatal // F — an internal/parse failure Info // I — informational only Refactor // R — a refactoring suggestion )
The severity levels, in ascending order of seriousness. The zero value is Convention, RuboCop's default for most Style/Layout/Metrics cops.
type SimpleTextFormatter ¶
type SimpleTextFormatter struct{}
SimpleTextFormatter reproduces `rubocop --format simple`: for each file with offenses a "== path ==" header followed by one aligned line per offense, then a blank line and the summary.
func (SimpleTextFormatter) Format ¶
func (SimpleTextFormatter) Format(results []FileResult) string
Format renders results in the simple text style.
type Source ¶
type Source struct {
// Path is the host-supplied filename used in messages that name the file
// (e.g. Lint/DuplicateMethods); "" when inspecting an anonymous string.
Path string
// Raw is the original source, verbatim.
Raw string
// Lines are Raw split on "\n" with the newlines removed; Lines[0] is line 1.
// A trailing newline does not produce a final empty element, matching how
// RuboCop counts physical lines.
Lines []string
// Tokens is the full lexer output including the terminating EOF token.
Tokens []token.Token
// AST is the parsed program, or nil when the source failed to parse.
AST *ast.Program
// ParseErr is the parse error, or nil.
ParseErr error
// contains filtered or unexported fields
}
Source is the processed view of one Ruby source string handed to every cop: the raw bytes, the lines split for the line-oriented Layout cops, the lexed token stream (each token carrying its 1-based Line/Col and MRI's SpaceBefore flag), and the parsed AST (nil if the source does not parse). RuboCop cops likewise mix line, token and AST views; go-ruby-parser's AST nodes carry no positions, so token positions are how the AST cops locate their offenses.
