feat: built-in completions command with shell script generation#88
Open
nixel2007 wants to merge 11 commits intooscript-library:developfrom
Open
feat: built-in completions command with shell script generation#88nixel2007 wants to merge 11 commits intooscript-library:developfrom
nixel2007 wants to merge 11 commits intooscript-library:developfrom
Conversation
Добавлена команда `completions` на уровне cli-библиотеки, которая формирует скрипты автодополнения для bash, zsh и PowerShell. Новые возможности ПараметрКоманды: - ПоставщикДополнения(Объект, ИмяМетода) — регистрация поставщика вариантов автодополнения значений параметра. - ПолучитьЗначенияДополнения() — вызов поставщика и безопасное получение списка вариантов (с обработкой исключений). - ПолучитьИмя/ПолучитьСинонимы/ПолучитьТипПараметра — публичные аксессоры для расширенной работы с параметрами. Новые API КомандаПриложения: - ПолучитьОпцииПараметрами/ПолучитьАргументыПараметрами — доступ к объектам ПараметрКоманды (в отличие от ПолучитьТаблицуОпций, которая отдаёт только их свойства). КонсольноеПриложение автоматически регистрирует подкоманду `completions --shell bash|zsh|pwsh`. Команда обходит дерево подкоманд, опрашивает поставщиков дополнения у каждого параметра и запекает полученные списки в итоговый скрипт — никакого runtime обращения к приложению из скрипта автодополнения. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
Pull request overview
This PR, as presented in the diff, updates the package metadata version for the cli package.
Changes:
- Bump
clipackage version from0.11.0to0.12.0.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
- Moved КомандаДополнения.os from internal/completion/Классы/ to core/Классы/ (next to other public command classes). - Registered the class in packagedef so it can be instantiated by name. - #Использовать of the internal/completion subpackage (shell generators) now lives only in КомандаДополнения itself, not in КонсольноеПриложение. - Generators are constructed in ПриСозданииОбъекта instead of module body. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…r model Use the built-in table API instead of bespoke getters: the table already carries the fully-resolved НаименованияПараметров (with - / -- prefixes) and the argument name, so the heuristic about synonym length disappears. - КомандаПриложения: added 'Параметр' column to the help-data table, carrying the ПараметрКоманды object reference so consumers can reach the completion provider without extra getters. - Dropped ПолучитьОпцииПараметрами / ПолучитьАргументыПараметрами (added in previous commit, never used outside КомандаДополнения). - Dropped ПолучитьИмя / ПолучитьСинонимы / ПолучитьТипПараметра on ПараметрКоманды (fields Имя / Синонимы / ТипПараметра are already exported). - КомандаДополнения.ПостроитьОписаниеПараметра reads НаименованияПараметров straight from the table row — no ФлагИзСинонима heuristic any more. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Instead of carrying a reference to ПараметрКоманды, the help-data table row now carries the already-resolved list in a dedicated ЗначенияДополнения column, computed once in ПолучитьТаблицуПараметров via Параметр.ПолучитьЗначенияДополнения(). КомандаДополнения consumes only table columns — no reach-through to the parameter object. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
ПараметрКоманды no longer imports the external delegate package — the completion provider is invoked via the language-native Действие(Объект, ИмяМетода).Выполнить(). delegate stays as a cli-wide dependency for КомандаПриложения, which still uses Делегаты.Создать extensively. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
The &ПоставщикДополнения contract requires the method to return an array of strings, so return it as-is instead of defensively copying and string-coercing each element. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
All call sites used the same pattern — save a bound method, later invoke with one positional argument — and the built-in Действие type supports this 1:1: Делегаты.Создать(Объект, "Имя") -> Новый Действие(Объект, "Имя") Делегат.Исполнить(Арг) -> Действие.Выполнить(Арг) Removes the external delegate package from cli's dependency graph. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…erators КомандаДополнения.ПостроитьОписаниеКоманды теперь возвращает нормализованную модель с плоскими полями ИмяКаноническое, Алиасы, ИменаОпций, ЗначенияПоОпции, ЗначенияАргументов, Подкоманды. Генераторы bash/zsh/pwsh больше не итерируют по таблицам опций/аргументов — они работают с общей формой, что делает поведение единообразным на любой глубине подкоманд для всех трёх шеллов. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Вводится общий обход дерева команд ОбходчикКомандДополнения, который вызывает на посетителе (генераторе) методы НачатьКоманду / ПосетитьОпцию / ПосетитьАргумент / ПередПодкомандами / ОткрытьПодкоманду / ЗакрытьПодкоманду / ЗавершитьКоманду. Рекурсия по подкомандам живёт в одном месте. Генераторы bash/zsh/pwsh перестают строить промежуточную модель и работают напрямую с методами КомандаПриложения (ПолучитьТаблицуОпций, ПолучитьТаблицуАргументов, ПолучитьПодкоманды, ПолучитьСинонимы). Bash/Zsh эмитят инкрементально по мере обхода; pwsh выполняет post-order сериализацию хэш-таблицы дерева. Добавить новый шелл = написать ещё один посетитель. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Алиасы резолвятся при вводе (через case в bash/zsh и AliasMap-lookup в pwsh), но не должны замусоривать список вариантов автодополнения. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Ветка $words[CURRENT] == -* в генераторе zsh возвращала только аргументы команды, опции не показывались. Добавлена явная ветка с _values для флагов. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds a built-in
completionssubcommand to every cli-based application for generating shell completion scripts (bash, zsh, PowerShell).What's new
ПараметрКомандыПоставщикДополнения(Объект, ИмяМетода)— fluent method to register a completion-value provider on an option/argument. The provider is any exported no-arg function returningМассив<Строка>.ЕстьПоставщикДополнения()/ПолучитьЗначенияДополнения()— invoked by the completion codegen; the latter calls the provider via the nativeДействиеtype and returns its result directly.КомандаПриложенияThe existing help-table (
ПолучитьТаблицуОпций/ПолучитьТаблицуАргументов) now carries an extra columnЗначенияДополнения— the pre-computed provider result — so completion codegen consumes the same model the help renderer already uses. No new ad-hoc accessors are introduced on the command or parameter models.КомандаДополнения+internal/completionNew top-level command class that implements the
completionssubcommand. Shell-specific codegen lives behind a common generator interface (ГенераторДополненияBash/...Zsh/...Pwsh), wired by aТипОболочкиenum exposed as the--shelloption. Theinternal/completionpackage is#Использовать-d only byКомандаДополнения.КонсольноеПриложениеAuto-registers
Новый КомандаДополнения()as a subcommand. The command walks the command tree via the public cli API, invokes each parameter's completion provider, and bakes the resulting lists as literals into the generated shell script — no runtime calls to the app from the completion script.Why
Previously apps had to implement their own completion command and duplicate shell-script generation logic. Moving it into cli gives every cli-based app shell completions out of the box. Apps only need to annotate parameters with their provider method (e.g.
&ПоставщикДополнения("ПолучитьУстановленныеВерсии")in autumn-cli) or call.ПоставщикДополнения(...)fluently.Dependency change
The external
delegatepackage is no longer required — all call sites (both the new completion-provider dispatch and the pre-existing command-lifecycle handlers) now use the built-inДействиеtype.delegatehas been dropped frompackagedef.Testing
Tested via downstream ovm BDD suite (
features/completions.feature, all 10 assertions green) and autumn-cli smoke tests. No breaking changes to existing cli APIs; new methods are additive.Related
&ПоставщикДополненияannotation through the decorator to call.ПоставщикДополнения(...).Co-authored-by: Copilot 223556219+Copilot@users.noreply.github.com