Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Репортер в CodeQuality #3424

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from

Conversation

nixel2007
Copy link
Member

@nixel2007 nixel2007 commented Feb 20, 2025

Описание

Связанные задачи

Closes #3419

Чеклист

Общие

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

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

  • Описание диагностики заполнено для обоих языков (присутствуют файлы для обоих языков, для русского заполнено все подробно, перевод на английский можно опустить)

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

Copy link
Contributor

coderabbitai bot commented Feb 20, 2025

"""

Walkthrough

В этом пул-реквесте произведены изменения, касающиеся зависимостей проекта, документации и реализации нового отчётчика качества кода. В файле build.gradle.kts добавлена зависимость commons-codec и восстановлена commons-lang3. Документация расширена за счёт добавления нового репортера с ключом code-quality. Новый функционал реализован через классы CodeQualityReportEntry и CodeQualityReporter, которые собирают, обрабатывают и сериализуют данные диагностики в JSON-файл. Также добавлены тесты для проверки корректности работы нового функционала.

Changes

Файл(ы) Изменения
build.gradle.kts Добавлена зависимость commons-codec:1.16.0 и восстановлена зависимость commons-lang3:3.17.0.
docs/reporters/code-quality.md
docs/reporters/index.md
Добавлен новый репортер "code-quality" и обновлён список репортеров в документации.
src/main/java/com/.../reporters/CodeQualityReportEntry.java
src/main/java/com/.../reporters/CodeQualityReporter.java
Добавлены классы для отчёта качества кода: CodeQualityReportEntry (с внутренними классами и enum'ом) и CodeQualityReporter для генерации JSON-отчёта.
src/test/java/com/.../reporters/CodeQualityReportEntryTest.java
src/test/java/com/.../reporters/CodeQualityReporterTest.java
Добавлены тестовые классы для проверки корректности работы нового функционала отчётов по качеству кода.

Sequence Diagram(s)

sequenceDiagram
    participant A as AnalysisInfo
    participant R as CodeQualityReporter
    participant E as CodeQualityReportEntry
    participant OM as ObjectMapper
    participant F as "bsl-code-quality.json"

    A->>R: Передать данные анализа
    R->>E: Создать записи отчёта на основе диагностик
    R->>OM: Сериализовать список записей в JSON
    OM->>F: Записать JSON-отчёт в файл
    R->>Log: Логирование места сохранения отчёта
Loading

Possibly related PRs

  • Update dependencies #3306: В этом PR произведены изменения, связанные с восстановлением зависимости commons-lang3, что перекликается с текущими модификациями.
  • Fix tests, dependency updates #3361: Обновление версии commons-lang3 в данном PR имеет прямую связь с изменениями зависимостей в текущем пул-реквесте.

Poem

Я заяц-весельчак, спешу,
Код обновляю, не сплю.
В зависимостях порядок и свет,
Репортер новый — мой секрет.
JSON сверкает, словно звёздный путь,
Пусть ошибки бегут прочь!
🐇✨
"""


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9a8fe54 and c083549.

📒 Files selected for processing (1)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/CodeQualityReporter.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/CodeQualityReporter.java
⏰ Context from checks skipped due to timeout of 90000ms (21)
  • GitHub Check: build (23, macOS-latest)
  • GitHub Check: build (23, ubuntu-latest)
  • GitHub Check: build (23, windows-latest)
  • GitHub Check: build (21, macOS-latest)
  • GitHub Check: build (23, ubuntu-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (21, macOS-latest)
  • GitHub Check: build (21, ubuntu-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (17, macOS-latest)
  • GitHub Check: build (21, ubuntu-latest)
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build (17, macOS-latest)
  • GitHub Check: build (17, ubuntu-latest)
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build (17, ubuntu-latest)
  • GitHub Check: Analyse
  • GitHub Check: build
  • GitHub Check: Benchmark
  • GitHub Check: Analyze the repo with CodeSee
  • GitHub Check: Sentry

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@nixel2007 nixel2007 changed the title #3419 Репортер в CodeQuality Репортер в CodeQuality Feb 20, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

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

42-62: Расширьте тестовое покрытие.

Текущий тест проверяет только базовый сценарий. Рекомендуется добавить тесты для:

  • Всех уровней важности (DiagnosticSeverity)
  • Граничных случаев с пустыми строками
  • Проверки на null параметры
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ae97c9a and 89d2c33.

📒 Files selected for processing (7)
  • build.gradle.kts (1 hunks)
  • docs/reporters/code-quality.md (1 hunks)
  • docs/reporters/index.md (1 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/CodeQualityReportEntry.java (1 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/CodeQualityReporter.java (1 hunks)
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/CodeQualityReportEntryTest.java (1 hunks)
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/CodeQualityReporterTest.java (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (14)
  • GitHub Check: build (23, macOS-latest)
  • GitHub Check: build (23, windows-latest)
  • GitHub Check: Analyse
  • GitHub Check: build (23, ubuntu-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build
  • GitHub Check: build (23, windows-latest)
  • GitHub Check: build
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (17, macOS-latest)
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build (17, ubuntu-latest)
  • GitHub Check: Benchmark
🔇 Additional comments (5)
docs/reporters/code-quality.md (3)

1-2: Отличное оформление заголовка.
Заголовок "CodeQuality reporter" ясно отражает суть нового репортера.


3-4: Проверка ключа репортера.
Ключ репортера code-quality указан корректно. Убедитесь, что он согласуется с остальными частями проекта и используется при настройке новых функций.


5-7: Ясное и понятное описание.
Описание репортера хорошо сформулировано: указано, что вывод производится в файл bsl-code-quality.json, а ссылка на документацию GitLab выглядит корректно. Проверьте работоспособность гиперссылки и соответствие формата вывода требованиям.

docs/reporters/index.md (1)

12-12: Добавлена новая запись репортера.
Строка * [code-quality](code-quality.md); корректно добавлена в список реализованных репортеров. Убедитесь, что файл code-quality.md содержит актуальное и полное описание функциональности нового репортера.

build.gradle.kts (1)

107-108: Обновление зависимостей.
Добавлены зависимости:

  • implementation("commons-codec", "commons-codec", "1.16.0")
  • implementation("org.apache.commons", "commons-lang3", "3.17.0")
    Убедитесь, что указанные версии библиотек актуальны, совместимы с остальными зависимостями проекта и не содержат известных уязвимостей.

Comment on lines 69 to 71
File reportFile = new File(outputDir.toFile(), "./bsl-code-quality.json");
mapper.writeValue(reportFile, report);
LOGGER.info("CodeQuality report saved to {}", reportFile.getAbsolutePath());
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Улучшите обработку ошибок и конфигурацию.

Рекомендуемые улучшения:

  • Добавьте явную обработку IOException вместо @SneakyThrows
  • Вынесите имя файла "bsl-code-quality.json" в константу
  • Добавьте проверку на существование директории outputDir
+  private static final String REPORT_FILE_NAME = "bsl-code-quality.json";
+
   @Override
-  @SneakyThrows
   public void report(AnalysisInfo analysisInfo, Path outputDir) {
+    if (!Files.exists(outputDir)) {
+      Files.createDirectories(outputDir);
+    }
+    try {
       // ... existing code ...
-      File reportFile = new File(outputDir.toFile(), "./bsl-code-quality.json");
+      File reportFile = new File(outputDir.toFile(), REPORT_FILE_NAME);
       mapper.writeValue(reportFile, report);
       LOGGER.info("CodeQuality report saved to {}", reportFile.getAbsolutePath());
+    } catch (IOException e) {
+      LOGGER.error("Failed to write report: {}", e.getMessage());
+      throw new ReportGenerationException("Failed to generate code quality report", e);
+    }
   }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
File reportFile = new File(outputDir.toFile(), "./bsl-code-quality.json");
mapper.writeValue(reportFile, report);
LOGGER.info("CodeQuality report saved to {}", reportFile.getAbsolutePath());
private static final String REPORT_FILE_NAME = "bsl-code-quality.json";
@Override
public void report(AnalysisInfo analysisInfo, Path outputDir) {
if (!Files.exists(outputDir)) {
Files.createDirectories(outputDir);
}
try {
// ... existing code ...
File reportFile = new File(outputDir.toFile(), REPORT_FILE_NAME);
mapper.writeValue(reportFile, report);
LOGGER.info("CodeQuality report saved to {}", reportFile.getAbsolutePath());
} catch (IOException e) {
LOGGER.error("Failed to write report: {}", e.getMessage());
throw new ReportGenerationException("Failed to generate code quality report", e);
}
}

Comment on lines +51 to +61
public CodeQualityReportEntry(String path, Diagnostic diagnostic, DiagnosticInfo diagnosticInfo) {
this.description = diagnostic.getMessage();
this.checkName = diagnosticInfo.getCode().getStringValue();
var fingerprintData = path + "//" + this.checkName + "//" + diagnostic.getRange();
this.fingerprint = sha256Hex(fingerprintData);
this.severity = SEVERITY_MAP.get(diagnosticInfo.getSeverity());
this.location = new Location();
this.location.path = path;
this.location.lines = new Lines();
this.location.lines.begin = diagnostic.getRange().getStart().getLine();
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Улучшите инкапсуляцию и безопасность.

Текущая реализация имеет несколько проблем:

  • Класс Location допускает прямое изменение полей
  • Отсутствует валидация входных параметров
  • Генерация fingerprint может быть улучшена
   public CodeQualityReportEntry(String path, Diagnostic diagnostic, DiagnosticInfo diagnosticInfo) {
+    if (path == null || diagnostic == null || diagnosticInfo == null) {
+      throw new IllegalArgumentException("All parameters must be non-null");
+    }
     this.description = diagnostic.getMessage();
     this.checkName = diagnosticInfo.getCode().getStringValue();
-    var fingerprintData = path + "//" + this.checkName + "//" + diagnostic.getRange();
+    var fingerprintData = String.format("%s//%s//%s", path, this.checkName, diagnostic.getRange());
     this.fingerprint = sha256Hex(fingerprintData);
     this.severity = SEVERITY_MAP.get(diagnosticInfo.getSeverity());
-    this.location = new Location();
-    this.location.path = path;
-    this.location.lines = new Lines();
-    this.location.lines.begin = diagnostic.getRange().getStart().getLine();
+    this.location = new Location(path, new Lines(diagnostic.getRange().getStart().getLine()));
   }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public CodeQualityReportEntry(String path, Diagnostic diagnostic, DiagnosticInfo diagnosticInfo) {
this.description = diagnostic.getMessage();
this.checkName = diagnosticInfo.getCode().getStringValue();
var fingerprintData = path + "//" + this.checkName + "//" + diagnostic.getRange();
this.fingerprint = sha256Hex(fingerprintData);
this.severity = SEVERITY_MAP.get(diagnosticInfo.getSeverity());
this.location = new Location();
this.location.path = path;
this.location.lines = new Lines();
this.location.lines.begin = diagnostic.getRange().getStart().getLine();
}
public CodeQualityReportEntry(String path, Diagnostic diagnostic, DiagnosticInfo diagnosticInfo) {
if (path == null || diagnostic == null || diagnosticInfo == null) {
throw new IllegalArgumentException("All parameters must be non-null");
}
this.description = diagnostic.getMessage();
this.checkName = diagnosticInfo.getCode().getStringValue();
var fingerprintData = String.format("%s//%s//%s", path, this.checkName, diagnostic.getRange());
this.fingerprint = sha256Hex(fingerprintData);
this.severity = SEVERITY_MAP.get(diagnosticInfo.getSeverity());
this.location = new Location(path, new Lines(diagnostic.getRange().getStart().getLine()));
}

Comment on lines +68 to +98
@Test
void report() throws IOException {

// given
Diagnostic diagnostic = new Diagnostic(
Ranges.create(0, 1, 2, 3),
"message",
DiagnosticSeverity.Error,
"test-source",
"Typo"
);

var documentContext = TestUtils.getDocumentContext("");
String sourceDir = ".";
FileInfo fileInfo = new FileInfo(sourceDir, documentContext, Collections.singletonList(diagnostic));
AnalysisInfo analysisInfo = new AnalysisInfo(LocalDateTime.now(), Collections.singletonList(fileInfo), sourceDir);

// when
reporter.report(analysisInfo, Path.of(sourceDir));

// then
ObjectMapper mapper = new ObjectMapper();
List<CodeQualityReportEntry> report = mapper.readValue(
file,
new TypeReference<ArrayList<CodeQualityReportEntry>>() {
}
);

assertThat(report).hasSize(1);

}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Расширьте тестовое покрытие и улучшите очистку ресурсов.

Рекомендуется:

  • Добавить тесты для различных сценариев ошибок
  • Проверить содержимое сгенерированного отчета
  • Использовать @TempDir для управления временными файлами
+  @TempDir
+  Path tempDir;
+
   @Test
   void report() throws IOException {
     // ... existing test ...
     
     // then
     ObjectMapper mapper = new ObjectMapper();
     List<CodeQualityReportEntry> report = mapper.readValue(
       file,
       new TypeReference<ArrayList<CodeQualityReportEntry>>() {
       }
     );
 
     assertThat(report).hasSize(1);
+    assertThat(report.get(0))
+      .hasFieldOrPropertyWithValue("checkName", "Typo")
+      .hasFieldOrPropertyWithValue("severity", CodeQualityReportEntry.Severity.INFO);
   }
+
+  @Test
+  void reportWithInvalidOutputDir() {
+    // given
+    var invalidDir = Path.of("/invalid/directory");
+    
+    // when/then
+    assertThatThrownBy(() -> reporter.report(analysisInfo, invalidDir))
+      .isInstanceOf(ReportGenerationException.class);
+  }

Committable suggestion skipped: line range outside the PR's diff.

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.

[MOD] Формат Code Qualty GitLab
1 participant