Skip to content

fix(cli): активировать workspace до поиска файлов для форматирования - #4594

Merged
nixel2007 merged 1 commit into
1c-syntax:developfrom
DimaShapovaloff:codex/fix-4575-cli-format
Oct 10, 2026
Merged

nixel2007 merged 1 commit into
1c-syntax:developfrom
DimaShapovaloff:codex/fix-4575-cli-format

Conversation

@DimaShapovaloff

@DimaShapovaloff DimaShapovaloff commented Oct 9, 2026 •

Copy link
Copy Markdown

Описание

CLI-команда format падает с ScopeNotActiveException при запуске без заранее активированного workspace: поиск файлов читает configuration.getExcludePaths() до создания контекста.

Поиск файлов и проверка пустого результата перенесены внутрь активного workspace. Добавлен параметризованный регрессионный тест для отдельного файла и каталога: проверяются успешное завершение, фактическое форматирование и освобождение контекста. На исходной реализации оба сценария воспроизводят ошибку.

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

Closes #4575

Чеклист

  • Ветка PR создана от актуального develop
  • Изменения ограничены исправлением и регрессионными тестами
  • Изменения покрыты тестами
  • Выполнен gradlew precommit

Проверка

  • Java 21, macOS.
  • test --tests '*FormatCommandTest' spotlessCheck bootJar: успешно; все 8 тестов команды прошли.
  • На исходной реализации два новых сценария падают с ScopeNotActiveException.
  • Собранный JAR проверен отдельными процессами java -jar … format -s … -q: файл и каталог успешно форматируются (код 0); пустой каталог и отсутствующий путь возвращают код 1 без ошибки контекста.
  • Проверена фактическая вставка отступа в тело процедуры.

Изменение относится к CLI, а не к диагностике BSL. SonarQube для проверки этого пути выполнения не использовался. Полный набор тестов проекта в рамках этого исправления не запускался.

Summary by CodeRabbit

  • Bug Fixes
    • Formatting now succeeds when run without an active workspace, whether targeting a single BSL file or a directory. Formatted content is preserved, and the workspace context is cleared after the command finishes.

@coderabbitai

coderabbitai Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: 1c-syntax/bsl-language-server/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 30c26250-1574-4d0e-b2ab-c03a41135e3e

📥 Commits

Reviewing files that changed from the base of the PR and between 1ceb3a8 and aa3c041.


📒 Files selected for processing (2)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommandTest.java

Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 0 remain after this review.



📝 Walkthrough

Walkthrough

FormatCommand.call() now creates and activates the workspace context before discovering files. Tests cover formatting a single file or directory without an initially active workspace.

Changes

CLI format workspace context

Layer / File(s) Summary
Activate context before file discovery
src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java, src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommandTest.java
File discovery and the empty-result check now run inside the workspace context. The parameterized test checks successful formatting and confirms that no workspace context remains afterward.

Priority: ➖ Normal

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Medium


Merge Risk: ⚪ Minimal · up to aa3c0

The change addresses the reported CLI formatting failure, and no material merge-blocking risk remains in the reviewed scope.

Pre-merge checks | Passed 4 | Failed 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 3 functions across 2 files. 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 clearly and concisely describes the main change: activating the workspace before discovering files for formatting in the CLI.
Linked Issues check Passed Для #4575 код активирует workspace до вызова findFilesForFormatting(). Чтение configuration.getExcludePaths() теперь выполняется внутри WorkspaceContextHolder.forUri(...). Параметризованный тест…
Out of Scope Changes check Passed По сводке PR изменены только FormatCommand.java и FormatCommandTest.java. Изменения исправляют порядок активации workspace и добавляют регрессионный тест для #4575. Нерелевантные изменения не уста…


  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR


  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

@sfaqer sfaqer left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Фикс правильный. Теперь findFilesForFormatting(), который читает workspace-scoped configuration.getExcludePaths(), вызывается внутри WorkspaceContextHolder.forUri(...) после addWorkspace, как и в AnalyzeCommand. Thread-local после close() восстанавливается, новый тест это проверяет.

Замечание к существующему тесту callWithExcludePathsRunsSuccessfully (стр. 67–82, вне диффа, поэтому пишу здесь). После этого PR тест фактически ничего не проверяет:

  • configuration.setExcludePaths(List.of("Catalogs")) применяется к тестовому workspace, который выставляет WorkspaceContextTestExecutionListener.
  • Команда же теперь читает конфигурацию нового workspace (tempDir), а она грузится из <tempDir>/.bsl-language-server.json (LanguageServerConfiguration.init). Значит, excludePaths там пустые.
  • Тест проверяет только код возврата, поэтому то, что исключения учитываются, больше никак не покрыто.

Предлагаю:

  • положить в tempDir файл .bsl-language-server.json с "excludePaths": ["Catalogs"];
  • проверить, что модуль из Catalogs не изменился, а модуль вне исключения отформатирован.

Заодно можно сбрасывать WorkspaceContextHolder в @BeforeEach для всего класса. Именно активный тестовый контекст в остальных тестах и скрывал исходный баг.


Generated by Claude Code


@ParameterizedTest
@ValueSource(booleans = {false, true})
void callFormatsWithoutActiveWorkspace(boolean singleFile) throws Exception {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Nit:

  • У соседних тестов есть однострочный javadoc и разметка // given / // when / // then, здесь их нет.
  • Перед закрывающей } класса осталась лишняя пустая строка (стр. 188).

Generated by Claude Code

@nixel2007
nixel2007 merged commit 7ec676c into 1c-syntax:develop Oct 10, 2026
25 checks passed
@nixel2007

Copy link
Copy Markdown
Member

Спасибо!

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.

[BUG] CLI format падает с ScopeNotActiveException: workspace-scoped конфиг читается до активации контекста

3 participants