feat: Добавлена функция исключения путей в BSL Language Server#3805
feat: Добавлена функция исключения путей в BSL Language Server#3805johnnyshut wants to merge 4 commits into1c-syntax:developfrom
Conversation
📝 WalkthroughWalkthroughAdds root-relative path exclusion: new PathExclusionUtils, an excludePaths configuration option and schema entries, and applies exclusions in initial context population, workspace file event handlers, and CLI file-collection/format flows. Changes
Sequence Diagram(s)sequenceDiagram
participant FileWatcher as FileWatcher
participant Workspace as BSLWorkspaceService
participant Config as LanguageServerConfiguration
participant Excluder as PathExclusionUtils
participant Store as DocumentStore
FileWatcher->>Workspace: notify created/changed (URI)
Workspace->>Config: resolve configurationRoot & excludePaths
Workspace->>Excluder: isExcluded(configurationRoot, path, excludePaths)
alt excluded
Excluder-->>Workspace: true
Workspace->>Store: skip add/update and further processing
else not excluded
Excluder-->>Workspace: false
Workspace->>Store: add/update document and continue processing
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In
`@src/test/java/com/github/_1c_syntax/bsl/languageserver/utils/PathExclusionUtilsTest.java`:
- Around line 54-59: The test isExcludedReturnsFalseWhenPathIsOutsideRoot
currently constructs a path inside the root (root.resolve("sibling")), so it
doesn't exercise the "outside root" case; update the test to create a path that
is truly outside the root (for example use
root.getParent().resolve("sibling").resolve("file.bsl") or build a totally
different absolute base) and keep the assertion against
PathExclusionUtils.isExcluded(root, path, List.of("other")) unchanged so the
method is validated for an external path.
🧹 Nitpick comments (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfiguration.java (1)
123-128: Align with project convention for immutable config defaults.Project convention uses immutable defaults (
List.of(),Set.of()) in configuration classes, as evidenced byTestRunnerAdapterOptions. Since@Dataannotation generates setters, mutability is handled through Lombok-generated setters rather than mutable defaults. ChangeexcludePathsto useList.of()for consistency with the pattern.No in-place mutations of
excludePathswere found, so the change is safe.♻️ Proposed change
- private List<String> excludePaths = new ArrayList<>(); + private List<String> excludePaths = List.of();
src/test/java/com/github/_1c_syntax/bsl/languageserver/utils/PathExclusionUtilsTest.java
Show resolved
Hide resolved
dc2112e to
3dc978d
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In
`@src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLWorkspaceService.java`:
- Around line 186-194: The method isExcludedPath should guard against a null
return from configuration.getExcludePaths() to avoid a NullPointerException;
update isExcludedPath (which uses serverContext.getConfigurationRoot(),
configuration.getExcludePaths(), and calls PathExclusionUtils.isExcluded) to
treat a null patterns the same as an empty list (e.g., check patterns == null ||
patterns.isEmpty() or substitute Collections.emptyList()) before calling
PathExclusionUtils.isExcluded so the method returns false when there are no
patterns.
In
`@src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/PathExclusionUtils.java`:
- Around line 53-72: The isExcluded method currently calls root.relativize(path)
and can throw IllegalArgumentException for non-subpaths; change it to first
check that the path is a subpath of root (e.g., use
path.normalize().startsWith(root.normalize()) or an equivalent startsWith check)
and if not return false immediately, then call relativize and proceed to test
patterns via matchesPattern; remove or avoid throwing IllegalArgumentException
for that case so non-subpaths simply yield false.
🧹 Nitpick comments (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfiguration.java (1)
58-59: Prefer immutable default forexcludePaths.If callers replace the list via setter (instead of mutating it in place), using an immutable default aligns with project conventions and avoids shared mutable state.
♻️ Proposed refactor
-import java.util.ArrayList; import java.util.List; @@ - private List<String> excludePaths = new ArrayList<>(); + private List<String> excludePaths = List.of();Based on learnings: In BSL Language Server configuration classes, immutable collections (Set.of, List.of) should be used for default values, while mutability is achieved through setters generated by Data annotation.
Also applies to: 123-128
src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLWorkspaceService.java
Show resolved
Hide resolved
src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/PathExclusionUtils.java
Show resolved
Hide resolved
- Добавлен класс PathExclusionUtils для обработки исключения путей на основе заданных пользователем шаблонов. - Обновлены классы BSLWorkspaceService, AnalyzeCommand, FormatCommand и ServerContext для использования логики исключения путей. - Добавлен параметр конфигурации 'excludePaths' в LanguageServerConfiguration и обновлен файл schema.json в соответствии с этим изменением. - Улучшены методы обработки файлов для пропуска исключенных путей во время создания и изменения файлов. Это повышает производительность, предотвращая ненужную обработку файлов в указанных каталогах.
… в ServerContext и PathExclusionUtils - Добавлены тесты для AnalyzeCommand и FormatCommand, проверяющие функциональность и обработку исключенных путей. - Обновлен ServerContextTest для проверки исключения путей из конфигурации. - Добавлен новый утилитный класс PathExclusionUtilsTest для тестирования логики исключения путей. - Включен файл конфигурации .bsl-language-server-exclude-paths.json для настройки исключенных путей. Эти изменения улучшают тестовое покрытие и обеспечивают корректную работу новых функций исключения путей.
5fc3704 to
8502b8c
Compare
There was a problem hiding this comment.
Pull request overview
This pull request adds an excludePaths configuration option to BSL Language Server, allowing users to exclude specified directories and files from indexing and analysis. The feature supports both simple directory names (e.g., .git, node_modules) and glob patterns (e.g., **/.git/**).
Changes:
- Added
excludePathsfield to LanguageServerConfiguration with JSON schema documentation - Implemented PathExclusionUtils utility for cross-platform path matching using simple name segments and glob patterns
- Integrated exclusion logic into ServerContext.populateContext(), BSLWorkspaceService file watchers, and CLI commands (analyze, format)
- Added comprehensive unit and integration tests covering various exclusion scenarios
Reviewed changes
Copilot reviewed 13 out of 13 changed files in this pull request and generated 8 comments.
Show a summary per file
| File | Description |
|---|---|
| src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfiguration.java | Added excludePaths field as a List with default empty ArrayList |
| src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/PathExclusionUtils.java | New utility class implementing path exclusion logic with support for simple names and glob patterns |
| src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java | Filters files in populateContext() based on excludePaths configuration |
| src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLWorkspaceService.java | Added isExcludedPath() method and integrated exclusion checks in file watcher event handlers |
| src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java | Filters files during analysis based on excludePaths configuration |
| src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java | Filters files during formatting based on excludePaths configuration |
| src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json | Added JSON schema definition for excludePaths array |
| src/test/java/com/github/_1c_syntax/bsl/languageserver/utils/PathExclusionUtilsTest.java | Unit tests covering path matching logic, edge cases, and platform-specific scenarios |
| src/test/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContextTest.java | Integration test verifying exclusion during context population |
| src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLWorkspaceServiceTest.java | Tests for file watcher exclusion behavior and test infrastructure improvements |
| src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommandTest.java | CLI analyze command tests with exclusion configuration |
| src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommandTest.java | CLI format command tests with exclusion configuration |
| src/test/resources/.bsl-language-server-exclude-paths.json | Test configuration file with sample excludePaths |
src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/PathExclusionUtils.java
Outdated
Show resolved
Hide resolved
src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommandTest.java
Outdated
Show resolved
Hide resolved
| normalizedRoot = resolveCanonical(normalizedRoot); | ||
| normalizedPath = resolveCanonical(normalizedPath); |
There was a problem hiding this comment.
Performance consideration: The resolveCanonical method is called for both root and path on every isExcluded call (lines 66-67). For large projects with many files, this could result in many filesystem operations. Consider caching the canonical root path since it doesn't change during the lifetime of the context, or only resolving to canonical form when necessary (e.g., when symbolic links are involved).
There was a problem hiding this comment.
Кэширование не делаем потому что: PathExclusionUtils - статическая утилита, корень и пути приходят аргументами, контекста для кэша нет. Вызовы resolveCanonical нужны для корректной работы на Windows (разные пути из URI и из ФС). Без них ломается проверка исключений. Если профилирование покажет, что это узкое место, кэш можно добавить на уровне вызывающего кода (например, в BSLWorkspaceService), а не внутри утилиты.
src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLWorkspaceService.java
Outdated
Show resolved
Hide resolved
src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/PathExclusionUtils.java
Outdated
Show resolved
Hide resolved
src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json
Outdated
Show resolved
Hide resolved
src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLWorkspaceService.java
Outdated
Show resolved
Hide resolved
src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/PathExclusionUtils.java
Outdated
Show resolved
Hide resolved
- Обновлен BSLWorkspaceService для обработки нулевых шаблонов в конфигурации исключения путей. - Улучшен PathExclusionUtils для нормализации шаблонов glob и добавлена обработка ошибок для недопустимых шаблонов. - Пересмотрена документация schema.json для большей ясности в отношении шаблонов исключения путей. - Добавлен тестовый пример для обеспечения правильной обработки недопустимых шаблонов glob в PathExclusionUtilsTest. Эти изменения повышают надежность функциональности исключения путей и улучшают руководство пользователя в схеме конфигурации.
- Внедрен SLF4J логгер для класса BSLWorkspaceService. - Добавлено отладочное сообщение при возникновении исключения при приведении пути к файловой системе. Эти изменения улучшат возможности отладки и помогут в диагностике проблем с путями в файловой системе.
|



Описание
Добавлена опция конфигурации
excludePathsдля исключения указанных каталогов и файлов из индексации и анализа.Изменения:
.bsl-language-server.json) добавлено полеexcludePaths— массив строк (по умолчанию[]). Элементы задают пути для исключения: простые имена каталогов (например,.git,node_modules) или glob-паттерны (например,**/.git/**,**/.*).PathExclusionUtils: для простых имён (без/и*) проверка идёт по сегментам пути (кроссплатформенно); для паттернов с/или*используется Java NIO PathMatcher (glob).ServerContext.populateContext()— при первоначальном сканировании проекта;BSLWorkspaceService.didChangeWatchedFiles— при создании/изменении файлов по file watcher;AnalyzeCommand(CLI-a) иFormatCommand(CLI-f) — при анализе и форматировании.excludePathsвschema.json.PathExclusionUtilsTest(юнит-тесты для сопоставления путей) иServerContextTest.testPopulateContextExcludesPathsFromConfig()(интеграционный тест фильтрации при populateContext).Связанные задачи
Closes #3584
Чеклист
Общие
gradlew precommit)Дополнительно
Пример конфигурации в
.bsl-language-server.json:{ "excludePaths": [".git", ".*", "node_modules"] }.git— всё внутри каталога.gitне индексируется..*— каталоги и файлы с именем, начинающимся с точки (.git,.idea,.vscodeи т.п.).node_modules— каталогnode_modulesи его содержимое.Поддерживаются и полные glob-паттерны, например:
"**/.git/**","**/vendor/**".Логика реализована на стороне BSL Language Server (один конфиг для всех клиентов: VSCode, IDEA и т.д.).
Summary by CodeRabbit
New Features
Bug Fixes
Documentation
Tests