perf(reporters): вычислять метрики документов только при необходимости#4278
Conversation
Добавлен метод DiagnosticReporter#isMetricCalculationRequired (по умолчанию false); true возвращает только JsonReporter, который действительно сохраняет метрики в отчёт. ReportersAggregator агрегирует признак по активным репортерам, а AnalyzeCommand вызывает DocumentContext#getMetrics лишь тогда, когда метрики нужны хотя бы одному активному репортеру. Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_011gTyREUsxuGJVkkbmMcsx7
📝 WalkthroughWalkthroughChangesThe analysis command now calculates document metrics only when an active reporter requires them. Reporter implementations declare this requirement through a new interface method, and tests cover reporter defaults, aggregation, and both analysis paths. Conditional metric calculation
Estimated code review effort: 3 (Moderate) | ~20 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
ConsoleReporter выводит FileInfo целиком (включая MetricStorage) через toString, поэтому без метрик печатал бы metrics=null. Добавлено переопределение isMetricCalculationRequired() -> true. Тесты обновлены: console теперь требует метрики, значение по умолчанию false проверяется на не переопределяющем репортере (tslint). Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_011gTyREUsxuGJVkkbmMcsx7
89bcb1c to
49054f0
Compare
…й тест - признак isMetricCalculationRequired для каждого репортера — в его *ReporterTest (json/console -> true; generic/junit/code-quality/sarif/tslint -> false); - агрегирование признака по активным репортерам — @nested в ReportersAggregatorTest (пусто/без метрик -> false; хотя бы один требует -> true); - интеграционная проверка условного вычисления метрик — в AnalyzeCommandTest (метрики нужны -> FileInfo.metrics != null; не нужны -> null). Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_011gTyREUsxuGJVkkbmMcsx7
fcb7ced to
e9accaf
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/DiagnosticReporter.java (1)
49-61: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove calling scenarios from Javadoc.
As per coding guidelines, Javadoc should describe the contract of a method, not calling scenarios or who invokes it. The sentence
Это позволяет пропустить вычисление метрик, если ни один из активных репортеров их не использует.explains how the caller uses the method rather than its contract.♻️ Proposed fix
* Признак того, что репортеру для формирования отчета необходимы метрики документов. * <p> * Значение по умолчанию — {`@code` false}. Переопределяется в {`@code` true} только теми - * репортерами, которые действительно включают метрики в отчет (в файл или иной вывод). - * Это позволяет пропустить вычисление метрик, если ни один из активных репортеров их не использует. + * репортерами, которые действительно включают метрики в отчет (в файл или иной вывод). * * `@return` {`@code` true}, если репортеру нужны метрики документов, иначе {`@code` false} */🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/DiagnosticReporter.java` around lines 49 - 61, Remove the caller-oriented sentence from the Javadoc of DiagnosticReporter.isMetricCalculationRequired(), keeping only the method’s contract, default value, and meaning of a true result.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In
`@src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/DiagnosticReporter.java`:
- Around line 49-61: Remove the caller-oriented sentence from the Javadoc of
DiagnosticReporter.isMetricCalculationRequired(), keeping only the method’s
contract, default value, and meaning of a true result.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: d9630220-f885-431a-b79d-ab9f682e1b7a
📒 Files selected for processing (11)
src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/ConsoleReporter.javasrc/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/DiagnosticReporter.javasrc/test/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommandTest.javasrc/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/CodeQualityReporterTest.javasrc/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/ConsoleReporterTest.javasrc/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/GenericReporterTest.javasrc/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/JUnitReporterTest.javasrc/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/JsonReporterTest.javasrc/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/ReportersAggregatorTest.javasrc/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/SarifReporterTest.javasrc/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/TSLintReporterTest.java
🚧 Files skipped from review as they are similar to previous changes (2)
- src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/ConsoleReporterTest.java
- src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/ConsoleReporter.java
Описание
Раньше при пакетном анализе (
analyze) метрики документа (DocumentContext#getMetrics) вычислялись для каждого файла безусловно, хотя дорогое ленивое вычисление нужно лишь тем репортерам, что действительно включают метрики в свой вывод.Изменения:
DiagnosticReporterдобавлен метод с реализацией по умолчаниюboolean isMetricCalculationRequired()→false.trueвозвращают репортеры, реально включающие метрики в отчёт:JsonReporter(json) — сериализует весьAnalysisInfo(включаяFileInfo.metrics) в файл;ConsoleReporter(console) — печатаетFileInfoцеликом (черезtoString, включаяMetricStorage) в вывод; без метрик выводил быmetrics=null.generic,junit,code-quality,sarif,tslint) используют только диагностики и остаются на значении по умолчаниюfalse.ReportersAggregator#isMetricCalculationRequired()агрегирует признак по активным (отфильтрованным опцией--reporter) репортерам.AnalyzeCommandвызываетgetMetrics()только если этого требует хотя бы один активный репортер; иначе вFileInfoпередаётсяnull(поле помечено@JsonInclude(NON_NULL)).Связанные задачи
Closes
Чеклист
Общие
gradlew precommit)Для диагностик
Дополнительно
Тесты — по существующим классам:
isMetricCalculationRequired()для каждого репортера — в его же*ReporterTest:json/console→true;generic/junit/code-quality/sarif/tslint→false;@Nested-группа вReportersAggregatorTest: пусто →false, все без метрик →false, хотя бы один требует →true,console→true;AnalyzeCommandTest: активен репортёр с метриками →FileInfo.metrics != nullдля всех файлов; активен только репортёр без метрик →FileInfo.metrics == null(вычисление пропущено).End-to-end проверка (собран
-exec.jar, прогнанanalyzeна тестовом модуле):-r json→ вbsl-json.jsonметрики присутствуют и корректны (procedures:1, functions:1, statements:4, cyclomaticComplexity:3).-r console: сравнение сборок до/после — раньшеmetrics=null, теперьmetrics=MetricStorage(procedures=1, functions=1, …, cyclomaticComplexity=3).-r generic|tslint|junit|code-quality|sarifпо отдельности → отчёты формируются,exit=0, ошибок нет.Итоговая классификация: метрики требуют
jsonиconsole; не требуют —generic,junit,code-quality,sarif,tslint.Замечание по локальному прогону: полный
gradlew check/precommitв среде выполнить не удалось (проект требует Gradle 9.6.1, дистрибутив которого недоступен из-за сетевой политики). Прогнаны целевые тесты репортеров,ReportersAggregatorTestиAnalyzeCommandTest+ ручная end-to-end проверка. Полный прогон выполнит CI.🤖 Generated with Claude Code
Summary by CodeRabbit
Performance
Tests