Skip to content

Commit

Permalink
Merge pull request #3408 from 1c-syntax/feature/ProtectedModule
Browse files Browse the repository at this point in the history
Feature/protected module
  • Loading branch information
theshadowco authored Feb 10, 2025
2 parents 9cac003 + 3c8401f commit 432bbc7
Show file tree
Hide file tree
Showing 11 changed files with 209 additions and 2 deletions.
18 changes: 18 additions & 0 deletions docs/diagnostics/ProtectedModule.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Защищенные модули (ProtectedModule)

<!-- Блоки выше заполняются автоматически, не трогать -->
## Описание диагностики
<!-- Описание диагностики заполняется вручную. Необходимо понятным языком описать смысл и схему работу -->
Отсутствие исходников модуля в конфигурации не рекомендуется.
В случае закрытого, запароленного модуля понижается качество кода, нельзя сделать ревью кода, версионирование изменений не ведется.

## Примеры
<!-- В данном разделе приводятся примеры, на которые диагностика срабатывает, а также можно привести пример, как можно исправить ситуацию -->

## Источники
<!-- Необходимо указывать ссылки на все источники, из которых почерпнута информация для создания диагностики -->
<!-- Примеры источников
* Источник: [Стандарт: Тексты модулей](https://its.1c.ru/db/v8std#content:456:hdoc)
* Полезная информация: [Отказ от использования модальных окон](https://its.1c.ru/db/metod8dev#content:5272:hdoc)
* Источник: [Cognitive complexity, ver. 1.4](https://www.sonarsource.com/docs/CognitiveComplexity.pdf) -->
16 changes: 16 additions & 0 deletions docs/en/diagnostics/ProtectedModule.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Protected modules (ProtectedModule)

<!-- Блоки выше заполняются автоматически, не трогать -->
## Description
<!-- Описание диагностики заполняется вручную. Необходимо понятным языком описать смысл и схему работу -->

## Examples
<!-- В данном разделе приводятся примеры, на которые диагностика срабатывает, а также можно привести пример, как можно исправить ситуацию -->

## Sources
<!-- Необходимо указывать ссылки на все источники, из которых почерпнута информация для создания диагностики -->
<!-- Примеры источников
* Источник: [Стандарт: Тексты модулей](https://its.1c.ru/db/v8std#content:456:hdoc)
* Полезная информация: [Отказ от использования модальных окон](https://its.1c.ru/db/metod8dev#content:5272:hdoc)
* Источник: [Cognitive complexity, ver. 1.4](https://www.sonarsource.com/docs/CognitiveComplexity.pdf) -->
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/*
* This file is a part of BSL Language Server.
*
* Copyright (c) 2018-2025
* Alexey Sosnoviy <[email protected]>, Nikita Fedkin <[email protected]> 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.DiagnosticScope;
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.DiagnosticType;
import com.github._1c_syntax.bsl.languageserver.utils.MdoRefBuilder;
import com.github._1c_syntax.bsl.languageserver.utils.Ranges;
import com.github._1c_syntax.bsl.mdo.Module;
import com.github._1c_syntax.bsl.mdo.ModuleOwner;
import com.github._1c_syntax.bsl.types.ConfigurationSource;
import com.github._1c_syntax.bsl.types.ModuleType;
import org.eclipse.lsp4j.Range;

@DiagnosticMetadata(
type = DiagnosticType.CODE_SMELL,
severity = DiagnosticSeverity.MAJOR,
minutesToFix = 5,
tags = {
DiagnosticTag.BADPRACTICE,
DiagnosticTag.SUSPICIOUS
},
modules = {
ModuleType.SessionModule
},
scope = DiagnosticScope.BSL,
canLocateOnProject = true
)

public class ProtectedModuleDiagnostic extends AbstractDiagnostic {

/**
* Рендж на который будут повешены замечания
* Костыль, но пока так
*/
private Range diagnosticRange;

@Override
protected void check() {

var configuration = documentContext.getServerContext().getConfiguration();
if (configuration.getConfigurationSource() == ConfigurationSource.EMPTY) {
return;
}

diagnosticRange = documentContext.getSymbolTree().getModule().getSelectionRange();
if (Ranges.isEmpty(diagnosticRange)) {
return;
}

configuration.getChildren().stream()
.filter(md -> md instanceof ModuleOwner)
.map(md -> (ModuleOwner) md)
.forEach((ModuleOwner moduleOwner) -> {
var hasProtected = moduleOwner.getModules().stream()
.filter(Module::isProtected)
.findAny();
if (hasProtected.isPresent()) {
addDiagnostic(moduleOwner);
}
});
}

private void addDiagnostic(ModuleOwner moduleOwner) {
var ownerMDOName = MdoRefBuilder.getLocaleOwnerMdoName(documentContext, moduleOwner);
diagnosticStorage.addDiagnostic(diagnosticRange, info.getMessage(ownerMDOName));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1592,6 +1592,16 @@
"title": "Procedure should not return Value",
"$id": "#/definitions/ProcedureReturnsValue"
},
"ProtectedModule": {
"description": "Protected modules",
"default": true,
"type": [
"boolean",
"object"
],
"title": "Protected modules",
"$id": "#/definitions/ProtectedModule"
},
"PublicMethodsDescription": {
"description": "All public methods must have a description",
"default": true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,9 @@
"ProcedureReturnsValue": {
"$ref": "parameters-schema.json#/definitions/ProcedureReturnsValue"
},
"ProtectedModule": {
"$ref": "parameters-schema.json#/definitions/ProtectedModule"
},
"PublicMethodsDescription": {
"$ref": "parameters-schema.json#/definitions/PublicMethodsDescription"
},
Expand Down Expand Up @@ -694,7 +697,7 @@
"type": "string"
},
"default": [
"Тест",
"\u0422\u0435\u0441\u0442",
"Test"
]
},
Expand All @@ -713,7 +716,7 @@
"getTestsByTestRunner": {
"$id": "#/properties/codeLens/testRunner/getTestsByTestRunner",
"type": "boolean",
"title": "Use testrunner to get test method names. By default, use internal parser to find methods annotated with &Тест.",
"title": "Use testrunner to get test method names. By default, use internal parser to find methods annotated with &\u0422\u0435\u0441\u0442.",
"default": true
},
"getTestsArguments": {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
diagnosticMessage=The source code of the module is missing due to password protection. %s
diagnosticName=Protected modules
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
diagnosticMessage=Исходный код модуля отсутствует из-за защиты паролем. %s
diagnosticName=Защищенные модули
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* This file is a part of BSL Language Server.
*
* Copyright (c) 2018-2025
* Alexey Sosnoviy <[email protected]>, Nikita Fedkin <[email protected]> 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.utils.Ranges;
import com.github._1c_syntax.bsl.types.ModuleType;
import com.github._1c_syntax.utils.Absolute;
import org.eclipse.lsp4j.Diagnostic;
import org.eclipse.lsp4j.Range;
import org.junit.jupiter.api.Test;

import java.util.List;

import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;

class ProtectedModuleDiagnosticTest extends AbstractDiagnosticTest<ProtectedModuleDiagnostic> {
ProtectedModuleDiagnosticTest() {
super(ProtectedModuleDiagnostic.class);
}

private static final String PATH_TO_METADATA = "src/test/resources/metadata/subSystemFilter";

@Test
void test() {
initServerContext(Absolute.path(PATH_TO_METADATA));
var documentContext = spy(getDocumentContext());
when(documentContext.getModuleType()).thenReturn(ModuleType.SessionModule);

List<Diagnostic> diagnostics = getDiagnostics(documentContext);
assertThat(diagnostics, true)
.hasSize(1)
.allMatch(
diagnostic -> diagnostic.getRange().equals(getRange()))
.anyMatch(diagnostic -> diagnostic.getMessage()
.equals("Исходный код модуля отсутствует из-за защиты паролем. ОбщийМодуль.ОбщийМодуль1"))
;
}

private static Range getRange() {
return Ranges.create(0, 0, 9);
}
}
2 changes: 2 additions & 0 deletions src/test/resources/diagnostics/ProtectedModuleDiagnostic.bsl
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Процедура Метод()
КонецПроцедуры

0 comments on commit 432bbc7

Please sign in to comment.