analyzer

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package analyzer implements commentlen, a configurable size and style linter for Go comments.

Every comment in a file is classified into exactly one kind — package doc, exported doc, unexported doc, field, inline, trailing or other — and gets the limits configured for that kind: number of lines and width. On top of the size rules the linter enforces a comment-to-code ratio, a per-function budget of inline comments, a set of banned phrases and tags, and godoc grammar.

Nothing is mandatory: every check, kind, file and single comment can be silenced through settings, through a path or text pattern, or through a //commentlen:disable directive in the source.

The analyzer needs syntax only. It never asks for type information, so it stays in golangci-lint's fast load mode, and it does one AST walk plus one pass over the file's comments — no per-comment allocation, no regexp in the hot path unless a check is configured to need one.

Index

Constants

View Source
const DirectivePrefix = "//commentlen:"

DirectivePrefix is the marker the linter answers to in source files.

View Source
const Doc = "checks the size and shape of comments: per-kind length limits, " +
	"comment-to-code ratio, banned phrases and godoc grammar"

Doc is the analyzer's one-line description.

View Source
const Name = "commentlen"

Name is the linter name, as used in .golangci.yml and in //nolint directives.

Variables

This section is empty.

Functions

func KindNames

func KindNames() []string

KindNames returns every valid kind key, in declaration order.

func MustNew

func MustNew(s Settings) *analysis.Analyzer

MustNew is New for callers that build the analyzer from a literal, such as the standalone binary.

func New

func New(s Settings) (*analysis.Analyzer, error)

New builds the analyzer from already-decoded settings.

Types

type BannedPattern

type BannedPattern struct {
	// Pattern is a Go regexp matched against the comment text.
	Pattern string `json:"pattern"`
	// Message is what the user sees. Defaults to naming the pattern.
	Message string `json:"message"`
}

BannedPattern is one forbidden phrase and the diagnostic it produces.

type GodocSettings

type GodocSettings struct {
	Enabled *bool `json:"enabled"`
	// StartsWithName requires the Go convention "Name does ...".
	StartsWithName *bool `json:"starts-with-name"`
	// Capitalized requires an upper-case first letter.
	Capitalized *bool `json:"capitalized"`
	// EndsWithPeriod requires a terminating period on the last line.
	EndsWithPeriod *bool `json:"ends-with-period"`
	// ReportsWhether reports "returns true if" on bool-returning functions,
	// which the standard library spells "reports whether".
	ReportsWhether *bool `json:"reports-whether"`
	// Scope is "exported" (default) or "all".
	Scope string `json:"scope"`
}

GodocSettings configures the grammar rules applied to doc comments.

type Kind

type Kind uint8

Kind is the classification of a comment. Every comment in a file belongs to exactly one kind, and all size limits are configured per kind.

const (
	// KindPackage is the package doc comment, the one directly above `package x`.
	KindPackage Kind = iota
	// KindExported is a doc comment on an exported top-level declaration.
	KindExported
	// KindUnexported is a doc comment on an unexported top-level declaration.
	KindUnexported
	// KindField is a comment on a struct field, interface method or group element.
	KindField
	// KindInline is a comment on its own line inside a function body.
	KindInline
	// KindTrailing is a same-line comment after code inside a function body.
	KindTrailing
	// KindOther is everything else: floating, inside literals, end of file.
	KindOther
)

The comment kinds recognized by the linter.

func (Kind) String

func (k Kind) String() string

String returns the configuration key of the kind.

type KindSettings

type KindSettings struct {
	// Disabled turns off every check for this kind.
	Disabled *bool `json:"disabled"`
	// Forbidden reports any comment of this kind, whatever its size.
	Forbidden *bool `json:"forbidden"`
	// MaxLines caps the number of counted lines. 0 means unlimited.
	MaxLines *int `json:"max-lines"`
	// MaxWidth caps the width of a single line in runes. 0 means unlimited.
	MaxWidth *int `json:"max-width"`
}

KindSettings are the size limits of one comment kind.

type Override added in v0.2.0

type Override struct {
	// Path is a regexp matched against the slash-separated file path.
	Path string `json:"path"`

	Settings
}

Override is a settings layer applied to the files whose path matches Path. It accepts every key of Settings except preset, overrides, and the four that select files at all: skip-generated, skip-tests, exclude-files and generated-extra.

The typical use is lifting the size limits in tests while keeping the content rules, which apply to test prose just as much.

type RatioSettings

type RatioSettings struct {
	Enabled *bool `json:"enabled"`
	// Max is the allowed comment-lines / code-lines ratio. Default 1.0.
	Max *float64 `json:"max"`
	// MinCodeLines skips the check when the described code is shorter than this,
	// so that a one-liner may still carry a two-line explanation. Default 2.
	MinCodeLines *int `json:"min-code-lines"`
	// Kinds lists the kinds the ratio applies to. Default ["inline"].
	Kinds []string `json:"kinds"`
}

RatioSettings configures the "a comment must not be longer than the code it describes" rule.

type Settings

type Settings struct {
	// Preset picks the baseline every other field is layered on top of:
	// "balanced" (default), "strict" or "loose".
	Preset string `json:"preset"`

	// SkipGenerated skips files carrying a "Code generated ... DO NOT EDIT."
	// marker above the package clause. Default true.
	SkipGenerated *bool `json:"skip-generated"`
	// GeneratedExtra are additional regexps matched against the comments above
	// the package clause; a match marks the file as generated.
	GeneratedExtra []string `json:"generated-extra"`
	// SkipTests skips _test.go files entirely. Default false.
	SkipTests *bool `json:"skip-tests"`
	// ExcludeFiles are regexps matched against the file path (slash-separated).
	ExcludeFiles []string `json:"exclude-files"`

	// ExcludePatterns are regexps matched against a comment's text; a match
	// exempts that comment from every check.
	ExcludePatterns []string `json:"exclude-patterns"`
	// IgnoreDirectives exempts tool directives (//go:generate, //nolint, …).
	// Default true.
	IgnoreDirectives *bool `json:"ignore-directives"`
	// DirectivePrefixesExtra adds prefixes treated as directives, for tools that
	// do not follow the //tool:name convention (e.g. "ffjson:").
	DirectivePrefixesExtra []string `json:"directive-prefixes-extra"`
	// IgnoreURLs excludes lines whose overlong part is a single URL or a long
	// unbreakable token from the width check. Default true.
	IgnoreURLs *bool `json:"ignore-urls"`
	// IgnoreCodeBlocks excludes godoc code blocks (indented or “` fenced) from
	// both the width and the line-count checks. Default true.
	IgnoreCodeBlocks *bool `json:"ignore-code-blocks"`
	// CountBlankLines counts empty comment lines towards max-lines.
	// Default false.
	CountBlankLines *bool `json:"count-blank-lines"`
	// WidthIncludesIndent measures width from column 1 rather than from the
	// comment marker. Default true.
	WidthIncludesIndent *bool `json:"width-includes-indent"`

	// Defaults applies to every kind that has no explicit entry in Kinds.
	Defaults KindSettings `json:"defaults"`
	// Kinds holds the per-kind limits, keyed by kind name: package, exported,
	// unexported, field, inline, trailing, other.
	Kinds map[string]KindSettings `json:"kinds"`

	// MaxInlinePerFunc caps how many inline comments one function body may hold.
	// 0 disables the check.
	MaxInlinePerFunc *int `json:"max-inline-per-func"`

	Ratio RatioSettings `json:"ratio"`
	Style StyleSettings `json:"style"`
	Godoc GodocSettings `json:"godoc"`

	// Overrides relax or tighten the settings for the files matching a path.
	// The first matching entry wins, so order them from most to least specific.
	Overrides []Override `json:"overrides"`
}

Settings is the user-facing configuration of the linter. It is decoded from the `linters.settings.custom.commentlen.settings` block of .golangci.yml, so every field name here is a YAML key.

All scalar fields are pointers: a nil pointer means "not set by the user" and falls back to the preset. Slices replace the preset value; the *-extra slices append to it instead.

type StyleSettings

type StyleSettings struct {
	//commentlen:ignore  the doc has to name the markers it bans
	// Tags reports these words when used as a tag (TODO, FIXME, …).
	Tags        []string `json:"tags"`
	TagsEnabled *bool    `json:"tags-enabled"`

	// Patterns replaces the default banned-phrase list.
	Patterns []BannedPattern `json:"patterns"`
	// PatternsExtra appends to the default banned-phrase list.
	PatternsExtra []BannedPattern `json:"patterns-extra"`
	// UseDefaultPatterns keeps the built-in phrase list. Default true.
	UseDefaultPatterns *bool `json:"use-default-patterns"`

	// Banners reports decorative separators and ASCII art.
	Banners *bool `json:"banners"`
	//commentlen:ignore  the doc has to name what it bans
	// Metadata reports @author, dates and change-history lines.
	Metadata *bool `json:"metadata"`
	// CommentedCode reports commented-out code.
	CommentedCode *bool `json:"commented-code"`
	// CommentedCodeMinLines is how many consecutive code-looking lines are
	// needed before reporting. Default 2.
	CommentedCodeMinLines *int `json:"commented-code-min-lines"`
}

StyleSettings configures the content checks: banned tags, banned phrases, decorative banners, metadata and commented-out code.

Jump to

Keyboard shortcuts

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