ktn-linter

module
v1.3.91 Latest Latest
Warning

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

Go to latest
Published: Jan 10, 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-005:
    enabled: true
    threshold: 50          # Max lines (default: 35)
    exclude:
      - "cmd/**"           # Exclude for this rule

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

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

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

Rules with configurable thresholds:

Rule Parameter Default
KTN-COMMENT-001 maxCommentLength 80
KTN-COMMENT-002 minPackageCommentLength 3
KTN-COMMENT-005 minStructDocLines 2
KTN-FUNC-005 maxFunctionLength 35
KTN-FUNC-006 maxParameters 5
KTN-FUNC-010 maxReturnValues 3
KTN-FUNC-011 maxCyclomaticComplexity 8
KTN-FUNC-012 maxNestedDepth 4
KTN-VAR-009 maxScopeLines 50
KTN-VAR-012 maxLineLength 120
KTN-VAR-016 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: func001/bad.go -> only KTN-FUNC-001 (not KTN-CONST-001, 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-001 INFO Inline comments too long (>80 characters)
KTN-COMMENT-002 WARNING Descriptive comment before package
KTN-COMMENT-003 WARNING Required comment for constants
KTN-COMMENT-004 WARNING Required comment for package var
KTN-COMMENT-005 WARNING Required documentation for struct (>=2 lines)
KTN-COMMENT-006 WARNING Function documentation (Params/Returns)
KTN-COMMENT-007 WARNING Comments on branches/returns/logic
Constants (6 rules) - ERROR/WARNING/INFO
Code Severity Description
KTN-CONST-001 ERROR Explicit type required
KTN-CONST-002 INFO Grouping and placement before var
KTN-CONST-003 INFO CamelCase naming (no underscores)
KTN-CONST-004 WARNING Unused constants
KTN-CONST-005 INFO Duplicate constants
KTN-CONST-006 INFO Magic constants (prefer named)
Variables (36 rules) - ERROR/WARNING/INFO
Code Severity Description
KTN-VAR-001 WARNING Explicit type required for package var
KTN-VAR-002 WARNING Ordered declarations (const before var)
KTN-VAR-003 ERROR Required camelCase naming
KTN-VAR-004 WARNING Min variable length (scope-aware)
KTN-VAR-005 WARNING Max length 30 characters
KTN-VAR-006 ERROR Variable shadowing detection
KTN-VAR-007 INFO := vs var (zero-value aware)
KTN-VAR-008 INFO Preallocate slices with known capacity
KTN-VAR-009 INFO Avoid make([]T, length) with append
KTN-VAR-010 INFO Preallocate bytes.Buffer with Grow
KTN-VAR-011 INFO Use strings.Builder for concatenations
KTN-VAR-012 WARNING Avoid allocations in hot loops
KTN-VAR-013 INFO Pointers for structs >64 bytes as parameter
KTN-VAR-014 INFO sync.Pool for repeated buffers
KTN-VAR-015 INFO Avoid repeated string() conversions
KTN-VAR-016 INFO Group in a single var() block
KTN-VAR-017 INFO Preallocate maps with known capacity
KTN-VAR-018 INFO Use [N]T instead of make([]T, N) <=64 bytes
KTN-VAR-019 ERROR Mutex copies (sync.Mutex, sync.RWMutex)
KTN-VAR-020 INFO Prefer nil slice to empty slice
KTN-VAR-021 WARNING Receiver consistency (pointer vs value)
KTN-VAR-022 WARNING Avoid pointer to interface
KTN-VAR-023 WARNING crypto/rand for sensitive data
KTN-VAR-024 INFO any vs interface{} (Go 1.18+)
KTN-VAR-025 INFO Use clear() built-in (Go 1.21+)
KTN-VAR-026 INFO Use min()/max() built-in (Go 1.21+)
KTN-VAR-027 INFO range over integer (Go 1.22+)
KTN-VAR-028 INFO Loop var copy obsolete (Go 1.22+)
KTN-VAR-029 INFO slices.Grow instead of make+copy (Go 1.21+)
KTN-VAR-030 INFO slices.Clone instead of make+copy (Go 1.21+)
KTN-VAR-031 INFO maps.Clone instead of manual loop (Go 1.21+)
KTN-VAR-033 INFO cmp.Or for default values (Go 1.22+)
KTN-VAR-034 INFO WaitGroup.Go (Go 1.25+)
KTN-VAR-035 INFO slices.Contains instead of loop (Go 1.21+)
KTN-VAR-036 INFO slices.Index instead of loop (Go 1.21+)
KTN-VAR-037 INFO maps.Keys/Values iterators (Go 1.23+)
Functions (17 rules) - ERROR/WARNING/INFO
Code Severity Description
KTN-FUNC-001 ERROR Error always in last return position
KTN-FUNC-002 ERROR Context always as first parameter
KTN-FUNC-003 ERROR Avoid else after return/continue/break
KTN-FUNC-004 ERROR Unused private functions (dead code)
KTN-FUNC-005 WARNING Max 35 lines of pure code
KTN-FUNC-006 WARNING Max 5 parameters per function
KTN-FUNC-007 WARNING No side effects in getters
KTN-FUNC-008 WARNING Unused parameters prefixed with _
KTN-FUNC-009 INFO No magic numbers (use named constants)
KTN-FUNC-010 INFO No naked returns (except <5 lines)
KTN-FUNC-011 INFO Max cyclomatic complexity 10
KTN-FUNC-012 INFO Named returns for >3 return values
KTN-FUNC-013 WARNING Prefer empty slice/map to nil
KTN-FUNC-014 INFO Prefer min/max builtins (Go 1.21+)
KTN-FUNC-015 INFO Use clear() builtin (Go 1.21+)
KTN-FUNC-016 INFO Use range N (Go 1.22+)
KTN-FUNC-017 INFO Error message format (lowercase, no period)
Structures (9 rules) - WARNING/INFO
Code Severity Description
KTN-STRUCT-001 INFO Getters/setters convention: Field() and SetField()
KTN-STRUCT-002 WARNING NewX() constructor required (allowed suffixes: NewXxxWithOption)
KTN-STRUCT-003 WARNING No Get prefix for getters
KTN-STRUCT-004 INFO One Go file per struct (DTOs can be grouped)
KTN-STRUCT-005 INFO Field order (exported before private)
KTN-STRUCT-006 INFO No serialization tags on private fields
KTN-STRUCT-007 INFO DTO exported fields without json/xml tags
KTN-STRUCT-008 WARNING Receiver type consistency (pointer vs value)
KTN-STRUCT-009 WARNING Receiver name consistency (1-2 letters, not this/self)

Getters/Setters Convention (STRUCT-001):

  • 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 (12 rules) - ERROR/WARNING/INFO
Code Severity Description
KTN-TEST-001 ERROR Test files must end with _internal/_external_test.go
KTN-TEST-002 WARNING Orphan test file (no source file)
KTN-TEST-003 WARNING Test coverage for public functions
KTN-TEST-004 WARNING Table-driven pattern required
KTN-TEST-005 WARNING t.Skip() forbidden
KTN-TEST-006 WARNING 1:1 pattern for test/source files
KTN-TEST-007 WARNING Public tests only in _external_test.go
KTN-TEST-008 WARNING Private tests only in _internal_test.go
KTN-TEST-009 WARNING Package convention (white-box/black-box)
KTN-TEST-010 WARNING Tests must contain assertions
KTN-TEST-011 WARNING Tests must cover error cases
KTN-TEST-012 INFO Number of cases vs cyclomatic complexity
Interfaces (3 rules) - WARNING/INFO
Code Severity Description
KTN-INTERFACE-001 WARNING Unused interface
KTN-INTERFACE-003 INFO -er convention for single-method interfaces
KTN-INTERFACE-004 INFO Excessive use of interface{}/any
Goroutines (2 rules) - WARNING
Code Severity Description
KTN-GOROUTINE-001 WARNING Immediate defer after resource acquisition
KTN-GOROUTINE-002 WARNING Missing goroutine documentation
Iterators (5 rules) - INFO (Go 1.23+)
Code Severity Description
KTN-ITER-001 INFO Invalid iterator signature
KTN-ITER-002 INFO Ignored yield return
KTN-ITER-003 INFO slices.Collect(maps.Keys()) to collect keys
KTN-ITER-004 INFO slices.Collect for iterators
KTN-ITER-005 INFO iter.Pull must have defer stop()
Receivers (4 rules) - WARNING/INFO
Code Severity Description
KTN-RECEIVER-001 ERROR Mixed receivers (pointer/value) on same type
KTN-RECEIVER-002 INFO Receiver name 1-2 chars, not this/self/me
KTN-RECEIVER-003 WARNING Inconsistent generic receivers
KTN-RECEIVER-004 WARNING Unnecessary pointer to map/func/chan
API (1 rule) - WARNING
Code Severity Description
KTN-API-001 WARNING Minimal interfaces on consumer side for external dependencies
Generics (5 rules) - ERROR/WARNING/INFO (Go 1.18+)
Code Severity Description
KTN-GENERIC-001 ERROR Comparable constraint required for == and !=
KTN-GENERIC-002 WARNING Unnecessary generics on interface types
KTN-GENERIC-003 WARNING golang.org/x/exp/constraints deprecated -> cmp
KTN-GENERIC-005 WARNING Type params must not shadow predeclared identifiers
KTN-GENERIC-006 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: 93.9%
  • 100% packages: utils, formatter, ktn, ktnconst, modernize, severity
  • Go version: 1.25+
  • Total KTN rules: 107 (7 comment + 6 const + 17 func + 5 generic + 2 goroutine + 3 interface + 5 iter + 4 receiver + 9 struct + 12 test + 36 var + 1 api)
  • Total modernize: 17 active analyzers / 18 total
  • 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/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 implements KTN linter rules for error handling.
Package ktnerror implements KTN linter rules for error handling.
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/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.
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