Skip to content

perf(reporters): вычислять метрики документов только при необходимости#4278

Merged
nixel2007 merged 3 commits into
developfrom
claude/reporter-metric-calculation-fldux6
Jul 16, 2026
Merged

perf(reporters): вычислять метрики документов только при необходимости#4278
nixel2007 merged 3 commits into
developfrom
claude/reporter-metric-calculation-fldux6

Conversation

@nixel2007

@nixel2007 nixel2007 commented Jul 16, 2026

Copy link
Copy Markdown
Member

Описание

Раньше при пакетном анализе (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

Чеклист

Общие

  • Ветка PR обновлена из develop
  • Отладочные, закомментированные и прочие, не имеющие смысла участки кода удалены
  • Изменения покрыты тестами
  • Обязательные действия перед коммитом выполнены (запускал команду gradlew precommit)

Для диагностик

  • Не применимо — диагностики не затронуты

Дополнительно

Тесты — по существующим классам:

  • признак isMetricCalculationRequired() для каждого репортера — в его же *ReporterTest: json/consoletrue; generic/junit/code-quality/sarif/tslintfalse;
  • агрегирование признака по активным репортерам — @Nested-группа в ReportersAggregatorTest: пусто → false, все без метрик → false, хотя бы один требует → true, consoletrue;
  • интеграционная (verify) проверка условного вычисления — в 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

    • Analysis now calculates file metrics only when an active report format requires them.
    • Analysis can complete faster when metrics are not needed, while preserving metrics for console and JSON reports.
  • Tests

    • Added coverage verifying metric calculation across supported report formats and analysis scenarios.

Добавлен метод 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
@coderabbitai

coderabbitai Bot commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

The 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

Layer / File(s) Summary
Reporter metric requirement contract
src/main/java/.../reporters/*.java, src/test/java/.../reporters/*Test.java
DiagnosticReporter provides a false default; JsonReporter and ConsoleReporter return true; ReportersAggregator checks active reporters. Reporter tests cover these behaviors.
Conditional analysis metric retrieval
src/main/java/.../cli/AnalyzeCommand.java, src/test/java/.../cli/AnalyzeCommandTest.java
AnalyzeCommand passes the aggregated requirement through file processing and supplies either computed or null metrics. Tests verify both outcomes.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed Title accurately summarizes the main change: document metrics are computed only when needed.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/reporter-metric-calculation-fldux6

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

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
@nixel2007
nixel2007 force-pushed the claude/reporter-metric-calculation-fldux6 branch from 89bcb1c to 49054f0 Compare July 16, 2026 08:29
@github-actions

Copy link
Copy Markdown
Contributor

Test Results

 3 660 files  +12   3 660 suites  +12   1h 42m 42s ⏱️ - 4m 23s
 3 629 tests +13   3 611 ✅ +13   18 💤 ±0  0 ❌ ±0 
21 774 runs  +78  21 662 ✅ +78  112 💤 ±0  0 ❌ ±0 

Results for commit fcb7ced. ± Comparison against base commit ef1aaef.

…й тест

- признак 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
@nixel2007
nixel2007 force-pushed the claude/reporter-metric-calculation-fldux6 branch from fcb7ced to e9accaf Compare July 16, 2026 10:51

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/DiagnosticReporter.java (1)

49-61: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove 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

📥 Commits

Reviewing files that changed from the base of the PR and between 89bcb1c and e9accaf.

📒 Files selected for processing (11)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/ConsoleReporter.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/DiagnosticReporter.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommandTest.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/CodeQualityReporterTest.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/ConsoleReporterTest.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/GenericReporterTest.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/JUnitReporterTest.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/JsonReporterTest.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/ReportersAggregatorTest.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/SarifReporterTest.java
  • src/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

@nixel2007
nixel2007 enabled auto-merge July 16, 2026 11:15
@nixel2007
nixel2007 disabled auto-merge July 16, 2026 11:17
@nixel2007
nixel2007 merged commit 70f73aa into develop Jul 16, 2026
34 checks passed
@nixel2007
nixel2007 deleted the claude/reporter-metric-calculation-fldux6 branch July 16, 2026 11:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants