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

Опциональный параметр диагностики Typo (caseInsensitive) #2945

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -111,22 +111,30 @@ public class TypoDiagnostic extends AbstractDiagnostic {
type = String.class
)
private String userWordsToIgnore = DEFAULT_USER_WORDS_TO_IGNORE;
@DiagnosticParameter(
type = Boolean.class
)
private Boolean caseInsensitive = false;

@Override
public void configure(Map<String, Object> configuration) {
super.configure(configuration);
minWordLength = Math.max(minWordLength, DEFAULT_MIN_WORD_LENGTH);
}

private Set<String> getWordsToIgnore() {
private List<String> getWordsToIgnore() {
Copy link
Member

Choose a reason for hiding this comment

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

В чем логика замены Set на List?

var delimiter = ",";
String exceptions = SPACES_PATTERN.matcher(info.getResourceString("diagnosticExceptions")).replaceAll("");
if (!userWordsToIgnore.isEmpty()) {
exceptions = exceptions + delimiter + SPACES_PATTERN.matcher(userWordsToIgnore).replaceAll("");
}

if (caseInsensitive) {
exceptions = exceptions.toLowerCase();
Copy link
Member

Choose a reason for hiding this comment

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

В параметрах lowerCase должна быть явно указана локаль (в проекте вроде используется English)
https://rules.sonarsource.com/java/RSPEC-1449

}

return Arrays.stream(exceptions.split(delimiter))
.collect(Collectors.toSet());
.collect(Collectors.toList());
}

private static JLanguageTool acquireLanguageTool(String lang) {
Expand All @@ -140,7 +148,7 @@ private static void releaseLanguageTool(String lang, JLanguageTool languageTool)
private Map<String, List<Token>> getTokensMap(
DocumentContext documentContext
) {
Set<String> wordsToIgnore = getWordsToIgnore();
List<String> wordsToIgnore = getWordsToIgnore();
Map<String, List<Token>> tokensMap = new HashMap<>();

Trees.findAllRuleNodes(documentContext.getAst(), rulesToFind).stream()
Expand All @@ -150,12 +158,14 @@ private Map<String, List<Token>> getTokensMap(
.filter(token -> !FORMAT_STRING_PATTERN.matcher(token.getText()).find())
.forEach((Token token) -> {
String curText = QUOTE_PATTERN.matcher(token.getText()).replaceAll("").trim();
String[] camelCaseSplitedWords = StringUtils.splitByCharacterTypeCamelCase(curText);
String[] camelCaseSplitWords = StringUtils.splitByCharacterTypeCamelCase(curText);

Arrays.stream(camelCaseSplitedWords)
Arrays.stream(camelCaseSplitWords)
.filter(Predicate.not(String::isBlank))
.filter(element -> element.length() >= minWordLength)
.filter(Predicate.not(wordsToIgnore::contains))
.filter(element -> wordsToIgnore.stream().noneMatch(word
Copy link
Member

Choose a reason for hiding this comment

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

Здесь замена Set на List сделала поиск слова медленнее. contains в сете работает за О(1), здесь же теперь линейный поиск за O(N), в результате сложность всего стрима стала из линейной квадратичной

-> (caseInsensitive && word.equalsIgnoreCase(element))
|| (!caseInsensitive && word.equals(element))))
.forEach(element -> tokensMap.computeIfAbsent(element, newElement -> new ArrayList<>()).add(token));
}
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1766,6 +1766,12 @@
"default": 3,
"type": "integer",
"title": "Minimum length for checked words"
},
"caseInsensitive": {
"description": "Excluded words are case-insensitive",
"default": false,
"type": "boolean",
"title": "Excluded words are case-insensitive"
}
},
"$id": "#/definitions/Typo"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@ diagnosticExceptions=Str,Autotest,Infobase,Enums,Len,Desc,Asc,Overridable,GUID,E
Sys,Saas,www,yyyy,xsl,src,deserialization,Params,Archiver,Serializer,xsi,ico,epf,cfu,txt,htm,rtf,ppt,vsd,mpp,mdb,msg,rar,exe,grs,geo,jpg,bmp,\
tif,gif,png,pdf,odt,odf,odp,odg,ods,erf,docx,xlsx,pptx,utf,xsd,SRVR,saas,wsdl,Apdex,APDEX,uid,XLS,XLSX,html,TXT,ODT,Addin,DIB
minWordLength=Minimum length for checked words
userWordsToIgnore=Dictionary for excluding words (comma separated)
userWordsToIgnore=Dictionary for excluding words (comma separated)
caseInsensitive=Excluded words are case-insensitive
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@ diagnosticExceptions=Автогенерируемых,Автогруппиров
,Студотряде,Субконто,Таб,Техподдержки,Токене,Транслите,Тэги,Тэгов,Убыв,Физлица,Финализировать,Фич,Хэш,Штрихкодам\
,Штрихкодом,Штрихкоду,Мдд,Чммсс
minWordLength=Минимальная длина проверяемых слов
userWordsToIgnore=Пользовательский словарь исключений (через запятую)
userWordsToIgnore=Пользовательский словарь исключений (через запятую)
caseInsensitive=Не учитывать регистр в словаре исключений
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,22 @@ void testConfigureUserWordsToIgnore() {
.hasRange(8, 13, 8, 18);
}

@Test
void testConfigureUserWordsToIgnoreCaseInsensitive() {

Map<String, Object> configuration = diagnosticInstance.getInfo().getDefaultConfiguration();
configuration.put("userWordsToIgnore", "ваРинаты");
configuration.put("caseInsensitive", true);
diagnosticInstance.configure(configuration);

List<Diagnostic> diagnostics = getDiagnostics();

assertThat(diagnostics).hasSize(2);
assertThat(diagnostics, true)
.hasRange(1, 13, 1, 21)
.hasRange(8, 13, 8, 18);
}

@Test
void testConfigureUserWordsToIgnoreWithSpaces() {

Expand Down
1 change: 1 addition & 0 deletions src/test/resources/diagnostics/TypoDiagnostic.bsl
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@
Возврат;
Сообщить("ыть"); // срабатывание здесь
ДеньНедели = Формат(ДатаКолонки, "ДФ=ддд"); // Нет срабатывания. Форматная строка
ЗапроситьДанныеОКВЭДФССВТранзакции = Истина; // Нет срабатывания. Аббревиатура
КонецФункции