-
Notifications
You must be signed in to change notification settings - Fork 109
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
base: develop
Are you sure you want to change the base?
Репортер в CodeQuality #3424
Conversation
""" WalkthroughВ этом пул-реквесте произведены изменения, касающиеся зависимостей проекта, документации и реализации нового отчётчика качества кода. В файле Changes
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: Логирование места сохранения отчёта
Possibly related PRs
Poem
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ Context from checks skipped due to timeout of 90000ms (21)
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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
📒 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")
Убедитесь, что указанные версии библиотек актуальны, совместимы с остальными зависимостями проекта и не содержат известных уязвимостей.
File reportFile = new File(outputDir.toFile(), "./bsl-code-quality.json"); | ||
mapper.writeValue(reportFile, report); | ||
LOGGER.info("CodeQuality report saved to {}", reportFile.getAbsolutePath()); |
There was a problem hiding this comment.
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.
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); | |
} | |
} |
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(); | ||
} |
There was a problem hiding this comment.
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.
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())); | |
} |
@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); | ||
|
||
} |
There was a problem hiding this comment.
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.
|
Описание
Связанные задачи
Closes #3419
Чеклист
Общие
gradlew precommit
)Для диагностик
Дополнительно