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

Диагностика поиска запрещенных слов #1836

Merged
merged 27 commits into from
Oct 7, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
cbb90e7
заготовка под диагностику
Golovanoff Aug 26, 2021
2cbfebf
файлы ресурсов диагностики
Golovanoff Aug 26, 2021
31daa52
файл с кодом 1с для тестирования диагностики
Golovanoff Aug 26, 2021
a6f41bd
тестовый класс
Golovanoff Aug 30, 2021
efe008f
работающий поиск
Golovanoff Aug 30, 2021
1b3ad3d
накидал параметр диагностики
Golovanoff Aug 30, 2021
e100afd
переписал через documentContext, но теперь надо нормальную регулярку
Golovanoff Aug 30, 2021
56fa6eb
сделал выкусывание комментариев, тесты отходят. но не учитывается //…
Golovanoff Aug 31, 2021
dd70d4d
убрал исключение комментариев - теперь просто поиск по модулю
Golovanoff Aug 31, 2021
26a09b5
подготовка к ПР
Golovanoff Sep 1, 2021
708282f
добавил инормацию о лицензии
Golovanoff Sep 1, 2021
5a453e1
пофиксил часть замечаний по ПР
Golovanoff Sep 1, 2021
fc1acf0
сделал параметр диагностики сразу паттерном
Golovanoff Sep 1, 2021
6a32a70
почистил импорты
Golovanoff Sep 2, 2021
742362a
переписал на поиск по всему документу. без разбития на строки
Golovanoff Sep 2, 2021
9943a9c
переписал на поиск по всему документу. без разбития на строки
Golovanoff Sep 2, 2021
e5801c8
обработку переносов строк перевесил на getContetnList(), пусть он :)
Golovanoff Sep 5, 2021
b995935
вернул в BadWords поиск по строкам
Golovanoff Sep 23, 2021
36f4e78
Merge pull request #1 from 1c-syntax/develop
Golovanoff Sep 23, 2021
65bf68c
Merge branch 'develop' into BadWords
Golovanoff Sep 23, 2021
6e85e48
Проверку на заполненость паттерна сделал покрасивее
Golovanoff Sep 23, 2021
4602c29
отключил диагностику по дефолту
Golovanoff Sep 28, 2021
7086e30
поправил документацию
Golovanoff Sep 28, 2021
8a3a8e4
Убрал %s.
Golovanoff Sep 30, 2021
886dee4
Поправил документацию, удалил метод-обертку createPattern.
Golovanoff Oct 7, 2021
096b80b
Merge branch '1c-syntax:develop' into develop
Golovanoff Oct 7, 2021
6d6778e
Смержил с последним develop.
Golovanoff Oct 7, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions docs/diagnostics/BadWords.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Запрещенные слова (BadWords)

| Тип | Поддерживаются<br>языки | Важность | Включена<br>по умолчанию | Время на<br>исправление (мин) | Теги |
|:-------------:|:-----------------------------:|:--------:|:------------------------------:|:-----------------------------------:|:--------:|
| `Дефект кода` | `BSL`<br>`OS` | `Важный` | `Нет` | `1` | `design` |

## Параметры


| Имя | Тип | Описание | Значение<br>по умолчанию |
|:----------:|:--------:|:-------------------------------------------:|:------------------------------:|
| `badWords` | `Строка` | `Регулярное выражение для слов-исключений.` | `` |
<!-- Блоки выше заполняются автоматически, не трогать -->
## Описание диагностики
В тексте модулей не должны встречаться запрещенные слова.
Список запрещенных слов задается регулярным выражением.
Поиск производится без учета регистра символов.

**Примеры настройки:**

"редиска|лопух|экзистенциальность"

"ло(х|шара|шпед)"

## Сниппеты

<!-- Блоки ниже заполняются автоматически, не трогать -->
### Экранирование кода

```bsl
// BSLLS:BadWords-off
// BSLLS:BadWords-on
```

### Параметр конфигурационного файла

```json
"BadWords": {
"badWords": ""
}
```
5 changes: 3 additions & 2 deletions docs/diagnostics/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,19 @@

## Список реализованных диагностик

Общее количество: **150**
Общее количество: **151**

* Потенциальная уязвимость: **4**
* Уязвимость: **4**
* Ошибка: **48**
* Дефект кода: **94**
* Дефект кода: **95**


| Ключ | Название | Включена по умолчанию | Важность | Тип | Тэги |
| --- | --- | :-: | --- | --- | --- |
[AllFunctionPathMustHaveReturn](AllFunctionPathMustHaveReturn.md) | Все возможные пути выполнения функции должны содержать оператор Возврат | Да | Важный | Дефект кода | `unpredictable`<br>`badpractice`<br>`suspicious`
[AssignAliasFieldsInQuery](AssignAliasFieldsInQuery.md) | Назначение псевдонимов выбранным полям в запросе | Да | Важный | Дефект кода | `standard`<br>`sql`<br>`badpractice`
[BadWords](BadWords.md) | Запрещенные слова | Да | Важный | Дефект кода | `design`
[BeginTransactionBeforeTryCatch](BeginTransactionBeforeTryCatch.md) | Нарушение правил работы с транзакциями для метода 'НачатьТранзакцию' | Да | Важный | Ошибка | `standard`
[CachedPublic](CachedPublic.md) | Кеширование программного интерфейса | Да | Важный | Дефект кода | `standard`<br>`design`
[CanonicalSpellingKeywords](CanonicalSpellingKeywords.md) | Каноническое написание ключевых слов | Да | Информационный | Дефект кода | `standard`
Expand Down
41 changes: 41 additions & 0 deletions docs/en/diagnostics/BadWords.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Prohibited words (BadWords)

| Type | Scope | Severity | Activated<br>by default | Minutes<br>to fix | Tags |
|:------------:|:-------------------:|:--------:|:-----------------------------:|:-----------------------:|:--------:|
| `Code smell` | `BSL`<br>`OS` | `Major` | `No` | `1` | `design` |

## Parameters


| Name | Type | Description | Default value |
|:----------:|:--------:|:------------------------------------------:|:-------------:|
| `badWords` | `String` | `Regular expression for prohibited words.` | `` |
<!-- Блоки выше заполняются автоматически, не трогать -->
## Description
Software modules should not contain prohibited words.
Golovanoff marked this conversation as resolved.
Show resolved Hide resolved
The list of forbidden words is set by a regular expression.
The search is case-insensitive.

**For example:**

"singularity|avada kedavra|Donald"

"transcenden(tal|ce)"

## Snippets

<!-- Блоки ниже заполняются автоматически, не трогать -->
### Diagnostic ignorance in code

```bsl
// BSLLS:BadWords-off
// BSLLS:BadWords-on
```

### Parameter for config

```json
"BadWords": {
"badWords": ""
}
```
5 changes: 3 additions & 2 deletions docs/en/diagnostics/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,19 @@ To escape individual sections of code or files from triggering diagnostics, you

## Implemented diagnostics

Total: **150**
Total: **151**

* Security Hotspot: **4**
* Vulnerability: **4**
* Error: **48**
* Code smell: **94**
* Code smell: **95**


| Key | Name| Enabled by default | Severity | Type | Tags |
| --- | --- | :-: | --- | --- | --- |
[AllFunctionPathMustHaveReturn](AllFunctionPathMustHaveReturn.md) | All execution paths of a function must have a Return statement | Yes | Major | Code smell | `unpredictable`<br>`badpractice`<br>`suspicious`
[AssignAliasFieldsInQuery](AssignAliasFieldsInQuery.md) | Assigning aliases to selected fields in a query | Yes | Major | Code smell | `standard`<br>`sql`<br>`badpractice`
[BadWords](BadWords.md) | Prohibited words | Yes | Major | Code smell | `design`
[BeginTransactionBeforeTryCatch](BeginTransactionBeforeTryCatch.md) | Violating transaction rules for the 'BeginTransaction' method | Yes | Major | Error | `standard`
[CachedPublic](CachedPublic.md) | Cached public methods | Yes | Major | Code smell | `standard`<br>`design`
[CanonicalSpellingKeywords](CanonicalSpellingKeywords.md) | Canonical keyword writing | Yes | Info | Code smell | `standard`
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* This file is a part of BSL Language Server.
*
* Copyright (c) 2018-2021
* Alexey Sosnoviy <labotamy@gmail.com>, Nikita Gryzlov <nixel2007@gmail.com> and contributors
*
* SPDX-License-Identifier: LGPL-3.0-or-later
*
* BSL Language Server is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 of the License, or (at your option) any later version.
*
* BSL Language Server is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with BSL Language Server.
*/
package com.github._1c_syntax.bsl.languageserver.diagnostics;

import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata;
import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType;
import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity;
import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag;
import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticParameter;

import com.github._1c_syntax.utils.CaseInsensitivePattern;

import java.util.Map;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

@DiagnosticMetadata(
type = DiagnosticType.CODE_SMELL,
severity = DiagnosticSeverity.MAJOR,
minutesToFix = 1,
activatedByDefault = false,
tags = {
DiagnosticTag.DESIGN
}
)
public class BadWordsDiagnostic extends AbstractDiagnostic {

private static final String BAD_WORDS_DEFAULT = "";

@DiagnosticParameter(
type = String.class,
defaultValue = BAD_WORDS_DEFAULT
)
private Pattern badWords = CaseInsensitivePattern.compile(BAD_WORDS_DEFAULT);

@Override
public void configure(Map<String, Object> configuration) {
this.badWords = CaseInsensitivePattern.compile(
(String) configuration.getOrDefault("badWords", BAD_WORDS_DEFAULT));
}

@Override
protected void check() {

if (badWords.pattern().isBlank()) {
return;
}

String[] moduleLines = documentContext.getContentList();
for (int i = 0; i < moduleLines.length; i++) {
Matcher matcher = badWords.matcher(moduleLines[i]);
while (matcher.find()) {
diagnosticStorage.addDiagnostic(i, matcher.start(), i, matcher.end());
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
diagnosticMessage=Prohibited word found.
diagnosticName=Prohibited words
badWords=Regular expression for prohibited words.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
diagnosticMessage=В тексте модуля найдено запрещенное слово.
Golovanoff marked this conversation as resolved.
Show resolved Hide resolved
diagnosticName=Запрещенные слова
badWords=Регулярное выражение для слов-исключений.
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
* This file is a part of BSL Language Server.
*
* Copyright (c) 2018-2021
* Alexey Sosnoviy <labotamy@gmail.com>, Nikita Gryzlov <nixel2007@gmail.com> and contributors
*
* SPDX-License-Identifier: LGPL-3.0-or-later
*
* BSL Language Server is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 of the License, or (at your option) any later version.
*
* BSL Language Server is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with BSL Language Server.
*/
package com.github._1c_syntax.bsl.languageserver.diagnostics;

import org.eclipse.lsp4j.Diagnostic;
import org.junit.jupiter.api.Test;

import java.util.List;
import java.util.Map;

import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat;

class BadWordsDiagnosticTest extends AbstractDiagnosticTest<BadWordsDiagnostic>{
BadWordsDiagnosticTest() {
super(BadWordsDiagnostic.class);
}

@Test
void test() {

List<Diagnostic> diagnostics = getDiagnostics();
assertThat(diagnostics).hasSize(0); // Проверка количества
}

@Test
void testConfigure() {

Map<String, Object> configuration = diagnosticInstance.info.getDefaultConfiguration();
configuration.put("badWords", "лотус|шмотус");
diagnosticInstance.configure(configuration);

List<Diagnostic> diagnostics = getDiagnostics();

assertThat(diagnostics).hasSize(6);
assertThat(diagnostics, true)
.hasRange(0, 42, 0, 47)
.hasRange(0, 48, 0, 54)
.hasRange(4, 4, 4, 9)
.hasRange(6, 24, 6, 29)
.hasRange(6, 34, 6, 39)
.hasRange(8, 4, 8, 10);
}
}
9 changes: 9 additions & 0 deletions src/test/resources/diagnostics/BadWordsDiagnostic.bsl
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// при наличии в списке запрещенных слов "лотус/шмотус" // тут должно сработать дважды

Запрос = Новый Запрос;
Запрос.Текст = "ВЫБРАТЬ ПЕРВЫЕ 1
| Лотус.Ссылка КАК Узел //тут должно сработать
|ИЗ
| ПланОбмена.ДиспетчерЛотус КАК Лотус"; //тут должно сработать дважды

УзелШмотуса = Запрос.Выполнить().Выгрузить()[0].Ссылка; //тут должно сработать