ktn-linter

module
v0.106.1 Latest Latest
Warning

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

Go to latest
Published: Feb 2, 2026 License: MIT

README

KTN-Linter

Go Version

Strict Go linter for enforcing best practices and style rules.

Strict rule: 0 issues = 0 issues (even INFO). STOP and fix immediately.

Installation

To install ktn-linter on any Go project:

curl -sSL https://raw.githubusercontent.com/kodflow/ktn-linter/main/install.sh | bash

Or download and run the script:

wget https://raw.githubusercontent.com/kodflow/ktn-linter/main/install.sh
chmod +x install.sh
./install.sh

The script:

  • Downloads the binary from GitHub releases (linux/darwin, amd64/arm64)
  • Installs to /usr/local/bin or ~/.local/bin
  • Optionally configures golangci-lint
  • Creates a Makefile with ktn-linter targets
Installation from Source
git clone https://github.com/kodflow/ktn-linter
cd ktn-linter
make build      # Compiles the binary to builds/

Usage on Any Project

Once installed (via install.sh), use ktn-linter on any Go project:

# In your Go project
ktn-linter lint ./...                # Lint the entire project
ktn-linter lint --help               # Display help
ktn-linter lint --simple ./pkg/...   # Simplified format on pkg/
ktn-linter lint --fix ./...          # Automatically apply modernize fixes
ktn-linter lint --config .ktn-linter.yaml ./...  # Use a config file

Configuration (v1.4.0+)

KTN-Linter can be configured via a .ktn-linter.yaml file:

version: 1

# Global exclusions (all rules)
exclude:
  - "**/testdata/**"
  - "**/*_generated.go"
  - "vendor/**"

# Per-rule configuration
rules:
  KTN-FUNC-MAXSTMT:
    enabled: true
    threshold: 50          # Max lines (default: 35)
    exclude:
      - "cmd/**"           # Exclude for this rule

  KTN-FUNC-CYCLO:
    threshold: 15          # Max cyclomatic complexity (default: 10)

  KTN-COMMENT-LINELEN:
    enabled: false         # Disable the rule

  KTN-VAR-MAKEAPPEND:
    threshold: 100         # Struct size for pointer (default: 64)

Rules with configurable thresholds:

Rule Parameter Default
KTN-COMMENT-LINELEN maxCommentLength 80
KTN-COMMENT-PKGDOC minPackageCommentLength 3
KTN-COMMENT-STRUCT minStructDocLines 2
KTN-FUNC-MAXSTMT maxFunctionLength 35
KTN-FUNC-MAXPARAM maxParameters 5
KTN-FUNC-NAKEDRET maxReturnValues 3
KTN-FUNC-CYCLO maxCyclomaticComplexity 8
KTN-FUNC-NAMERET maxNestedDepth 4
KTN-VAR-MAKEAPPEND maxScopeLines 50
KTN-VAR-HOTLOOP maxLineLength 120
KTN-VAR-GROUP maxDeclarations 10

Config file lookup:

  1. Path specified with --config
  2. .ktn-linter.yaml in the current directory
  3. .ktn-linter.yml in the current directory
  4. Recursively searches parent directories

Flag --fix (v1.3.0+):

Automatically applies fixes suggested by SAFE modernize analyzers:

  • interface{} -> any (Go 1.18+) - Only safe analyzer currently
  • Complex fixes (slices.Contains, CutSuffix, etc.): use go install golang.org/x/tools/gopls/internal/analysis/modernize/cmd/modernize@latest && modernize -fix ./...

The --fix flag only applies simple transformations that don't require adding imports, to avoid corrupting code.

Integration with golangci-lint (optional):

The install.sh script offers to automatically configure .golangci.yml to integrate ktn-linter as a custom linter.

# After installation
golangci-lint run ./...   # Runs golangci-lint + ktn-linter

Usage (Linter Development)

make test      # Tests + coverage (generates COVERAGE.MD)
make coverage  # Generates only the COVERAGE.MD report
make lint      # Runs the KTN linter on production code
make validate  # Validates that all testdata good.go/bad.go are correct
make build     # Compiles the ktn-linter binary to builds/
make install   # Compiles and installs ktn-linter to /usr/local/bin
make fmt       # Formats Go code with go fmt across the entire project
make help      # Help

Testdata validation: make validate automatically verifies that:

  • All good.go: 0 errors (100% compliant)
  • All bad.go: ONLY errors from their specific rule
    • Ex: funcerrlast/bad.go -> only KTN-FUNC-ERRLAST (not KTN-CONST-TYPED, etc.)
  • No redeclarations between good.go and bad.go

See COVERAGE.MD for the detailed coverage report.

VSCode Integration

Automatic linting: The Go extension automatically runs the linter on save (Ctrl+S).

View errors in testdata files:

  1. Open a testdata file (ex: pkg/analyzer/ktn/const/testdata/src/const001/const001.go)
  2. Save (Ctrl+S) -> Errors appear immediately
  3. Open the Problems tab (Ctrl+Shift+M) -> 50 errors detected

Features:

  • Automatic linting (production + testdata)
  • Simple format for VSCode (file:line:col: message (CODE))
  • Errors visible in editor and Problems tab
  • Automatic binary build on each save

Commands:

make lint           # Lint production only (excludes testdata)
make lint-testdata  # Check detection on testdata (784 errors)

Configuration: .vscode/settings.json, .vscode/tasks.json, .vscode/keybindings.json Wrapper: bin/golangci-lint-wrapper (simple format, includes testdata)

Implemented Rules (ordered by criticality)

Comments and Documentation (7 rules) - INFO/WARNING
Code Severity Description
KTN-COMMENT-LINELEN INFO Inline comments too long (>80 characters)
KTN-COMMENT-PKGDOC WARNING Descriptive comment before package
KTN-COMMENT-CONST WARNING Required comment for constants
KTN-COMMENT-VAR WARNING Required comment for package var
KTN-COMMENT-STRUCT WARNING Required documentation for struct (>=2 lines)
KTN-COMMENT-FUNC WARNING Function documentation (Params/Returns)
KTN-COMMENT-BLOCK WARNING Comments on branches/returns/logic
Constants (6 rules) - ERROR/WARNING/INFO
Code Severity Description
KTN-CONST-TYPED ERROR Explicit type required
KTN-CONST-ORDER INFO Grouping and placement before var
KTN-CONST-CAMEL INFO CamelCase naming (no underscores)
KTN-CONST-MINLEN WARNING Unused constants
KTN-CONST-MAXLEN INFO Duplicate constants
KTN-CONST-SHADOW INFO Magic constants (prefer named)
Variables (36 rules) - ERROR/WARNING/INFO
Code Severity Description
KTN-VAR-EXPLICIT WARNING Explicit type required for package var
KTN-VAR-ORDER WARNING Ordered declarations (const before var)
KTN-VAR-CAMEL ERROR Required camelCase naming
KTN-VAR-MINLEN WARNING Min variable length (scope-aware)
KTN-VAR-MAXLEN WARNING Max length 30 characters
KTN-VAR-SHADOW ERROR Variable shadowing detection
KTN-VAR-SHORTDECL INFO := vs var (zero-value aware)
KTN-VAR-SLICECAP INFO Preallocate slices with known capacity
KTN-VAR-MAKEAPPEND INFO Avoid make([]T, length) with append
KTN-VAR-GROW INFO Preallocate bytes.Buffer with Grow
KTN-VAR-STRBUILDER INFO Use strings.Builder for concatenations
KTN-VAR-HOTLOOP WARNING Avoid allocations in hot loops
KTN-VAR-BIGSTRUCT INFO Pointers for structs >64 bytes as parameter
KTN-VAR-SYNCPOOL INFO sync.Pool for repeated buffers
KTN-VAR-STRCONV INFO Avoid repeated string() conversions
KTN-VAR-GROUP INFO Group in a single var() block
KTN-VAR-MAPCAP INFO Preallocate maps with known capacity
KTN-VAR-ARRAY INFO Use [N]T instead of make([]T, N) <=64 bytes
KTN-VAR-MUTEXCOPY ERROR Mutex copies (sync.Mutex, sync.RWMutex)
KTN-VAR-NILSLICE INFO Prefer nil slice to empty slice
KTN-VAR-RECVCONS WARNING Receiver consistency (pointer vs value)
KTN-VAR-PTRINTF WARNING Avoid pointer to interface
KTN-VAR-WEAKRAND WARNING crypto/rand for sensitive data
KTN-VAR-USEANY INFO any vs interface{} (Go 1.18+)
KTN-VAR-USECLEAR INFO Use clear() built-in (Go 1.21+)
KTN-VAR-USEMINMAX INFO Use min()/max() built-in (Go 1.21+)
KTN-VAR-RANGEINT INFO range over integer (Go 1.22+)
KTN-VAR-LOOPVAR INFO Loop var copy obsolete (Go 1.22+)
KTN-VAR-SLICEGROW INFO slices.Grow instead of make+copy (Go 1.21+)
KTN-VAR-SLICECLONE INFO slices.Clone instead of make+copy (Go 1.21+)
KTN-VAR-MAPCLONE INFO maps.Clone instead of manual loop (Go 1.21+)
KTN-VAR-CMPOR INFO cmp.Or for default values (Go 1.22+)
KTN-VAR-WGGO INFO WaitGroup.Go (Go 1.25+)
KTN-VAR-CONTAINS INFO slices.Contains instead of loop (Go 1.21+)
KTN-VAR-INDEX INFO slices.Index instead of loop (Go 1.21+)
KTN-VAR-COLLECTKEYS INFO maps.Keys/Values iterators (Go 1.23+)
Functions (19 rules) - ERROR/WARNING/INFO
Code Severity Description
KTN-FUNC-ERRLAST ERROR Error always in last return position
KTN-FUNC-CTXFIRST ERROR Context always as first parameter
KTN-FUNC-EARLYRET ERROR Avoid else after return/continue/break
KTN-FUNC-DEADCODE ERROR Unused private functions (dead code)
KTN-FUNC-CYCLO ERROR Max cyclomatic complexity 8
KTN-FUNC-MAXLOC ERROR Max 50 lines of code (LOC)
KTN-FUNC-MAXSTMT WARNING Max 35 statements per function
KTN-FUNC-MAXPARAM WARNING Max 5 parameters per function
KTN-FUNC-PUREGET WARNING No side effects in getters
KTN-FUNC-UNUSEDARG WARNING Unused parameters prefixed with _
KTN-FUNC-BLANKPARAM WARNING Blank _ in params must be interface-required
KTN-FUNC-NOMAGIC INFO No magic numbers (use named constants)
KTN-FUNC-NAKEDRET INFO No naked returns (except <5 lines)
KTN-FUNC-NAMERET INFO Named returns for >3 return values
KTN-FUNC-GROUPARG INFO Group parameters of same type
KTN-FUNC-MINMAX INFO Prefer min/max builtins (Go 1.21+)
KTN-FUNC-USECLEAR INFO Use clear() builtin (Go 1.21+)
KTN-FUNC-RANGEINT INFO Use range N (Go 1.22+)
KTN-FUNC-ERRFMT INFO Error message format (lowercase, no period)
Structures (9 rules) - WARNING/INFO
Code Severity Description
KTN-STRUCT-ACCESSOR INFO Getters/setters convention: Field() and SetField()
KTN-STRUCT-CTOR WARNING NewX() constructor required (allowed suffixes: NewXxxWithOption)
KTN-STRUCT-NOGET WARNING No Get prefix for getters
KTN-STRUCT-ONEFILE INFO One Go file per struct (DTOs can be grouped)
KTN-STRUCT-PUBFIRST INFO Field order (exported before private)
KTN-STRUCT-PRIVTAG INFO No serialization tags on private fields
KTN-STRUCT-JSONTAG INFO DTO exported fields without json/xml tags
KTN-STRUCT-RECVTYPE WARNING Receiver type consistency (pointer vs value)
KTN-STRUCT-RECVNAME WARNING Receiver name consistency (1-2 letters, not this/self)

Getters/Setters Convention (STRUCT-ACCESSOR):

  • Getters/setters are OPTIONAL
  • If present: x.Value() for get, x.SetValue(v) for set
  • If getter exists but name != field (ex: Value() returns foo), suggest renaming to Foo()
Tests (20 rules) - ERROR/WARNING/INFO
Code Severity Description
KTN-TEST-SUFFIX ERROR Test files must end with _internal/_external_test.go
KTN-TEST-SETENV ERROR t.Setenv/t.Chdir forbidden with t.Parallel
KTN-TEST-HASGO WARNING Orphan test file (no source file)
KTN-TEST-COVERAGE WARNING Test coverage for public functions
KTN-TEST-TABLE WARNING Table-driven pattern required
KTN-TEST-NOSKIP WARNING t.Skip() forbidden
KTN-TEST-SPLIT WARNING 1:1 pattern for test/source files
KTN-TEST-EXTPUB WARNING Public tests only in _external_test.go
KTN-TEST-INTPRIV WARNING Private tests only in _internal_test.go
KTN-TEST-PKGNAME WARNING Package convention (white-box/black-box)
KTN-TEST-ASSERT WARNING Tests must contain assertions
KTN-TEST-ERRCASES WARNING Tests must cover error cases
KTN-TEST-SUBPARALLEL WARNING Subtests should have t.Parallel when parent does
KTN-TEST-CLEANUP WARNING Use t.Cleanup instead of defer with parallel subtests
KTN-TEST-TMPDIR INFO Prefer t.TempDir() over os.TempDir()
KTN-TEST-CHDIR INFO Prefer t.Chdir() over os.Chdir()
KTN-TEST-TMPFILE INFO Use t.TempDir() in os.CreateTemp
KTN-TEST-MKDIR INFO Use t.TempDir() instead of os.MkdirTemp()
KTN-TEST-CASECNT INFO Number of cases vs cyclomatic complexity
KTN-TEST-PARALLELPOS INFO t.Parallel should be first statement
Interfaces (3 rules) - WARNING/INFO
Code Severity Description
KTN-INTERFACE-UNUSED WARNING Unused interface
KTN-INTERFACE-ERNAME INFO -er convention for single-method interfaces
KTN-INTERFACE-ANYUSE INFO Excessive use of interface{}/any
Goroutines (2 rules) - WARNING
Code Severity Description
KTN-GOROUTINE-DEFER WARNING Immediate defer after resource acquisition
KTN-GOROUTINE-LIFECYCLE WARNING Missing goroutine documentation
Iterators (5 rules) - INFO (Go 1.23+)
Code Severity Description
KTN-ITER-SIGNATURE INFO Invalid iterator signature
KTN-ITER-YIELD INFO Ignored yield return
KTN-ITER-MAPKEYS INFO slices.Collect(maps.Keys()) to collect keys
KTN-ITER-COLLECT INFO slices.Collect for iterators
KTN-ITER-PULLSTOP INFO iter.Pull must have defer stop()
Receivers (4 rules) - WARNING/INFO
Code Severity Description
KTN-RECEIVER-MIXPTR ERROR Mixed receivers (pointer/value) on same type
KTN-RECEIVER-NAME INFO Receiver name 1-2 chars, not this/self/me
KTN-RECEIVER-GENERIC WARNING Inconsistent generic receivers
KTN-RECEIVER-PTRMAP WARNING Unnecessary pointer to map/func/chan
API (1 rule) - WARNING
Code Severity Description
KTN-API-MINIF WARNING Minimal interfaces on consumer side for external dependencies
Generics (5 rules) - ERROR/WARNING/INFO (Go 1.18+)
Code Severity Description
KTN-GENERIC-CMPEQ ERROR Comparable constraint required for == and !=
KTN-GENERIC-NOANY WARNING Unnecessary generics on interface types
KTN-GENERIC-USECMP WARNING golang.org/x/exp/constraints deprecated -> cmp
KTN-GENERIC-SHADOW WARNING Type params must not shadow predeclared identifiers
KTN-GENERIC-ORDERED ERROR cmp.Ordered constraint required for <, >, +, -, *, /, %
Modernize (17 active rules / 18 total) golang.org/x/tools

Official Go analyzer suite to modernize code with the latest language and stdlib features:

Go 1.18+

  • any: interface{}any

Go 1.21+

  • minmax: if a > b { return a }max(a, b)
  • slicescontains: Manual loop -> slices.Contains()
  • slicessort: sort.Slice()slices.Sort()
  • slicesdelete: append(a[:i], a[i+1:]...)slices.Delete()

Go 1.22+

  • rangeint: for i := 0; i < n; i++for range n
  • forvar: Removes unnecessary x := x in loops
  • reflecttypefor: reflect.TypeOf(T{})reflect.TypeFor[T]()

Go 1.23+

  • mapsloop: Manual loop -> maps.Keys/Values()
  • stditerators: Modernize to stdlib iterators
  • stringsseq: Modernize string manipulation

Go 1.24+

  • bloop: for b.Nb.Loop()
  • testingcontext: Manual context -> t.Context()

General optimizations

  • fmtappendf: append(x, fmt.Sprintf(...)) -> fmt.Appendf()
  • stringsbuilder: Concatenation += -> strings.Builder
  • stringscutprefix: HasPrefix+TrimPrefix -> CutPrefix()
  • omitzero: Removes redundant zero values
  • waitgroup: Manual pattern -> wg.Go()

Disabled analyzers (known bugs or instability):

  • newexpr: &T{} -> new(T) (disabled: panic in some cases)

Update: go get -u golang.org/x/tools/go/analysis/passes/modernize@latest && go mod tidy

Statistics

  • Global coverage: 96.6%
  • 100% packages: utils, formatter, severity, prompt, testhelper, rules
  • Go version: 1.25+
  • Total KTN rules: 161 (1 api + 7 comment + 6 const + 19 func + 5 generic + 2 goroutine + 3 interface + 5 iter + 4 receiver + 9 struct + 20 test + 36 var + 25 govet + 17 modernize)
  • Detailed report: See COVERAGE.MD

Structure

/workspace/
├── cmd/ktn-linter/     # Binary
├── pkg/analyzer/       # Analysis rules
└── pkg/formatter/      # Output formatting

Directories

Path Synopsis
cmd
ktn-linter command
Package main provides the entry point for the ktn-linter CLI tool.
Package main provides the entry point for the ktn-linter CLI tool.
ktn-linter/cmd
Package cmd implements the CLI commands for ktn-linter.
Package cmd implements the CLI commands for ktn-linter.
pkg
analyzer/govet
Package govet wraps golang.org/x/tools go vet analyzers.
Package govet wraps golang.org/x/tools go vet analyzers.
analyzer/ktn
Package ktn provides the master registry for all KTN lint rules.
Package ktn provides the master registry for all KTN lint rules.
analyzer/ktn/ktnapi
Package ktnapi provides analyzers for API design lint rules.
Package ktnapi provides analyzers for API design lint rules.
analyzer/ktn/ktncomment
Package ktncomment provides analyzers for comment formatting rules.
Package ktncomment provides analyzers for comment formatting rules.
analyzer/ktn/ktnconst
Package ktnconst implements KTN linter rules.
Package ktnconst implements KTN linter rules.
analyzer/ktn/ktnerror
Package ktnerror provides analyzers for error handling rules.
Package ktnerror provides analyzers for error handling rules.
analyzer/ktn/ktnfunc
Package ktnfunc provides analyzers for function-related lint rules.
Package ktnfunc provides analyzers for function-related lint rules.
analyzer/ktn/ktngeneric
Package ktngeneric implements KTN linter rules for generic functions.
Package ktngeneric implements KTN linter rules for generic functions.
analyzer/ktn/ktngoroutine
Package ktngoroutine provides analyzers for goroutine-related lint rules.
Package ktngoroutine provides analyzers for goroutine-related lint rules.
analyzer/ktn/ktninterface
Package ktninterface provides analyzers for interface-related lint rules.
Package ktninterface provides analyzers for interface-related lint rules.
analyzer/ktn/ktniter
Package ktniter provides analyzers for Go 1.23+ iterator lint rules.
Package ktniter provides analyzers for Go 1.23+ iterator lint rules.
analyzer/ktn/ktnreceiver
Package ktnreceiver provides analyzers for method receiver lint rules.
Package ktnreceiver provides analyzers for method receiver lint rules.
analyzer/ktn/ktnstruct
Package ktnstruct provides analyzers for struct-related lint rules.
Package ktnstruct provides analyzers for struct-related lint rules.
analyzer/ktn/ktnswitch
Package ktnswitch provides analyzers for switch statement rules.
Package ktnswitch provides analyzers for switch statement rules.
analyzer/ktn/ktntest
Package ktntest provides analyzers for test file lint rules.
Package ktntest provides analyzers for test file lint rules.
analyzer/ktn/ktnvar
Package ktnvar provides analyzers for variable-related lint rules.
Package ktnvar provides analyzers for variable-related lint rules.
analyzer/ktn/testhelper
Package testhelper implements KTN linter rules.
Package testhelper implements KTN linter rules.
analyzer/modernize
Package modernize wraps golang.org/x/tools modernize analyzers.
Package modernize wraps golang.org/x/tools modernize analyzers.
analyzer/shared
Package shared provides common utilities for static analysis.
Package shared provides common utilities for static analysis.
analyzer/utils
Package utils provides AST utility functions for analyzers.
Package utils provides AST utility functions for analyzers.
cache
Package cache provides file analysis caching to avoid re-scanning unchanged files.
Package cache provides file analysis caching to avoid re-scanning unchanged files.
config
Package config provides configuration management for KTN linter rules.
Package config provides configuration management for KTN linter rules.
formatter
Package formatter provides output formatting for lint diagnostics.
Package formatter provides output formatting for lint diagnostics.
messages
Package messages provides structured error messages for KTN rules.
Package messages provides structured error messages for KTN rules.
orchestrator
Package orchestrator coordinates the linting pipeline.
Package orchestrator coordinates the linting pipeline.
prompt
Package prompt provides AI-optimized prompt generation for KTN linter violations.
Package prompt provides AI-optimized prompt generation for KTN linter violations.
rules
Package rules provides rule information extraction and formatting utilities.
Package rules provides rule information extraction and formatting utilities.
severity
Package severity defines severity levels for lint rules.
Package severity defines severity levels for lint rules.
updater
Package updater provides self-update functionality for ktn-linter binary.
Package updater provides self-update functionality for ktn-linter binary.

Jump to

Keyboard shortcuts

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