Skip to content

Добавлена поддержка новых атрибутов качества и важности для диагностик#411

Draft
theshadowco wants to merge 2 commits intodevelopfrom
feature/newAttributes
Draft

Добавлена поддержка новых атрибутов качества и важности для диагностик#411
theshadowco wants to merge 2 commits intodevelopfrom
feature/newAttributes

Conversation

@theshadowco
Copy link
Member

@theshadowco theshadowco commented Feb 20, 2026

Правильнее делать атрибуты в диагностика в бсллс.

Этот реквест - просто пример, что надо

@coderabbitai
Copy link

coderabbitai bot commented Feb 20, 2026

Walkthrough

Рефакторинг класса BSLLanguageServerRuleDefinition: открыты внутренние отображения как публичные константы (REPOSITORY_NAME, RULE_TYPE_MAP, OLD_SEVERITY_MAP, CLEAN_CODE_ATTRIBUTE_MAP, IMPACTS_MAP) и добавлена логика вычисления атрибутов чистого кода и влияний правил по диагностическим тегам; добавлены тесты покрытия для новых карт.

Изменения

Когорта / Файл(ы) Описание
Основная реализация
src/main/java/com/github/_1c_syntax/bsl/sonar/language/BSLLanguageServerRuleDefinition.java
Изменена видимость и добавлены новые публичные константы: REPOSITORY_NAME, RULE_TYPE_MAP, OLD_SEVERITY_MAP, CLEAN_CODE_ATTRIBUTE_MAP, IMPACTS_MAP. Переименованы/добавлены фабрики карт (createOldDiagnosticSeverityMap, createCleanCodeAttributeMap, createImpactsMap). Добавлена приватная логика computeImpact(List<DiagnosticTag>). При создании правил теперь устанавливаются CleanCodeAttribute и дефолтные воздействия (impacts).
Тестирование
src/test/java/com/github/_1c_syntax/bsl/sonar/language/BSLLanguageServerRuleDefinitionTest.java
Добавлены тесты smokyAllTags, smokyAllTypes, smokyAllSeverity для проверки полноты покрытий публичных отображений (IMPACTS_MAP, CLEAN_CODE_ATTRIBUTE_MAP, RULE_TYPE_MAP, OLD_SEVERITY_MAP) соответствующими enum-значениями.

Оценка трудозатратности рецензирования кода

🎯 3 (Умеренно сложно) | ⏱️ ~20 минут

Стихотворение

🐰 Я — кролик, радость в лапках ношу,

Отображенья в мир открыты к бою,
Теги и влияния берём на слух,
Правила крепче стали — вот так нужно,
Пойду морковку съем — и к коду пойду! 🥕

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning Автор не предоставил описание pull request. Описание отсутствует полностью. Добавьте описание pull request, которое объясняет цель, причину и последствия этих изменений для других разработчиков.
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 (1 passed)
Check name Status Explanation
Title check ✅ Passed Заголовок точно отражает основное изменение: добавлена поддержка новых атрибутов качества (CleanCodeAttribute) и важности (Impacts) для диагностик.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/newAttributes

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 and usage tips.

Copy link

@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: 1

🧹 Nitpick comments (2)
src/main/java/com/github/_1c_syntax/bsl/sonar/language/BSLLanguageServerRuleDefinition.java (1)

69-73: Публичные мутабельные коллекции — риск непреднамеренного изменения.

Карты OLD_SEVERITY_MAP, RULE_TYPE_MAP, CLEAN_CODE_ATTRIBUTE_MAP и IMPACTS_MAP объявлены как public static final, но сами EnumMap/HashMap остаются мутабельными. Любой внешний код может вызвать .put() / .remove() и повредить маппинг для всего приложения.

Рекомендуется обернуть возвращаемые карты в Collections.unmodifiableMap() в соответствующих create* методах.

♻️ Пример исправления (для каждого create-метода)
   private static Map<DiagnosticSeverity, String> createOldDiagnosticSeverityMap() {
     Map<DiagnosticSeverity, String> map = new EnumMap<>(DiagnosticSeverity.class);
     // ... put entries ...
-    return map;
+    return Collections.unmodifiableMap(map);
   }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@src/main/java/com/github/_1c_syntax/bsl/sonar/language/BSLLanguageServerRuleDefinition.java`
around lines 69 - 73, The public static final maps OLD_SEVERITY_MAP,
RULE_TYPE_MAP, CLEAN_CODE_ATTRIBUTE_MAP and IMPACTS_MAP are initialized with
mutable Map instances exposing the internal state; update each factory method
(createOldDiagnosticSeverityMap, createRuleTypeMap, createCleanCodeAttributeMap,
createImpactsMap) to wrap the populated map in Collections.unmodifiableMap(...)
before returning so external callers cannot mutate the maps and the public
constants remain effectively immutable.
src/test/java/com/github/_1c_syntax/bsl/sonar/language/BSLLanguageServerRuleDefinitionTest.java (1)

71-81: Хорошие smoke-тесты для полноты маппингов.

Тесты корректно проверяют, что все значения DiagnosticTag покрыты в обоих маппингах. Однако стоит рассмотреть добавление теста на логику агрегации в computeImpact — например, что при нескольких тегах с одинаковым SoftwareQuality выбирается наивысший Severity. Это важная бизнес-логика, не покрытая текущими smoke-тестами.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@src/test/java/com/github/_1c_syntax/bsl/sonar/language/BSLLanguageServerRuleDefinitionTest.java`
around lines 71 - 81, Add a focused unit test for
BSLLanguageServerRuleDefinition.computeImpact that verifies aggregation logic:
create multiple DiagnosticTag values that map (via IMPACTS_MAP) to the same
SoftwareQuality but different Severity levels, call
BSLLanguageServerRuleDefinition.computeImpact(...) with those tags and assert
the returned Impact/Severity equals the highest Severity among them; name the
test (e.g., smokyComputeImpactAggregation) and use existing enums DiagnosticTag,
SoftwareQuality and Severity to locate the relevant mappings and to construct
expected results.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@src/main/java/com/github/_1c_syntax/bsl/sonar/language/BSLLanguageServerRuleDefinition.java`:
- Around line 154-165: The stream mapping of diagnosticInfo.getTags() to
CLEAN_CODE_ATTRIBUTE_MAP::get and the computeImpact lookup from IMPACTS_MAP may
produce nulls causing NPEs; update the flow to drop missing mappings before
using sorted/findFirst and before accessing impact.getLeft()/getRight(): in the
CLEAN_CODE_ATTRIBUTE_MAP path (diagnosticInfo.getTags() ->
CLEAN_CODE_ATTRIBUTE_MAP::get -> newRule::setCleanCodeAttribute) add a filter to
remove null mappings before distinct/sorted/findFirst, and in computeImpact
(IMPACTS_MAP.get(tag) -> impact.getLeft()/getRight() ->
newRule::addDefaultImpact) skip tags that return null from IMPACTS_MAP or
otherwise handle absent mappings safely so you never call getLeft()/getRight()
on null.

---

Nitpick comments:
In
`@src/main/java/com/github/_1c_syntax/bsl/sonar/language/BSLLanguageServerRuleDefinition.java`:
- Around line 69-73: The public static final maps OLD_SEVERITY_MAP,
RULE_TYPE_MAP, CLEAN_CODE_ATTRIBUTE_MAP and IMPACTS_MAP are initialized with
mutable Map instances exposing the internal state; update each factory method
(createOldDiagnosticSeverityMap, createRuleTypeMap, createCleanCodeAttributeMap,
createImpactsMap) to wrap the populated map in Collections.unmodifiableMap(...)
before returning so external callers cannot mutate the maps and the public
constants remain effectively immutable.

In
`@src/test/java/com/github/_1c_syntax/bsl/sonar/language/BSLLanguageServerRuleDefinitionTest.java`:
- Around line 71-81: Add a focused unit test for
BSLLanguageServerRuleDefinition.computeImpact that verifies aggregation logic:
create multiple DiagnosticTag values that map (via IMPACTS_MAP) to the same
SoftwareQuality but different Severity levels, call
BSLLanguageServerRuleDefinition.computeImpact(...) with those tags and assert
the returned Impact/Severity equals the highest Severity among them; name the
test (e.g., smokyComputeImpactAggregation) and use existing enums DiagnosticTag,
SoftwareQuality and Severity to locate the relevant mappings and to construct
expected results.

@sonarqubecloud
Copy link

Quality Gate Failed Quality Gate failed

Failed conditions
B Maintainability Rating on New Code (required ≥ A)

See analysis details on SonarQube Cloud

Catch issues before they fail your Quality Gate with our IDE extension SonarQube for IDE

Copy link

@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.

🧹 Nitpick comments (2)
src/main/java/com/github/_1c_syntax/bsl/sonar/language/BSLLanguageServerRuleDefinition.java (2)

158-163: .sorted() неявно зависит от порядка объявления CleanCodeAttribute в SonarQube API.

CleanCodeAttribute — Java enum, и .sorted() без компаратора упорядочивает по ordinal(). Выбор итогового атрибута для правила зависит от порядка объявления констант в чужом API, который может поменяться при обновлении версии SonarQube. Комментарий «пока так» это признаёт, но стоит явно зафиксировать намеренный порядок приоритетов или использовать явный компаратор.

♻️ Вариант с явным компаратором-заглушкой (для будущего уточнения)
     diagnosticInfo.getTags().stream()
       .map(CLEAN_CODE_ATTRIBUTE_MAP::get)
       .distinct()
-      .sorted()
+      .sorted(Comparator.naturalOrder()) // TODO: заменить на осмысленный приоритет атрибутов
       .findFirst()
       .ifPresent(newRule::setCleanCodeAttribute);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@src/main/java/com/github/_1c_syntax/bsl/sonar/language/BSLLanguageServerRuleDefinition.java`
around lines 158 - 163, The current stream pipeline maps
diagnosticInfo.getTags() via CLEAN_CODE_ATTRIBUTE_MAP and then uses .sorted()
which relies on CleanCodeAttribute's enum ordinal order (unstable across
SonarQube versions); instead define and use an explicit priority ordering (e.g.,
a Comparator<CleanCodeAttribute> or a priority map) and apply it in the stream
before findFirst(), so replace the implicit .sorted() with
.sorted(yourExplicitComparator) or .min(yourExplicitComparator) when computing
the value passed to newRule::setCleanCodeAttribute to make the priority
deterministic and independent of the enum declaration order.

212-213: EnumMap вместо HashMap для ключа-enum SoftwareQuality.

Поскольку SoftwareQuality — перечисление с фиксированным числом значений, EnumMap даёт чуть лучшую производительность и более явно передаёт намерение.

♻️ Предлагаемая замена
-    Map<SoftwareQuality, Severity> map = new HashMap<>();
+    Map<SoftwareQuality, Severity> map = new EnumMap<>(SoftwareQuality.class);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@src/main/java/com/github/_1c_syntax/bsl/sonar/language/BSLLanguageServerRuleDefinition.java`
around lines 212 - 213, Replace the HashMap with an EnumMap in computeImpact to
reflect that keys are the SoftwareQuality enum: change the map
declaration/initialization in computeImpact(List<DiagnosticTag> tags) from new
HashMap<>() to new EnumMap<>(SoftwareQuality.class) and keep all subsequent uses
of the map (put/get/containsKey) unchanged so the method uses
EnumMap<SoftwareQuality, Severity> for better performance and clearer intent.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In
`@src/main/java/com/github/_1c_syntax/bsl/sonar/language/BSLLanguageServerRuleDefinition.java`:
- Around line 155-163: The stream pipeline using
diagnosticInfo.getTags().stream().map(CLEAN_CODE_ATTRIBUTE_MAP::get) can produce
nulls from CLEAN_CODE_ATTRIBUTE_MAP::get and later operations (distinct/sorted)
will throw NPE; update the pipeline to filter out null mappings before
distinct/sorted/findFirst and then call newRule.setCleanCodeAttribute only if
present (e.g., map -> filter(Objects::nonNull) or flatMap to Optional),
referencing diagnosticInfo.getTags(), CLEAN_CODE_ATTRIBUTE_MAP::get, and
newRule.setCleanCodeAttribute so the code safely ignores unmapped tags.
- Around line 212-222: computeImpact currently assumes IMPACTS_MAP.get(tag) is
non-null and calls impact.getLeft()/getRight(), which can NPE; change
computeImpact to null-check the result of IMPACTS_MAP.get(tag) (the local
variable impact) and skip the tag if impact is null before accessing
impact.getLeft() or impact.getRight(); ensure the loop over DiagnosticTag still
updates map only when impact is non-null so the method returns a correct
Map<SoftwareQuality, Severity>.

---

Nitpick comments:
In
`@src/main/java/com/github/_1c_syntax/bsl/sonar/language/BSLLanguageServerRuleDefinition.java`:
- Around line 158-163: The current stream pipeline maps diagnosticInfo.getTags()
via CLEAN_CODE_ATTRIBUTE_MAP and then uses .sorted() which relies on
CleanCodeAttribute's enum ordinal order (unstable across SonarQube versions);
instead define and use an explicit priority ordering (e.g., a
Comparator<CleanCodeAttribute> or a priority map) and apply it in the stream
before findFirst(), so replace the implicit .sorted() with
.sorted(yourExplicitComparator) or .min(yourExplicitComparator) when computing
the value passed to newRule::setCleanCodeAttribute to make the priority
deterministic and independent of the enum declaration order.
- Around line 212-213: Replace the HashMap with an EnumMap in computeImpact to
reflect that keys are the SoftwareQuality enum: change the map
declaration/initialization in computeImpact(List<DiagnosticTag> tags) from new
HashMap<>() to new EnumMap<>(SoftwareQuality.class) and keep all subsequent uses
of the map (put/get/containsKey) unchanged so the method uses
EnumMap<SoftwareQuality, Severity> for better performance and clearer intent.

@theshadowco theshadowco marked this pull request as draft February 20, 2026 06:52
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.

1 participant