Skip to content

feat: Добавлена ​​функция исключения путей в BSL Language Server#3805

Open
johnnyshut wants to merge 4 commits into1c-syntax:developfrom
johnnyshut:feature/path-exclussion
Open

feat: Добавлена ​​функция исключения путей в BSL Language Server#3805
johnnyshut wants to merge 4 commits into1c-syntax:developfrom
johnnyshut:feature/path-exclussion

Conversation

@johnnyshut
Copy link
Contributor

@johnnyshut johnnyshut commented Feb 3, 2026

Описание

Добавлена опция конфигурации excludePaths для исключения указанных каталогов и файлов из индексации и анализа.

Изменения:

  • В конфигурацию BSL Language Server (.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) — при анализе и форматировании.
  • Файлы из исключённых путей по-прежнему можно открывать в редакторе (didOpen); исключение действует только на массовую индексацию и file watcher.
  • Добавлена схема и описание excludePaths в schema.json.
  • Добавлены тесты: PathExclusionUtilsTest (юнит-тесты для сопоставления путей) и ServerContextTest.testPopulateContextExcludesPathsFromConfig() (интеграционный тест фильтрации при populateContext).

Связанные задачи

Closes #3584

Чеклист

Общие

  • Ветка PR обновлена из develop
  • Отладочные, закомментированные и прочие, не имеющие смысла участки кода удалены
  • Изменения покрыты тестами
  • Обязательные действия перед коммитом выполнены (запускал команду 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

    • Configurable excludePaths to skip files from indexing, analysis, formatting, CLI commands, and live file events.
  • Bug Fixes

    • File-watching, workspace population, formatting and analyze flows now respect configured excludes and avoid processing excluded files.
  • Documentation

    • Configuration schema updated with excludePaths array, examples, and default empty list.
  • Tests

    • Added unit and integration tests covering exclusion matching, CLI behavior, context population, and workspace events.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 3, 2026

📝 Walkthrough

Walkthrough

Adds 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

Cohort / File(s) Summary
Path Exclusion Utility
src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/PathExclusionUtils.java
New non-instantiable utility exposing isExcluded(Path root, Path path, List<String> patterns) with canonicalization, simple-name and glob matching, and defensive handling.
Configuration & Schema
src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfiguration.java, src/main/resources/.../configuration/schema.json
Adds excludePaths: List<String> to runtime configuration and JSON schema (default []) to declare root-relative exclude patterns.
Workspace Service
src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLWorkspaceService.java
Integrates exclusion checks into created/changed file handlers; early-return for excluded URIs to skip add/update and rebuild flows; adds logging.
Context Population
src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java
Filters initial file discovery by configured exclude patterns before populating the server context.
CLI Commands
src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java, src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java
File collection/formatting now apply exclude filtering when configuration root and exclude paths are present; FormatCommand now depends on LanguageServerConfiguration.
Tests
src/test/java/.../utils/PathExclusionUtilsTest.java, src/test/java/.../context/ServerContextTest.java, src/test/java/.../BSLWorkspaceServiceTest.java, src/test/java/.../cli/*CommandTest.java
Adds comprehensive unit tests for PathExclusionUtils and updates integration/CLI tests to cover excludePaths behavior and excluded-file event scenarios.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • nixel2007

Poem

🐇 I hop through folders, patterns in paw,
I sniff the globs and skip the straw,
I nudge out CommonModules, dotdirs, and more,
Quiet the watch, leave fewer doors,
Carrot-debugged and ready to soar! 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.37% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: Добавлена ​​функция исключения путей в BSL Language Server' clearly and specifically describes the main change: adding path exclusion functionality to the BSL Language Server.
Linked Issues check ✅ Passed The PR fully addresses issue #3584 requirements: implements configurable path exclusion via excludePaths configuration option, supports simple names and glob patterns, applies exclusion during initial scanning and file watcher events, and includes comprehensive tests.
Out of Scope Changes check ✅ Passed All changes are directly related to implementing path exclusion functionality as specified in issue #3584. The additions to configuration, utilities, CLI commands, workspace service, and tests are all aligned with the stated objectives.

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
Contributor

@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

🤖 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 by TestRunnerAdapterOptions. Since @Data annotation generates setters, mutability is handled through Lombok-generated setters rather than mutable defaults. Change excludePaths to use List.of() for consistency with the pattern.

No in-place mutations of excludePaths were found, so the change is safe.

♻️ Proposed change
-  private List<String> excludePaths = new ArrayList<>();
+  private List<String> excludePaths = List.of();

@johnnyshut johnnyshut force-pushed the feature/path-exclussion branch from dc2112e to 3dc978d Compare February 3, 2026 12:34
Copy link
Contributor

@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: 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 for excludePaths.

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

- Добавлен класс PathExclusionUtils для обработки исключения путей на основе заданных пользователем шаблонов.

- Обновлены классы BSLWorkspaceService, AnalyzeCommand, FormatCommand и ServerContext для использования логики исключения путей.

- Добавлен параметр конфигурации 'excludePaths' в LanguageServerConfiguration и обновлен файл schema.json в соответствии с этим изменением.

- Улучшены методы обработки файлов для пропуска исключенных путей во время создания и изменения файлов.

Это повышает производительность, предотвращая ненужную обработку файлов в указанных каталогах.
… в ServerContext и PathExclusionUtils

- Добавлены тесты для AnalyzeCommand и FormatCommand, проверяющие функциональность и обработку исключенных путей.
- Обновлен ServerContextTest для проверки исключения путей из конфигурации.
- Добавлен новый утилитный класс PathExclusionUtilsTest для тестирования логики исключения путей.
- Включен файл конфигурации .bsl-language-server-exclude-paths.json для настройки исключенных путей.

Эти изменения улучшают тестовое покрытие и обеспечивают корректную работу новых функций исключения путей.
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

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 excludePaths field 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

Comment on lines +66 to +67
normalizedRoot = resolveCanonical(normalizedRoot);
normalizedPath = resolveCanonical(normalizedPath);
Copy link

Copilot AI Feb 4, 2026

Choose a reason for hiding this comment

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

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

Copilot uses AI. Check for mistakes.
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Кэширование не делаем потому что: PathExclusionUtils - статическая утилита, корень и пути приходят аргументами, контекста для кэша нет. Вызовы resolveCanonical нужны для корректной работы на Windows (разные пути из URI и из ФС). Без них ломается проверка исключений. Если профилирование покажет, что это узкое место, кэш можно добавить на уровне вызывающего кода (например, в BSLWorkspaceService), а не внутри утилиты.

- Обновлен BSLWorkspaceService для обработки нулевых шаблонов в конфигурации исключения путей.

- Улучшен PathExclusionUtils для нормализации шаблонов glob и добавлена ​​обработка ошибок для недопустимых шаблонов.

- Пересмотрена документация schema.json для большей ясности в отношении шаблонов исключения путей.

- Добавлен тестовый пример для обеспечения правильной обработки недопустимых шаблонов glob в PathExclusionUtilsTest.

Эти изменения повышают надежность функциональности исключения путей и улучшают руководство пользователя в схеме конфигурации.
- Внедрен SLF4J логгер для класса BSLWorkspaceService.
- Добавлено отладочное сообщение при возникновении исключения при приведении пути к файловой системе.

Эти изменения улучшат возможности отладки и помогут в диагностике проблем с путями в файловой системе.
@sonarqubecloud
Copy link

sonarqubecloud bot commented Feb 5, 2026

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