entrolint

module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 4, 2026 License: Apache-2.0

README

entrolint

Code rots toward disorder. entrolint measures the entropy — and keeps it from growing on every PR.

entrolint оценивает качество и сложность поддержки кода через метафору энтропии из статистической физики. Чистый, упорядоченный, легко изменяемый код — это система с низкой энтропией. Запутанный, сильно связанный, трудно поддерживаемый код — система с высокой энтропией.

И как во втором начале термодинамики, энтропия кодовой базы без вмешательства только растёт. Задача entrolint — измерять её и не давать ей расти незаметно.

Зачем

Обычные линтеры ловят отдельные нарушения стиля. entrolint смотрит на картину целиком: даёт одно число — энтропию — которое отражает, насколько тяжело будет поддерживать этот код, и показывает, как это число меняется с каждым изменением.

Два режима

scan — карта температур всей репы

Проходит по кодовой базе, считает энтропийный балл (S) для каждого файла и пакета и подсвечивает горячие точки (hotspots) — места с самой высокой энтропией. Это первые кандидаты на рефакторинг.

check — гейт на пулл-реквест

Считает ΔS (дельту энтропии) между base и head: повысило изменение беспорядок или понизило. Встраивается в CI и не пропускает PR, которые ухудшают поддерживаемость сверх заданного порога.

Положительная ΔS = код стало тяжелее поддерживать.

Быстрый старт

# Самые «горячие» 10 файлов репы:
entrolint scan --top 10

# Гейт на PR: сравнить feature-ветку с dev, провалиться при превышении порога.
entrolint check --base dev --head HEAD

# Машино-читаемый отчёт для CI / PR-бота:
entrolint check --base origin/dev --head HEAD --json > delta.json

scan печатает таблицу со столбцами PATH | S | T | DOMINANT. check печатает строку вердикта (PASS/FAIL) + разложение по файлам и возвращает exit code 1 при превышении delta_s_max.

Конфигурация

.entrolint.yaml в корне репозитория (опционально — без файла используются дефолты):

weights:
  cyclomatic: 1.0
  nesting:    0.8
  length:     0.5
delta_s_max:       0.05   # порог ΔS_density для check
churn_since_days:  90     # окно для churn-фактора (входит в T, не в S)

Модель энтропии

Энтропия складывается из взвешенной суммы «микросостояний» — отдельных измеримых факторов беспорядка. В духе формулы Больцмана S = k · ln(W): чем больше число способов, которыми код может быть запутан, тем выше энтропия.

В v0.1 микросостояния, входящие в S:

Микросостояние О чём
Цикломатическая сложность сколько ветвлений в коде
Глубина вложенности насколько глубоко вложены блоки
Длина функций / файлов размер единиц кода

Churn (как часто файл меняется) входит в температуру T = S · ξ(churn) — горячими становятся не просто сложные, а ещё и часто переписываемые места.

Планируется (см. ROADMAP):

Микросостояние Когда
Scaling class (O(…)) v0.2 ✅ — предсказательный слой
Связанность (coupling) v0.3 — графовая метрика по импортам
Дублирование v0.3 — хеширование AST-поддеревьев

Терминология

  • Энтропия (S) — мера беспорядка и сложности поддержки. Выше = хуже.
  • ΔS — изменение энтропии, вносимое пулл-реквестом.
  • Горячая точка (hotspot) — файл или пакет с высокой энтропией.
  • Микросостояние — отдельный фактор, вносящий вклад в S.
  • Температура — нормализованная энтропия файла для визуализации карты.

Статус

📦 v0.2 — к scan/check добавлен предсказательный слой: детекторы O-классов (shotgun, implementor_scan, switch_case_symmetry, identifier_fanout, state_multiplier) дают строку scaling_class рядом с ΔS. Формула, веса и порог считаются нестабильными до v1.0 — между релизами числа S могут смещаться.

Лицензия

MIT (см. LICENSE).

Directories

Path Synopsis
cmd
entrolint command
internal
cli
Package cli wires the entrolint command tree.
Package cli wires the entrolint command tree.
engine/analyzer/golang
Package golang walks a Go module/directory and produces parsed microstate.File values ready for scoring.
Package golang walks a Go module/directory and produces parsed microstate.File values ready for scoring.
engine/cache
Package cache persists thermo calibration parameters to `.entrolint.cache.json` so subsequent scans don't have to refit the lognormal distributions or recompute k.
Package cache persists thermo calibration parameters to `.entrolint.cache.json` so subsequent scans don't have to refit the lognormal distributions or recompute k.
engine/config
Package config loads entrolint's per-repo configuration from `.entrolint.yaml`.
Package config loads entrolint's per-repo configuration from `.entrolint.yaml`.
engine/gitx
Package gitx wraps the local git operations entrolint needs.
Package gitx wraps the local git operations entrolint needs.
engine/microstate
Package microstate defines the contract for entrolint entropy contributors and provides the per-microstate implementations.
Package microstate defines the contract for entrolint entropy contributors and provides the per-microstate implementations.
engine/pipeline
Package pipeline orchestrates the entrolint analysis end-to-end: walks the source tree, computes microstates, calibrates the thermo engine (or loads cached calibration), and produces ranked file scores.
Package pipeline orchestrates the entrolint analysis end-to-end: walks the source tree, computes microstates, calibrates the thermo engine (or loads cached calibration), and produces ranked file scores.
engine/thermo
Package thermo implements the entrolint v0.1 entropy formula: S = k · Σᵢ wᵢ · ln(1 + mᵢ_norm), with per-microstate self- calibrated lognormal-CDF normalization and k chosen so that the median file scores S = 1.
Package thermo implements the entrolint v0.1 entropy formula: S = k · Σᵢ wᵢ · ln(1 + mᵢ_norm), with per-microstate self- calibrated lognormal-CDF normalization and k chosen so that the median file scores S = 1.
scaling
Package scaling computes the predictive scaling class (O-notation) of a PR alongside the descriptive ΔS.
Package scaling computes the predictive scaling class (O-notation) of a PR alongside the descriptive ΔS.
scaling/detectors/identifierfanout
Package identifierfanout detects PRs that touch ≥ TouchedRatio of the call-sites of an exported symbol the PR also defines — the O(refs) shape from docs/scaling.md.
Package identifierfanout detects PRs that touch ≥ TouchedRatio of the call-sites of an exported symbol the PR also defines — the O(refs) shape from docs/scaling.md.
scaling/detectors/implementorscan
Package implementorscan detects PRs that ripple through ≥ a configurable fraction of an interface's implementors — the canonical O(implementors) shape from docs/scaling.md.
Package implementorscan detects PRs that ripple through ≥ a configurable fraction of an interface's implementors — the canonical O(implementors) shape from docs/scaling.md.
scaling/detectors/shotgun
Package shotgun detects scatter-PR patterns: one logical change scattered across ≥ MinFiles Go files with no common AST parent.
Package shotgun detects scatter-PR patterns: one logical change scattered across ≥ MinFiles Go files with no common AST parent.
scaling/detectors/statemultiplier
Package statemultiplier detects PRs that add a state-multiplying parameter (bool or enum-typed) to an exported function or method — the O(2ⁿ) shape from docs/scaling.md.
Package statemultiplier detects PRs that add a state-multiplying parameter (bool or enum-typed) to an exported function or method — the O(2ⁿ) shape from docs/scaling.md.
scaling/detectors/switchsymmetry
Package switchsymmetry detects PRs that touch ≥ a configurable fraction of `switch` statements over the same enum-like named type — the O(switch arms) shape from docs/scaling.md.
Package switchsymmetry detects PRs that touch ≥ a configurable fraction of `switch` statements over the same enum-like named type — the O(switch arms) shape from docs/scaling.md.
scaling/typesx
Package typesx provides the shared go/types loading and lookup helpers used by every typed scaling detector.
Package typesx provides the shared go/types loading and lookup helpers used by every typed scaling detector.
version
Package version exposes build-time identification.
Package version exposes build-time identification.

Jump to

Keyboard shortcuts

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