diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dc02ad64..f8b8ebf1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -64,3 +64,70 @@ jobs: - run: dart pub get - run: dart analyze --fatal-infos - run: dart test + + shell_completion: + name: Shell completion integration + strategy: + fail-fast: false + matrix: + include: + # Bash and PowerShell are preinstalled on the Ubuntu runners; + # Zsh, Fish and Carapace are installed below. + - platform: ubuntu-latest + shells: bash,zsh,fish,pwsh,carapace + # PowerShell is preinstalled on the Windows runners. The other + # shells' test harnesses are POSIX scripts and do not run there. + - platform: windows-latest + shells: pwsh + runs-on: ${{ matrix.platform }} + defaults: + run: + working-directory: packages/config + env: + CARAPACE_VERSION: 1.8.1 + steps: + - uses: actions/checkout@v4 + - uses: dart-lang/setup-dart@v1.7.1 + with: + sdk: stable + + - name: Install Zsh and Fish + if: runner.os == 'Linux' + run: | + sudo apt-get update + sudo apt-get install -y zsh fish + + # The runner image makes /usr/share writable by everyone. Zsh does not + # initialize its completion system from such directories without asking + # the user, which it cannot do in the tests. + - name: Make the Zsh function directories secure + if: runner.os == 'Linux' + run: | + zsh -fc 'autoload -Uz compaudit; compaudit 2>/dev/null' | + xargs -r sudo chmod go-w + + - name: Install Carapace + if: runner.os == 'Linux' + run: | + curl -sSL -o /tmp/carapace.tar.gz \ + "https://github.com/carapace-sh/carapace-bin/releases/download/v${CARAPACE_VERSION}/carapace-bin_${CARAPACE_VERSION}_linux_amd64.tar.gz" + sudo tar -xzf /tmp/carapace.tar.gz -C /usr/local/bin carapace + + - name: Show shell versions + if: runner.os == 'Linux' + run: | + bash --version | head -n 1 + zsh --version + fish --version + pwsh --version + carapace --version + + - name: Show shell versions + if: runner.os == 'Windows' + run: pwsh --version + + - run: dart pub get + - name: Run the completion tests in the shells supported on ${{ runner.os }} + run: dart test test/command/completion/shell_integration_test.dart + env: + CLI_COMPLETION_SHELLS: ${{ matrix.shells }} diff --git a/packages/config/README_command.md b/packages/config/README_command.md new file mode 100644 index 00000000..e7500f05 --- /dev/null +++ b/packages/config/README_command.md @@ -0,0 +1,340 @@ +# New Dart CLI authoring framework + +The new `CommandRunner` builds a command-line application from a tree of +commands, typed options, and middlewares. It resolves each +command's configuration from the command line, environment variables, and +configuration files, then runs the last command. Middlewares on a command wraps +the commands below it. + +The command tree, options, and middleware are defined when the runner is created. +Mistakes in those definitions are fail-fast. A mistake in the user's input is +reported as a usage error. Help and shell completion are built in. + +## Design + +Uses the concept of middlewares to customize the execution logic +of the command tree. The legacy CommandRunner relied on method overrides +to customize the execution logic. This middleware approach allows for +cleaner composition. + +Separates static configuration from dynamic execution. The command tree, +options, middlewares, settings for usage output and error handling are +configured statically. Execution performs configuration resolution and +command execution and these do not mutate the CommandRunner, Command, or +Option instances. This provides separation of concerns and makes the command +code reentrant, which also makes it easier to write tests. + +## Persistent options + +A persistent option belongs to the command that defines it and may be written +anywhere after that command on the command line, including after its subcommands. +The value is recorded on the defining command's context where it can be read by +that command as well as its successor commands. + +Global options are the root command's persistent options, so they are valid +anywhere on the command line: + +```sh +executable --verbose subcommand +executable subcommand --verbose +executable subcommand nested --verbose +``` + +A persistent option of a branch command starts at that command: + +```sh +executable build --profile ci check +executable build check --profile ci +``` + +Both set `build`'s `--profile`. A command's own (non-persistent) options are +valid on that command, before the next subcommand. + +> Persistent options are always named; a positional option cannot be persistent, + since it would conflict with additional subcommands. + +## Action options + +An action option behaves similarly to a subcommand. It has a run method and the +runner runs it instead of a subcommand. + +### Example: --version action option + +`--version` is often supported by CLI commands and typically perform no work +besides printing the version information. + +```sh +executable --version +executable --version subcommand # prints the version, subcommand is not run +executable subcommand --version # the same, when --version is a global option +``` + +The rest of the command line is still parsed, so an unknown subcommand or +option is an error. + +### Built-in action options + +`--completion ` is automatically defined in on a runner with no +subcommands. A runner with subcommands has the `completion` subcommand instead. +Both print the completion script for a shell. The subcommand can also install +it, see [Shell completion](#shell-completion). + +### Help + +`--help` / `-h` is an action option and also a persistent option, so it may come +before or after other subcommands. It prints the usage of the last command on +the line. + +```sh +executable --help +executable --help subcommand +executable subcommand --help +``` + +## Commands / actions accepting incomplete command lines + +A command runs when its command line is complete: mandatory options are set, a +mandatory exclusive group has a choice, and a command that requires a +subcommand has one. + +A command or action option that sets `acceptsPartialCommandLine` can runs on +an incomplete line. Action options do this by default; commands do not. This +effectively means that the runner reports what was written on the command line +and ignores any errors due to what was left out: + +- Ignored: a mandatory option never written, a mandatory exclusive group with + no member chosen, and a required subcommand never named. +- Reported: unknown options and subcommands, invalid values, options that + exclude each other, and a missing value for an option that was written + (`--target` with nothing after it). + +The ignored errors stay on `CommandContext.config.errors`. + +```sh +executable deploy --help # prints usage, even without mandatory options +executable help deploy # prints usage, via the help command +executable deploy --bogus --help # error: unknown option +executable deploy --help --target # error: missing value for --target +``` + +The built-ins `--help`, the `help` command, and `--completion` accept an +incomplete line. +A custom command opts in by overriding `acceptsPartialCommandLine`. + +## Shell completion + +The `CommandRunner` in `package:config/command.dart` has built-in command line +completion for Bash, Zsh, Fish, PowerShell and the +[Carapace](https://carapace.sh) completion framework. It is enabled by default +and requires no work from the CLI developer. + +End users install the completion once. A `CommandRunner` with subcommands gets +a `completion` subcommand, whose `install` subcommand installs the completion +for the current user: + +```sh +mycli completion install # for the shell it is run from +mycli completion install --dry-run # only print what it would do +mycli completion install --shell zsh # for a given shell +``` + +It prints each change it makes. The script is saved where the shell looks for +it, and for the shells that need it, lines that load the script are appended +to the shell's startup file: + +| Shell | Script | Startup file | +|------------|------------------------------------------------------------|-----------------------------------------| +| Bash | `~/.local/share/bash-completion/completions/mycli` | `~/.bashrc` (macOS: `~/.bash_profile`) | +| Zsh | `~/.local/share/zsh/site-functions/_mycli` | `~/.zshrc` | +| Fish | `~/.config/fish/completions/mycli.fish` | | +| PowerShell | `Completions/mycli.ps1` next to the profile | `$PROFILE` | +| Carapace | `carapace/specs/mycli.yaml` in the user config directory | | + +`XDG_DATA_HOME`, `XDG_CONFIG_HOME`, `BASH_COMPLETION_USER_DIR` and `ZDOTDIR` +are honored. Installing again overwrites the script and leaves a startup file +that already loads it as it is. In Zsh, the added lines also initialize the +completion system (`compinit`) if the startup file has not done so. + +Without a subcommand, `completion` prints the script instead, for a manual +installation: + +```sh +# Bash: add to ~/.bashrc +source <(mycli completion --shell bash) +# Zsh: add to ~/.zshrc after compinit, or save as _mycli in a directory on $fpath +source <(mycli completion --shell zsh) +# Fish +mycli completion --shell fish > ~/.config/fish/completions/mycli.fish +# PowerShell: add to $PROFILE +mycli completion --shell powershell | Out-String | Invoke-Expression +# Carapace: save to the specs directory shown by `carapace --help` +mycli completion --shell carapace > ~/.config/carapace/specs/mycli.yaml +``` + +`--shell` and `--command` are persistent options of `completion`, so they may +be written before or after `install`. When `--shell` is not given, the shell +is detected (`detectCompletionShell`): it is the nearest ancestor process that +is a shell the user types in, so a wrapper script of the CLI does not hide the +shell it was started from. Failing that it is the login shell (`$SHELL`), or +PowerShell on Windows. If no supported shell is found, a usage error asks for +`--shell`. Carapace is not a shell and is always given explicitly. + +A `CommandRunner` without subcommands has the built-in global option +`--completion ` instead (listed under "Global options" next to +`--help`), which prints the same script: + +```sh +source <(mycli --completion bash) +``` + +Like `--help`, `--completion` acts on the command line as given: when present, +the script is printed and nothing else runs, even if the command line is +otherwise incomplete. The installation instructions for a shell are in the +comment header of its script; `mycli completion --help` lists them for all +shells. + +For a wrapper script of the CLI (same commands and options under another +name), install or generate the script with `--command `: +`mycli completion install --command mywrap`, or +`source <(mycli completion --shell bash --command mywrap)`. The script then +completes `mywrap`, while sending the completion requests to `mycli` directly, +so that nothing the wrapper prints or adds to the arguments can interfere. +Programs without subcommands can do the same via the API, +`CompletionShell.bash.script('mycli', commandName: 'mywrap', viaOption: true)`. + +The scripts contain no commands or options. On each TAB, the shell runs +`mycli __complete ` and the runner answers +with the alternatives, so the installed script keeps working when the CLI is +updated. The request and response format is that of Cobra's `__complete` +command (one `valuedescription` line per alternative, then a `:` +directive line), which is why Carapace can bridge to it. + +The completion output must be the only output on stdout. After a completion +response or script has been written, `CommandRunner.run()` returns null, and +anything the program then prints (such as the result) would corrupt it. A +program that does so should set `CompletionSettings.exitAfterResponse`, see +below: the process then exits with exit code 0 as soon as the completion +output has been written. + +### What gets completed + +- Subcommand names (not hidden ones), with the first line of their description. +- Option names: `--name`, `--no-name` for negatable flags, and `-x` + abbreviations, excluding hidden options and non-repeatable options already + given on the command line. Subcommands spelled like options + (e.g. `--version`) are included. +- Option values and positional arguments, depending on the option type: + - `EnumOption`: the enum values. + - Options with `allowedValues` (or `allowedHelp`): those values, with the + help text as description. + - `MultiOption`: the allowed element values, keeping the elements already + typed before the separator (`a,b` offers `a,b,c`). + - `DirOption`: the shell's own directory completion. + - `FileOption`, and any other option type without known values + (e.g. `StringOption`, `IntOption`): the shell's own file completion. + - `FlagOption`: nothing. +- `--option=value` is completed as well. +- Mutually exclusive option groups: once an option of a `MutuallyExclusive` + group is given (by name or as a positional argument), the other options of + the group are no longer offered, and a positional argument belonging to the + group is not completed. + +Completion works on partial command lines, so missing mandatory options or +subcommands never block it. The same goes for the built-in `help` command: +`mycli help deploy` shows the usage of `deploy` even though its mandatory +options are not given, just like `mycli deploy --help` does. + +### Custom completion for an option type + +Override `complete` on an option type to offer your own alternatives, +synchronously or asynchronously: + +```dart +class ServerOption extends StringOption { + const ServerOption({super.argName, super.helpText}); + + @override + Future complete(final CompletionContext context) async { + final servers = await fetchServerNames(); + return CompletionResult.values([ + for (final server in servers) + CompletionCandidate(server.name, description: server.region), + ]); + } +} +``` + +`CompletionContext` provides the word being completed, the preceding words, +the commands on the command line, and the raw (unvalidated) string values of +the options already typed, via `context.parsedArgs`. The shell's environment +variables are available as `context.environment` for custom completions that +need them (e.g. a server URL to fetch the alternatives from). + +When the `CommandRunner` completes an option value, it also resolves the +configurations of the commands typed so far, from the arguments, environment +variables, configuration files and the configuration broker, like when the +command line is run. Since the command line is not finished, errors such as +missing mandatory options are not reported. They stay on +`CommandContext.config.errors`. `commandContextOf(context)` returns the +resolved context of the last command, and its `prev` contexts are those of +the preceding commands: + +```dart +@override +CompletionResult complete(final CompletionContext context) { + final leaf = commandContextOf(context); + final project = leaf?.config.optionalValue(projectOption); + return CompletionResult.strings(resourceNames(project)); +} +``` + +The middleware of those commands runs as well, around the `complete` call, +so that it can prepare what `complete` needs, e.g. store a service on +`CommandContext.provider`. No command `run` method is called. A middleware +tells the two apart with `CommandContext.isCompletion`, and should skip +anything meant only for a command being run, such as analytics or printing: +output on stdout would end up among the completion alternatives. + +Subcommand and option name completion neither resolves configurations nor +runs middleware. Completion should be fast and should not throw. If resolving +the configurations, a middleware or `complete` throws, nothing is offered. + +Besides `CompletionResult.values(...)` and `.strings(...)`, the result can be +`CompletionResult.files(extensions: ['yaml', 'yml'])`, `.directories()` or +`.none()`. The candidates are offered as returned; the shell filters them by +the typed prefix. + +### Settings + +```dart +CommandRunner( + 'mycli', + 'My CLI', + // Disable all completion support: + completion: CompletionSettings.disabled, + // Or keep it but leave the completion command out of the usage help: + // completion: CompletionSettings(hideCommand: true), + // Or exit the process right after completion output, instead of returning + // from run(): completion: CompletionSettings(exitAfterResponse: true), +); +``` + +A CLI that defines its own `completion` subcommand takes precedence over the +built-in one. That subcommand can be a `CompletionCommand` with its own +`CompletionInstaller`: + +```dart +CompletionCommand( + installer: CompletionInstaller(environment: {'HOME': sandboxHome}), +) +``` + +The options of the built-in command, `--shell` and `--command` +(`CompletionOption`) and `--dry-run` (`CompletionInstallOption`), +must not be the names of global options of the application. + +The built-in global options `--help` and `--completion` +(`BuiltinGlobalOption`) are kept apart from the application's typed +`globalOptions`, so they are available for any option type without being +listed; the application's global options must not share their names or +abbreviations. diff --git a/packages/config/example/command_example.dart b/packages/config/example/command_example.dart new file mode 100644 index 00000000..252bd239 --- /dev/null +++ b/packages/config/example/command_example.dart @@ -0,0 +1,253 @@ +import 'dart:async' show FutureOr; +import 'dart:io' show exit; + +import 'package:config/command.dart'; +import 'package:config/config.dart'; + +const _version = '1.0.0'; + +/// A CommandRunner framework example that uses: +/// - global options, action options, and regular options +/// - middleware for usage analytics +/// - middleware for command span timing +/// - storing state on the [ContextProvider] +/// - subcommands with options and run functions +Future main(final List args) async { + final dateCommand = CommandImpl.leafWithRunFunction( + name: 'date', + description: 'Display the current date', + options: DateOption.values, + run: (final CommandContext runContext) { + final utc = runContext.config.value(DateOption.utc); + final date = utc ? DateTime.timestamp() : DateTime.now(); + print(date.toIso8601String()); + return null; + }, + ); + + final versionCommand = CommandImpl.leafWithRunFunction( + name: 'version', + description: 'Display the version', + run: (final CommandContext runContext) { + print('version $_version'); + return 0; + }, + ); + + final branchCommand = CommandImpl.branch( + name: 'branch', + description: 'Branch command with subcommands', + subcommands: [ + CommandImpl.leafWithRunFunction( + name: 'child', + description: 'Child command', + run: (final CommandContext runContext) { + print('running child command'); + return 0; + }, + ), + ], + ); + + bool analyticsEnabled() => true; + + final runner = CommandRunner( + 'command_example', + 'A simple example using CommandRunner and Command', + globalOptions: GlobalOption.values, + subcommands: [ + dateCommand, + versionCommand, + branchCommand, + ], + canRunAsLeafCommand: true, + // This example prints after the runner returns, which would corrupt the + // output of a shell completion request: exit right after that instead. + completion: const CompletionSettings(exitAfterResponse: true), + usageOutput: UsageOutputHandler( + addExceptionHandlers: [ + UsageExceptions.simpleHandler( + (_, _, _) => makeAnalyticsSender(analyticsEnabled, onAnalyticsEvent)( + 'invalid', + ), + ), + ], + ), + middlewares: [ + AnalyticsMiddleware(analyticsEnabled).middleware, + const CommandSpanMiddleware().middleware, + ], + ); + + try { + final result = await runner.run(args); + print('>>> result: $result'); + if (result is int) { + exit(result); + } + } on UsageException { + print('\nUsage exception, exiting with code 1'); + exit(1); + } +} + +/// `--version` / `-v`: prints the version instead of running a subcommand. +class VersionActionOption extends FlagOption with ActionOptionMixin { + /// Creates the version action option. + const VersionActionOption() + : super( + argName: 'version', + argAbbrev: 'v', + negatable: false, + helpText: 'Display the version', + ); + + @override + FutureOr run( + final CommandContext context, + ) { + print('version $_version'); + return null; + } +} + +/// Options of the example's root command. +enum GlobalOption implements OptionDefinition { + size( + IntOption( + argName: 'size', + argAbbrev: 's', + argAliases: ['c', 'scope'], + envName: 'COMMAND_EXAMPLE_SIZE', + configKeys: ['size'], + helpText: + 'Excercises option usage formatting with a long long long long long' + ' long long long long help text.', + defaultsTo: 1024, + valueHelp: 'value-help', + allowedValues: [1024, 2048, 4096, 8192, 16384], + ), + ), + version(VersionActionOption()); + + const GlobalOption(this.option); + + @override + final ConfigOptionBase option; +} + +/// Options for the `date` command. +enum DateOption implements OptionDefinition { + utc( + FlagOption( + argName: 'utc', + argAbbrev: 'u', + helpText: 'Display timestamps in UTC timezone instead of local.', + negatable: true, + defaultsTo: false, + envName: 'COMMAND_EXAMPLE_DISPLAY_UTC', + ), + ); + + const DateOption(this.option); + + @override + final ConfigOptionBase option; +} + +/////////////// +// Analytics example + +/// A function type for tracking events. +typedef OnAnalyticsEvent = + void Function( + String event, { + Map? properties, + }); + +/// Prints an analytics event. Stands in for a real analytics client. +void onAnalyticsEvent( + final String event, { + final Map? properties, +}) { + print('Analytics event: $event, properties: $properties'); +} + +/// Returns an [OnAnalyticsEvent] that sends events only when analytics is on. +OnAnalyticsEvent makeAnalyticsSender( + final bool Function() analyticsEnabled, + final OnAnalyticsEvent onAnalyticsEvent, +) { + return ( + final String event, { + final Map? properties, + }) { + if (analyticsEnabled()) { + try { + onAnalyticsEvent.call(event, properties: properties); + } catch (_) { + // Silently ignore analytics sending errors to not disrupt the main flow + } + } + }; +} + +/// Sends the command name before the command line runs. +/// +/// Middleware also runs when the shell completes an option value. That is +/// not a command execution, so no event is sent then. +class AnalyticsMiddleware extends CommandMiddlewareHooks { + final bool Function() analyticsEnabled; + + const AnalyticsMiddleware(this.analyticsEnabled); + + @override + CommandContext onRun( + final CommandContext context, + ) { + if (context.isCompletion) return context; + makeAnalyticsSender(analyticsEnabled, onAnalyticsEvent)( + context.root().next?.command.name ?? context.command.name, + ); + return context; + } +} + +/////////////// +// Command span example (logic before and after a command runs) + +/// Stopwatch for one command span, stored on the run's [ContextProvider]. +class CommandSpan { + final Stopwatch stopwatch = Stopwatch()..start(); +} + +/// Times a command from the moment it starts until it returns. +/// +/// The stopwatch is stored on [CommandContext.provider] so the middleware +/// object itself holds no per-run state. +/// +/// Does nothing when the shell completes an option value: no command runs +/// then, and anything printed would corrupt the completion response. +class CommandSpanMiddleware + extends CommandMiddlewareHooks { + const CommandSpanMiddleware(); + + @override + CommandContext onRun(final CommandContext context) { + if (context.isCompletion) return context; + context.provider.store(CommandSpan()); + print('>>> ${context.leaf().command.name} started'); + return context; + } + + @override + T? onReturn(final CommandContext context, final T? response) { + if (context.isCompletion) return response; + final stopwatch = context.provider.fetch().stopwatch..stop(); + print( + '>>> ${context.leaf().command.name} returned $response ' + 'after ${stopwatch.elapsed.inMilliseconds} ms', + ); + return response; + } +} diff --git a/packages/config/lib/command.dart b/packages/config/lib/command.dart new file mode 100644 index 00000000..90e8a103 --- /dev/null +++ b/packages/config/lib/command.dart @@ -0,0 +1 @@ +export 'src/command/commands.dart'; diff --git a/packages/config/lib/middleware.dart b/packages/config/lib/middleware.dart new file mode 100644 index 00000000..3188daea --- /dev/null +++ b/packages/config/lib/middleware.dart @@ -0,0 +1,2 @@ +export 'src/middleware/middleware.dart'; +export 'src/middleware/middleware_hooks.dart'; diff --git a/packages/config/lib/src/command/abstract_command.dart b/packages/config/lib/src/command/abstract_command.dart new file mode 100644 index 00000000..3573e65d --- /dev/null +++ b/packages/config/lib/src/command/abstract_command.dart @@ -0,0 +1,238 @@ +import 'dart:async' show FutureOr; + +import '../../middleware.dart' show MiddlewareChain, Middleware; +import '../config/config.dart' + show + OptionDefinition, + CommandDefinition, + Configuration, + ConfigurationBroker, + ArgParseResult, + NewParsedArgs; +import 'command.dart' show Command; +import 'command_context.dart'; +import 'command_middleware.dart'; +import 'command_runner.dart' show CommandRunner; +import 'context_provider.dart'; +import 'help_command.dart'; +import 'usage_generator.dart' show UsageGenerator; + +/// Common base class for all commands, [CommandRunner] and [Command]. +abstract class AbstractCommand + implements CommandDefinition { + /// The usage string generator for this command. + final UsageGenerator usageGenerator; + + /// If non-null, specifies the line length for usage output wrapping. + int? usageLineLength; + + @override + final List persistentOptions; + + @override + final List options; + + @override + final bool canRunAsLeafCommand; + + AbstractCommand? _parent; + + final List> _subcommands; + + /// Built-in subcommands, see [subcommands]. + final List> _builtinSubcommands; + + /// The built-in help command, created lazily since every command, + /// including the help command itself, has one. + late final HelpCommand _helpCommand = HelpCommand().._parent = this; + + final MiddlewareChain, CommandContext> _middlewareChain; + + /// [builtinSubcommands] are added after the defined [subcommands] when + /// this command has subcommands, unless a subcommand with the same name + /// is defined. The `help` command is always built in, as the last one. + AbstractCommand({ + required this.usageGenerator, + this.usageLineLength, + final List? persistentOptions, + final List? options, + final List>? subcommands, + final List>? builtinSubcommands, + final List>? middlewares, + final bool? canRunAsLeafCommand, + }) : persistentOptions = List.from(persistentOptions ?? []), + options = List.from(options ?? []), + canRunAsLeafCommand = canRunAsLeafCommand ?? false, + _subcommands = List.from(subcommands ?? []), + _builtinSubcommands = List.from(builtinSubcommands ?? []), + _middlewareChain = MiddlewareChain(middlewares) { + for (final subcommand in [..._subcommands, ..._builtinSubcommands]) { + subcommand.parent = this; + } + } + + @override + String get usage => usageGenerator.generate(this); + + @override + List allOptions({final bool onlyPersistent = false}) => [ + ...persistentOptions, + if (!onlyPersistent) ...options, + ]; + + /// Provides the configuration broker for resolving the configuration for this + /// command, if any. [prevContext] and its predecessor contexts are the + /// resolved contexts of the parent commands. + ConfigurationBroker? configBroker( + final CommandContext? prevContext, + ) => null; + + /// Whether this command accepts a partial command line, i.e. runs as the + /// last command on the command line even if the command line is incomplete. + /// + /// {@template acceptsPartialCommandLine} + /// Incomplete means that this or the preceding commands have configuration + /// errors, such as missing mandatory subcommand, positional arguments, + /// options or option values, or mutually exclusive groups without a mandatory + /// choice. + /// These errors remain available in `CommandContext.config.errors`. + /// Command line parse errors, such as unknown options or subcommands, + /// are still raised. + /// + /// True for the built-in help command, which shows the usage of the + /// preceding command regardless of whether its arguments are complete, + /// like the `--help` option does. Custom `CommandResolver`s should + /// honor this. + /// {@endtemplate} + bool get acceptsPartialCommandLine => false; + + bool get hasParent => _parent != null; + + AbstractCommand get parent { + if (_parent == null) throw StateError('Parent command of $name not set'); + return _parent!; + } + + /// Notionally protected; may only be called once. + /// Throws a [StateError] if this command already has a parent. + set parent(final AbstractCommand parent) { + if (_parent != null) { + throw StateError( + 'Command $name already has the parent command ${_parent?.name}', + ); + } + _parent = parent; + } + + /// Convenience method to get the root CommandRunner from any command. + CommandRunner get runner { + AbstractCommand command = this; + while (command.hasParent) { + command = command.parent; + } + if (command is! CommandRunner) { + throw StateError('Root command $command is not a CommandRunner'); + } + return command; + } + + /// Adds a middleware to this command. + /// Middlewares are invoked in the order they are added. + void addMiddleware( + final Middleware, CommandContext> middleware, + ) { + _middlewareChain.addMiddleware(middleware); + } + + /// Adds an option to this command. + /// [persistent] indicates whether the option should be persistent across this + /// command's subcommands. + void addOption(final O option, {final bool? persistent}) { + if (persistent == true) { + persistentOptions.add(option); + } else { + options.add(option); + } + } + + /// Adds a subcommand to this command. + /// + /// Throws a [StateError] if [subcommand] already has a parent command. + void addSubcommand(final Command subcommand) { + subcommand.parent = this; + _subcommands.add(subcommand); + } + + /// Returns the subcommands for this command. + /// Injects the built-in subcommands (including `help`) if there is + /// at least one subcommand and there is not already a subcommand with + /// the same name present. + @override + List> get subcommands { + if (_subcommands.isEmpty) return []; + return [ + ..._subcommands, + for (final builtin in [..._builtinSubcommands, _helpCommand]) + if (!_subcommands.any((final command) => command.name == builtin.name)) + builtin, + ]; + } + + /// Given a parsed command line, environmnent variables, a context provider, + /// and the resolved command contexts of the parent commands, + /// resolves the configuration for this command and returns a [CommandContext] + /// for it. + CommandContext resolveCmd( + final ArgParseResult parseResult, + final Map? env, + final ContextProvider provider, + final CommandContext? prevContext, { + required final CommandRunMode runMode, + }) { + final parsedArgs = NewParsedArgs(parseResult); + + final Configuration config = Configuration.resolveNoExcept( + options: [...persistentOptions, ...options], + parsedArgs: parsedArgs, + env: env, + configBroker: configBroker(prevContext), + ignoreUnexpectedPositionalArgs: runner.ignoreUnexpectedPositionalArgs, + ); + + return CommandContext( + command: this, + config: config, + prev: prevContext, + provider: provider, + runMode: runMode, + ); + } + + /// Runs this command, including its middlewares (hooks). + /// + /// When [runNextCommand] is omitted, this command is run, + /// wrapped by the middlewares of this command. + /// When [runNextCommand] is provided, it is run instead of [run], + /// wrapped by the middlewares of this command. + /// + /// Typically not overridden by subclasses. + FutureOr runCommand( + final CommandContext context, { + final CommandHandler? runNextCommand, + }) { + final terminalHandler = runNextCommand ?? runAsLeaf; + final handler = _handlerChain(terminalHandler); + return handler(context); + } + + /// Builds a handler chain with this command's middlewares, + /// concluded with the given terminal handler. + CommandHandler _handlerChain( + final CommandHandler terminalHandler, + ) => _middlewareChain.handlerChain(terminalHandler); + + /// Runs this command as a leaf command. + /// + /// Invoked only when this command is the last command on the command line. + FutureOr runAsLeaf(final CommandContext context); +} diff --git a/packages/config/lib/src/command/builtin_global_option.dart b/packages/config/lib/src/command/builtin_global_option.dart new file mode 100644 index 00000000..aee66c9a --- /dev/null +++ b/packages/config/lib/src/command/builtin_global_option.dart @@ -0,0 +1,70 @@ +import 'dart:async' show FutureOr; + +import '../config/config.dart' + show ConfigOptionBase, EnumOption, EnumParser, FlagOption, OptionDefinition; +import 'command_context.dart'; +import 'command_runner.dart' show ActionOptionMixin; +import 'completion/completion.dart' show printCompletionScript; +import 'completion/completion_shell.dart' show CompletionShell; +import 'help_command.dart' show printCommandUsage; + +/// The built-in global options of a command runner, +/// see `CommandRunner.builtinPersistentOptions`. +enum BuiltinGlobalOption implements OptionDefinition { + /// Shows the usage of the last command on the command line. + help(HelpActionOption()), + + /// `--completion `: prints the completion script for the shell. + completion(CompletionActionOption()); + + const BuiltinGlobalOption(this.option); + + @override + final ConfigOptionBase option; +} + +class HelpActionOption extends FlagOption with ActionOptionMixin { + const HelpActionOption() + : super( + argName: 'help', + argAbbrev: 'h', + negatable: false, + helpText: 'Print this usage information.', + ); + + @override + FutureOr run( + final CommandContext context, + ) { + printCommandUsage(context.leaf()); + return null; + } +} + +class CompletionActionOption extends EnumOption + with ActionOptionMixin { + const CompletionActionOption() + : super( + enumParser: const EnumParser(CompletionShell.values), + argName: 'completion', + helpText: 'Print the shell completion script for the shell.', + ); + + @override + FutureOr run( + final CommandContext context, + ) { + final completionShell = context.builtinConfig.optionalValue( + BuiltinGlobalOption.completion, + ); + if (completionShell == null) { + throw StateError('Completion shell value is null'); + } + // (Exits the process after writing the script if + // CompletionSettings.exitAfterResponse is true.) + return printCompletionScript( + context.command.runner, + completionShell, + ).then((final _) => null); + } +} diff --git a/packages/config/lib/src/command/command.dart b/packages/config/lib/src/command/command.dart new file mode 100644 index 00000000..beac7791 --- /dev/null +++ b/packages/config/lib/src/command/command.dart @@ -0,0 +1,302 @@ +import 'dart:async' show FutureOr; + +import '../config/config.dart' + show + OptionDefinition, + CommandUsageDefinition, + CommandAliasesDefinition, + UsageException; +import 'abstract_command.dart'; +import 'command_context.dart'; +import 'command_middleware.dart'; +import 'usage_generator.dart' + show StandardCommandUsageGenerator, UsageGenerator; + +/// A [Command] is a named task on the command line. +/// It is a "branch" command if it has subcommands, otherwise it is a "leaf" command. +/// Leaf commands have a [run] method that is called when the command is executed. +/// +/// All commands can have middlewares that are executed before and after +/// their subcommands and run method. +/// +/// All commands can have options. For a branch command, the options are +/// "persistent", i.e. they are available anywhere to the right on the command +/// line (across any subcommands). Leaf command options can be positional, +/// i.e. directly as values without being prefixed by an option name. +/// (Branch commands can't have positional options as they would conflict with +/// subcommand names.) +/// +/// See also [CommandImpl] for easy set up of [Command] objects via parameters +/// rather than overriding fields. +/// +/// See also [BridgeCommand] if migrating from the legacy args package, extend +/// from it instead of the old Command class to make the transition easier. +abstract class Command + extends AbstractCommand { + CommandUsageDefinition? _usageDefinition; + CommandAliasesDefinition? _aliasesDefinition; + + /// Returns the usage definition this command was constructed with, or the + /// default blank one. + /// Override this method to provide a dynamic usage definition. + @override + CommandUsageDefinition get usageDefinition => + _usageDefinition ??= const CommandUsageDefinition(); + + /// Returns the aliases definition this command was constructed with, or the + /// default blank one. + /// Override this method to provide a dynamic aliases definition. + @override + CommandAliasesDefinition get aliasesDefinition => + _aliasesDefinition ??= const CommandAliasesDefinition(); + + Command({ + final CommandUsageDefinition? usageDefinition, + final CommandAliasesDefinition? aliasesDefinition, + final UsageGenerator? usageGenerator, + super.persistentOptions, + super.options, + super.subcommands, + super.middlewares, + super.canRunAsLeafCommand, + }) : _usageDefinition = usageDefinition, + _aliasesDefinition = aliasesDefinition, + super( + usageGenerator: + usageGenerator ?? const StandardCommandUsageGenerator(), + ); + + @override + FutureOr runAsLeaf(final CommandContext context) { + return run(context); + } + + /// Runs this command as a leaf command. Implemented by subclasses. + FutureOr run(final CommandContext context); +} + +/// A bridge command that closes the gap between Command and the old args +/// package's Command class. +/// +/// Most of the members of the old class are present here, and they are used +/// to initialize this command. +/// +/// Subclasses using the old Command class' members can extend this class to +/// make the transition to the new Command class easier. (Note that ArgParser +/// and ArgResults related members are not present, and the run method signature +/// is different, which is necessary with the modernized Command design.) +abstract class BridgeCommand + extends Command { + @override + CommandUsageDefinition get usageDefinition => + _usageDefinition ??= CommandUsageDefinition( + description: description, + usageFooter: usageFooter, + category: category, + hidden: hidden, + summary: summary, + invocation: _customInvocation, + ); + + @override + CommandAliasesDefinition get aliasesDefinition => + _aliasesDefinition ??= CommandAliasesDefinition( + aliases: aliases, + suggestionAliases: suggestionAliases, + ); + + BridgeCommand({ + super.persistentOptions, + super.options, + super.subcommands, + super.middlewares, + super.canRunAsLeafCommand, + final UsageGenerator? usageGenerator, + }) : super( + usageGenerator: + usageGenerator ?? const StandardCommandUsageGenerator(), + ); + + /// Must be overridden by subclass. + @override + String get name; + + /// Must be overridden by subclass. + String get description; + + String get category => ''; + + String? get usageFooter => null; + + bool get hidden => false; + + List get aliases => const []; + + List get suggestionAliases => const []; + + /// A short description of this command, shown in the parent's usage. + String get summary => description.split('\n').first; + + /// This command's own invocation, i.e. its name and arguments without + /// the parent command names. + /// A subclass that overrides this getter with another text gets that text + /// in the usage, see [CommandUsageDefinition.invocation]. + String get invocation => _defaultInvocation; + + String get _defaultInvocation => subcommands.isNotEmpty + ? '$name [arguments]' + : '$name [arguments]'; + + /// The [invocation] if it is customized, otherwise null. + String? get _customInvocation { + final invocation = this.invocation; + return invocation == _defaultInvocation ? null : invocation; + } + + bool get takesArguments => + allOptions().any((final option) => option.option.argPos != null); + + void printUsage() => runner.usageOutput.printUsage(this); + + Never usageException(final String message) => + throw UsageException(message, usage); +} + +/// The type of the [Command.run] method. +typedef CommandRunFunction = + FutureOr Function(CommandContext context); + +/// A parameterized implementation of [Command] for easy set up +/// of a command object via parameters rather than overriding fields. +/// +/// Classes extending this must override the [run] method. +/// If you don't need a class at all, use [CommandImpl.branch], or +/// [CommandImpl.leafWithRunFunction] with a run function. +abstract class CommandImpl + extends Command { + @override + final String name; + + CommandImpl({ + required this.name, + required final String description, + final String? usageFooter, + final String? category, + final bool? hidden, + final List? aliases, + final List? suggestionAliases, + super.persistentOptions, + super.options, + super.subcommands, + super.middlewares, + super.canRunAsLeafCommand, + }) : super( + usageDefinition: CommandUsageDefinition( + description: description, + usageFooter: usageFooter, + category: category, + hidden: hidden, + ), + aliasesDefinition: CommandAliasesDefinition( + aliases: aliases, + suggestionAliases: suggestionAliases, + ), + ); + + /// Creates a new branch command (i.e. a command with subcommands) via + /// parameters rather than writing a class and overriding its fields. + /// + /// If [canRunAsLeafCommand] is true, the command prints its usage when + /// it is the last command on the command line, like the command runner. + static CommandImpl branch({ + required final String name, + required final String description, + final String? usageFooter, + final String? category, + final bool? hidden, + final List? aliases, + final List? suggestionAliases, + final List>? middlewares, + final List? persistentOptions, + final List>? subcommands, + final bool canRunAsLeafCommand = false, + }) { + return _CommandWithRunFunction( + name: name, + description: description, + usageFooter: usageFooter, + category: category, + hidden: hidden, + aliases: aliases, + suggestionAliases: suggestionAliases, + middlewares: middlewares, + persistentOptions: persistentOptions, + subcommands: subcommands, + canRunAsLeafCommand: canRunAsLeafCommand, + run: (final CommandContext context) { + final command = context.command; + if (!command.canRunAsLeafCommand) { + throw UnsupportedError( + 'Branch command ${command.name} should not be run()', + ); + } + command.runner.usageOutput.printUsage(command); + return null; + }, + ); + } + + /// Creates a new leaf command via parameters rather than writing a class and + /// overriding its fields. + static CommandImpl leafWithRunFunction({ + required final String name, + required final String description, + final String? usageFooter, + final String? category, + final bool? hidden, + final List? aliases, + final List? suggestionAliases, + final List? options, + final List>? middlewares, + required final CommandRunFunction run, + }) { + return _CommandWithRunFunction( + name: name, + description: description, + usageFooter: usageFooter, + category: category, + hidden: hidden, + aliases: aliases, + suggestionAliases: suggestionAliases, + middlewares: middlewares, + options: options, + run: run, + ); + } +} + +class _CommandWithRunFunction + extends CommandImpl { + final CommandRunFunction _run; + + _CommandWithRunFunction({ + required super.name, + required super.description, + required super.usageFooter, + required super.category, + required super.hidden, + required super.aliases, + required super.suggestionAliases, + required super.middlewares, + super.persistentOptions, + super.options, + super.subcommands, + super.canRunAsLeafCommand, + required final CommandRunFunction run, + }) : _run = run; + + @override + FutureOr run(final CommandContext context) { + return _run(context); + } +} diff --git a/packages/config/lib/src/command/command_context.dart b/packages/config/lib/src/command/command_context.dart new file mode 100644 index 00000000..4459f927 --- /dev/null +++ b/packages/config/lib/src/command/command_context.dart @@ -0,0 +1,87 @@ +import '../../config.dart' show OptionDefinition, Configuration; +import 'abstract_command.dart'; +import 'builtin_global_option.dart'; +import 'context_provider.dart'; + +/// Whether a command context is being used to run or to complete the command line. +enum CommandRunMode { + /// The command line is being executed. + execution, + + /// The command line is being completed. + completion, +} + +/// The configuration context for the individual command being run. +/// +/// The contexts for the commands on the command line form a linked list +/// via the prev and next fields. +class CommandContext { + final AbstractCommand command; + + /// Whether this context is part of executing or completing the command line. + final CommandRunMode runMode; + + /// Whether middleware is running for completion rather than execution. + bool get isCompletion => runMode == CommandRunMode.completion; + + /// The configuration of the command's own (application-defined) options. + final Configuration config; + + /// The configuration of the command's built-in options. + /// Empty for commands without built-in options. + final Configuration builtinConfig; + + /// The context of the preceding command on the command line. + /// Null if this is the root command. + final CommandContext? prev; + + /// The context of the succeeding command on the command line. + /// Null if this is the leaf command. + late final CommandContext? next; + + /// User-defined objects / state provider. + final ContextProvider provider; + + CommandContext({ + required this.command, + required this.config, + required this.prev, + required this.provider, + required this.runMode, + final Configuration? builtinConfig, + }) : builtinConfig = + builtinConfig ?? + Configuration.fromValues(values: const {}); + + CommandContext copyWith({ + final AbstractCommand? command, + final Configuration? config, + final Configuration? builtinConfig, + final CommandContext? prev, + final CommandContext? next, + final ContextProvider? provider, + final CommandRunMode? runMode, + }) { + return CommandContext( + command: command ?? this.command, + config: config ?? this.config, + builtinConfig: builtinConfig ?? this.builtinConfig, + prev: prev ?? this.prev, + provider: provider ?? this.provider, + runMode: runMode ?? this.runMode, + )..next = next ?? this.next; + } + + /// Returns the root command's context. + CommandContext root() { + final prevContext = prev; + return prevContext == null ? this : prevContext.root(); + } + + /// Returns the leaf command's context. + CommandContext leaf() { + final nextContext = next; + return nextContext == null ? this : nextContext.leaf(); + } +} diff --git a/packages/config/lib/src/command/command_middleware.dart b/packages/config/lib/src/command/command_middleware.dart new file mode 100644 index 00000000..a81fbb70 --- /dev/null +++ b/packages/config/lib/src/command/command_middleware.dart @@ -0,0 +1,84 @@ +import 'dart:async' show FutureOr; + +import '../../middleware.dart'; +import '../config/config.dart' show OptionDefinition; +import 'command_context.dart'; + +typedef CommandHandler = + Handler, CommandContext>; + +typedef CommandMiddleware = + Middleware, CommandContext>; + +/// Convenience class for easier type binding of [MiddlewareHooks] for commands. +class CommandMiddlewareHooks + extends MiddlewareHooks> { + const CommandMiddlewareHooks(); +} + +/// Convenience class for easier type binding of [MiddlewareComposer] for commands. +class CommandMiddlewareComposer + extends MiddlewareComposer> { + const CommandMiddlewareComposer({ + super.onRun, + super.onReturn, + super.onError, + }); +} + +/// Convenience methods for creating [CommandMiddleware]s. +abstract class Middlewares { + /// Factory function to create a [CommandMiddleware] with the given hooks. + static CommandMiddleware withHooks({ + final OnRun>? onRun, + final OnReturn>? onReturn, + final OnError>? onError, + }) { + return CommandMiddlewareComposer( + onRun: onRun, + onReturn: onReturn, + onError: onError, + ).middleware; + } + + /// Creates a [CommandMiddleware] with a variant of [onRun] that does not + /// return a value, intended for use before the command is run but no need to + /// change the context. + static CommandMiddleware onBeforeRun( + final FutureOr Function(CommandContext) onRun, + ) { + return withHooks( + onRun: (final ctx) async { + await onRun(ctx); + return ctx; + }, + ); + } + + /// Creates a [CommandMiddleware] with the given [onRun] hook. + /// + /// See [MiddlewareHooks.onRun]. + static CommandMiddleware onRun( + final OnRun> onRun, + ) { + return withHooks(onRun: onRun); + } + + /// Creates a [CommandMiddleware] with the given [onReturn] hook. + /// + /// See [MiddlewareHooks.onReturn]. + static CommandMiddleware onReturn( + final OnReturn> onReturn, + ) { + return withHooks(onReturn: onReturn); + } + + /// Creates a [CommandMiddleware] with the given [onError] hook. + /// + /// See [MiddlewareHooks.onError]. + static CommandMiddleware onError( + final OnError> onError, + ) { + return withHooks(onError: onError); + } +} diff --git a/packages/config/lib/src/command/command_resolver.dart b/packages/config/lib/src/command/command_resolver.dart new file mode 100644 index 00000000..afcdfeb4 --- /dev/null +++ b/packages/config/lib/src/command/command_resolver.dart @@ -0,0 +1,199 @@ +import '../config/arg_parser/arg_parser.dart' + show + ArgParseResult, + DoubleDashHandling, + ParserSettings, + scanAndParseCommands, + subcommandRequiredErrorPrefix; +import '../config/config.dart' + show + CommandDefinition, + OptionDefinition, + UsageException, + CommandUsageException; +import '../config/output_formatting.dart' show formatConfigError; +import 'abstract_command.dart'; +import 'command_context.dart'; +import 'command_runner.dart' + show CommandRunner, specifiedActionOption, ActionOptionMixin; +import 'context_provider.dart'; + +/// Interface for the command resolver, which resolves the configurations for +/// each command on the command line. +/// +/// Custom implementations of this interface can be used to change the +/// standard command resolution process. +abstract interface class CommandResolver { + /// Resolves the configurations for each command on the command line. + /// + /// Returns the chain of resolved command contexts for the commands on the + /// command line. The first context is for the root command, and has the same + /// option type [O] as the runner. + /// + /// Throws [UsageException] on configuration input errors including + /// command line arguments, environment variables, and configuration files. + /// + /// When [runMode] is [CommandRunMode.completion], those errors are left on + /// the contexts and no exception is thrown, so a command line that is not + /// finished can still be completed. [runMode] is recorded on every context + /// in the chain. + CommandContext resolveConfigurations( + final Iterable args, + final Map? env, + final ContextProvider provider, { + required final CommandRunMode runMode, + }); +} + +/// The standard command resolver. +class StandardCommandResolver + implements CommandResolver { + /// The runner whose command tree and parser settings are resolved. + final CommandRunner runner; + + const StandardCommandResolver(this.runner); + + @override + CommandContext resolveConfigurations( + final Iterable args, + final Map? env, + final ContextProvider provider, { + required final CommandRunMode runMode, + }) { + final argParseResult = scanAndParseCommands( + args, + rootCommand: runner, + settings: ParserSettings( + doubleDashHandling: runner.ignoreUnexpectedPositionalArgs + ? DoubleDashHandling.passThroughRest + : DoubleDashHandling.noSpecialHandling, + suggestionDistanceLimit: runner.suggestionDistanceLimit, + ), + ); + + final contextChain = resolveNext( + argParseResult, + env, + provider, + null, + runMode: runMode, + ); + + final CommandContext contexts = contextChain as CommandContext; + + throwIfConfigurationErrors(contexts, runMode); + + return contexts; + } + + CommandContext resolveNext( + final ArgParseResult argParseResult, + final Map? env, + final ContextProvider provider, + final CommandContext? prevContext, { + required final CommandRunMode runMode, + }) { + final command = argParseResult.command; + if (command == null) throw StateError('ArgParseResult.command is null'); + if (command is! AbstractCommand) { + throw StateError( + 'ArgParseResult.command is not an AbstractCommand: ${command.runtimeType}', + ); + } + + final context = command.resolveCmd( + argParseResult, + env, + provider, + prevContext, + runMode: runMode, + ); + + if (argParseResult.child case final ArgParseResult child) { + final nextContext = resolveNext( + child, + env, + provider, + context, + runMode: runMode, + ); + context.next = nextContext; + } else { + context.next = null; + } + + return context; + } + + /// Throws a [CommandUsageException] if any command on the command line + /// has configuration errors, including command line parse errors. + void throwIfConfigurationErrors( + final CommandContext contexts, + final CommandRunMode runMode, + ) { + // Completion mode: Resolves a partial command line. Errors stay on the + // contexts for middleware and completion to inspect. + if (runMode == CommandRunMode.completion) return; + + final acceptsPartialCommandLine = _acceptsPartialCommandLine(contexts); + + final commandErrors = <(CommandDefinition, Iterable)>[]; + CommandContext? context = contexts; + while (context != null) { + final allErrors = context.config.errors.followedBy( + context.builtinConfig.errors, + ); + final errors = acceptsPartialCommandLine + ? allErrors.where((final error) => !_isMissingValueError(error)) + : allErrors; + commandErrors.add((context.command, errors)); + context = context.next; + } + _throwIfErrors(commandErrors); + } + + /// Whether [error] reports a value that was never supplied. + /// + /// `Missing value for option` stays reportable: that option was written + /// on the command line. + bool _isMissingValueError(final String error) { + if (error.startsWith(subcommandRequiredErrorPrefix)) return true; + if (error.endsWith('is mandatory')) return true; + if (error.endsWith('requires one of the options to be provided')) { + return true; + } + return false; + } + + bool _acceptsPartialCommandLine(final CommandContext contexts) { + if (specifiedActionOption(contexts) + case final ActionOptionMixin actionOption) { + return actionOption.acceptsPartialCommandLine; + } + + if (contexts.leaf().command.acceptsPartialCommandLine) return true; + + return false; + } + + void _throwIfErrors( + final Iterable<(CommandDefinition, Iterable)> commandErrors, + ) { + final messages = []; + CommandDefinition? firstCommandWithErrors; + + for (final (command, errors) in commandErrors) { + if (errors.isEmpty) continue; + messages.addAll( + errors.map( + (final error) => '${command.name}: ${formatConfigError(error)}', + ), + ); + firstCommandWithErrors ??= command; + } + + if (firstCommandWithErrors != null) { + throw CommandUsageException(messages.join('\n'), firstCommandWithErrors); + } + } +} diff --git a/packages/config/lib/src/command/command_runner.dart b/packages/config/lib/src/command/command_runner.dart new file mode 100644 index 00000000..96c425ac --- /dev/null +++ b/packages/config/lib/src/command/command_runner.dart @@ -0,0 +1,526 @@ +import 'dart:async' show Future, FutureOr; +import 'dart:io' show Platform, stderr; + +import '../config/arg_parser/arg_parser.dart' + show CommandAliasesDefinition, CommandDefinition, CommandUsageDefinition; +import '../config/config.dart' + show + OptionDefinition, + Configuration, + UsageException, + ParsedArgs, + ConfigOptionBase, + FlagOption, + MultiOption, + ArgParseResult, + NewParsedArgs, + ValueSourceType; +import 'abstract_command.dart'; +import 'builtin_global_option.dart'; +import 'command_context.dart'; +import 'command_resolver.dart'; +import 'completion/completion.dart'; +import 'context_provider.dart'; +import 'usage_generator.dart' show StandardRunnerUsageGenerator, UsageGenerator; +import 'usage_output.dart'; + +/// A command runner for a command line application. +/// +/// Runs a command line by parsing the command line arguments, environment variables, +/// and configuration files, and running the commands on the command line. +/// +/// Returns the result of the nested middleware chain for the commands on +/// the command line. Each ancestor's middleware wraps the commands that +/// follow it. Only the last command's [run] is invoked. +/// +/// T is the return type of the run methods of this runner and the commands. +/// [CommandRunner.run] returns the result of the nested middleware chain. +/// When each middleware returns the result of its next handler, that is the +/// result of the last command on the command line. +/// This means that T must match across the runner and all its commands. +/// Using int as T can be sensible in order to return the exit code that the +/// command executable should return. +/// +/// ## Design +/// +/// Uses the concept of middlewares to customize the execution logic +/// of the command tree. The legacy CommandRunner relied on method overrides +/// to customize the execution logic. This middleware approach allows for +/// cleaner composition. +/// +/// Separates static configuration from dynamic execution. The command tree, +/// options, middlewares, settings for usage output and error handling are +/// configured statically. Execution performs configuration resolution and +/// command execution and these do not mutate the CommandRunner, Command, or +/// Option instances. This provides separation of concerns and makes the command +/// code reentrant. +/// +/// ## Phases and Error Handling +/// +/// There are three phases to the execution of a command runner that are run +/// in sequence and have distinct error handling: +/// 1. Validation: Checking the consistency of the commands and options +/// 2. Resolution: Resolving the configurations for the command line, env vars, and config files +/// 3. Execution: Running the command line and any middlewares +/// +/// Configuration validation runs first and validates the consistency of all the +/// defined commands and options. Validation errors are considered programming +/// errors and if any errors are found a [ConfigDefinitionError] is thrown. +/// +/// Configuration resolution runs next and resolves the current configurations +/// for the command line, env vars, and config files. Resolution errors are user +/// errors and if any errors are found, usage guidance is printed and a +/// [UsageException] is thrown (under the default settings). +/// +/// Command execution is last and runs the current command line and any +/// middlewares defined in it. If any exceptions are thrown they will propagate +/// to the original caller unless intercepted by a middleware. +class CommandRunner + extends AbstractCommand { + /// The name of the executable being run. + /// + /// Used for error reporting and [usageDefinition]. + final String executableName; + + /// The global option definitions (the root command's persistent options). + List get globalOptions => persistentOptions; + + /// The built-in global options, e.g. `--help`. + List get builtinPersistentOptions => [ + BuiltinGlobalOption.help, + if (completion.enabled && subcommands.isEmpty) + BuiltinGlobalOption.completion, + ]; + + @override + List allOptions({final bool onlyPersistent = false}) => [ + ...builtinPersistentOptions, + ...persistentOptions, + if (!onlyPersistent) ...options, + ]; + + /// The name of the executable being run. + @override + String get name => executableName; + + @override + final CommandUsageDefinition usageDefinition; + + /// There are no aliases for the root command. + @override + final CommandAliasesDefinition aliasesDefinition = + const CommandAliasesDefinition(); + + /// Whether a positional argument that matches no positional option is allowed. + /// If true, such arguments are included in [Configuration.remainingPosArgs] + /// of the last command's configuration. + /// This also enables the `--` double dash argument, which stops parsing of + /// the command line and instead puts the following arguments in + /// [Configuration.remainingPosArgs] of the last parsed command. + /// + /// When false, the default, those arguments are included in the + /// [UsageException] thrown before any command runs. + final bool ignoreUnexpectedPositionalArgs; + + /// The maximum edit distance allowed when suggesting possible intended + /// commands. + /// + /// Set to `0` in order to disable suggestions, defaults to `2`. + final int suggestionDistanceLimit; + + /// The settings and behavior for the usage output - + /// controls the help output and the usage exception output. + final UsageOutputHandler usageOutput; + + /// The settings for the built-in shell completion support. + /// + /// Enabled by default, see [CompletionSettings]. + final CompletionSettings completion; + + /// Resolves the configurations for each command on the command line. + late final CommandResolver resolver = StandardCommandResolver(this); + + /// Creates a new command runner with the given executable name and description. + /// + /// [globalOptions] is the list of global options. + /// Global options are "persistent" which means they are valid anywhere on the + /// command line. + /// + /// The built-in global option `--help` / `-h` is available in addition, + /// as is `--completion ` for a runner without subcommands, + /// see [builtinPersistentOptions]. + /// + /// [subcommands] is a list of subcommands that will be added to + /// the runner. Can also be added later using [addSubcommand]. + /// + /// [middlewares] is a list of middlewares that will be added to the runner. + /// + /// [ignoreUnexpectedPositionalArgs] is a boolean that determines whether unexpected positional arguments should be ignored. + /// + /// [rootFooter] is a string that will be added to the runner's usage footer. + /// + /// [completion] configures the built-in shell completion support, + /// which is enabled by default. See [CompletionSettings]. + CommandRunner( + this.executableName, + final String description, { + final List? globalOptions, + final String? rootFooter, + super.subcommands, + super.middlewares, + super.canRunAsLeafCommand, + super.usageLineLength, + final UsageGenerator? usageGenerator, + final bool? ignoreUnexpectedPositionalArgs, + final int? suggestionDistanceLimit, + final UsageOutputHandler? usageOutput, + final CompletionSettings? completion, + }) : usageDefinition = CommandUsageDefinition( + description: description, + usageFooter: rootFooter, + ), + usageOutput = usageOutput ?? UsageOutputHandler(), + completion = completion ?? const CompletionSettings(), + ignoreUnexpectedPositionalArgs = ignoreUnexpectedPositionalArgs ?? false, + suggestionDistanceLimit = suggestionDistanceLimit ?? 2, + super( + usageGenerator: usageGenerator ?? const StandardRunnerUsageGenerator(), + persistentOptions: globalOptions, + builtinSubcommands: [ + if (completion?.enabled ?? true) + CompletionCommand(hidden: completion?.hideCommand ?? false), + ], + ); + + /// Runs a command line by parsing [args] and [env] (and [configBroker], when + /// available) and running the last command on the command line. + /// + /// Returns a [Future] with the result. Synchronous work runs immediately, + /// and a synchronous command result is still delivered on the future. + /// + /// Resolves the global configuration and the individual command + /// configurations before invoking the commands or their middlewares. + /// Throws a [UsageException] on [args] parse errors and configuration + /// resolution errors. All discovered parse and resolution errors are included + /// in the message of that exception. + /// + /// The caller may provide a [ContextProvider], otherwise a default, empty + /// one is created and used. + /// + /// Returns the result of the nested middleware chain for the commands on + /// the command line. Each ancestor's middleware wraps the commands that + /// follow it. Only the last command's [run] is invoked. When every + /// middleware returns the result of its next handler, the result is that + /// of the last command. + /// + /// When `--help`, `-h`, or a `help` command is present on a command + /// line, prints usage for the last command and returns `null` without + /// running any command. + /// + /// To make a subcommand which is named like an option, simply define it, for example: + /// ```dart + /// CommandImpl.leafWithRunFunction( + /// name: 'version', + /// aliases: ['--version', '-v'], + /// description: 'Display the version', + /// run: (CommandContext context) { + /// print('version 1.0.0'); + /// }, + /// ); + /// ``` + /// + /// Throws [ConfigDefinitionError] if any command or option *definition* is + /// invalid, before running any middleware or commands. + /// + /// Throws [UsageException] if any configuration input including arguments, + /// environment variables, and configuration files is invalid, + /// unless [CommandUsageSettings.noUsageException] is true. + Future run( + final Iterable args, { + final Map? env, + final ContextProvider? provider, + }) async { + try { + return await Future.sync( + () => _run(args, env: env, customProvider: provider), + ); + } on TypeError catch (error, stackTrace) { + stderr.writeln( + ">>> If this happens, O and T may need to be bound explicitly, due to limitations in Dart's generic type inference.\n" + ' E.g. `CommandRunner(...)`\n' + '${error.runtimeType}: $error\n' + '$stackTrace', + ); + rethrow; + } + } + + FutureOr _run( + final Iterable args, { + final Map? env, + final ContextProvider? customProvider, + }) { + final envVars = env ?? Platform.environment; + final argList = args.toList(); + + if (completion.enabled) { + if (argList.isNotEmpty && argList.first == _completeRequestCommand) { + return _serveCompletionRequest(argList.sublist(1), envVars); + } + } + + final provider = customProvider ?? ContextProvider(); + final contexts = resolveConfigurations(argList, envVars, provider); + if (contexts == null) return null; + + contexts.provider.store(OriginalCommandLine(argList)); + + return runCommandLine(contexts); + } + + /// Serves a completion request from a shell completion script: + /// writes the completion alternatives for the partial command line + /// [words] to [CompletionSettings.sinks]. + /// + /// Completing an option value resolves the configurations of the commands + /// typed so far and runs their middleware in [CommandRunMode.completion]. + /// The command `run` methods are not called. Subcommand and option-name + /// completion does not resolve or run middleware. + /// + /// The [env] map is used when resolving option values and is also passed + /// through to custom `ConfigOptionBase.complete` implementations, as + /// `CompletionContext.environment`. + /// + /// Exits the process with 0 after writing the response if + /// [CompletionSettings.exitAfterResponse] is true. + Future _serveCompletionRequest( + final List words, + final Map env, + ) async { + final engine = CompletionEngine( + this, + resolver: resolver, + ignoreUnexpectedPositionalArgs: ignoreUnexpectedPositionalArgs, + onError: (final error, final stackTrace) { + completion.sinks.err.writeln( + 'Completion failed: $error\n$stackTrace', + ); + }, + ); + final response = await engine.complete(words, environment: env); + await writeCompletionOutput(this, response.format()); + return null; + } + + /// Resolves the configurations for all commands on the command line + /// and returns the list of contexts for the commands. + /// + /// On configuration input errors (including command line arguments, + /// environment variables, and configuration files), a usage error message + /// is printed and a [UsageException] is thrown. + /// This behavior can be changed by passing a custom [UsageOutputHandler] + /// on construction, for example by suppressing UsageException from being + /// thrown in which case null is returned instead. + /// + /// If null is returned, the runner returns null without running any command. + /// + /// This method can be overridden by subclasses. + CommandContext? resolveConfigurations( + final Iterable args, + final Map? env, + final ContextProvider provider, + ) { + try { + return resolver.resolveConfigurations( + args, + env, + provider, + runMode: CommandRunMode.execution, + ); + } on UsageException catch (e, s) { + final exception = usageOutput.onUsageException(e, fromCommand: this); + if (exception == null) return null; + Error.throwWithStackTrace(exception, s); + } + } + + @override + CommandContext resolveCmd( + final ArgParseResult parseResult, + final Map? env, + final ContextProvider provider, + final CommandContext? prevContext, { + required final CommandRunMode runMode, + }) { + final parsedArgs = NewParsedArgs(parseResult); + + final Configuration config = Configuration.resolveNoExcept( + options: [...persistentOptions, ...options], + parsedArgs: parsedArgs, + env: env, + configBroker: configBroker(prevContext), + ignoreUnexpectedPositionalArgs: runner.ignoreUnexpectedPositionalArgs, + ); + + // Note, parse errors and positional arguments of [parsedArgs] belong to the + // regular configuration and are not reported again here. + final builtinConfig = Configuration.resolveNoExcept( + options: builtinPersistentOptions, + parsedArgs: _FilteredParsedArgs(parsedArgs), + env: env, + ); + + return CommandContext( + command: this, + config: config, + builtinConfig: builtinConfig, + prev: prevContext, + provider: provider, + runMode: runMode, + ); + } + + /// Runs the command line, i.e. the middlewares of the commands on the command + /// line and run the tail command. + FutureOr runCommandLine(final CommandContext contexts) { + return _runNested(contexts); + } + + /// Runs the commands on the command line as one nested middleware chain. + /// + /// The first command's middleware is the outermost span. Each following + /// command's middleware runs inside the previous command's middleware. + /// Only the last command's [run] is invoked. + FutureOr _runNested( + final CommandContext context, + ) { + final next = context.next == null + ? null + : (final CommandContext forwarded) { + // (forwarded context may have been replaced by a middleware) + final next = forwarded.next; + if (next == null) { + throw StateError( + '${forwarded.command.name} has no following command.', + ); + } + return _runNested(next); + }; + + final actionOption = _specifiedActionOptions(context).firstOrNull; + if (actionOption != null) { + return actionOption.run(context); + } + + return context.command.runCommand(context, runNextCommand: next); + } + + /// Runs this command runner when it is the last command on the command line. + /// + /// By default it prints the usage for the command, but this can be overridden + /// by subclasses. + /// See also [CommandDefinition.canRunAsLeafCommand], which needs to be true + /// to allow this root command to run without any subcommands. + @override + FutureOr runAsLeaf(final CommandContext context) { + usageOutput.printUsage(context.command); + return null; + } +} + +/// The hidden built-in root command word that serves completion requests +/// from the shell completion scripts. +/// +/// The request has the form: +/// ``` +/// __complete ... +/// ``` +/// where the words are the command line arguments typed so far and the last +/// word is the (possibly empty) partial word being completed. +/// +/// The response on stdout is one line per completion candidate, in the form +/// `value` or `valuedescription`, followed by a final line `:` +/// where N is the sum of the [CompletionDirective] flags. +/// +/// This is the protocol of Cobra's `__complete` command, which is understood +/// by third-party completion engines such as Carapace. +const String _completeRequestCommand = '__complete'; + +/// ActionOptionMixin can be added to an option definition to make CommandRunner +/// run it as an "action option" when it is specified on the command line. +mixin ActionOptionMixin { + /// Whether this action option accepts a partial command line, + /// i.e. runs even if the command line is incomplete. + /// + /// True by default for action options. + /// + /// {@macro acceptsPartialCommandLine} + bool get acceptsPartialCommandLine => true; + + /// Runs this action option. + /// + /// [context] is the context of the command that defined this action option. + FutureOr run( + final CommandContext context, + ); +} + +ActionOptionMixin? specifiedActionOption(final CommandContext contexts) { + CommandContext? context = contexts; + while (context != null) { + final actionOption = _specifiedActionOptions(context).firstOrNull; + if (actionOption != null) return actionOption; + context = context.next; + } + return null; +} + +List _specifiedActionOptions( + final CommandContext context, +) { + final allArgOptions = [ + ...context.config.optionsWhereSource( + (final ValueSourceType s) => s == ValueSourceType.arg, + ), + ...context.builtinConfig.optionsWhereSource( + (final ValueSourceType s) => s == ValueSourceType.arg, + ), + ]; + return allArgOptions + .map((final option) => option.option) + .whereType() + .toList(); +} + +class OriginalCommandLine { + final List args; + + OriginalCommandLine(this.args); +} + +/// The parsed option values of a command, without its parse errors and +/// positional arguments, which belong to the command's own configuration. +class _FilteredParsedArgs implements ParsedArgs { + final ParsedArgs _args; + + _FilteredParsedArgs(this._args); + + @override + bool wasParsed(final ConfigOptionBase option) => _args.wasParsed(option); + + @override + bool flag(final FlagOption option) => _args.flag(option); + + @override + String option(final ConfigOptionBase option) => _args.option(option); + + @override + List multiOption(final MultiOption option) => + _args.multiOption(option); + + @override + List get rest => const []; + + @override + List get parseErrors => const []; +} diff --git a/packages/config/lib/src/command/commands.dart b/packages/config/lib/src/command/commands.dart new file mode 100644 index 00000000..9715ad36 --- /dev/null +++ b/packages/config/lib/src/command/commands.dart @@ -0,0 +1,16 @@ +/// The command framework: command runner, commands, contexts, middleware, +/// help, usage output and shell completion. +library; + +export 'builtin_global_option.dart'; +export 'command.dart'; +export 'command_context.dart'; +export 'command_middleware.dart'; +export 'command_resolver.dart'; +export 'command_runner.dart'; +export 'completion/completion.dart'; +export 'context_provider.dart'; +export 'help_command.dart'; +export 'output_sinks.dart'; +export 'usage_generator.dart'; +export 'usage_output.dart'; diff --git a/packages/config/lib/src/command/completion/command_completion_context.dart b/packages/config/lib/src/command/completion/command_completion_context.dart new file mode 100644 index 00000000..423a9870 --- /dev/null +++ b/packages/config/lib/src/command/completion/command_completion_context.dart @@ -0,0 +1,46 @@ +import '../../config/completion.dart'; +import '../../config/options.dart' show OptionDefinition; +import '../command_context.dart'; + +/// A [CompletionContext] that carries the command contexts resolved for +/// the words typed so far. +/// +/// Produced by the command runner when completing an option value. +/// [leafContext] is the last command, after that command's middleware +/// `onRun`. [CommandContext.runMode] is [CommandRunMode.completion]. +/// Ancestors are [CommandContext.prev]. [CommandContext.provider] is shared +/// by the chain; middleware publishes services there for +/// `ConfigOptionBase.complete` to fetch. +class CommandCompletionContext extends CompletionContext { + /// The leaf command context after its middleware `onRun`. + final CommandContext leafContext; + + CommandCompletionContext({ + required this.leafContext, + required super.wordToComplete, + required super.precedingWords, + required super.commands, + required super.parsedArgs, + required super.environment, + }); +} + +/// The leaf [CommandContext] resolved for this completion, if the command +/// runner prepared one. +/// +/// Null when completion did not resolve the command line. +/// +/// [T] is the command runner's result type. Omit the type arguments to +/// accept whatever result type was used. +/// +/// Walk [CommandContext.prev] toward the root. Root options, including +/// global options, are on [CommandContext.root]. The leaf command's own +/// options are on the returned context. +CommandContext? commandContextOf( + final CompletionContext context, +) { + if (context is! CommandCompletionContext) return null; + final leaf = context.leafContext; + if (leaf is CommandContext) return leaf; + return null; +} diff --git a/packages/config/lib/src/command/completion/completion.dart b/packages/config/lib/src/command/completion/completion.dart new file mode 100644 index 00000000..ffa6a037 --- /dev/null +++ b/packages/config/lib/src/command/completion/completion.dart @@ -0,0 +1,12 @@ +/// Shell completion support for the command framework. +library; + +export 'command_completion_context.dart'; +export 'completion_command.dart'; +export 'completion_engine.dart'; +export 'completion_installer.dart'; +export 'completion_protocol.dart'; +export 'completion_settings.dart'; +export 'completion_shell.dart'; +export 'completion_shell_detection.dart'; +export 'option_value_completion.dart'; diff --git a/packages/config/lib/src/command/completion/completion_command.dart b/packages/config/lib/src/command/completion/completion_command.dart new file mode 100644 index 00000000..143e2851 --- /dev/null +++ b/packages/config/lib/src/command/completion/completion_command.dart @@ -0,0 +1,302 @@ +import 'dart:io' show IOSink, exit; + +import '../../config/config.dart' + show + CommandUsageDefinition, + CommandUsageException, + ConfigOptionBase, + Configuration, + EnumOption, + EnumParser, + FlagOption, + OptionDefinition, + StringOption; +import '../command.dart' show Command; +import '../command_context.dart' show CommandContext; +import '../command_runner.dart' show CommandRunner; +import 'completion_installer.dart'; +import 'completion_shell.dart'; +import 'completion_shell_detection.dart'; + +/// The options of the [CompletionCommand]. They are persistent, +/// i.e. also valid after its `install` subcommand. +enum CompletionOption implements OptionDefinition { + /// The shell to generate the script for. When not given, it is the shell + /// the command is most likely run from, see [detectCompletionShell]. + shell( + EnumOption( + enumParser: EnumParser(CompletionShell.values), + argName: 'shell', + fromCustom: _detectShell, + helpText: + 'The shell to generate the completion script for. ' + 'Detected from the shell the command is run from if not given.', + ), + ), + + /// The command name to complete instead of the executable name, + /// for a wrapper script of the executable. + command( + StringOption( + argName: 'command', + helpText: + 'Complete this command name instead, e.g. a wrapper script ' + 'that forwards to the executable with the same commands and options. ' + 'The completion requests are sent to the executable directly.', + ), + ); + + const CompletionOption(this.option); + + @override + final ConfigOptionBase option; +} + +/// The custom value provider of [CompletionOption.shell]. +CompletionShell? _detectShell(final Configuration _) => detectCompletionShell(); + +/// The options of the [CompletionInstallCommand]. +enum CompletionInstallOption implements OptionDefinition { + /// Prints the steps of the installation without performing them. + dryRun( + FlagOption( + argName: 'dry-run', + negatable: false, + defaultsTo: false, + helpText: 'Print what the installation does without doing it.', + ), + ); + + const CompletionInstallOption(this.option); + + @override + final ConfigOptionBase option; +} + +/// The built-in `completion` command, which prints the completion script +/// for a shell to [CompletionSettings.sinks]. Its `install` subcommand, +/// [CompletionInstallCommand], installs the script instead. +/// +/// Automatically added as a subcommand of a [CommandRunner] that has +/// subcommands, unless disabled via `CompletionSettings` or a subcommand +/// named `completion` is defined. +class CompletionCommand extends Command { + @override + final String name = 'completion'; + + final bool _hidden; + + /// [installer] performs the installations of the `install` subcommand. + /// By default the script is installed for the current user and platform. + CompletionCommand({ + final bool hidden = false, + final CompletionInstaller? installer, + }) : _hidden = hidden, + super( + persistentOptions: CompletionOption.values, + subcommands: [CompletionInstallCommand(installer: installer)], + canRunAsLeafCommand: true, + ); + + @override + CommandUsageDefinition get usageDefinition => CommandUsageDefinition( + description: + 'Generate a shell completion script.\n\n' + 'The script needs to be installed only once: it asks ' + '$_executableName for the completion alternatives, so it keeps ' + 'up automatically when $_executableName is updated.\n\n' + 'To install it, run `$_executableName completion install`.\n\n' + '${completionInstallationOverview(_executableName, heading: 'Manual installation:')}\n\n' + 'For a wrapper script with name , generate or install ' + 'the script with `--command `.', + hidden: _hidden, + ); + + String get _executableName => hasParent ? parent.name : ''; + + @override + Future run(final CommandContext context) async { + final request = _CompletionRequest.of(context); + if (request == null) return null; + await writeCompletionOutput(request.runner, request.script); + return null; + } +} + +/// The `completion install` command, which installs the completion script +/// for the current user with a [CompletionInstaller], and prints the steps +/// of the installation to [CompletionSettings.sinks]. +/// +/// The shell and the command name to complete are given by the persistent +/// options of its parent, the [CompletionCommand]. +class CompletionInstallCommand extends Command { + @override + final String name = 'install'; + + final CompletionInstaller? _installer; + + CompletionInstallCommand({final CompletionInstaller? installer}) + : _installer = installer, + super( + options: CompletionInstallOption.values, + usageDefinition: const CommandUsageDefinition( + description: + 'Install the shell completion script for the current user.\n\n' + 'Prints the changes it makes: the script is saved where the ' + 'shell (or bash-completion, or Carapace) looks for it, and ' + 'for Bash, Zsh and PowerShell a line that loads it is added ' + 'to the startup file of the shell. Installing again updates ' + 'the script.', + ), + ); + + @override + Future run( + final CommandContext context, + ) async { + final request = _CompletionRequest.of(context); + if (request == null) return null; + final dryRun = context.config.value(CompletionInstallOption.dryRun); + + // The script is saved in a file named after the command: a path + // would name a file elsewhere. + final commandName = request.commandName; + if (commandName != null && + !CompletionInstaller.isCommandName(commandName)) { + _reportUsageError( + context, + 'Cannot install the completion for "$commandName". ' + 'Specify the name of the command with --command, not its path.', + ); + return null; + } + + final steps = (_installer ?? CompletionInstaller()).plan( + request.shell, + name: request.name, + script: request.script, + executableName: request.runner.executableName, + ); + + final out = request.runner.completion.sinks.out; + out.writeln( + 'Installing the ${request.shell.displayName} completion ' + 'for ${request.name}${dryRun ? ' (dry run, nothing is changed)' : ''}:', + ); + for (final step in steps) { + out.writeln(' ${step.description.replaceAll('\n', '\n ')}'); + if (!dryRun) step.perform(); + } + if (!dryRun) out.writeln(request.shell.activationInstruction); + return null; + } +} + +/// What a `completion` command line asks for: the completion script of +/// [shell] for the command [name] of [runner]. +class _CompletionRequest { + final CommandRunner runner; + final CompletionShell shell; + + /// The command name to complete instead of the executable name, if any. + final String? commandName; + + _CompletionRequest(this.runner, this.shell, this.commandName); + + String get name => commandName ?? runner.executableName; + + String get script => shell.script( + runner.executableName, + description: runner.usageDefinition.description, + viaOption: runner.subcommands.isEmpty, + commandName: commandName, + ); + + /// The request of the command line that ends with [context], whose + /// [CompletionOption]s are those of the [CompletionCommand] on it. + /// + /// If the shell is neither given nor detected, a usage error is reported + /// for the command of [context]. Returns null if the usage output + /// settings of the runner suppress the exception. + static _CompletionRequest? of( + final CommandContext context, + ) { + final runner = context.command.runner; + CommandContext? completion = context; + while (completion != null && completion.command is! CompletionCommand) { + completion = completion.prev; + } + if (completion == null) { + throw StateError( + 'The ${context.command.name} command requires a CompletionCommand ' + 'before it on the command line.', + ); + } + + final config = completion.config; + final shell = config.optionalValue(CompletionOption.shell); + if (shell == null) { + _reportUsageError( + context, + 'Could not detect the shell. Specify it with --shell.', + ); + return null; + } + return _CompletionRequest( + runner, + shell, + config.optionalValue(CompletionOption.command), + ); + } +} + +/// Reports the usage error [message] for the command of [context]. +/// Returns if the usage output settings of the runner suppress the +/// exception. +void _reportUsageError( + final CommandContext context, + final String message, +) { + final command = context.command; + final exception = command.runner.usageOutput.onUsageException( + CommandUsageException('${command.name}: $message', command), + fromCommand: command, + ); + if (exception != null) throw exception; +} + +/// Writes the completion script of [shell] for [runner] to +/// [CompletionSettings.sinks]. See [writeCompletionOutput]. +/// +/// [commandName] generates the script for a wrapper of the executable +/// instead, see [CompletionShell.script]. +Future printCompletionScript( + final CommandRunner runner, + final CompletionShell shell, { + final String? commandName, +}) { + return writeCompletionOutput( + runner, + _CompletionRequest(runner, shell, commandName).script, + ); +} + +/// Writes the completion [output] (a response or a script) to +/// [CompletionSettings.sinks]. +/// +/// The usage output sinks are not used. They are for help text, and may +/// reformat what they write. +/// +/// If `CompletionSettings.exitAfterResponse` is set, the output is then +/// flushed and the process exits with exit code 0, so that nothing the +/// program does after `CommandRunner.run()` can corrupt the output. +Future writeCompletionOutput( + final CommandRunner runner, + final String output, +) async { + final sink = runner.completion.sinks.out; + sink.write(output); + if (!runner.completion.exitAfterResponse) return; + if (sink is IOSink) await sink.flush(); + exit(0); +} diff --git a/packages/config/lib/src/command/completion/completion_engine.dart b/packages/config/lib/src/command/completion/completion_engine.dart new file mode 100644 index 00000000..6b9b3599 --- /dev/null +++ b/packages/config/lib/src/command/completion/completion_engine.dart @@ -0,0 +1,562 @@ +import 'dart:async' show FutureOr; + +import '../../config/arg_parser/arg_parser.dart' + show + ArgParseResult, + DoubleDashHandling, + ParserSettings, + optionAwaitingValue, + scanAndParseCommands, + unknownSubcommandErrorPrefix; +import '../../config/config.dart' + show + CommandDefinition, + CompletionCandidate, + CompletionContext, + CompletionResult, + ConfigOptionBase, + FlagOption, + MultiOption, + MutuallyExclusive, + OptionDefinition, + ParsedArgs; +import '../command_resolver.dart'; +import 'completion_protocol.dart'; +import 'option_value_completion.dart'; + +/// Computes the completion candidates for a partial command line, +/// using the command tree and option definitions of a root command. +/// +/// The partial command line is parsed with the regular argument parser, +/// so the same rules apply as when running the command line: persistent +/// options, option aliases and abbreviations, `--option=value`, `--`, etc. +/// +/// The engine never throws; on any error it responds with +/// [CompletionDirective.error]. +class CompletionEngine { + final CommandDefinition rootCommand; + + /// See `CommandRunner.ignoreUnexpectedPositionalArgs`. + final bool ignoreUnexpectedPositionalArgs; + + /// Receives a diagnostic message when a completion request fails. + final void Function(Object error, StackTrace stackTrace)? onError; + + /// When set, option-value completion resolves the command line typed so far + /// and runs that chain's middleware before asking the option for candidates. + /// + /// Subcommand and option-name completion does not use it. Without a + /// resolver, option values are completed from the raw command line only. + final CommandResolver? resolver; + + const CompletionEngine( + this.rootCommand, { + this.resolver, + this.ignoreUnexpectedPositionalArgs = false, + this.onError, + }); + + /// Completes the last of [words], the (possibly empty) word being typed, + /// given the preceding words on the command line. + /// + /// [words] does not include the executable name. + /// + /// [environment] is passed to [resolver], when one is given, and to + /// custom `ConfigOptionBase.complete` implementations as + /// `CompletionContext.environment`. + Future complete( + final List words, { + final Map environment = const {}, + }) async { + try { + return await _complete(words, environment); + } catch (e, s) { + onError?.call(e, s); + return const CompletionResponse.error(); + } + } + + /// A word no user types, appended to the preceding words to find out from + /// the parser whether the word being completed is the value of an option. + static const _sentinel = '\u0000\u0000'; + + Future _complete( + final List allWords, + final Map environment, + ) async { + final words = allWords.isEmpty ? const [''] : allWords; + final current = words.last; + + // Shell I/O redirection (`>`, `>>`, `2>`, `>file`, ...) is not a command + // argument. The cursor word is a filename, which the shell completes. + // Here-documents (`<<`, `<<<`) are not file redirections. + if (_isRedirectionTarget(words)) { + return const CompletionResponse.files(); + } + // Earlier redirections would otherwise be parsed as arguments. + final preceding = _withoutRedirections( + words.sublist(0, words.length - 1), + ); + + final parsed = scanAndParseCommands( + [...preceding, _sentinel], + rootCommand: rootCommand, + settings: ParserSettings( + doubleDashHandling: ignoreUnexpectedPositionalArgs + ? DoubleDashHandling.passThroughRest + : DoubleDashHandling.noSpecialHandling, + ), + ); + final chain = parsed.toList(); + final line = _CommandLine( + chain: chain, + preceding: preceding, + environment: environment, + ); + + // After `--`, nothing is parsed; let the shell complete files. + if (line.leaf.unparsedArgs.contains(_sentinel)) { + return const CompletionResponse.files(); + } + + // The word being completed is the value of the preceding option. + final valueOption = _optionAwaitingValue(line); + if (valueOption != null) { + return _completeOptionValue(line, valueOption, current); + } + + // The word being completed is an option with an attached value: + // `--option=val`, `-o=val`, or `-abo=val` where the value belongs to + // the last option of the cluster. The response contains the bare values, + // the shell scripts re-attach the option prefix. + if (current.startsWith('-') && current.contains('=')) { + final equals = current.indexOf('='); + final spelling = optionAwaitingValue(current.substring(0, equals)); + final option = spelling == null + ? null + : _findOptionBySpelling(line, spelling); + if (option == null) return const CompletionResponse.nothing(); + return _completeOptionValue(line, option, current.substring(equals + 1)); + } + + if (current.startsWith('-')) { + return _completeOptionNames(line, current); + } + + if (line.leafCommand.subcommands.isNotEmpty) { + // After an unknown subcommand word, no subcommand is valid anymore. + if (line.hasRejectedSubcommand) return const CompletionResponse.nothing(); + return _completeSubcommands(line.leafCommand, current); + } + + return _completePositional(line, current); + } + + /// The option whose value is the word being completed, if any. + ConfigOptionBase? _optionAwaitingValue(final _CommandLine line) { + for (final result in line.chain) { + for (final entry in result.regularOptions.entries) { + if (entry.value == _sentinel) return entry.key; + } + for (final entry in result.multiOptions.entries) { + if (entry.value.contains(_sentinel)) return entry.key; + } + } + + // The parser may have consumed the sentinel as the value of an option + // without recording it, e.g. for an option specified more than once. + // In that case the sentinel was not treated as a word. + final leaf = line.leaf; + final isWord = + leaf.positionalWords.contains(_sentinel) || + leaf.errors.any((final error) => error.contains(_sentinel)); + if (isWord || line.preceding.isEmpty) return null; + + final spelling = optionAwaitingValue(line.preceding.last); + if (spelling == null) return null; + final option = _findOptionBySpelling(line, spelling); + return option is FlagOption ? null : option; + } + + /// Finds the option visible on the leaf command that is spelled + /// `--name`, `--alias`, or `-x`. + ConfigOptionBase? _findOptionBySpelling( + final _CommandLine line, + final String spelling, + ) { + for (final option in line.visibleOptions) { + if (spelling.startsWith('--')) { + final name = spelling.substring(2); + if (option.argName == name) return option; + if (option.argAliases?.contains(name) == true) return option; + if (option is FlagOption && name == 'no-${option.argName}') { + return option; + } + } else if (spelling.length == 2 && spelling.startsWith('-')) { + if (option.argAbbrev == spelling[1]) return option; + } + } + return null; + } + + Future _completeOptionValue( + final _CommandLine line, + final ConfigOptionBase option, + final String word, + ) async { + // Complete the last element of a multi-value option word, e.g. `a,b`. + var prefix = ''; + var elementWord = word; + if (option is MultiOption) { + final separator = option.multiParser.separator; + if (separator is String && separator.isNotEmpty) { + final index = word.lastIndexOf(separator); + if (index >= 0) { + prefix = word.substring(0, index + separator.length); + elementWord = word.substring(index + separator.length); + } + } + } + + final prelude = CompletionPrelude( + wordToComplete: elementWord, + precedingWords: line.preceding, + commands: line.commands, + parsedArgs: _ChainParsedArgs(line.chain), + environment: line.environment, + ); + + final FutureOr pending; + final resolver = this.resolver; + if (resolver != null) { + pending = OptionValueCompletion(resolver).completeOption( + prelude, + option.complete, + ); + } else { + pending = option.complete( + CompletionContext( + wordToComplete: prelude.wordToComplete, + precedingWords: prelude.precedingWords, + commands: prelude.commands, + parsedArgs: prelude.parsedArgs, + environment: prelude.environment, + ), + ); + } + final result = pending is Future + ? await pending + : pending; + return CompletionResponse.fromResult(result, prefix: prefix); + } + + CompletionResponse _completeOptionNames( + final _CommandLine line, + final String current, + ) { + final includeShort = !current.startsWith('--'); + final candidates = []; + + for (final option in line.visibleOptions) { + final name = option.argName; + if (name == null || option.hide) continue; + if (option is! MultiOption && line.wasGiven(option)) continue; + if (line.isExcluded(option)) continue; + + final description = _firstLine(option.helpText); + candidates.add(CompletionCandidate('--$name', description: description)); + if (option is FlagOption && + option.negatable && + !option.hideNegatedUsage) { + candidates.add( + CompletionCandidate('--no-$name', description: description), + ); + } + final abbrev = option.argAbbrev; + if (includeShort && abbrev != null) { + candidates.add( + CompletionCandidate('-$abbrev', description: description), + ); + } + } + + // Subcommands spelled like options, e.g. `--version`. + for (final subcommand in line.leafCommand.subcommands) { + if (subcommand.usageDefinition.hidden) continue; + final description = _firstLine(subcommand.usageDefinition.description); + for (final spelling in [ + subcommand.name, + ...subcommand.aliasesDefinition.aliases, + ]) { + if (!spelling.startsWith('-')) continue; + if (!includeShort && !spelling.startsWith('--')) continue; + candidates.add(CompletionCandidate(spelling, description: description)); + } + } + + return CompletionResponse( + _matching(candidates, current), + directive: CompletionDirective.noFileCompletion, + ); + } + + CompletionResponse _completeSubcommands( + final CommandDefinition command, + final String current, + ) { + final candidates = [ + for (final subcommand in command.subcommands) + if (!subcommand.usageDefinition.hidden && + !subcommand.name.startsWith('-')) + CompletionCandidate( + subcommand.name, + description: _firstLine(subcommand.usageDefinition.description), + ), + ]; + return CompletionResponse( + _matching(candidates, current), + directive: CompletionDirective.noFileCompletion, + ); + } + + Future _completePositional( + final _CommandLine line, + final String current, + ) async { + final index = line.leaf.positionalWords + .where((final word) => word != _sentinel) + .length; + for (final option in line.leafCommand.options) { + if (option.option.argPos == index) { + if (line.isExcluded(option.option)) { + return const CompletionResponse.nothing(); + } + return _completeOptionValue(line, option.option, current); + } + } + return ignoreUnexpectedPositionalArgs + ? const CompletionResponse.files() + : const CompletionResponse.nothing(); + } + + static List _matching( + final List candidates, + final String prefix, + ) { + return [ + for (final candidate in candidates) + if (candidate.value.startsWith(prefix)) candidate, + ]; + } + + static String? _firstLine(final String? text) { + if (text == null) return null; + final line = text.trim().split('\n').first.trim(); + return line.isEmpty ? null : line; + } +} + +/// Whether the cursor word of [words] is the target of a file redirection. +/// +/// The target is the cursor word when that word is an operator (`>`, `2>`, +/// `>>file`) or when the word before it is a bare operator (`> file`). +bool _isRedirectionTarget(final List words) { + if (_redirectionTarget(words.last) != null) return true; + return words.length >= 2 && _redirectionTarget(words[words.length - 2]) == ''; +} + +/// [words] without file redirections and the filename each one names. +/// +/// A bare operator consumes the next word (`> out.txt`). An operator glued +/// to its filename is a single word (`>out.txt`). A file-descriptor prefix +/// that Bash split off the operator (`2` `>`) is left in place: it cannot +/// be told apart from a real argument that happens to be a number. +List _withoutRedirections(final List words) { + final kept = []; + for (var i = 0; i < words.length; i++) { + final target = _redirectionTarget(words[i]); + if (target == null) { + kept.add(words[i]); + continue; + } + if (target.isEmpty && i + 1 < words.length) i++; + } + return kept; +} + +/// The filename after a leading file-redirection operator, or null when +/// [word] is not one. +/// +/// Empty when [word] is only the operator (`>`, `>>`, `2>`, `>&`). +/// An optional descriptor prefix (`2`, `{name}`, `&`) is part of the operator. +/// Here-documents (`<<`, `<<<`) return null. +/// +/// Kept in agreement with `__FN___redirect_rest` in the Bash script. +String? _redirectionTarget(final String word) { + if (word.startsWith('<<')) return null; + final match = _fileRedirection.firstMatch(word); + if (match == null) return null; + return match[1] ?? ''; +} + +/// Longest operator first. The last group is the filename part. +final _fileRedirection = RegExp( + r'^(?:(?:\{[A-Za-z_][A-Za-z0-9_]*\})|\d*|&)?' + r'(?:&>>|>>|>&|>\||<>|<&|&>|[<>])' + r'(.*)$', +); + +/// The parsed state of the command line preceding the word being completed. +class _CommandLine { + final List chain; + final List preceding; + final Map environment; + + _CommandLine({ + required this.chain, + required this.preceding, + required this.environment, + }); + + ArgParseResult get leaf => chain.last; + + CommandDefinition get leafCommand => _commandOf(leaf); + + List get commands => [ + for (final result in chain) _commandOf(result), + ]; + + /// The options that can be given at the leaf command: its own options + /// and the persistent options, built-in or not, of it and its ancestors. + Iterable get visibleOptions sync* { + final seen = {}; + for (final command in commands) { + for (final option in command.allOptions(onlyPersistent: true)) { + if (seen.add(option.option)) yield option.option; + } + } + for (final option in leafCommand.options) { + if (seen.add(option.option)) yield option.option; + } + } + + bool wasParsed(final ConfigOptionBase option) { + return chain.any( + (final result) => + result.flagOptions.containsKey(option) || + result.regularOptions.containsKey(option) || + result.multiOptions.containsKey(option), + ); + } + + /// Whether [option] was given on the command line, by name or as a + /// positional argument. + bool wasGiven(final ConfigOptionBase option) { + if (wasParsed(option)) return true; + final argPos = option.argPos; + if (argPos == null) return false; + final positionalCount = leaf.positionalWords + .where((final word) => word != CompletionEngine._sentinel) + .length; + return argPos < positionalCount; + } + + /// Whether [option] can no longer be given because another option of its + /// [MutuallyExclusive] group was given on the command line. + bool isExcluded(final ConfigOptionBase option) { + final group = option.group; + if (group is! MutuallyExclusive) return false; + return visibleOptions.any( + (final other) => + other != option && other.group == group && wasGiven(other), + ); + } + + /// Whether a preceding word was rejected as an unknown subcommand + /// of the leaf command. + bool get hasRejectedSubcommand { + final rejected = leaf.errors.where( + (final error) => error.startsWith(unknownSubcommandErrorPrefix), + ); + return rejected.any( + (final error) => !error.contains(CompletionEngine._sentinel), + ); + } + + static CommandDefinition _commandOf(final ArgParseResult result) { + final command = result.command; + if (command == null) throw StateError('ArgParseResult.command is null'); + return command; + } +} + +/// The parsed arguments of all commands on the command line, as one view. +class _ChainParsedArgs implements ParsedArgs { + final List _chain; + + _ChainParsedArgs(this._chain); + + /// Whether [value] was typed, i.e. is not the placeholder for the word + /// being completed. + static bool _wasTyped(final String? value) => + value != null && value != CompletionEngine._sentinel; + + /// The option whose value is being completed has no value yet, and is + /// not parsed unless it was also given earlier on the command line. + @override + bool wasParsed(final ConfigOptionBase option) { + return _chain.any( + (final result) => + result.flagOptions.containsKey(option) || + _wasTyped(result.regularOptions[option]) || + (result.multiOptions[option]?.any(_wasTyped) ?? false), + ); + } + + @override + bool flag(final FlagOption option) { + for (final result in _chain) { + final value = result.flagOptions[option]; + if (value != null) return value; + } + throw StateError('Flag ${option.argName} not found'); + } + + @override + String option(final ConfigOptionBase option) { + for (final result in _chain) { + final value = result.regularOptions[option]; + if (value != null && _wasTyped(value)) return value; + } + throw StateError('Option ${option.argName} not found'); + } + + @override + List multiOption(final MultiOption option) { + for (final result in _chain) { + final values = result.multiOptions[option]; + if (values != null) { + return values + .where((final value) => value != CompletionEngine._sentinel) + .toList(); + } + } + throw StateError('Multi-option ${option.argName} not found'); + } + + @override + List get rest { + final leaf = _chain.last; + return [ + ...leaf.positionalWords, + ...leaf.unparsedArgs, + ].where((final word) => word != CompletionEngine._sentinel).toList(); + } + + @override + List get parseErrors => [ + for (final result in _chain) + for (final error in result.errors) + if (!error.contains(CompletionEngine._sentinel)) error, + ]; +} diff --git a/packages/config/lib/src/command/completion/completion_installer.dart b/packages/config/lib/src/command/completion/completion_installer.dart new file mode 100644 index 00000000..9bd1e485 --- /dev/null +++ b/packages/config/lib/src/command/completion/completion_installer.dart @@ -0,0 +1,446 @@ +import 'dart:convert' show Utf8Decoder, Utf8Encoder; +import 'dart:io' + show Directory, File, FileMode, FileSystemException, Platform, Process; +import 'dart:typed_data' show ByteData, Endian, Uint8List; + +import 'package:path/path.dart' as p; + +import 'completion_shell.dart'; + +/// A step of a completion installation: a change to the file system, +/// or a note that a file needs no change. +class CompletionInstallStep { + /// What the step does, as printed by `completion install`. + /// A change to the content of a file has the added lines on the lines + /// that follow the first one. + final String description; + + final void Function() _perform; + + CompletionInstallStep(this.description, this._perform); + + /// Makes the change described by [description]. + void perform() => _perform(); +} + +/// Installs the completion script of a shell for the current user, +/// in the way that is the common practice for the shell: +/// +/// - Bash: the script is saved in the user directory of bash-completion, +/// which loads it on demand. Since bash-completion may not be installed, +/// the script is also sourced from `~/.bashrc`. On macOS, where terminals +/// start login shells, it is sourced from `~/.bash_profile` instead (or +/// from `~/.bash_login` or `~/.profile` if that is the file in use). +/// - Zsh: the script is saved as an autoloadable `_name` function file and +/// sourced from `.zshrc`, after initializing the completion system +/// (`compinit`) unless the startup file has already done so. +/// - Fish: the script is saved in the Fish user completions directory, +/// from where Fish loads it on demand. +/// - PowerShell: the script is saved next to the PowerShell profile +/// (`$PROFILE`) and loaded from it. +/// - Carapace: the spec is saved in the Carapace user specs directory. +/// +/// The XDG base directories are honored where the shell honors them. +/// An installation can be repeated: the script is overwritten, and a +/// startup file that already loads it is left as it is. +/// +/// A startup file is read and appended to in its own encoding: UTF-16 or +/// UTF-32 if it starts with the byte order mark of that encoding (as a +/// profile written by Windows PowerShell does), otherwise UTF-8. +class CompletionInstaller { + /// The environment variables that determine the installation locations. + final Map environment; + + /// The operating system to install for, as in [Platform.operatingSystem]. + final String operatingSystem; + + final String? Function() _queryPowerShellProfile; + + final p.Context _path; + + /// [environment] and [operatingSystem] default to those of the process. + /// + /// [powerShellProfile] returns the path of the PowerShell profile on + /// Windows, or null if unknown. By default PowerShell is asked for it, + /// since the location depends on the PowerShell edition and on where the + /// user's documents folder is. Elsewhere the path follows from the + /// environment. + CompletionInstaller({ + final Map? environment, + final String? operatingSystem, + final String? Function()? powerShellProfile, + }) : this._( + environment ?? Platform.environment, + operatingSystem ?? Platform.operatingSystem, + powerShellProfile ?? _askPowerShellForProfile, + ); + + CompletionInstaller._( + this.environment, + this.operatingSystem, + this._queryPowerShellProfile, + ) : _path = p.Context( + style: operatingSystem == 'windows' ? p.Style.windows : p.Style.posix, + ); + + bool get _isWindows => operatingSystem == 'windows'; + + bool get _isMacOS => operatingSystem == 'macos'; + + /// Whether a completion can be installed for the command [name]. + /// + /// The script is saved in a file named after the command, which is how + /// the shells find it. The name must therefore be the name of the command + /// as a file name, not a path to it: not empty, `.` or `..`, and without + /// path separators (`/` and `\`) and control characters. + static bool isCommandName(final String name) { + return name.isNotEmpty && + name != '.' && + name != '..' && + !_notInCommandName.hasMatch(name); + } + + static final _notInCommandName = RegExp(r'[/\\\x00-\x1f\x7f]'); + + static void _checkCommandName(final String name) { + if (isCommandName(name)) return; + throw ArgumentError.value( + name, + 'name', + 'Not a command name to install a completion for: ' + 'it must be a file name without a directory', + ); + } + + /// Plans the installation of [script], the completion script of [shell] + /// for the command [name], and returns its steps in order. + /// + /// Nothing is changed until the steps are performed. The steps are + /// planned from the current state of the file system: directories that + /// exist are not created, and a startup file that already loads the + /// script is not changed. + /// + /// [executableName] is named in the startup file as the origin of the + /// lines added to it. + /// + /// Throws an [ArgumentError] if [name] is not a command name, see + /// [isCommandName], and a [FileSystemException] if the user's home + /// directory is unknown. + List plan( + final CompletionShell shell, { + required final String name, + required final String script, + required final String executableName, + }) { + final scriptFile = scriptPath(shell, name); + final startupFile = startupFilePath(shell); + final plannedDirectories = {}; + return [ + ..._createDirectory(_path.dirname(scriptFile), plannedDirectories), + CompletionInstallStep( + 'Write $scriptFile', + () => File(scriptFile).writeAsStringSync(script), + ), + if (startupFile != null) + ..._addToStartupFile(startupFile, [ + '# $name shell completion, ' + 'added by `$executableName completion install`.', + ..._loadLines(shell, scriptFile), + ], plannedDirectories), + ]; + } + + /// The file that the completion script of [shell] for the command [name] + /// is installed as. + /// + /// Throws an [ArgumentError] if [name] is not a command name, see + /// [isCommandName]: as a path it would name a file elsewhere. + String scriptPath(final CompletionShell shell, final String name) { + _checkCommandName(name); + return switch (shell) { + CompletionShell.bash => _path.join( + environment.valueOf('BASH_COMPLETION_USER_DIR') ?? + _path.join(_dataHome, 'bash-completion'), + 'completions', + name, + ), + CompletionShell.zsh => _path.join( + _dataHome, + 'zsh', + 'site-functions', + '_$name', + ), + CompletionShell.fish => _path.join( + _configHome, + 'fish', + 'completions', + '$name.fish', + ), + CompletionShell.powershell => _path.join( + _path.dirname(_powerShellProfile), + 'Completions', + '$name.ps1', + ), + CompletionShell.carapace => _path.join( + _carapaceConfigDir, + 'carapace', + 'specs', + '$name.yaml', + ), + }; + } + + /// The shell startup file that loads the installed script of [shell], + /// or null if the shell finds the script by itself. + String? startupFilePath(final CompletionShell shell) { + return switch (shell) { + CompletionShell.bash => _bashStartupFile, + CompletionShell.zsh => _path.join( + environment.valueOf('ZDOTDIR') ?? _home, + '.zshrc', + ), + CompletionShell.powershell => _powerShellProfile, + CompletionShell.fish || CompletionShell.carapace => null, + }; + } + + /// The lines of the startup file of [shell] that load [scriptFile]. + /// The last one is the line that names the file. + List _loadLines( + final CompletionShell shell, + final String scriptFile, + ) { + final file = shell == CompletionShell.powershell + ? "'${scriptFile.replaceAll("'", "''")}'" + : shellQuote(scriptFile); + return switch (shell) { + CompletionShell.bash => ['[ -r $file ] && source $file'], + CompletionShell.zsh => [ + r'(( $+functions[compdef] )) || { autoload -Uz compinit && compinit; }', + '[[ -r $file ]] && source $file', + ], + CompletionShell.powershell => [ + 'if (Test-Path -LiteralPath $file) { . $file }', + ], + CompletionShell.fish || CompletionShell.carapace => const [], + }; + } + + List _createDirectory( + final String directory, + final Set plannedDirectories, + ) { + final isPlanned = plannedDirectories.any( + (final planned) => + planned == directory || _path.isWithin(directory, planned), + ); + if (isPlanned || Directory(directory).existsSync()) return const []; + plannedDirectories.add(directory); + return [ + CompletionInstallStep( + 'Create directory $directory', + () => Directory(directory).createSync(recursive: true), + ), + ]; + } + + /// Appends [lines] to the startup file at [path], + /// unless it contains the last line already. + /// + /// An existing file is read and appended to in its own encoding. + List _addToStartupFile( + final String path, + final List lines, + final Set plannedDirectories, + ) { + final file = File(path); + final bytes = file.existsSync() ? file.readAsBytesSync() : null; + final encoding = bytes == null + ? _TextEncoding.utf8 + : _TextEncoding.of(bytes); + final content = bytes == null ? null : encoding.decode(bytes); + if (content != null && content.contains(lines.last)) { + return [ + CompletionInstallStep('Keep $path, it already loads the script', () {}), + ]; + } + + // Start on a new line, after an empty line. + final separator = content == null || content.isEmpty + ? '' + : content.endsWith('\n') + ? '\n' + : '\n\n'; + return [ + ..._createDirectory(_path.dirname(path), plannedDirectories), + CompletionInstallStep( + [ + '${content == null ? 'Create' : 'Append to'} $path:', + for (final line in lines) ' $line', + ].join('\n'), + () => file.writeAsBytesSync( + encoding.encode('$separator${lines.join('\n')}\n'), + mode: FileMode.append, + ), + ), + ]; + } + + String get _home { + final home = + environment.valueOf('HOME') ?? + (_isWindows ? environment.valueOf('USERPROFILE') : null); + if (home != null) return home; + throw FileSystemException( + 'Cannot determine the home directory: the environment variable ' + '${_isWindows ? 'USERPROFILE' : 'HOME'} is not set', + ); + } + + String get _dataHome => + environment.valueOf('XDG_DATA_HOME') ?? + _path.join(_home, '.local', 'share'); + + String get _configHome => + environment.valueOf('XDG_CONFIG_HOME') ?? _path.join(_home, '.config'); + + /// The user configuration directory as Carapace determines it: + /// that of the XDG base directories if set, else that of the platform. + String get _carapaceConfigDir { + final xdgConfigHome = environment.valueOf('XDG_CONFIG_HOME'); + if (xdgConfigHome != null) return xdgConfigHome; + if (_isWindows) { + return environment.valueOf('APPDATA') ?? + _path.join(_home, 'AppData', 'Roaming'); + } + if (_isMacOS) return _path.join(_home, 'Library', 'Application Support'); + return _path.join(_home, '.config'); + } + + /// `~/.bashrc`, which is read by interactive shells that are not login + /// shells. On macOS, the file that login shells read instead: the first + /// of the candidates that exists is the only one Bash reads. + String get _bashStartupFile { + if (!_isMacOS) return _path.join(_home, '.bashrc'); + final candidates = [ + for (final name in const ['.bash_profile', '.bash_login', '.profile']) + _path.join(_home, name), + ]; + return candidates.firstWhere( + (final candidate) => File(candidate).existsSync(), + orElse: () => candidates.first, + ); + } + + late final String _powerShellProfile = _findPowerShellProfile(); + + String _findPowerShellProfile() { + const profile = 'Microsoft.PowerShell_profile.ps1'; + if (!_isWindows) return _path.join(_configHome, 'powershell', profile); + return _queryPowerShellProfile() ?? + _path.join(_home, 'Documents', 'PowerShell', profile); + } +} + +/// Asks PowerShell for the path of the profile of the current user. +/// Prefers PowerShell 7+ (`pwsh`) to Windows PowerShell (`powershell`). +String? _askPowerShellForProfile() { + for (final executable in const ['pwsh', 'powershell']) { + try { + final result = Process.runSync(executable, const [ + '-NoLogo', + '-NoProfile', + '-NonInteractive', + '-Command', + r'$PROFILE', + ]); + final profile = (result.stdout as String).trim(); + if (result.exitCode == 0 && profile.isNotEmpty) return profile; + } on Exception { + // Not installed: try the next one. + } + } + return null; +} + +/// The text encoding of a startup file. The UTF-16 and UTF-32 encodings +/// are recognized by their byte order mark; a file without one is UTF-8. +enum _TextEncoding { + utf8(1, Endian.little), + utf16LittleEndian(2, Endian.little), + utf16BigEndian(2, Endian.big), + utf32LittleEndian(4, Endian.little), + utf32BigEndian(4, Endian.big); + + /// The number of bytes of a code unit. + final int _unitSize; + + /// The byte order of a code unit. + final Endian _endian; + + const _TextEncoding(this._unitSize, this._endian); + + static const _byteOrderMark = 0xfeff; + + /// The encoding of the file content [bytes]. + static _TextEncoding of(final Uint8List bytes) { + bool startsWith(final List prefix) { + if (bytes.length < prefix.length) return false; + for (var i = 0; i < prefix.length; i++) { + if (bytes[i] != prefix[i]) return false; + } + return true; + } + + // The UTF-32 marks first: the little-endian one starts with the + // little-endian mark of UTF-16. + if (startsWith(const [0xff, 0xfe, 0x00, 0x00])) return utf32LittleEndian; + if (startsWith(const [0x00, 0x00, 0xfe, 0xff])) return utf32BigEndian; + if (startsWith(const [0xff, 0xfe])) return utf16LittleEndian; + if (startsWith(const [0xfe, 0xff])) return utf16BigEndian; + return utf8; + } + + /// The text of the file content [bytes], without the byte order mark. + /// Malformed content is decoded as far as possible. + String decode(final Uint8List bytes) { + if (this == utf8) { + return const Utf8Decoder(allowMalformed: true).convert(bytes); + } + final data = ByteData.sublistView(bytes); + final units = [ + for (var i = 0; i + _unitSize <= bytes.length; i += _unitSize) + _unitSize == 2 + ? data.getUint16(i, _endian) + : data.getUint32(i, _endian), + ]; + if (units.isNotEmpty && units.first == _byteOrderMark) units.removeAt(0); + if (_unitSize == 2) return String.fromCharCodes(units); + return String.fromCharCodes([ + for (final unit in units) unit > 0x10ffff ? 0xfffd : unit, + ]); + } + + /// The bytes of [text] to append to a file with this encoding. + List encode(final String text) { + if (this == utf8) return const Utf8Encoder().convert(text); + final units = _unitSize == 2 ? text.codeUnits : text.runes.toList(); + final data = ByteData(units.length * _unitSize); + for (var i = 0; i < units.length; i++) { + if (_unitSize == 2) { + data.setUint16(i * _unitSize, units[i], _endian); + } else { + data.setUint32(i * _unitSize, units[i], _endian); + } + } + return data.buffer.asUint8List(); + } +} + +extension on Map { + /// The value of the variable [name], or null if it is not set or empty. + String? valueOf(final String name) { + final value = this[name]; + return value == null || value.isEmpty ? null : value; + } +} diff --git a/packages/config/lib/src/command/completion/completion_protocol.dart b/packages/config/lib/src/command/completion/completion_protocol.dart new file mode 100644 index 00000000..789e6d1f --- /dev/null +++ b/packages/config/lib/src/command/completion/completion_protocol.dart @@ -0,0 +1,136 @@ +import '../../config/completion.dart'; + +/// Flags that instruct the shell how to treat the completion response. +/// +/// Compatible with Cobra's ShellCompDirective values. +abstract final class CompletionDirective { + /// An error occurred, the shell should offer nothing. + static const int error = 1; + + /// Do not append a space after a single inserted candidate. + static const int noSpace = 2; + + /// Do not fall back to file completion when there are no candidates. + static const int noFileCompletion = 4; + + /// Perform file completion restricted to the file extensions listed as + /// candidate lines (without a leading dot). + static const int filterFileExtensions = 8; + + /// Perform directory completion only. + static const int filterDirectories = 16; + + /// Present the candidates in the given order instead of sorting them. + static const int keepOrder = 32; + + /// Plain candidates with file completion fallback. + static const int defaultDirective = 0; +} + +/// The response to a completion request, see [completeRequestCommand]. +class CompletionResponse { + /// The candidate lines. For [CompletionDirective.filterFileExtensions] + /// these are the file extensions. + final List candidates; + + /// The sum of the [CompletionDirective] flags. + final int directive; + + const CompletionResponse( + this.candidates, { + required this.directive, + }); + + /// A response with no candidates where the shell offers nothing. + const CompletionResponse.nothing() + : candidates = const [], + directive = CompletionDirective.noFileCompletion; + + /// A response with no candidates where the shell performs native file + /// completion. + const CompletionResponse.files() + : candidates = const [], + directive = CompletionDirective.defaultDirective; + + /// A response indicating that an error occurred. + const CompletionResponse.error() + : candidates = const [], + directive = CompletionDirective.error; + + /// Converts a [CompletionResult] of an option value into a response. + /// + /// [prefix] is prepended to every candidate value, used when only the + /// trailing part of the word was completed (e.g. after a list separator). + factory CompletionResponse.fromResult( + final CompletionResult result, { + final String prefix = '', + }) { + switch (result.pathMode) { + case CompletionPathMode.directories: + return const CompletionResponse( + [], + directive: CompletionDirective.filterDirectories, + ); + case CompletionPathMode.files: + if (result.fileExtensions.isEmpty) { + return const CompletionResponse.files(); + } + return CompletionResponse( + [for (final ext in result.fileExtensions) CompletionCandidate(ext)], + directive: CompletionDirective.filterFileExtensions, + ); + case CompletionPathMode.none: + var directive = CompletionDirective.noFileCompletion; + if (result.noSpace) directive |= CompletionDirective.noSpace; + return CompletionResponse( + [ + for (final candidate in result.candidates) + prefix.isEmpty + ? candidate + : CompletionCandidate( + '$prefix${candidate.value}', + description: candidate.description, + ), + ], + directive: directive, + ); + } + } + + /// Whether the shell may fall back to file completion. + bool get allowsFileCompletion => + directive & CompletionDirective.noFileCompletion == 0 && + directive & CompletionDirective.error == 0; + + /// Formats the response in the wire format, see [completeRequestCommand]. + String format() { + final buffer = StringBuffer(); + for (final candidate in candidates) { + buffer.write(_sanitizeValue(candidate.value)); + final description = candidate.description; + if (description != null && description.isNotEmpty) { + buffer.write('\t'); + buffer.write(_sanitizeDescription(description)); + } + buffer.writeln(); + } + buffer.writeln(':$directive'); + return buffer.toString(); + } + + /// One or more line or field separators, which values and descriptions + /// must not contain. + static const _separators = r'[\t\r\n]+'; + + /// The value is the text to insert, so the spaces at its ends are kept. + /// Separators are dropped at the ends and replaced by a space elsewhere. + static String _sanitizeValue(final String text) { + return text + .replaceAll(RegExp('^$_separators|$_separators\$'), '') + .replaceAll(RegExp(_separators), ' '); + } + + static String _sanitizeDescription(final String text) { + return text.replaceAll(RegExp(_separators), ' ').trim(); + } +} diff --git a/packages/config/lib/src/command/completion/completion_settings.dart b/packages/config/lib/src/command/completion/completion_settings.dart new file mode 100644 index 00000000..606283ad --- /dev/null +++ b/packages/config/lib/src/command/completion/completion_settings.dart @@ -0,0 +1,49 @@ +import '../output_sinks.dart'; + +/// Settings for the built-in shell completion support of a `CommandRunner`. +/// +/// Completion is enabled by default. It adds: +/// - a hidden `__complete` request handler that the shell completion scripts +/// call to obtain the completion alternatives, +/// - a `completion` subcommand that prints the completion script for a +/// shell, and installs it with `completion install`, when the runner has +/// subcommands, +/// - a `--completion ` global option that does the same, when the +/// runner has no subcommands. +/// +/// The generated scripts carry their installation instructions in their +/// comment header, so that they are available for both kinds of runners. +class CompletionSettings { + /// Whether completion support is enabled. + final bool enabled; + + /// Whether the `completion` subcommand is hidden from the usage help. + final bool hideCommand; + + /// Whether the process exits (with exit code 0) as soon as a completion + /// response or a completion script has been written. + /// + /// False by default: `CommandRunner.run()` then returns null after the + /// completion output. + /// + /// The completion output must be the only output on stdout: anything the + /// program prints after `CommandRunner.run()` returns would corrupt the + /// response read by the shell, or the script being sourced. Set to true + /// to prevent that without requiring the program to check what was run. + /// The completion output is flushed before exiting when it is an `IOSink` + /// (stdout is). + final bool exitAfterResponse; + + /// Where completion responses, scripts, and failure diagnostics are written. + final OutputSinks sinks; + + const CompletionSettings({ + this.enabled = true, + this.hideCommand = false, + this.exitAfterResponse = false, + this.sinks = const OutputSinks(), + }); + + /// Disables completion support entirely. + static const CompletionSettings disabled = CompletionSettings(enabled: false); +} diff --git a/packages/config/lib/src/command/completion/completion_shell.dart b/packages/config/lib/src/command/completion/completion_shell.dart new file mode 100644 index 00000000..1b986755 --- /dev/null +++ b/packages/config/lib/src/command/completion/completion_shell.dart @@ -0,0 +1,281 @@ +import 'scripts/bash_completion_script.dart'; +import 'scripts/carapace_completion_spec.dart'; +import 'scripts/fish_completion_script.dart'; +import 'scripts/powershell_completion_script.dart'; +import 'scripts/zsh_completion_script.dart'; + +/// The shells and completion frameworks for which completion scripts +/// can be generated. +enum CompletionShell { + bash('Bash'), + zsh('Zsh'), + fish('Fish'), + powershell('PowerShell'), + carapace('Carapace'); + + /// The display name. + final String displayName; + + const CompletionShell(this.displayName); + + /// Generates the completion script (or spec) for [executableName]. + /// + /// The script is independent of the commands and options of the + /// executable: it asks the executable for the completion alternatives + /// via the `__complete` request, so it needs to be installed only once. + /// + /// [description] is a short description of the executable, included + /// where the format supports it. + /// + /// [viaOption] selects how the script is requested from the executable in + /// the installation instructions of the script header: with the + /// `completion --shell ` command (the default) or, for an + /// executable without subcommands, with the `--completion ` option. + /// + /// [commandName] makes the script complete that command name instead of + /// [executableName], for a wrapper script that forwards to the executable + /// and has the same commands and options. The completion requests are + /// then sent to [executableName] directly, bypassing the wrapper. + String script( + final String executableName, { + final String? description, + final bool viaOption = false, + final String? commandName, + }) { + final name = commandName ?? executableName; + final header = scriptHeader( + executableName, + viaOption: viaOption, + commandName: commandName, + ); + // Requests go to the command as typed on the command line, unless the + // script is for a wrapper: then they go to the executable directly. + final program = name == executableName ? null : executableName; + return switch (this) { + CompletionShell.bash => bashCompletionScript( + name, + header, + program: program, + ), + CompletionShell.zsh => zshCompletionScript( + name, + header, + program: program, + ), + CompletionShell.fish => fishCompletionScript( + name, + header, + program: program, + ), + CompletionShell.powershell => powershellCompletionScript( + name, + header, + program: program, + ), + CompletionShell.carapace => carapaceCompletionSpec( + name, + header, + program: executableName, + description: description, + ), + }; + } + + /// The command line that prints the completion script for this shell: + /// ` completion --shell `, or ` --completion ` if + /// [viaOption]. With a [commandName], the `completion` command's + /// `--command ` option is added. + /// + /// An [executableName] or [commandName] that is not a plain word, such as + /// a path with a space, is quoted for this shell. + String scriptCommand( + final String executableName, { + final bool viaOption = false, + final String? commandName, + }) { + final isPowerShell = this == CompletionShell.powershell; + final word = isPowerShell ? powershellWord : shellWord; + final quotedExecutable = word(executableName); + // PowerShell runs a quoted command name only with the call operator. + final executable = isPowerShell && quotedExecutable != executableName + ? '& $quotedExecutable' + : quotedExecutable; + final command = viaOption ? '--completion' : 'completion --shell'; + final forCommand = commandName == null || viaOption + ? '' + : ' --command ${word(commandName)}'; + return '$executable $command $name$forCommand'; + } + + /// The comment lines for the header of the generated script: what + /// generated it, how to install it ([installInstructions]) and why it + /// needs to be installed only once. + String scriptHeader( + final String executableName, { + final bool viaOption = false, + final String? commandName, + }) { + final exe = executableName; + final name = commandName ?? exe; + final lines = [ + 'Generated by `${scriptCommand(exe, viaOption: viaOption, commandName: commandName)}`.', + ...installInstructions( + exe, + viaOption: viaOption, + commandName: commandName, + ).split('\n'), + '', + 'The script contains no commands or options. The completion alternatives', + if (name == exe) + 'are requested from the executable (`$exe __complete ...`), so it keeps' + else + 'are requested from $exe directly (`$exe __complete ...`), so it keeps', + 'working when the executable is updated.', + ]; + return lines.map((final l) => l.isEmpty ? '#' : '# $l').join('\n'); + } + + /// The command that installs the completion script for this shell, + /// e.g. `source <(mycli completion --shell bash)`. + /// + /// See [installLocation] for where to run or add it, + /// and [scriptCommand] for [viaOption] and [commandName]. + String installCommand( + final String executableName, { + final bool viaOption = false, + final String? commandName, + }) { + final name = commandName ?? executableName; + final script = scriptCommand( + executableName, + viaOption: viaOption, + commandName: commandName, + ); + return switch (this) { + CompletionShell.bash || CompletionShell.zsh => 'source <($script)', + CompletionShell.fish => '$script > ~/.config/fish/completions/$name.fish', + CompletionShell.powershell => '$script | Out-String | Invoke-Expression', + CompletionShell.carapace => + '$script > ~/.config/carapace/specs/$name.yaml', + }; + } + + /// The shell startup file to add [installCommand] to, + /// or null if the command is run once instead. + String? get installLocation => switch (this) { + CompletionShell.bash => '~/.bashrc', + CompletionShell.zsh => '~/.zshrc, after compinit', + CompletionShell.powershell => r'$PROFILE', + CompletionShell.fish || CompletionShell.carapace => null, + }; + + /// One-line installation instruction for this shell: + /// the [installCommand], followed by the [installLocation] as a comment. + String installInstruction( + final String executableName, { + final bool viaOption = false, + final String? commandName, + }) { + final command = installCommand( + executableName, + viaOption: viaOption, + commandName: commandName, + ); + final location = installLocation; + return location == null ? command : '$command # in $location'; + } + + /// Longer installation instructions for this shell, including + /// alternative ways to install the script where available, and how to + /// activate the installed completion ([activationInstruction]). + String installInstructions( + final String executableName, { + final bool viaOption = false, + final String? commandName, + }) { + final name = commandName ?? executableName; + final script = scriptCommand( + executableName, + viaOption: viaOption, + commandName: commandName, + ); + final command = installCommand( + executableName, + viaOption: viaOption, + commandName: commandName, + ); + final install = switch (this) { + CompletionShell.bash => + 'Add to ~/.bashrc:\n' + ' $command\n' + 'or save it once:\n' + ' $script > /etc/bash_completion.d/$name', + CompletionShell.zsh => + 'Add to ~/.zshrc (after compinit):\n' + ' $command\n' + 'or save it once to a directory in \$fpath ' + '(then remove ~/.zcompdump* to rebuild the completion cache):\n' + ' $script > "\${fpath[1]}/_$name"', + CompletionShell.fish => 'Save it once:\n $command', + CompletionShell.powershell => + 'Add to your PowerShell profile (\$PROFILE):\n $command', + CompletionShell.carapace => + 'Save it once to the Carapace specs directory ' + '(shown by `carapace --help`):\n' + ' $command\n' + '(macOS: ~/Library/Application Support/carapace/specs/$name.yaml)', + }; + return '$install\n$activationInstruction'; + } + + /// How to make a newly installed completion take effect in the current + /// shell session, e.g. by reloading the shell. + String get activationInstruction => switch (this) { + CompletionShell.bash => 'Then reload the shell:\n exec bash', + CompletionShell.zsh => 'Then reload the shell:\n exec zsh', + CompletionShell.fish => 'Fish loads it automatically, no reload needed.', + CompletionShell.powershell => 'Then reload the profile:\n . \$PROFILE', + CompletionShell.carapace => 'Then start a new shell session.', + }; +} + +/// Short installation instructions for all shells, one line per shell, +/// under a [heading]. Used in the usage of the `completion` command. +String completionInstallationOverview( + final String executableName, { + final bool viaOption = false, + final String heading = 'Installation:', +}) { + const labelWidth = 12; + return [ + heading, + for (final shell in CompletionShell.values) + ' ${'${shell.displayName}:'.padRight(labelWidth)} ' + '${shell.installInstruction(executableName, viaOption: viaOption)}', + ].join('\n'); +} + +/// A name for [executableName] that is safe to use in shell identifiers: +/// letters, digits and underscores only. +String shellIdentifier(final String executableName) { + final sanitized = executableName.replaceAll(RegExp(r'[^A-Za-z0-9_]'), '_'); + if (sanitized.isEmpty || RegExp(r'^[0-9]').hasMatch(sanitized)) { + return '_$sanitized'; + } + return sanitized; +} + +/// [value] as a single-quoted string literal for POSIX shells and Fish. +String shellQuote(final String value) { + return "'${value.replaceAll("'", r"'\''")}'"; +} + +/// [value] as one word of a command line for POSIX shells and Fish: +/// as it is if it is a plain word, otherwise quoted with [shellQuote]. +String shellWord(final String value) { + return _plainShellWord.hasMatch(value) ? value : shellQuote(value); +} + +/// Words that no supported shell expands or splits. A leading `~` is plain, +/// so that a path in the home directory stays one. +final _plainShellWord = RegExp(r'^[A-Za-z0-9_~./][A-Za-z0-9_@%+:,./-]*$'); diff --git a/packages/config/lib/src/command/completion/completion_shell_detection.dart b/packages/config/lib/src/command/completion/completion_shell_detection.dart new file mode 100644 index 00000000..965ca0d9 --- /dev/null +++ b/packages/config/lib/src/command/completion/completion_shell_detection.dart @@ -0,0 +1,113 @@ +import 'dart:io' show Platform, Process, pid; + +import 'completion_shell.dart'; + +/// Determines the shell that the user most likely runs the program from, +/// or null if there is no such [CompletionShell]. +/// +/// The alternatives are tried in this order: +/// 1. The nearest ancestor process that is a supported shell which the user +/// types in. A shell that runs a script or a command (`bash wrapper.sh`, +/// `sh -c ...`) is passed over, so that a wrapper script of the program +/// does not hide the shell it was started from. +/// 2. The user's login shell, from the `SHELL` environment variable. +/// 3. PowerShell on Windows, where the ancestor processes are not inspected. +/// +/// [CompletionShell.carapace] is a completion framework rather than a shell +/// and is never detected. +/// +/// [environment] defaults to the environment of the process, and +/// [isWindows] to the platform it runs on. [ancestorCommandLines] are the +/// command lines (the executable followed by its arguments) of the ancestor +/// processes, nearest first. By default they are read with `ps`. +CompletionShell? detectCompletionShell({ + final Map? environment, + final Iterable>? ancestorCommandLines, + final bool? isWindows, +}) { + final windows = isWindows ?? Platform.isWindows; + final commandLines = + ancestorCommandLines ?? + (windows ? const >[] : _ancestorCommandLines()); + for (final commandLine in commandLines) { + final shell = _typedInShell(commandLine); + if (shell != null) return shell; + } + + final loginShell = (environment ?? Platform.environment)['SHELL']; + final shell = loginShell == null ? null : _shellOfExecutable(loginShell); + return shell ?? (windows ? CompletionShell.powershell : null); +} + +/// The shell of [commandLine], unless it runs a script or a command: +/// then it has an operand, i.e. an argument that is not an option. +CompletionShell? _typedInShell(final List commandLine) { + if (commandLine.isEmpty) return null; + final hasOperand = commandLine + .skip(1) + .any((final argument) => !argument.startsWith('-')); + return hasOperand ? null : _shellOfExecutable(commandLine.first); +} + +/// The shell run by [executable], which may be a path, the `-zsh` form of +/// a login shell, a versioned name such as `zsh-5.9`, or a Windows `.exe`. +CompletionShell? _shellOfExecutable(final String executable) { + final name = executable.split(RegExp(r'[/\\]')).last.toLowerCase(); + final match = _shellName.firstMatch(name); + return switch (match?[1]) { + 'bash' => CompletionShell.bash, + 'zsh' => CompletionShell.zsh, + 'fish' => CompletionShell.fish, + 'pwsh' || 'powershell' => CompletionShell.powershell, + _ => null, + }; +} + +final _shellName = RegExp( + r'^-?(bash|zsh|fish|pwsh|powershell)(-[0-9.]+)?(\.exe)?$', +); + +/// More ancestors than this are not inspected. +const _maxAncestors = 16; + +/// The command lines of the ancestor processes, nearest first. +/// +/// Lazy, so that no more ancestors are inspected than needed. +Iterable> _ancestorCommandLines() sync* { + var parent = _processInfo(pid)?.parentPid; + for (var i = 0; i < _maxAncestors && parent != null && parent > 0; i++) { + final process = _processInfo(parent); + if (process == null) return; + yield process.commandLine; + parent = process.parentPid; + } +} + +/// The parent and the command line of the process [processId], +/// or null if they can't be read. +/// +/// The command line is split at whitespace, which is good enough to tell +/// options from operands. +({int parentPid, List commandLine})? _processInfo(final int processId) { + final String output; + try { + final result = Process.runSync('ps', [ + '-o', + 'ppid=,args=', + '-p', + '$processId', + ]); + if (result.exitCode != 0) return null; + output = result.stdout as String; + } on Exception { + // `ps` is missing, not permitted, or printed undecodable text. + return null; + } + + final lines = output.trim().split('\n'); + if (lines.length != 1) return null; + final fields = lines.single.trim().split(RegExp(r'\s+')); + final parentPid = int.tryParse(fields.first); + if (parentPid == null) return null; + return (parentPid: parentPid, commandLine: fields.sublist(1)); +} diff --git a/packages/config/lib/src/command/completion/option_value_completion.dart b/packages/config/lib/src/command/completion/option_value_completion.dart new file mode 100644 index 00000000..482a7489 --- /dev/null +++ b/packages/config/lib/src/command/completion/option_value_completion.dart @@ -0,0 +1,97 @@ +import 'dart:async' show Future, FutureOr; + +import '../../config/arg_parser/arg_parser.dart' show CommandDefinition; +import '../../config/arg_parser_facade.dart' show ParsedArgs; +import '../../config/completion.dart'; +import '../../config/options.dart' show OptionDefinition; +import '../command_context.dart'; +import '../command_resolver.dart'; +import '../context_provider.dart'; +import 'command_completion_context.dart'; + +/// The command line state for one option-value completion. +/// +/// [parsedArgs] is the parse of the words including a placeholder for the +/// value being completed. Configurations are resolved from [precedingWords] +/// only, so that placeholder is not a resolved option value. +class CompletionPrelude { + final String wordToComplete; + final List precedingWords; + final List commands; + final ParsedArgs parsedArgs; + final Map environment; + + const CompletionPrelude({ + required this.wordToComplete, + required this.precedingWords, + required this.commands, + required this.parsedArgs, + required this.environment, + }); +} + +/// Completes an option value after resolving the command line typed so far. +/// +/// Uses [resolver] for the configurations, then runs the middleware of those +/// commands in [CommandRunMode.completion]. [complete] is called where the +/// leaf command's `run` would run, so each middleware's `onRun` has finished +/// and its `onReturn` runs afterwards. No command `run` method is called. +class OptionValueCompletion { + final CommandResolver resolver; + + const OptionValueCompletion(this.resolver); + + Future completeOption( + final CompletionPrelude prelude, + final FutureOr Function(CompletionContext context) + complete, + ) async { + final contexts = resolver.resolveConfigurations( + prelude.precedingWords, + prelude.environment, + ContextProvider(), + runMode: CommandRunMode.completion, + ); + + CompletionResult? result; + await _runMiddlewares(contexts, (final leaf) async { + final pending = complete( + CommandCompletionContext( + leafContext: leaf, + wordToComplete: prelude.wordToComplete, + precedingWords: prelude.precedingWords, + commands: prelude.commands, + parsedArgs: prelude.parsedArgs, + environment: prelude.environment, + ), + ); + result = pending is Future ? await pending : pending; + }); + return result ?? const CompletionResult.none(); + } + + /// Runs the middleware of each command on [context]'s chain, outermost + /// first, and invokes [complete] at the leaf. + FutureOr _runMiddlewares( + final CommandContext context, + final Future Function(CommandContext leaf) + complete, + ) { + final next = context.next == null + ? (final CommandContext forwarded) async { + await complete(forwarded); + return null; + } + : (final CommandContext forwarded) { + final child = forwarded.next; + if (child == null) { + throw StateError( + '${forwarded.command.name} has no following command.', + ); + } + return _runMiddlewares(child, complete); + }; + + return context.command.runCommand(context, runNextCommand: next); + } +} diff --git a/packages/config/lib/src/command/completion/scripts/bash_completion_script.dart b/packages/config/lib/src/command/completion/scripts/bash_completion_script.dart new file mode 100644 index 00000000..16e59747 --- /dev/null +++ b/packages/config/lib/src/command/completion/scripts/bash_completion_script.dart @@ -0,0 +1,205 @@ +import '../completion_shell.dart' show shellIdentifier, shellQuote, shellWord; + +/// Generates the Bash completion script for the command [name]. +/// +/// The completion requests are sent to the command as typed, or to +/// [program] if given (when [name] is a wrapper of it). +/// +/// Works with Bash 4.4+ fully, and degrades gracefully on Bash 3.2 (macOS): +/// there `compopt` is unavailable so the no-space and no-sort directives +/// are ignored. The bash-completion package is used when loaded +/// (`_init_completion`, `_filedir`) but is not required. +String bashCompletionScript( + final String name, + final String header, { + final String? program, +}) { + final fn = '__${shellIdentifier(name)}'; + return _template + .replaceAll('__HEADER__', header) + .replaceAll( + '__PROGRAM__', + program == null ? r'${words[0]}' : shellQuote(program), + ) + .replaceAll('__FN__', fn) + // The command name as an argument of `complete`: one word. + .replaceAll('__EXE_WORD__', shellWord(name)) + .replaceAll('__EXE__', name); +} + +const _template = r''' +# bash completion for __EXE__ -*- shell-script -*- +# +__HEADER__ + +# Minimal replacement for _init_completion of the bash-completion package: +# sets words, cword and cur without treating '=' and ':' as word breaks. +__FN___init_completion() +{ + local i word prev='' + words=() + cword=0 + for ((i = 0; i < ${#COMP_WORDS[@]}; i++)); do + word=${COMP_WORDS[i]} + if ((i > 0)) && [[ $word == [=:] || $prev == [=:] ]]; then + words[${#words[@]}-1]+=$word + else + words+=("$word") + fi + ((i == COMP_CWORD)) && cword=$((${#words[@]} - 1)) + prev=$word + done + cur=${words[cword]} +} + +# The filename after a leading file-redirection operator, if $1 is one. +# Prints nothing and returns 0 for a bare operator (`>`, `2>`, `>>`). +# Returns 1 for ordinary words and for here-documents (`<<`, `<<<`). +# Kept in agreement with the redirection handling in the completion engine. +__FN___redirect_rest() +{ + case $1 in + '<<<'*|'<<'*) return 1 ;; + esac + local re='^((\{[A-Za-z_][A-Za-z0-9_]*\})|[0-9]*|&)?(&>>|>>|>&|>\||<>|<&|&>|[<>])(.*)$' + [[ $1 =~ $re ]] || return 1 + printf '%s' "${BASH_REMATCH[4]}" +} + +# Appends the lines that compgen prints for the given arguments to COMPREPLY +# as they are: a file name such as `f[1].txt` is not expanded as a pattern. +__FN___compgen() +{ + local line + while IFS= read -r line; do + [[ -n $line ]] && COMPREPLY+=("$line") + done <<<"$(compgen "$@")" +} + +# File name completion: -d for directories only, or a pattern of file name +# extensions such as 'yaml|yml', or nothing for all files. +__FN___filedir() +{ + # The cursor word may be the operator itself (`>`) or an operator + # glued to a filename (`>file`). Complete the filename part only. + local rest + if rest=$(__FN___redirect_rest "$cur"); then + cur=$rest + fi + local first=${#COMPREPLY[@]} i + if declare -F _filedir >/dev/null 2>&1; then + if [[ $1 == -d || -z $1 ]]; then + _filedir "$@" + else + _filedir "@($1)" + fi + else + type compopt &>/dev/null && compopt -o filenames 2>/dev/null + if [[ $1 == -d ]]; then + __FN___compgen -d -- "$cur" + elif [[ -n $1 ]]; then + __FN___compgen -d -- "$cur" + local ext + local -a exts + IFS='|' read -r -a exts <<<"$1" + for ext in "${exts[@]}"; do + __FN___compgen -f -X "!*.$ext" -- "$cur" + done + else + __FN___compgen -f -- "$cur" + fi + fi + # The file names replace a whole `--option=value` word when '=' is not + # a word break (see valuePrefix in the caller): keep the option. + if [[ -n $valuePrefix ]]; then + for ((i = first; i < ${#COMPREPLY[@]}; i++)); do + COMPREPLY[i]=$valuePrefix${COMPREPLY[i]} + done + fi +} + +__FN___complete() +{ + local cur prev words cword + COMPREPLY=() + if declare -F _init_completion >/dev/null 2>&1; then + _init_completion -n =: || return + else + __FN___init_completion || return + fi + + # The completion request: the words before the cursor word, then the + # (possibly empty) cursor word. + local cmd=__PROGRAM__ out + [[ $cmd == "~"* ]] && cmd=${HOME}${cmd#"~"} + out=$("$cmd" __complete "${words[@]:1:cword-1}" "$cur" 2>/dev/null) + + # The last line of the response is the directive, e.g. ':4'. + local directive=0 lastLine=${out##*$'\n'} + if [[ $lastLine == :* ]]; then + directive=${lastLine#:} + if [[ $out == "$lastLine" ]]; then + out='' + else + out=${out%$'\n'*} + fi + fi + [[ $directive =~ ^[0-9]+$ ]] || directive=0 + + local directiveError=1 directiveNoSpace=2 directiveNoFiles=4 + local directiveFileExt=8 directiveDirs=16 directiveKeepOrder=32 + + ((directive & directiveError)) && return + + # When completing `--option=value`, the response holds the bare values. + # Bash treats '=' as a word break (by default) and replaces only the part + # after it, so complete that part only. + local valuePrefix='' + if [[ $cur == -*=* ]]; then + [[ $COMP_WORDBREAKS != *=* ]] && valuePrefix=${cur%%=*}= + cur=${cur#*=} + fi + + if type compopt &>/dev/null; then + ((directive & directiveNoSpace)) && compopt -o nospace + ((directive & directiveKeepOrder)) && compopt -o nosort 2>/dev/null + fi + + local -a comps=() + local line + while IFS= read -r line; do + [[ -n $line ]] && comps+=("${line%%$'\t'*}") + done <<<"$out" + + if ((directive & directiveFileExt)); then + # The completions are the file extensions: join them to a pattern. + local pattern + pattern=$(IFS='|'; printf '%s' "${comps[*]}") + __FN___filedir "$pattern" + elif ((directive & directiveDirs)); then + __FN___filedir -d + else + local comp + for comp in "${comps[@]}"; do + [[ $comp == "$cur"* ]] && COMPREPLY+=("$valuePrefix$comp") + done + if ((${#COMPREPLY[@]} == 0)); then + ((directive & directiveNoFiles)) || __FN___filedir + elif ((${#COMPREPLY[@]} == 1)); then + # A single value is inserted as is: escape special characters. + COMPREPLY[0]=$(printf '%q' "${COMPREPLY[0]}") + fi + fi + + # Bash replaces only the part of the word after the last ':' when ':' + # is a word break, so remove the part up to it from the values. + if [[ $cur == *:* && $COMP_WORDBREAKS == *:* ]]; then + local prefix=$valuePrefix${cur%"${cur##*:}"} i + for i in "${!COMPREPLY[@]}"; do + COMPREPLY[i]=${COMPREPLY[i]#"$prefix"} + done + fi +} + +complete -F __FN___complete __EXE_WORD__ +'''; diff --git a/packages/config/lib/src/command/completion/scripts/carapace_completion_spec.dart b/packages/config/lib/src/command/completion/scripts/carapace_completion_spec.dart new file mode 100644 index 00000000..e95f69df --- /dev/null +++ b/packages/config/lib/src/command/completion/scripts/carapace_completion_spec.dart @@ -0,0 +1,38 @@ +/// Generates a Carapace spec for the command [name]. +/// +/// The spec bridges to the `__complete` request of [program] (the +/// executable, which [name] is or wraps) via Carapace's Cobra bridge (the +/// request protocol is the same), so it needs to be installed only once in +/// the Carapace specs directory. +/// See https://carapace-sh.github.io/carapace-bin/spec.html. +String carapaceCompletionSpec( + final String name, + final String header, { + required final String program, + final String? description, +}) { + final summary = description?.trim().split('\n').first.trim(); + final buffer = StringBuffer() + ..writeln('# carapace spec for $name') + ..writeln('#') + ..writeln(header) + ..writeln('name: ${_yamlString(name)}'); + if (summary != null && summary.isNotEmpty) { + buffer.writeln('description: ${_yamlString(summary)}'); + } + buffer + ..writeln('parsing: disabled') + ..writeln('completion:') + ..writeln(' positionalany:') + ..writeln(' - ${_yamlString('\$carapace.bridge.Cobra([$program])')}'); + return buffer.toString(); +} + +/// A double-quoted YAML scalar. +String _yamlString(final String value) { + final escaped = value + .replaceAll(r'\', r'\\') + .replaceAll('"', r'\"') + .replaceAll('\n', r'\n'); + return '"$escaped"'; +} diff --git a/packages/config/lib/src/command/completion/scripts/fish_completion_script.dart b/packages/config/lib/src/command/completion/scripts/fish_completion_script.dart new file mode 100644 index 00000000..5b8e0191 --- /dev/null +++ b/packages/config/lib/src/command/completion/scripts/fish_completion_script.dart @@ -0,0 +1,89 @@ +import '../completion_shell.dart' show shellIdentifier, shellQuote; + +/// Generates the Fish completion script for the command [name]. +/// +/// The completion requests are sent to the command as typed, or to +/// [program] if given (when [name] is a wrapper of it). +String fishCompletionScript( + final String name, + final String header, { + final String? program, +}) { + final fn = '__${shellIdentifier(name)}'; + return _template + .replaceAll('__HEADER__', header) + .replaceAll( + '__PROGRAM__', + program == null ? r'$words[1]' : shellQuote(program), + ) + .replaceAll('__FN__', fn) + .replaceAll('__EXE__', name); +} + +const _template = r''' +# fish completion for __EXE__ -*- shell-script -*- +# +__HEADER__ + +# Tests whether bit $argv[2] is set in directive $argv[1]. +function __FN___directive_has + test (math "floor($argv[1] / $argv[2]) % 2") -eq 1 +end + +function __FN___complete + # The words before the cursor word, and the (possibly empty) cursor word. + set -l words (commandline -opc) + set -l current (commandline -ct) + test (count $current) -eq 0; and set current '' + + set -l cmd __PROGRAM__ + set -l out ($cmd __complete $words[2..-1] "$current" 2>/dev/null) + + # The last line of the response is the directive, e.g. ':4'. + set -l directive 0 + if test (count $out) -gt 0; and string match -qr '^:[0-9]+$' -- "$out[-1]" + set directive (string sub -s 2 -- "$out[-1]") + set -e out[-1] + end + + if __FN___directive_has $directive 1 + return 1 + end + + # When completing `--option=value`, the response holds the bare values + # which are inserted after the option prefix. + set -l prefix '' + set -l value "$current" + if string match -qr -- '^-[^=]*=' "$current" + set prefix (string match -r -- '^-[^=]*=' "$current") + set value (string replace -r -- '^-[^=]*=' '' "$current") + end + + if __FN___directive_has $directive 8 + # Files with one of the given extensions, and directories. + set -l exts (string join '|' -- (string escape --style=regex -- $out)) + for path in (__fish_complete_path "$value") + set -l name (string split -m1 \t -- $path)[1] + if string match -qr -- '/$' "$name"; or string match -qr -- "\\.($exts)\$" "$name" + printf '%s%s\n' "$prefix" "$path" + end + end + else if __FN___directive_has $directive 16 + for path in (__fish_complete_directories "$value") + printf '%s%s\n' "$prefix" "$path" + end + else + for comp in $out + printf '%s%s\n' "$prefix" "$comp" + end + if test (count $out) -eq 0; and not __FN___directive_has $directive 4 + for path in (__fish_complete_path "$value") + printf '%s%s\n' "$prefix" "$path" + end + end + end +end + +complete -c __EXE__ -e +complete -c __EXE__ -f -a '(__FN___complete)' +'''; diff --git a/packages/config/lib/src/command/completion/scripts/powershell_completion_script.dart b/packages/config/lib/src/command/completion/scripts/powershell_completion_script.dart new file mode 100644 index 00000000..d27c2977 --- /dev/null +++ b/packages/config/lib/src/command/completion/scripts/powershell_completion_script.dart @@ -0,0 +1,185 @@ +import '../completion_shell.dart' show shellIdentifier; + +/// Generates the PowerShell completion script for the command [name]. +/// +/// The completion requests are sent to the command as typed, or to +/// [program] if given (when [name] is a wrapper of it). +/// +/// Requires PowerShell 5.1+. +String powershellCompletionScript( + final String name, + final String header, { + final String? program, +}) { + final fn = '__${shellIdentifier(name)}'; + return _template + .replaceAll('__HEADER__', header) + .replaceAll( + '__PROGRAM__', + program == null ? r'$words[0]' : powershellQuote(program), + ) + .replaceAll('__FN__', fn) + .replaceAll('__EXE__', name); +} + +/// [value] as a single-quoted PowerShell string literal. +String powershellQuote(final String value) => + "'${value.replaceAll("'", "''")}'"; + +/// [value] as one word of a PowerShell command line: as it is if it is +/// a plain word, otherwise quoted with [powershellQuote]. +String powershellWord(final String value) { + return _plainPowershellWord.hasMatch(value) ? value : powershellQuote(value); +} + +final _plainPowershellWord = RegExp(r'^[A-Za-z0-9_~./\\][A-Za-z0-9_:./\\-]*$'); + +const _template = r''' +# powershell completion for __EXE__ -*- shell-script -*- +# +__HEADER__ + +[scriptblock]$__FN___completer = { + param($WordToComplete, $CommandAst, $CursorPosition) + + $directiveError = 1 + $directiveNoSpace = 2 + $directiveNoFiles = 4 + $directiveFileExt = 8 + $directiveDirs = 16 + $directiveKeepOrder = 32 + + # The words before the cursor word, and the (possibly empty) cursor word. + # The cursor may have been moved back: complete up to the cursor word. + $words = @() + $current = '' + foreach ($element in $CommandAst.CommandElements) { + $extent = $element.Extent + if ($extent.StartOffset -ge $CursorPosition) { break } + if ($element -is [System.Management.Automation.Language.StringConstantExpressionAst]) { + $text = $element.Value + } else { + $text = $extent.Text + } + if ($extent.EndOffset -lt $CursorPosition) { + $words += $text + continue + } + if ($extent.EndOffset -gt $CursorPosition) { + $text = $extent.Text.Substring(0, $CursorPosition - $extent.StartOffset) + } + $current = $text + break + } + if ($words.Count -eq 0) { return } + $program = __PROGRAM__ + $arguments = @($words | Select-Object -Skip 1) + + # Before PowerShell 7.3 (or in legacy argument passing mode) an empty + # string argument is dropped unless passed as "". + $requestWord = $current + if ($current -eq '') { + $legacy = ($PSVersionTable.PSVersion -lt [version]'7.3.0') -or + ($PSNativeCommandArgumentPassing -eq 'Legacy') + if ($legacy) { $requestWord = '""' } + } + + $out = @(& $program __complete @arguments $requestWord 2>$null) + + # The last line of the response is the directive, e.g. ':4'. + $directive = 0 + if ($out.Count -gt 0 -and $out[-1] -match '^:(\d+)$') { + $directive = [int]$Matches[1] + $out = @($out | Select-Object -SkipLast 1) + } + + # PowerShell completes paths itself when a completer returns nothing. + # Returning a single space prevents that (an empty string is rejected + # by CompletionResult). + $nothing = ' ' + + if (($directive -band $directiveError) -ne 0) { $nothing; return } + + # When completing `--option=value`, the response holds the bare values + # which are inserted after the option prefix. + $prefix = '' + $value = $current + if ($current -match '^(-[^=]*=)(.*)$') { + $prefix = $Matches[1] + $value = $Matches[2] + } + + $space = ' ' + if (($directive -band $directiveNoSpace) -ne 0) { $space = '' } + try { + $mode = (Get-PSReadLineKeyHandler -ErrorAction Stop | Where-Object { $_.Key -eq 'Tab' }).Function + } catch { + $mode = '' + } + if ($mode -ne 'Complete' -and $mode -ne 'MenuComplete') { $space = '' } + + function New-Result($text, $listText, $type, $toolTip) { + if (-not $toolTip) { $toolTip = $listText } + [System.Management.Automation.CompletionResult]::new($text, $listText, $type, $toolTip) + } + + # The characters to escape in the inserted completion text. + $escape = '\s|#|@|\$|;|,|''|\{|\}|\(|\)|"|`|\||<|>|&' + + # Path completion for directories, or files with the given extensions. + # The typed path is literal: its directory is listed and the names in it + # are matched by prefix, so that no wildcard in it (`[1]`) is expanded. + function Complete-Paths($dirsOnly, $extensions) { + $index = $value.LastIndexOfAny([char[]]@('/', '\')) + $dir = $value.Substring(0, $index + 1) + $leaf = $value.Substring($index + 1) + $parent = if ($dir) { $dir } else { '.' } + $results = @(Get-ChildItem -LiteralPath $parent -Force -ErrorAction SilentlyContinue | ForEach-Object { + $name = $_.Name + if (-not $name.StartsWith($leaf, [System.StringComparison]::OrdinalIgnoreCase)) { return } + $isDir = $_.PSIsContainer + if ($dirsOnly -and -not $isDir) { return } + if ($extensions -and -not $isDir -and ($extensions -notcontains $_.Extension.TrimStart('.'))) { return } + $name = $_.Name + $path = if ($dir) { Join-Path $dir $name } else { $name } + if ($isDir) { $path += [System.IO.Path]::DirectorySeparatorChar } + $type = if ($isDir) { 'ProviderContainer' } else { 'ProviderItem' } + New-Result ($prefix + ($path -replace $escape, '`$&')) $name $type $path + }) + if ($results.Count -eq 0) { $nothing } else { $results } + } + + if (($directive -band $directiveFileExt) -ne 0) { + Complete-Paths $false @($out) + return + } + if (($directive -band $directiveDirs) -ne 0) { + Complete-Paths $true $null + return + } + + $results = @($out | ForEach-Object { + $name, $description = $_.Split("`t", 2) + if ($name -like "$value*") { + [PSCustomObject]@{ Name = $name; Description = $description } + } + }) + if (($directive -band $directiveKeepOrder) -eq 0) { + $results = @($results | Sort-Object -Property Name) + } + + if ($results.Count -eq 0) { + # Nothing matched: PowerShell completes paths, unless disabled. + if (($directive -band $directiveNoFiles) -ne 0) { $nothing } + return + } + + foreach ($result in $results) { + $text = $prefix + ($result.Name -replace $escape, '`$&') + if ($results.Count -eq 1 -or $mode -eq 'MenuComplete') { $text += $space } + New-Result $text $result.Name 'ParameterValue' $result.Description + } +} + +Register-ArgumentCompleter -Native -CommandName '__EXE__' -ScriptBlock $__FN___completer +'''; diff --git a/packages/config/lib/src/command/completion/scripts/zsh_completion_script.dart b/packages/config/lib/src/command/completion/scripts/zsh_completion_script.dart new file mode 100644 index 00000000..59f384b9 --- /dev/null +++ b/packages/config/lib/src/command/completion/scripts/zsh_completion_script.dart @@ -0,0 +1,110 @@ +import '../completion_shell.dart' show shellQuote; + +/// Generates the Zsh completion script for the command [name]. +/// +/// The completion requests are sent to the command as typed, or to +/// [program] if given (when [name] is a wrapper of it). +/// +/// The script can be sourced (`source <(exe completion --shell zsh)`) or saved as +/// `_exe` in a directory on `$fpath` for autoloading. +String zshCompletionScript( + final String name, + final String header, { + final String? program, +}) { + return _template + .replaceAll('__HEADER__', header) + .replaceAll( + '__PROGRAM__', + program == null ? r'${(Q)words[1]}' : shellQuote(program), + ) + .replaceAll('__EXE__', name); +} + +const _template = r''' +#compdef __EXE__ +compdef ___EXE__ __EXE__ + +# zsh completion for __EXE__ -*- shell-script -*- +# +__HEADER__ + +___EXE__() +{ + local directiveError=1 directiveNoSpace=2 directiveNoFiles=4 + local directiveFileExt=8 directiveDirs=16 directiveKeepOrder=32 + + local cur=${words[CURRENT]} cmd out lastLine directive=0 line comp + local -a completions compaddOpts describeOpts + + # The cursor may have been moved back: complete up to the cursor word. + words=("${(@)words[1,CURRENT]}") + + # When completing `--option=value`, the response holds the bare values + # which are inserted after the option prefix. + if [[ $cur == -*=* ]]; then + compaddOpts+=(-P "${cur%%=*}=") + fi + + cmd=__PROGRAM__ + [[ $cmd == '~'* ]] && cmd=${HOME}${cmd#'~'} + + # The completion request: the words before the cursor word, then the + # (possibly empty) cursor word. + out=$("$cmd" __complete "${(@Q)words[2,-1]}" 2>/dev/null) + + # The last line of the response is the directive, e.g. ':4'. + lastLine=${out##*$'\n'} + if [[ $lastLine == :* ]]; then + directive=${lastLine#:} + if [[ $out == "$lastLine" ]]; then + out='' + else + out=${out%$'\n'*} + fi + fi + [[ $directive == <-> ]] || directive=0 + + (( directive & directiveError )) && return 1 + (( directive & directiveNoSpace )) && compaddOpts+=(-S '') + (( directive & directiveKeepOrder )) && describeOpts+=(-V) + + for line in ${(f)out}; do + [[ -z $line ]] && continue + # valuedescription becomes value:description for _describe, + # which removes one level of backslashes from the value: escape + # the backslashes in it, then its ':'. + comp=${line%%$'\t'*} + comp=${comp//\\/\\\\} + comp=${comp//:/\\:} + if [[ $line == *$'\t'* ]]; then + comp="$comp:${line#*$'\t'}" + fi + completions+=("$comp") + done + + if (( directive & directiveFileExt )); then + # The completions are the file extensions: one glob matching any. + _files -g "*.(${(j:|:)completions})" "${compaddOpts[@]}" + elif (( directive & directiveDirs )); then + _files -/ "${compaddOpts[@]}" + else + if (( ${#completions} )) && + _describe "${describeOpts[@]}" -t values 'values' completions \ + "${compaddOpts[@]}"; then + return 0 + fi + # Nothing matched: file completion unless disabled. Returning 1 lets + # zsh try other matchers, such as matching in the middle of words. + (( directive & directiveNoFiles )) && return 1 + _files "${compaddOpts[@]}" + fi +} + +# Run the completion when autoloaded from $fpath by compinit (the file body +# is then the function body), but not when sourced or eval-ed. +if [[ $funcstack[1] == ___EXE__ && ${zsh_eval_context[-1]} == loadautofunc ]] +then + ___EXE__ +fi +'''; diff --git a/packages/config/lib/src/command/context_provider.dart b/packages/config/lib/src/command/context_provider.dart new file mode 100644 index 00000000..34452c94 --- /dev/null +++ b/packages/config/lib/src/command/context_provider.dart @@ -0,0 +1,69 @@ +/// A type-keyed bag of values shared for one command run. +/// +/// The type argument of [fetch], [maybeFetch], [has], [store], and [remove] +/// is the slot. `store(StdOutLogger())` is retrieved with +/// `fetch()`, including when the value's runtime type is a subtype. +abstract interface class ContextProvider { + factory ContextProvider([final Map? values]) = + _MapContextProvider; + + /// Returns the value stored under `T`. + /// + /// Throws [ContextValueNotFound] when the slot is empty or holds a value + /// that is not a `T`. + T fetch(); + + /// Returns the value stored under `T`, or null when [fetch] would throw. + T? maybeFetch(); + + /// Whether a value of type `T` is stored. + bool has(); + + /// Stores [value] under `T`, replacing any previous value in that slot. + void store(final T value); + + /// Removes the value stored under `T`, if any. + void remove(); +} + +/// Thrown when [ContextProvider.fetch] finds no value of the requested type. +class ContextValueNotFound implements Exception { + /// The type argument passed to [ContextProvider.fetch]. + final Type type; + + ContextValueNotFound(this.type); + + @override + String toString() => '$runtimeType: No $type value is stored in the context.'; +} + +class _MapContextProvider implements ContextProvider { + final Map _values; + + _MapContextProvider([final Map? values]) + : _values = values == null + ? {} + : Map.of(values); + + @override + T fetch() { + final value = maybeFetch(); + if (value == null) throw ContextValueNotFound(T); + return value; + } + + @override + T? maybeFetch() { + final value = _values[T]; + return value is T ? value : null; + } + + @override + bool has() => maybeFetch() != null; + + @override + void store(final T value) => _values[T] = value; + + @override + void remove() => _values.remove(T); +} diff --git a/packages/config/lib/src/command/help_command.dart b/packages/config/lib/src/command/help_command.dart new file mode 100644 index 00000000..1b0ea9e6 --- /dev/null +++ b/packages/config/lib/src/command/help_command.dart @@ -0,0 +1,141 @@ +import 'dart:async' show FutureOr; + +import 'package:collection/collection.dart'; + +import '../config/config.dart' + show OptionDefinition, CommandUsageDefinition, CommandAliasesDefinition; +import 'abstract_command.dart' show AbstractCommand; +import 'command.dart' show Command; +import 'command_context.dart' show CommandContext; + +/// Standard built-in help command. +/// +/// This command is hidden (not shown in the help output) but automatically +/// added as subcommand to all commands that have subcommands. +/// This enables the syntax `help build` for all commands in the command tree. +/// +/// When specified last on the command line it will show the help for the prior +/// command, e.g. `build help`. By extending this class and overriding [run] +/// this help output can be customized. Some command systems provide a more +/// extensive user guide when help is specified last in this way. +class HelpCommand extends Command { + @override + final String name = 'help'; + + HelpCommand() + : super( + usageDefinition: const CommandUsageDefinition( + description: 'Show help for a command.', + hidden: true, + invocation: 'help []', + ), + aliasesDefinition: const CommandAliasesDefinition(), + ); + + /// Help is shown for partial command lines, e.g. when the preceding + /// command is missing mandatory options or a subcommand. + @override + bool get acceptsPartialCommandLine => true; + + @override + bool get canRunAsLeafCommand => true; + + /// The sibling commands of this help command, i.e. the commands it can + /// show help for (including itself, i.e. `help help`), wrapped so that + /// `help ` shows usage. + @override + List> get subcommands => [ + ..._helpSubcommands( + this, + parent.subcommands.whereNot((final command) => command.name == name), + ), + _HelpSubcommand(parent: this, subcommand: this), + ]; + + @override + FutureOr run(final CommandContext context) { + // If run is called, this is the last command on the command line - + // show the help for the previous command. + final parent = context.prev; + if (parent == null) throw StateError('A parent command is expected'); + printCommandUsage(parent); + return null; + } +} + +/// Wraps the visible [commands] in [_HelpSubcommand]s. +List> _helpSubcommands( + final AbstractCommand parent, + final Iterable> commands, +) { + return commands + .whereNot((final command) => command.usageDefinition.hidden) + .map( + (final command) => _HelpSubcommand( + parent: parent, + subcommand: command, + ), + ) + .toList(); +} + +/// Wrapper that represents each actual subcommand but produces its usage help +/// instead of running it. By representing each subcommand to the parser, +/// it will correctly validate the command line with a 'help' command. +class _HelpSubcommand extends Command { + @override + String get name => _subcommand.name; + + @override + CommandUsageDefinition get usageDefinition => _subcommand.usageDefinition; + + @override + CommandAliasesDefinition get aliasesDefinition => + _subcommand.aliasesDefinition; + + @override + List get persistentOptions => _subcommand.persistentOptions; + + @override + List get options => _subcommand.options; + + /// The subcommands are wrapped as well, so that `help a b` shows the help + /// for the nested command `b` instead of running it. + @override + List> get subcommands => + _helpSubcommands(this, _subcommand.subcommands); + + /// The usage of the represented command, as shown by its `--help` option. + @override + String get usage => _subcommand.usage; + + final Command _subcommand; + + _HelpSubcommand({ + required final AbstractCommand parent, + required final Command subcommand, + }) : _subcommand = subcommand { + this.parent = parent; + } + + /// Help is shown for a command whether or not it requires a subcommand. + @override + bool get canRunAsLeafCommand => true; + + /// The represented command's options are mirrored for parsing but need + /// not be complete or valid to show its usage. + @override + bool get acceptsPartialCommandLine => true; + + @override + FutureOr run(final CommandContext context) { + printCommandUsage(context); + return null; + } +} + +/// Prints the usage of the contest's command to the usage output, +/// via the root command's [UsageOutputHandler]. +void printCommandUsage(final CommandContext context) { + context.command.runner.usageOutput.printUsage(context.command); +} diff --git a/packages/config/lib/src/command/output_sinks.dart b/packages/config/lib/src/command/output_sinks.dart new file mode 100644 index 00000000..d589ba33 --- /dev/null +++ b/packages/config/lib/src/command/output_sinks.dart @@ -0,0 +1,20 @@ +import 'dart:io' show stdout, stderr; + +/// Output sinks for [CommandRunner]. +class OutputSinks { + final StringSink? _out; + final StringSink? _err; + + /// The sink to write normal output to, e.g. usage guidance like --help output. + StringSink get out => _out ?? stdout; + + /// The sink to write diagnostics and error messages to, + /// e.g. when [UsageException] has been raised. + StringSink get err => _err ?? stderr; + + const OutputSinks({ + final StringSink? out, + final StringSink? err, + }) : _out = out, + _err = err; +} diff --git a/packages/config/lib/src/command/usage/command_usage.dart b/packages/config/lib/src/command/usage/command_usage.dart new file mode 100644 index 00000000..9c7e73c6 --- /dev/null +++ b/packages/config/lib/src/command/usage/command_usage.dart @@ -0,0 +1,403 @@ +import 'dart:collection' show SplayTreeMap; +import 'dart:math' as math; + +import '../../config/config.dart' show OptionDefinition; +import '../abstract_command.dart' show AbstractCommand; +import 'invocation_synopsis.dart' show commandInvocationSynopsis; +import 'options_usage.dart'; + +const _usagePrefix = 'Usage: '; + +String _runnerInvocation(final AbstractCommand command) { + final invocation = '${command.name} [global-options]'; + if (command.subcommands.isEmpty) return invocation; + return '$invocation [arguments]'; +} + +/// The usage invocation line. +/// +/// A custom invocation replaces this command's own name and argument +/// synopsis, and is appended to the parent command chain. +/// `executable branch leaf ` becomes `executable branch` plus that +/// custom string. +String _invocation(final AbstractCommand command, final bool isSubcommand) { + final custom = command.usageDefinition.invocation; + if (custom == null) { + return isSubcommand + ? commandInvocationSynopsis(command) + : _runnerInvocation(command); + } + + final parents = []; + var current = command; + while (current.hasParent) { + current = current.parent; + parents.add(current.name); + } + if (parents.isEmpty) return custom; + return '${parents.reversed.join(' ')} $custom'; +} + +/// Generates a string showing usage information for a command. +String commandUsage( + final AbstractCommand command, + final bool isSubcommand, + final int? lineLength, +) { + final headline = _wrapText( + command.usageDefinition.description, + length: lineLength, + hangingIndent: null, + ); + + final invocation = _invocation(command, isSubcommand); + + final buffer = StringBuffer() + ..writeln(headline) + ..writeln() + ..writeln( + _usagePrefix + + _wrapText( + invocation, + length: lineLength, + hangingIndent: _usagePrefix.length, + ), + ) + ..writeln(); + + final persistentOptions = _visibleOptions( + command.allOptions(onlyPersistent: true), + ); + if (persistentOptions.isNotEmpty) { + buffer.writeln( + getOptionsUsage( + persistentOptions, + isSubcommand: isSubcommand, + isPersistentOptions: true, + lineLength: lineLength, + ), + ); + } + + final options = _visibleOptions(command.options); + if (options.isNotEmpty) { + buffer.writeln( + getOptionsUsage( + options, + isSubcommand: isSubcommand, + isPersistentOptions: false, + lineLength: lineLength, + ), + ); + } + + if (command.subcommands.isNotEmpty) { + buffer + ..writeln( + getCommandUsage( + command.subcommands, + isSubcommand: isSubcommand, + lineLength: lineLength, + ), + ) + ..writeln(); + + if (!isSubcommand) { + buffer.writeln( + _wrapText( + 'Run "${command.name} help " for more information about a command.', + length: lineLength, + hangingIndent: null, + ), + ); + } + } + + if (isSubcommand) { + buffer.writeln( + _wrapText( + 'Run "${command.runner.name} help" to see global options.', + length: lineLength, + hangingIndent: null, + ), + ); + } + + if (command.usageDefinition.usageFooter != null) { + buffer.writeln(_makeFooter(command, lineLength)); + } + return buffer.toString(); +} + +/// The [options] that are listed in the usage, i.e. those not hidden. +List _visibleOptions( + final Iterable options, +) => options.where((final option) => !option.option.hide).toList(); + +String getOptionsUsage( + final List options, { + final bool isSubcommand = false, + final bool isPersistentOptions = false, + final int? lineLength, +}) { + final optionsHeading = isSubcommand + ? isPersistentOptions + ? 'Persistent options:' + : 'Options:' + : isPersistentOptions + ? 'Global options:' + : 'Options:'; + + final optionsUsage = OptionsUsageGenerator( + options, + lineLength: lineLength, + addGroupSeparators: true, + ).generate(); + + final buffer = StringBuffer() + ..writeln( + _wrapText( + optionsHeading, + length: lineLength, + hangingIndent: null, + ), + ) + ..write(optionsUsage); + + return buffer.toString(); +} + +/// Returns a string representation of [commands] fit for use in a usage string. +/// +/// [isSubcommand] indicates whether the commands should be called "commands" or +/// "subcommands". +String getCommandUsage( + final List cmds, { + final bool isSubcommand = false, + final int? lineLength, +}) { + final commands = { + for (final cmd in cmds) cmd.name: cmd, + }; + var names = commands.keys; + + // Filter out hidden ones, unless they are all hidden. + final visible = names.where( + (final name) => !commands[name]!.usageDefinition.hidden, + ); + if (visible.isNotEmpty) names = visible; + + // Show the commands alphabetically. + names = names.toList()..sort(); + + // Group the commands by category. + final commandsByCategory = SplayTreeMap>(); + for (final name in names) { + final category = commands[name]!.usageDefinition.category ?? ''; + commandsByCategory.putIfAbsent(category, () => []).add(commands[name]!); + } + final categories = commandsByCategory.keys.toList(); + + final length = names.map((final name) => name.length).reduce(math.max); + + final buffer = StringBuffer( + 'Available ${isSubcommand ? "sub" : ""}commands:', + ); + final columnStart = length + 5; + for (final category in categories) { + if (category != '') { + buffer.writeln(); + buffer.writeln(); + buffer.write(category); + } + for (final command in commandsByCategory[category]!) { + final lines = wrapTextAsLines( + _summary(command), + start: columnStart, + length: lineLength, + ); + buffer.writeln(); + buffer.write(' ${_padRight(command.name, length)} ${lines.first}'); + + for (final line in lines.skip(1)) { + buffer.writeln(); + buffer.write(' ' * columnStart); + buffer.write(line); + } + } + } + + return buffer.toString(); +} + +String _makeFooter(final AbstractCommand command, final int? lineLength) { + final formattedFooter = _wrapText( + command.usageDefinition.usageFooter!, + length: lineLength, + hangingIndent: null, + ); + return '\n$formattedFooter'; +} + +String _summary(final AbstractCommand command) => + command.usageDefinition.summary ?? + command.usageDefinition.description.split('\n').first; + +/// Pads [source] to [length] by adding spaces at the end. +String _padRight(final String source, final int length) => + source + ' ' * (length - source.length); + +/// Wraps a block of text into lines no longer than [length]. +/// +/// Tries to split at whitespace, but if that's not good enough to keep it +/// under the limit, then it splits in the middle of a word. +/// +/// Preserves indentation (leading whitespace) for each line (delimited by '\n') +/// in the input, and indents wrapped lines the same amount. +/// +/// If [hangingIndent] is supplied, then that many spaces are added to each +/// line, except for the first line, which leaves room for a prefix of that +/// width instead. This is useful for flowing text with a heading prefix +/// (e.g. "Usage: "): +/// +/// ```dart +/// var prefix = "Usage: "; +/// print( +/// prefix + wrapText(invocation, hangingIndent: prefix.length, length: 40), +/// ); +/// ``` +/// +/// yields: +/// ``` +/// Usage: app main_command +/// [arguments] +/// ``` +/// +/// If [length] is not specified, then no wrapping occurs, and the original +/// [text] is returned unchanged. +String _wrapText(final String text, {final int? length, int? hangingIndent}) { + if (length == null) return text; + hangingIndent ??= 0; + final splitText = text.split('\n'); + final result = []; + for (final (index, line) in splitText.indexed) { + var trimmedText = line.trimLeft(); + final leadingWhitespace = line.substring( + 0, + line.length - trimmedText.length, + ); + List notIndented; + if (hangingIndent != 0) { + // When we have a hanging indent, we want to wrap the first line at one + // width, and the rest at another (offset by hangingIndent), so we wrap + // them twice and recombine. The caller writes a prefix as wide as the + // hanging indent before the first line of the text, which is as narrow + // as the rest. + final prefixWidth = index == 0 ? hangingIndent : 0; + final firstLineWrap = wrapTextAsLines( + trimmedText, + length: length - leadingWhitespace.length - prefixWidth, + ); + notIndented = [firstLineWrap.removeAt(0)]; + trimmedText = trimmedText.substring(notIndented[0].length).trimLeft(); + if (firstLineWrap.isNotEmpty) { + notIndented.addAll( + wrapTextAsLines( + trimmedText, + length: length - leadingWhitespace.length - hangingIndent, + ), + ); + } + } else { + notIndented = wrapTextAsLines( + trimmedText, + length: length - leadingWhitespace.length, + ); + } + String? hangingIndentString; + result.addAll( + notIndented.map((final String line) { + // Don't return any lines with just whitespace on them. + if (line.isEmpty) return ''; + final result = '${hangingIndentString ?? ''}$leadingWhitespace$line'; + hangingIndentString ??= ' ' * hangingIndent!; + return result; + }), + ); + } + return result.join('\n'); +} + +/// Wraps a block of text into lines no longer than [length], +/// starting at the [start] column, and returns the result as a list of strings. +/// +/// Tries to split at whitespace, but if that's not good enough to keep it +/// under the limit, then splits in the middle of a word. Preserves embedded +/// newlines, but not indentation (it trims whitespace from each line). +/// +/// If [length] is not specified, then no wrapping occurs, and the original +/// [text] is returned after splitting it on newlines. Whitespace is not trimmed +/// in this case. +List wrapTextAsLines( + final String text, { + final int start = 0, + final int? length, +}) { + assert(start >= 0); + + /// Returns true if the code unit at [index] in [text] is a whitespace + /// character. + /// + /// Based on: https://en.wikipedia.org/wiki/Whitespace_character#Unicode + bool isWhitespace(final String text, final int index) { + final rune = text.codeUnitAt(index); + return rune >= 0x0009 && rune <= 0x000D || + rune == 0x0020 || + rune == 0x0085 || + rune == 0x1680 || + rune == 0x180E || + rune >= 0x2000 && rune <= 0x200A || + rune == 0x2028 || + rune == 0x2029 || + rune == 0x202F || + rune == 0x205F || + rune == 0x3000 || + rune == 0xFEFF; + } + + if (length == null) return text.split('\n'); + + final result = []; + final effectiveLength = math.max(length - start, 10); + for (var line in text.split('\n')) { + line = line.trim(); + if (line.length <= effectiveLength) { + result.add(line); + continue; + } + + var currentLineStart = 0; + int? lastWhitespace; + for (var i = 0; i < line.length; ++i) { + if (isWhitespace(line, i)) lastWhitespace = i; + + if (i - currentLineStart >= effectiveLength) { + // Back up to the last whitespace, unless there wasn't any, in which + // case we just split where we are. + if (lastWhitespace != null) i = lastWhitespace; + + result.add(line.substring(currentLineStart, i).trim()); + + // Skip any intervening whitespace. + while (isWhitespace(line, i) && i < line.length) { + i++; + } + + currentLineStart = i; + lastWhitespace = null; + } + } + result.add(line.substring(currentLineStart).trim()); + } + return result; +} diff --git a/packages/config/lib/src/command/usage/invocation_synopsis.dart b/packages/config/lib/src/command/usage/invocation_synopsis.dart new file mode 100644 index 00000000..e3461a6b --- /dev/null +++ b/packages/config/lib/src/command/usage/invocation_synopsis.dart @@ -0,0 +1,155 @@ +import 'dart:math' as math; + +import '../../config/config.dart' + show + ConfigOptionBase, + FlagOption, + MultiOption, + MutuallyExclusive, + MutuallyExclusiveMode, + OptionDefinition; +import '../abstract_command.dart' show AbstractCommand; + +/// Synopsis of [cmd]. +/// +/// Parent command names come first, then this command's positional options +/// in [ConfigOptionBase.argPos] order, then its persistent named options and +/// its own named options. An option with both a name and a position is shown +/// only in the positional slot. Optional tokens are wrapped in `[]`. +/// A mandatory mutually exclusive group is one `(a | b)` token. +/// A non-mandatory one is `[a | b]`. +/// +/// A command with subcommands ends in ` [arguments]`. +/// When [AbstractCommand.canRunAsLeafCommand] is set, a second `or:` line +/// omits that suffix. +String commandInvocationSynopsis(final AbstractCommand cmd) { + final path = _commandPath(cmd); + final tokens = _synopsisTokens(cmd); + final leaf = [path, ...tokens].join(' '); + if (cmd.subcommands.isEmpty) return leaf; + + final branch = [path, ...tokens, ' [arguments]'].join(' '); + if (!cmd.canRunAsLeafCommand) return branch; + return '$branch\n or: $leaf'; +} + +String _commandPath(final AbstractCommand cmd) { + final parents = [cmd.name]; + var command = cmd; + while (command.hasParent) { + command = command.parent; + parents.add(command.name); + } + return parents.reversed.join(' '); +} + +/// Positional tokens, then named tokens, for options that can be passed +/// on the command line. +List _synopsisTokens(final AbstractCommand command) { + final options = [ + ...command.persistentOptions, + ...command.options, + ].where(_isCommandLineOption).toList(); + + final groups = >{}; + final ungrouped = <({int index, OptionDefinition option})>[]; + for (var i = 0; i < options.length; i++) { + final option = options[i]; + final group = option.option.group; + if (group is MutuallyExclusive) { + groups.putIfAbsent(group, () => []).add(option); + } else { + ungrouped.add((index: i, option: option)); + } + } + + final positional = <({int sortKey, String token})>[]; + final named = <({int sortKey, String token})>[]; + + for (final entry in ungrouped) { + final option = entry.option.option; + final token = _bracketedToken(option); + final argPos = option.argPos; + if (argPos != null) { + positional.add((sortKey: argPos, token: token)); + } else { + named.add((sortKey: entry.index, token: token)); + } + } + + for (final MapEntry(key: group, value: members) in groups.entries) { + final token = _exclusiveGroupToken( + members, + mandatory: group.mode == MutuallyExclusiveMode.mandatory, + ); + final positions = [ + for (final member in members) + if (member.option.argPos case final int pos) pos, + ]; + if (positions.isNotEmpty) { + positional.add((sortKey: positions.reduce(math.min), token: token)); + } else { + named.add((sortKey: options.indexOf(members.first), token: token)); + } + } + + positional.sort((final a, final b) => a.sortKey.compareTo(b.sortKey)); + named.sort((final a, final b) => a.sortKey.compareTo(b.sortKey)); + return [...positional, ...named].map((final entry) => entry.token).toList(); +} + +bool _isCommandLineOption(final OptionDefinition option) { + final opt = option.option; + if (opt.hide) return false; + return opt.argName != null || opt.argPos != null; +} + +/// Long name, or the positional placeholder when [option] has [ConfigOptionBase.argPos]. +String _synopsisSyntax(final ConfigOptionBase option) { + final argPos = option.argPos; + if (argPos != null) return '<${_valuePlaceholder(option)}>'; + + final name = option.argName!; + if (option is FlagOption) { + if (option.negatable && !option.hideNegatedUsage) return '--[no-]$name'; + return '--$name'; + } + return '--$name=<${_valuePlaceholder(option)}>'; +} + +String _valuePlaceholder(final ConfigOptionBase option) { + final help = option.valueHelp; + if (help != null && help.isNotEmpty) return help; + return option.argName ?? 'arg${option.argPos}'; +} + +String _bracketedToken(final ConfigOptionBase option) { + final syntax = _synopsisSyntax(option); + final repeat = option is MultiOption; + if (option.mandatory) return repeat ? '$syntax...' : syntax; + return repeat ? '[$syntax]...' : '[$syntax]'; +} + +/// Positionals inside the group stay in [ConfigOptionBase.argPos] order, +/// then named alternatives in definition order. +String _exclusiveGroupToken( + final List members, { + required final bool mandatory, +}) { + final positional = + members.where((final member) => member.option.argPos != null).toList() + ..sort( + (final a, final b) => a.option.argPos!.compareTo(b.option.argPos!), + ); + final named = members.where((final member) => member.option.argPos == null); + final ordered = [...positional, ...named]; + final body = ordered + .map((final member) => _groupMemberSyntax(member.option)) + .join(' | '); + return mandatory ? '($body)' : '[$body]'; +} + +String _groupMemberSyntax(final ConfigOptionBase option) { + final syntax = _synopsisSyntax(option); + return option is MultiOption ? '$syntax...' : syntax; +} diff --git a/packages/config/lib/src/command/usage/options_usage.dart b/packages/config/lib/src/command/usage/options_usage.dart new file mode 100644 index 00000000..c918b7f3 --- /dev/null +++ b/packages/config/lib/src/command/usage/options_usage.dart @@ -0,0 +1,392 @@ +import '../../config/config.dart' + show + ConfigOptionBase, + OptionDefinition, + FlagOption, + ComparableValueOption, + EnumOption, + EnumParser, + MultiOption, + addOptionsToReceiver, + OptionReceiver; +import 'command_usage.dart' show wrapTextAsLines; + +class OptionsUsageGenerator { + late final List _optionItems; + final int? lineLength; + + OptionsUsageGenerator( + final Iterable options, { + this.lineLength, + final bool addGroupSeparators = false, + }) { + final receiver = OptionItemReceiver(); + addOptionsToReceiver( + options, + receiver, + addGroupSeparators: addGroupSeparators, + ); + _optionItems = receiver._optionItems; + } + + final Map _optionTitles = {}; + final Map _optionBodies = {}; + + String generate() { + final visibleOptions = _optionItems + .where((final i) => i.isOption) + .map((final i) => i.option) + .where((final o) => !o.hide) + .toList(); + if (visibleOptions.isEmpty) return ''; + + _optionTitles.addEntries( + visibleOptions.map((final o) => MapEntry(o, _generateOptionTitle(o))), + ); + + final maxTitleWidth = _optionTitles.values + .map((final t) => t.length) + .reduce((final a, final b) => a > b ? a : b); + const gutter = 4; + final indent = maxTitleWidth + gutter; + + _optionBodies.addEntries( + visibleOptions.map( + (final o) => MapEntry(o, _generateOptionBody(o, indent, lineLength)), + ), + ); + + final buffer = StringBuffer(); + for (final optionItem in _optionItems) { + if (optionItem.isOption) { + final title = _optionTitles[optionItem.option]; + final body = _optionBodies[optionItem.option]; + if (title == null || body == null) continue; + buffer.write(_writeCompactOption(title, body, indent)); + } else { + buffer + ..writeln() + ..writeln(optionItem.separator); + } + } + return buffer.toString(); + } + + static String _writeCompactOption( + final String title, + final String body, + final int indent, + ) { + final buffer = StringBuffer() + ..write(title.padRight(indent)) + ..write(body); + return buffer.toString(); + } + + static String _generateOptionTitle(final ConfigOptionBase option) { + final buffer = StringBuffer(); + if (option.argName != null) { + if (option.argPos != null) { + buffer.write('{${option.argPos}}, '); + } + if (option.argAbbrev != null) { + buffer.write('-${option.argAbbrev}, '); + } + if (option is FlagOption && + option.negatable && + !option.hideNegatedUsage) { + buffer.write('--[no-]${option.argName}'); + } else { + buffer.write('--${option.argName}'); + } + return buffer.toString(); + } else if (option.argPos != null) { + return '{${option.argPos}}'; + } + + if (option.envName != null) { + buffer.write('${option.envName}'); + return buffer.toString(); + } + + final configKeys = option.allConfigKeys; + if (configKeys.isNotEmpty) { + final title = configKeys.map((final k) => '{$k}').join(', '); + buffer.write(title); + return buffer.toString(); + } + return ''; + } + + String _generateOptionBody( + final ConfigOptionBase option, + final int indent, + final int? lineLength, + ) { + final allowedValuesHelp = _generateAllowedValuesHelp(option); + final range = allowedValuesHelp == null ? _generateRange(option) : null; + final defaultValue = allowedValuesHelp == null && range == null + ? _generateDefault(option) + : null; + + final buffer = LayoutStringBuffer(indent: indent, lineLength: lineLength) + ..writeln(_generateDescription(option), firstLineIndentDelta: -indent) + ..maybeWriteln(_generateEnvVarName(option)) + ..maybeWriteln(_generateConfigKeys(option)) + ..maybeWriteln(defaultValue) + ..maybeWriteln(_generateMandatory(option)) + ..maybeWriteln(_generateValueHelp(option)) + ..maybeWriteln(range) + ..maybeWriteln(allowedValuesHelp); + return buffer.toString(); + } + + static String _generateDescription(final ConfigOptionBase option) { + return option.helpText ?? ''; + } + + static String? _generateEnvVarName(final ConfigOptionBase option) { + return option.envName != null ? 'env "${option.envName}"' : null; + } + + static String? _generateConfigKeys(final ConfigOptionBase option) { + final configKeys = option.allConfigKeys; + if (configKeys.isEmpty) return null; + return configKeys.map((final k) => 'key "$k"').join('\n'); + } + + static String? _generateDefault(final ConfigOptionBase option) { + final def = option.defaultValueString(); + if (def == null) return null; + return '(defaults to $def)'; + } + + static String? _generateMandatory(final ConfigOptionBase option) { + return option.mandatory ? '(mandatory)' : null; + } + + static String? _generateValueHelp(final ConfigOptionBase option) { + final valueHelp = option.valueHelp ?? ''; + return valueHelp.isNotEmpty ? valueHelp : null; + } + + static String? _generateRange(final ConfigOptionBase option) { + if (option case final ComparableValueOption comparable) { + String? minStr, maxStr; + if (comparable.min case final Comparable min) { + minStr = option.valueParser.format(min); + } + if (comparable.max case final Comparable max) { + maxStr = option.valueParser.format(max); + } + if (minStr == null && maxStr == null) return null; + final range = 'values: [${minStr ?? ''} - ${maxStr ?? ''}]'; + final defaultValue = _generateDefault(option); + return '$range${defaultValue != null ? ' $defaultValue' : ''}'; + } + return null; + } + + static String? _generateAllowedValuesHelp(final ConfigOptionBase option) { + final helpValues = _allowedValueNames(option); + final allowedHelp = option.allowedHelp ?? {}; + + if (helpValues.isEmpty) { + if (allowedHelp.isEmpty) return null; + helpValues.addAll(allowedHelp.keys); + } else if (allowedHelp.isEmpty) { + final values = helpValues.map( + (final value) => _annotateDefault(option, value), + ); + return 'values: [${values.join(', ')}]'; + } + + final maxValueWidth = helpValues + .map((final v) => v.length) + .reduce((final a, final b) => a > b ? a : b); + final helpValueLabels = helpValues + .map((final v) => '[$v]'.padRight(maxValueWidth + 2)) + .toList(); + + final output = [ + for (var i = 0; i < helpValueLabels.length; i++) + '${helpValueLabels[i]} ' + '${_annotateDefaultDescription(option, helpValues[i], allowedHelp[helpValues[i]] ?? '')}', + ]; + return output.join('\n'); + } + + /// Names listed under an option. + /// + /// Uses [ConfigOptionBase.allowedValues] when that restriction is set, + /// which for a [MultiOption] is its [MultiOption.allowedElementValues]. + /// An [EnumOption] without one lists every value its parser accepts. + static List _allowedValueNames(final ConfigOptionBase option) { + if (option is MultiOption) { + final elements = option.allowedElementValues; + if (elements == null) return []; + return elements.map(option.multiParser.elementParser.format).toList(); + } + final allowed = option.allowedValues; + if (allowed != null) { + return allowed.map(option.valueParser.format).toList(); + } + if (option is EnumOption) { + final parser = option.valueParser as EnumParser; + return parser.enumValues.map(parser.format).toList(); + } + return []; + } + + static String _annotateDefaultDescription( + final ConfigOptionBase option, + final String value, + final String description, + ) { + if (!_isDefaultValue(option, value)) return description; + return '$description (default)'; + } + + static String _annotateDefault( + final ConfigOptionBase option, + final String value, + ) { + if (!_isDefaultValue(option, value)) return value; + return '$value (default)'; + } + + static bool _isDefaultValue( + final ConfigOptionBase option, + final String value, + ) { + final def = option.defaultValue(); + if (def == null) return false; + if (option is MultiOption && def is List) { + final format = option.multiParser.elementParser.format; + return def.any((final element) => format(element) == value); + } + return option.defaultValueString() == value; + } +} + +class LayoutStringBuffer { + final StringBuffer _buffer = StringBuffer(); + + int indent; + int? lineLength; + + LayoutStringBuffer({ + this.indent = 0, + this.lineLength, + }); + + void write( + final Object? obj, { + final int? firstLineIndentDelta, + final int? indentDelta, + final int? lineLength, + }) { + _buffer.write( + _layoutText( + obj.toString(), + firstLineIndentDelta, + indentDelta, + lineLength, + ), + ); + } + + void writeln( + final Object? obj, { + final int? firstLineIndentDelta, + final int? indentDelta, + final int? lineLength, + }) { + _buffer.writeln( + _layoutText( + obj.toString(), + firstLineIndentDelta, + indentDelta, + lineLength, + ), + ); + } + + void maybeWriteln( + final Object? obj, { + final int? firstLineIndentDelta, + final int? indentDelta, + final int? lineLength, + }) { + if (obj case final Object o) { + _buffer.writeln( + _layoutText( + o.toString(), + firstLineIndentDelta, + indentDelta, + lineLength, + ), + ); + } + } + + String _layoutText( + final String text, + final int? firstLineIndentDelta, + final int? indentDelta, + final int? lineLengthOverride, + ) { + final firstIndent = indent + (firstLineIndentDelta ?? 0); + final hangingIndent = indent + (indentDelta ?? 0); + + final lineLength = lineLengthOverride ?? this.lineLength; + final wrappedText = wrapTextAsLines( + text, + start: hangingIndent, + length: lineLength, + ); + return (' ' * firstIndent) + wrappedText.join('\n${' ' * hangingIndent}'); + } + + @override + String toString() { + return _buffer.toString(); + } +} + +class OptionOrSeparator { + final ConfigOptionBase? _option; + final String? _separator; + + OptionOrSeparator.option(ConfigOptionBase this._option) : _separator = null; + + OptionOrSeparator.separator(String this._separator) : _option = null; + + bool get isOption => _option != null; + + ConfigOptionBase get option { + if (_option == null) throw StateError('Option is null'); + return _option; + } + + String get separator { + if (_separator == null) throw StateError('Separator is null'); + return _separator; + } +} + +class OptionItemReceiver implements OptionReceiver { + final List _optionItems = []; + + OptionItemReceiver(); + + @override + void addOption(final OptionDefinition option) { + _optionItems.add(OptionOrSeparator.option(option.option)); + } + + @override + void addSeparator(final String separator) { + _optionItems.add(OptionOrSeparator.separator(separator)); + } +} diff --git a/packages/config/lib/src/command/usage/usage.dart b/packages/config/lib/src/command/usage/usage.dart new file mode 100644 index 00000000..ab7f1202 --- /dev/null +++ b/packages/config/lib/src/command/usage/usage.dart @@ -0,0 +1,4 @@ +/// Usage text generation for commands. +library; + +export 'command_usage.dart'; diff --git a/packages/config/lib/src/command/usage_generator.dart b/packages/config/lib/src/command/usage_generator.dart new file mode 100644 index 00000000..774339b7 --- /dev/null +++ b/packages/config/lib/src/command/usage_generator.dart @@ -0,0 +1,37 @@ +import 'abstract_command.dart' show AbstractCommand; +import 'usage/usage.dart' show commandUsage; + +/// A command usage string generator. +abstract interface class UsageGenerator { + /// Generates a formatted usage string for a command. + String generate(final AbstractCommand command); +} + +class StandardRunnerUsageGenerator implements UsageGenerator { + const StandardRunnerUsageGenerator(); + + @override + String generate(final AbstractCommand command) { + final lineLength = _getUsageLineLength(command); + return commandUsage(command, false, lineLength); + } +} + +class StandardCommandUsageGenerator implements UsageGenerator { + const StandardCommandUsageGenerator(); + + @override + String generate(final AbstractCommand command) { + final lineLength = _getUsageLineLength(command); + return commandUsage(command, true, lineLength); + } +} + +int? _getUsageLineLength(AbstractCommand command) { + int? lineLength = command.usageLineLength; + while (lineLength == null && command.hasParent) { + command = command.parent; + lineLength = command.usageLineLength; + } + return lineLength; +} diff --git a/packages/config/lib/src/command/usage_output.dart b/packages/config/lib/src/command/usage_output.dart new file mode 100644 index 00000000..b5b4d7a3 --- /dev/null +++ b/packages/config/lib/src/command/usage_output.dart @@ -0,0 +1,208 @@ +import '../../config.dart' + show UsageException, CommandUsageException, CommandDefinition; +import 'command_runner.dart' show CommandRunner; +import 'output_sinks.dart'; + +/// The settings and behavior for the usage output - +/// controls the help output and the usage exception output. +class UsageOutputHandler { + final OutputSinks sinks; + final UsageExceptionSettings exceptionSettings; + + final UsageExceptionHandler? _standardExceptionHandler; + final List _additionalExceptionHandlers; + + List get exceptionHandlers => [ + ..._additionalExceptionHandlers, + ?_standardExceptionHandler, + ]; + + /// The provided exception handlers are added before the standard exception handlers. + /// + /// The handler keeps its own growable copy of that list, so + /// [addUsageExceptionHandler] works on every instance, including one + /// constructed with no handlers. + UsageOutputHandler({ + this.sinks = const OutputSinks(), + this.exceptionSettings = const UsageExceptionSettings(), + final Iterable? addExceptionHandlers, + }) : _standardExceptionHandler = standardUsageExceptionHandler, + _additionalExceptionHandlers = List.of( + addExceptionHandlers ?? const [], + ); + + /// Replaces the standard exception handlers with the given exception handlers. + UsageOutputHandler.replace({ + this.sinks = const OutputSinks(), + this.exceptionSettings = const UsageExceptionSettings(), + required final Iterable exceptionHandlers, + }) : _standardExceptionHandler = null, + _additionalExceptionHandlers = List.of(exceptionHandlers); + + /// Adds [handler] after the handlers already registered and before the + /// standard handler. + void addUsageExceptionHandler(final UsageExceptionHandler handler) { + _additionalExceptionHandlers.add(handler); + } + + /// Writes [command]'s usage to [sink], or to [sinks.out] when omitted + /// (which is stdout unless overridden). + void printUsage( + final CommandDefinition command, { + final StringSink? sink, + }) { + (sink ?? sinks.out).write(command.usage); + } + + /// Handles a usage exception by invoking the registered exception handlers. + /// Returns the exception if it shall be rethrown, or null if it is suppressed. + UsageException? onUsageException( + UsageException exception, { + required final CommandDefinition? fromCommand, + }) { + for (final handler in exceptionHandlers) { + final e = handler(exception, this, fromCommand: fromCommand); + if (e == null) return null; + exception = e; + } + return exception; + } +} + +//////////////////////// +// UsageException handling and printing +//////////////////////// + +class UsageExceptionSettings { + /// Set to true for [CommandRunner.run] to not throw [UsageException] + /// on parsing and configuration input errors. + final bool noUsageException; + + /// Set to true for [CommandRunner.run] to not print usage guidance on + /// parsing and configuration input errors. + final bool noUsageExceptionOutput; + + /// The printer for the usage exception output. + final UsageExceptionPrinter exceptionPrinter; + + const UsageExceptionSettings({ + final bool? noUsageException, + final bool? noUsageExceptionOutput, + final UsageExceptionPrinter? exceptionPrinter, + }) : noUsageException = noUsageException ?? false, + noUsageExceptionOutput = noUsageExceptionOutput ?? false, + exceptionPrinter = + exceptionPrinter ?? const StandardUsageExceptionPrinter(); +} + +typedef UsageExceptionHandler = + UsageException? Function( + UsageException exception, + UsageOutputHandler usageOutput, { + required CommandDefinition? fromCommand, + }); + +UsageException? standardUsageExceptionHandler( + final UsageException exception, + final UsageOutputHandler usageOutput, { + required final CommandDefinition? fromCommand, +}) { + const handler = StandardUsageExceptionHandler(); + return handler.onUsageException( + exception, + usageOutput, + fromCommand: fromCommand, + ); +} + +class StandardUsageExceptionHandler { + const StandardUsageExceptionHandler(); + + UsageException? onUsageException( + final UsageException exception, + final UsageOutputHandler usageOutput, { + required final CommandDefinition? fromCommand, + }) { + if (!usageOutput.exceptionSettings.noUsageExceptionOutput) { + final exceptionPrinter = usageOutput.exceptionSettings.exceptionPrinter; + exceptionPrinter.printException( + exception, + usageOutput: usageOutput, + fromCommand: fromCommand, + ); + } + if (usageOutput.exceptionSettings.noUsageException) { + return null; + } + return exception; + } +} + +abstract class UsageExceptions { + static UsageExceptionHandler simpleHandler( + final void Function( + UsageException exception, + UsageOutputHandler usageOutput, + CommandDefinition? fromCommand, + ) + handler, + ) { + return ( + final UsageException exception, + final UsageOutputHandler usageOutput, { + required final CommandDefinition? fromCommand, + }) { + handler(exception, usageOutput, fromCommand); + return exception; + }; + } +} + +/// Interface of a usage exception printer, which implements the layout and +/// formatting of a usage exception printed to [OutputSinks.err]. +abstract interface class UsageExceptionPrinter { + /// Prints a usage exception to [OutputSinks.err]. + /// + /// If [exception] is a [CommandUsageException] (this is the expected normal + /// case), the usage for its command is printed. + /// If it is not, the [usage] field of the [UsageException] is printed, + /// along with the [fromCommand] usage if provided. + /// In other words [fromCommand] is only used as a fallback if the exception + /// is not a [CommandUsageException]. + void printException( + final UsageException exception, { + required final UsageOutputHandler usageOutput, + required final CommandDefinition? fromCommand, + }); +} + +/// The standard implementation of [UsageExceptionPrinter] which implements the +/// default layout and formatting of a usage exception printed to [OutputSinks.err]. +class StandardUsageExceptionPrinter implements UsageExceptionPrinter { + const StandardUsageExceptionPrinter(); + + @override + void printException( + final UsageException exception, { + required final UsageOutputHandler usageOutput, + final CommandDefinition? fromCommand, + }) { + usageOutput.sinks.err.writeln(exception.message); + usageOutput.sinks.err.writeln(''); + + if (exception is CommandUsageException) { + usageOutput.printUsage( + exception.command, + sink: usageOutput.sinks.err, + ); + } else { + if (exception.usage.isNotEmpty) { + usageOutput.sinks.err.writeln(exception.usage); + } + if (fromCommand != null) { + if (exception.usage.isNotEmpty) usageOutput.sinks.err.writeln('---'); + usageOutput.printUsage(fromCommand, sink: usageOutput.sinks.err); + } + } + } +} diff --git a/packages/config/lib/src/config/completion.dart b/packages/config/lib/src/config/completion.dart index 66be3dd8..e986c7fb 100644 --- a/packages/config/lib/src/config/completion.dart +++ b/packages/config/lib/src/config/completion.dart @@ -120,11 +120,15 @@ class CompletionResult { /// The state of the command line being completed, /// provided to `ConfigOptionBase.complete`. /// -/// Only the command line arguments are available; option values are not -/// resolved from environment variables, configuration files or the -/// configuration broker, and are not validated, because completion must be -/// fast and must never fail. The raw [environment] is available for custom -/// completions that depend on it. +/// [parsedArgs] is the raw command line, including a placeholder where the +/// value being completed will go. Option values are not validated here. +/// +/// When the command runner serves the completion, the context is a +/// `CommandCompletionContext`: the commands typed so far have been resolved +/// (arguments, environment variables, configuration files, and the +/// configuration broker) and their middleware has run in completion mode. +/// Read that chain with `commandContextOf`. Completion must still be fast +/// and should not throw. class CompletionContext { /// The partial text of the value being completed. May be empty. /// diff --git a/packages/config/lib/src/config/options.dart b/packages/config/lib/src/config/options.dart index d74916f7..17edd9f3 100644 --- a/packages/config/lib/src/config/options.dart +++ b/packages/config/lib/src/config/options.dart @@ -366,6 +366,11 @@ abstract class ConfigOptionBase implements OptionDefinition { /// /// The candidates need not be filtered by [CompletionContext.wordToComplete] /// since the shells do that; filtering is still recommended for large sets. + /// + /// When the command runner invokes this, [context] is a + /// `CommandCompletionContext`. `commandContextOf` returns the leaf + /// `CommandContext` of the commands typed so far, with resolved option + /// values and whatever middleware stored on its provider. FutureOr complete(final CompletionContext context) { final candidates = allowedValueCandidates(); if (candidates != null) return CompletionResult.values(candidates); diff --git a/packages/config/lib/src/middleware/middleware.dart b/packages/config/lib/src/middleware/middleware.dart new file mode 100644 index 00000000..8616a8e9 --- /dev/null +++ b/packages/config/lib/src/middleware/middleware.dart @@ -0,0 +1,31 @@ +typedef Handler = R Function(A arg); + +typedef Middleware = Handler Function(Handler next); + +class MiddlewareChain { + final List> _middlewares; + + MiddlewareChain([final List>? middlewares]) + : _middlewares = List.from(middlewares ?? []); + + /// Adds a middleware to the end of this chain. + void addMiddleware(final Middleware middleware) { + _middlewares.add(middleware); + } + + /// Returns a handler that runs this middleware chain with [terminalHandler] + /// at the end. + Handler handlerChain(final Handler terminalHandler) => + _nextHandler(_middlewares.iterator, terminalHandler); + + Handler _nextHandler( + final Iterator> mwIter, + final Handler terminalHandler, + ) { + if (mwIter.moveNext()) { + final middleware = mwIter.current; + return middleware(_nextHandler(mwIter, terminalHandler)); + } + return terminalHandler; + } +} diff --git a/packages/config/lib/src/middleware/middleware_hooks.dart b/packages/config/lib/src/middleware/middleware_hooks.dart new file mode 100644 index 00000000..c7024037 --- /dev/null +++ b/packages/config/lib/src/middleware/middleware_hooks.dart @@ -0,0 +1,120 @@ +import 'dart:async' show FutureOr; + +import 'middleware.dart'; + +/// Base class for easy creation of [Middleware] hooks. +/// +/// Use it as [Middleware] like this: +/// ```dart +/// final middleware = MiddlewareHooks().middleware; +/// ``` +class MiddlewareHooks { + const MiddlewareHooks(); + + /// Middleware method that produces the handler that runs these hooks. + /// Adheres to the [Middleware] signature. + Handler, A> middleware(final Handler, A> next) { + return (final A arg) async { + final useArg = await onRun(arg); + final R response; + try { + response = await next(useArg); + } catch (error, stackTrace) { + return await onError(error, stackTrace, useArg); + } + return await onReturn(useArg, response); + }; + } + + /// Hook method that is called before the next handler is run. + /// + /// The returned value is passed to the next handler. + /// + /// If it throws, the call chain is aborted + /// and the exception propagates to the caller. + FutureOr onRun(final A arg) { + return arg; + } + + /// Hook method that is called after the next handler returns normally. + /// + /// Returns the same type as the next handler's return type. + /// By default the response is returned unchanged. + /// + /// If it throws, the call chain is aborted + /// and the exception propagates to the caller. + FutureOr onReturn(final A arg, final R response) { + return response; + } + + /// Hook method that is called if the next handler throws. + /// + /// Returns the same type as the next handler's return type. + /// + /// If it throws, the call chain is aborted + /// and the exception propagates to the caller. + FutureOr onError( + final Object error, + final StackTrace stackTrace, + final A arg, + ) { + Error.throwWithStackTrace(error, stackTrace); + } +} + +typedef OnRun = FutureOr Function(A arg); +typedef OnReturn = FutureOr Function(A arg, R response); +typedef OnError = + FutureOr Function(Object error, StackTrace stackTrace, A arg); + +/// Helper class for easy composition with hook functions. +/// +/// Use it as [Middleware] like this: +/// ```dart +/// final middleware = MiddlewareComposer( +/// onRun: (final arg) async => arg, +/// onReturn: (final arg, final response) async => response, +/// onError: (final error, final stackTrace, final arg) async => +/// Error.throwWithStackTrace(error, stackTrace), +/// ).middleware; +/// ``` +class MiddlewareComposer extends MiddlewareHooks { + final OnRun? _onRun; + final OnReturn? _onReturn; + final OnError? _onError; + + /// Compose a middleware with one or more hook functions. + const MiddlewareComposer({ + final OnRun? onRun, + final OnReturn? onReturn, + final OnError? onError, + }) : _onRun = onRun, + _onReturn = onReturn, + _onError = onError; + + @override + FutureOr onRun(final A arg) { + final onRun = _onRun; + if (onRun == null) return arg; + return onRun(arg); + } + + @override + FutureOr onReturn(final A arg, final R response) { + final onReturn = _onReturn; + if (onReturn == null) return response; + return onReturn(arg, response); + } + + @override + FutureOr onError( + final Object error, + final StackTrace stackTrace, + final A arg, + ) { + if (_onError != null) { + return _onError.call(error, stackTrace, arg); + } + Error.throwWithStackTrace(error, stackTrace); + } +} diff --git a/packages/config/test/command/bridge_command_test.dart b/packages/config/test/command/bridge_command_test.dart new file mode 100644 index 00000000..d1d79f3f --- /dev/null +++ b/packages/config/test/command/bridge_command_test.dart @@ -0,0 +1,663 @@ +import 'dart:async'; + +import 'package:config/command.dart'; +import 'package:config/config.dart'; +import 'package:test/test.dart'; + +import 'command_fixtures.dart'; + +void main() { + group('Given a bridge command with only a name and description', () { + late _NamedBridge command; + + setUp(() { + command = _NamedBridge( + name: 'plain', + description: 'Does the plain thing', + ); + }); + + test( + 'when reading the usage definition then the description is copied', + () { + expect(command.usageDefinition.description, 'Does the plain thing'); + }, + ); + + test('when reading the usage definition then there is no footer', () { + expect(command.usageDefinition.usageFooter, isNull); + }); + + test('when reading the usage definition then the category is empty', () { + expect(command.usageDefinition.category, isEmpty); + }); + + test('when reading the usage definition then the command is visible', () { + expect(command.usageDefinition.hidden, isFalse); + }); + + test('when reading the alias definition then there are no aliases', () { + expect(command.aliasesDefinition.aliases, isEmpty); + }); + + test( + 'when reading the alias definition ' + 'then there are no suggestion aliases', + () { + expect(command.aliasesDefinition.suggestionAliases, isEmpty); + }, + ); + + test('when reading the summary then it is the description', () { + expect(command.summary, 'Does the plain thing'); + }); + + test( + 'when reading the invocation ' + 'then it is the command name and arguments', + () { + expect(command.invocation, 'plain [arguments]'); + }, + ); + + test( + 'when reading the usage definition ' + 'then the invocation is left to the usage generator', + () { + expect(command.usageDefinition.invocation, isNull); + }, + ); + + test('when asked whether it takes arguments then it does not', () { + expect(command.takesArguments, isFalse); + }); + + group('when it is added to a runner', () { + setUp(() { + _runner(subcommands: [command]); + }); + + test('then its usage shows the description and no footer', () { + expect( + command.usage, + _usage(const [ + 'Does the plain thing', + '', + 'Usage: tool plain', + '', + 'Run "tool help" to see global options.', + ]), + ); + }); + }); + + group('when it is run', () { + late String? result; + + setUp(() async { + result = await _runner(subcommands: [command]).run(['plain']); + }); + + test('then the run result is returned', () { + expect(result, 'plain'); + }); + }); + }); + + group( + 'Given a bridge command whose description changes after first usageDescription access', + () { + late _MutableDescription command; + + setUp(() { + command = _MutableDescription('First line\nkept in the definition'); + command.usageDefinition; + }); + + group('when the description changes', () { + setUp(() { + command.description = 'Second line\nignored by the definition'; + }); + + test('then the usage definition keeps the original description', () { + expect( + command.usageDefinition.description, + 'First line\nkept in the definition', + ); + }); + + test('then the summary uses the new first line', () { + expect(command.summary, 'Second line'); + }); + }); + }, + ); + + group('Given a bridge command with legacy documentation members', () { + late _DocumentedBridge command; + + setUp(() { + command = _DocumentedBridge(); + }); + + test( + 'when reading the usage definition then the description is copied', + () { + expect( + command.usageDefinition.description, + 'Build the project.\nMore detail here.', + ); + }, + ); + + test('when reading the usage definition then the footer is copied', () { + expect(command.usageDefinition.usageFooter, 'See the docs.'); + }); + + test('when reading the usage definition then the category is copied', () { + expect(command.usageDefinition.category, 'Project'); + }); + + test('when reading the usage definition then the command is visible', () { + expect(command.usageDefinition.hidden, isFalse); + }); + + test('when reading the alias definition then the aliases are copied', () { + expect(command.aliasesDefinition.aliases, ['b', 'compile']); + }); + + test( + 'when reading the alias definition ' + 'then the suggestion aliases are copied', + () { + expect(command.aliasesDefinition.suggestionAliases, ['bld']); + }, + ); + + test( + 'when reading the summary ' + 'then it is the first line of the description', + () { + expect(command.summary, 'Build the project.'); + }, + ); + + group('when it is added to a runner beside another command', () { + late CommandRunner runner; + + setUp(() { + runner = _runner( + subcommands: [ + command, + _NamedBridge(name: 'shown', description: 'Shown in help'), + _HiddenBridge(), + ], + ); + }); + + test('then its usage shows the full description and the footer', () { + expect( + command.usage, + _usage(const [ + 'Build the project.', + 'More detail here.', + '', + 'Usage: tool build', + '', + 'Run "tool help" to see global options.', + '', + 'See the docs.', + ]), + ); + }); + + test( + 'then the runner usage groups it by category ' + 'and omits the hidden command', + () { + expect( + runner.usage, + _usage(const [ + 'Tools', + '', + 'Usage: tool [global-options] [arguments]', + '', + 'Global options:', + '-h, --help Print this usage information.', + '', + 'Available commands:', + ' shown Shown in help', + '', + 'Project', + ' build Build the project.', + '', + 'Run "tool help " for more information about a command.', + ]), + ); + }, + ); + + group('when an alias is used', () { + late String? result; + + setUp(() async { + result = await runner.run(['compile']); + }); + + test('then the command runs', () { + expect(result, 'build'); + }); + }); + + group('when a suggestion alias is used', () { + late UsageException? error; + late String? result; + + setUp(() async { + result = null; + error = await _captureUsageError(() async { + result = await runner.run(['bld']); + }); + }); + + test('then the word is reported as an unknown subcommand', () { + expect( + error?.message, + 'tool: Unknown subcommand: "bld" (Did you mean build?)', + ); + }); + + test('then the command does not run', () { + expect(result, isNull); + }); + }); + + group('when the hidden command is invoked by name', () { + late String? result; + + setUp(() async { + result = await runner.run(['secret']); + }); + + test('then the hidden command runs', () { + expect(result, 'secret'); + }); + }); + }); + }); + + group('Given a bridge command that overrides summary and invocation', () { + late _CustomUsageBridge command; + late CommandRunner runner; + + setUp(() { + command = _CustomUsageBridge(); + runner = _runner(subcommands: [command]); + }); + + test('when reading the usage definition then the summary is copied', () { + expect(command.usageDefinition.summary, 'Download packages'); + }); + + test( + 'when reading the usage definition then the invocation is copied', + () { + expect(command.usageDefinition.invocation, 'get '); + }, + ); + + test('when reading the runner usage then the summary is shown', () { + expect( + runner.usage, + _usage(const [ + 'Tools', + '', + 'Usage: tool [global-options] [arguments]', + '', + 'Global options:', + '-h, --help Print this usage information.', + '', + 'Available commands:', + ' get Download packages', + '', + 'Run "tool help " for more information about a command.', + ]), + ); + }); + + test('when reading the command usage then the invocation is shown', () { + expect( + command.usage, + _usage(const [ + 'Download packages.', + 'More detail here.', + '', + 'Usage: tool get ', + '', + 'Run "tool help" to see global options.', + ]), + ); + }); + }); + + group('Given a bridge command with a subcommand', () { + late _NamedBridge build; + late _NamedBridge check; + + setUp(() { + check = _NamedBridge(name: 'check', description: 'Check the app'); + build = _NamedBridge( + name: 'build', + description: 'Build the app', + subcommands: [check], + ); + }); + + test('when reading the invocation then it asks for a subcommand', () { + expect(build.invocation, 'build [arguments]'); + }); + + test( + 'when reading the nested command invocation ' + 'then it is that command name and arguments', + () { + expect(check.invocation, 'check [arguments]'); + }, + ); + }); + + group('Given a bridge branch that can run as a leaf', () { + late _NamedBridge command; + + setUp(() { + command = _NamedBridge( + name: 'build', + description: 'Build the app', + canRunAsLeafCommand: true, + subcommands: [ + _NamedBridge(name: 'check', description: 'Check the app'), + ], + ); + }); + + test('when reading the invocation then it asks for a subcommand', () { + expect(command.invocation, 'build [arguments]'); + }); + }); + + group('Given a bridge command that starts without subcommands', () { + late _NamedBridge command; + + setUp(() { + command = _NamedBridge(name: 'build', description: 'Build the app'); + }); + + group('when a subcommand is added', () { + setUp(() { + command.addSubcommand( + _NamedBridge(name: 'check', description: 'Check the app'), + ); + }); + + test('then the invocation asks for a subcommand', () { + expect(command.invocation, 'build [arguments]'); + }); + }); + }); + + group('Given a bridge command with only a named option', () { + late _NamedBridge command; + + setUp(() { + command = _NamedBridge( + name: 'build', + description: 'Build the app', + options: const [ + FlagOption(argName: 'release', defaultsTo: false), + ], + ); + }); + + test('when asked whether it takes arguments then it does not', () { + expect(command.takesArguments, isFalse); + }); + }); + + group('Given a bridge command with a positional option', () { + late _NamedBridge command; + + setUp(() { + command = _NamedBridge( + name: 'build', + description: 'Build the app', + options: const [StringOption(argPos: 0)], + body: (final context) => context.config.findValueOf(argPos: 0), + ); + }); + + test('when asked whether it takes arguments then it does', () { + expect(command.takesArguments, isTrue); + }); + + group('when it is run with a positional word', () { + late String? result; + + setUp(() async { + result = await _runner( + subcommands: [command], + ).run(['build', 'lib/main.dart']); + }); + + test('then run receives that word', () { + expect(result, 'lib/main.dart'); + }); + }); + }); + + group('Given a bridge command with a positional persistent option', () { + late _NamedBridge command; + + setUp(() { + command = _NamedBridge( + name: 'build', + description: 'Build the app', + persistentOptions: const [StringOption(argPos: 0)], + ); + }); + + test('when asked whether it takes arguments then it does', () { + expect(command.takesArguments, isTrue); + }); + }); + + group('Given a bridge command registered on a runner', () { + late _NamedBridge command; + late _CapturedUsage usage; + + setUp(() { + usage = _CapturedUsage(); + command = _NamedBridge(name: 'build', description: 'Build the app'); + CommandRunner( + 'tool', + 'Tools', + usageOutput: usage.handler, + completion: CompletionSettings.disabled, + subcommands: [command], + ); + }); + + group('when usage is printed', () { + setUp(() { + command.printUsage(); + }); + + test('then the command usage is written to standard output', () { + expect(usage.out.toString(), command.usage); + }); + + test('then standard error stays empty', () { + expect(usage.err.toString(), isEmpty); + }); + }); + + group('when a usage exception is raised', () { + late UsageException? error; + + setUp(() { + error = _throwUsageException(command, 'Missing target.'); + }); + + test('then the given message is reported', () { + expect(error?.message, 'Missing target.'); + }); + + test('then the command usage is attached', () { + expect(error?.usage, command.usage); + }); + }); + }); +} + +CommandRunner _runner({ + required final List> subcommands, +}) { + return CommandRunner( + 'tool', + 'Tools', + subcommands: subcommands, + usageOutput: noUsageErrorOutput, + completion: CompletionSettings.disabled, + ); +} + +String _usage(final Iterable lines) => '${lines.join('\n')}\n'; + +Future _captureUsageError( + final Future Function() body, +) async { + try { + await body(); + } on UsageException catch (error) { + return error; + } + return null; +} + +UsageException? _throwUsageException( + final BridgeCommand command, + final String message, +) { + try { + command.usageException(message); + } on UsageException catch (error) { + return error; + } +} + +class _CapturedUsage { + final out = StringBuffer(); + final err = StringBuffer(); + + late final UsageOutputHandler handler = UsageOutputHandler( + sinks: OutputSinks(out: out, err: err), + ); +} + +class _NamedBridge extends BridgeCommand { + _NamedBridge({ + required this.name, + required this.description, + super.persistentOptions, + super.options, + super.subcommands, + super.canRunAsLeafCommand, + this.body, + }); + + @override + final String name; + + @override + final String description; + + final FutureOr Function( + CommandContext context, + )? + body; + + @override + FutureOr run( + final CommandContext context, + ) { + final body = this.body; + if (body != null) return body(context); + return name; + } +} + +class _MutableDescription extends BridgeCommand { + _MutableDescription(this.description); + + @override + String get name => 'plain'; + + @override + String description; + + @override + String? run(final CommandContext context) => name; +} + +class _DocumentedBridge extends BridgeCommand { + @override + String get name => 'build'; + + @override + String get description => 'Build the project.\nMore detail here.'; + + @override + String get category => 'Project'; + + @override + String? get usageFooter => 'See the docs.'; + + @override + List get aliases => const ['b', 'compile']; + + @override + List get suggestionAliases => const ['bld']; + + @override + String? run(final CommandContext context) => name; +} + +class _CustomUsageBridge extends BridgeCommand { + @override + String get name => 'get'; + + @override + String get description => 'Download packages.\nMore detail here.'; + + @override + String get summary => 'Download packages'; + + @override + String get invocation => 'get '; + + @override + String? run(final CommandContext context) => name; +} + +class _HiddenBridge extends BridgeCommand { + @override + String get name => 'secret'; + + @override + String get description => 'Hidden command'; + + @override + bool get hidden => true; + + @override + String? run(final CommandContext context) => name; +} diff --git a/packages/config/test/command/command_fixtures.dart b/packages/config/test/command/command_fixtures.dart new file mode 100644 index 00000000..68339c0b --- /dev/null +++ b/packages/config/test/command/command_fixtures.dart @@ -0,0 +1,92 @@ +import 'dart:async'; + +import 'package:config/command.dart'; +import 'package:config/config.dart'; + +/// Skips printing usage errors. +/// +/// Use this when a test asserts on [UsageException] and not on the printed text, +/// so a passing run does not write to the terminal. +final noUsageErrorOutput = UsageOutputHandler( + exceptionSettings: const UsageExceptionSettings(noUsageExceptionOutput: true), +); + +/// Runs [runner] and collects text written with [print]. +Future<({T? result, String output})> +runCapturingPrint( + final CommandRunner runner, + final List args, { + final Map? env, +}) async { + final lines = []; + final result = await runZoned( + () async => runner.run(args, env: env), + zoneSpecification: ZoneSpecification( + print: (final self, final parent, final zone, final line) { + lines.add(line); + }, + ), + ); + return (result: result, output: lines.join('\n')); +} + +/// A command that records [name] when it runs. +/// +/// [body] replaces the default result, which is the command name. +class RecordingCommand + extends CommandImpl { + RecordingCommand({ + required super.name, + required super.description, + required this.trace, + super.aliases, + super.suggestionAliases, + super.hidden, + super.options, + super.persistentOptions, + super.subcommands, + super.middlewares, + this.body, + }); + + final List trace; + + final FutureOr Function( + CommandContext context, + )? + body; + + @override + FutureOr run( + final CommandContext context, + ) { + trace.add(name); + final body = this.body; + if (body != null) return body(context); + return name; + } +} + +/// A runner that records its own name when the root command runs. +class TracingRunner + extends CommandRunner { + TracingRunner( + this.trace, { + super.subcommands, + super.middlewares, + super.canRunAsLeafCommand, + super.globalOptions, + // super.configBroker, + super.ignoreUnexpectedPositionalArgs, + super.rootFooter, + super.usageOutput, + }) : super('tool', 'Tools'); + + final List trace; + + @override + String? runAsLeaf(final CommandContext context) { + trace.add(name); + return name; + } +} diff --git a/packages/config/test/command/command_line_run_test.dart b/packages/config/test/command/command_line_run_test.dart new file mode 100644 index 00000000..4c9038ff --- /dev/null +++ b/packages/config/test/command/command_line_run_test.dart @@ -0,0 +1,512 @@ +import 'dart:async'; + +import 'package:config/command.dart'; +import 'package:config/config.dart'; +import 'package:test/test.dart'; + +import 'command_fixtures.dart'; + +void main() { + group('Given a runner with a build command', () { + late List trace; + late TracingRunner runner; + + setUp(() { + trace = []; + runner = TracingRunner( + trace, + usageOutput: noUsageErrorOutput, + subcommands: [ + RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + ), + ], + ); + }); + + group('when the runner is started with no arguments', () { + late UsageException? error; + + setUp(() async { + error = await _captureUsageError(() => runner.run([])); + }); + + test('then a subcommand is required', () { + expect(error?.message, 'tool: A subcommand is required under tool.'); + }); + + test('then no command runs', () { + expect(trace, isEmpty); + }); + }); + + group('when the build command is invoked', () { + late String? result; + + setUp(() async { + result = await runner.run(['build']); + }); + + test('then only the build command runs', () { + expect(trace, ['build']); + }); + + test('then the build command result is returned', () { + expect(result, 'build'); + }); + }); + + group('when the command line names an unknown command', () { + late UsageException? error; + + setUp(() async { + error = await _captureUsageError(() => runner.run(['missing'])); + }); + + test('then the unknown command is reported', () { + expect(error, isA()); + expect(error?.message, contains('missing')); + }); + + test('then no command runs', () { + expect(trace, isEmpty); + }); + }); + + group('when the command line contains an unknown option', () { + late UsageException? error; + + setUp(() async { + error = await _captureUsageError( + () => runner.run(['build', '--missing']), + ); + }); + + test('then the unknown option is reported', () { + expect(error?.message, 'build: Unknown option: --missing.'); + }); + + test('then no command runs', () { + expect(trace, isEmpty); + }); + }); + + group('when the leaf command receives an extra positional argument', () { + late UsageException? error; + + setUp(() async { + error = await _captureUsageError( + () => runner.run(['build', 'extra']), + ); + }); + + test('then the unexpected argument is reported', () { + expect( + error?.message, + "build: Unexpected positional argument(s): 'extra'", + ); + }); + + test('then no command runs', () { + expect(trace, isEmpty); + }); + }); + }); + + group('Given a runner that can run as a leaf', () { + late List trace; + late TracingRunner runner; + + setUp(() { + trace = []; + runner = TracingRunner( + trace, + canRunAsLeafCommand: true, + subcommands: [ + RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + ), + ], + ); + }); + + group('when the runner is started with no arguments', () { + late String? result; + + setUp(() async { + result = await runner.run([]); + }); + + test('then only the root command runs', () { + expect(trace, ['tool']); + }); + + test('then the root result is returned', () { + expect(result, 'tool'); + }); + }); + + group('when the build command is invoked', () { + late String? result; + + setUp(() async { + result = await runner.run(['build']); + }); + + test('then only the build command runs', () { + expect(trace, ['build']); + }); + + test('then the build command result is returned', () { + expect(result, 'build'); + }); + }); + }); + + group('Given a runner that ignores unexpected positional arguments', () { + late List trace; + late TracingRunner runner; + + setUp(() { + trace = []; + runner = TracingRunner( + trace, + ignoreUnexpectedPositionalArgs: true, + subcommands: [ + RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + ), + ], + ); + }); + + test( + 'when the leaf command receives an extra positional argument ' + 'then the command runs', + () async { + await runner.run(['build', 'extra']); + + expect(trace, ['build']); + }, + ); + }); + + group('Given a command created with a run function', () { + test( + 'when the runner invokes it ' + 'then that function result is returned', + () async { + final command = CommandImpl.leafWithRunFunction( + name: 'build', + description: 'Build the app', + run: (final context) => 'from-function', + ); + final runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [command], + ); + + expect(await runner.run(['build']), 'from-function'); + }, + ); + }); + + group('Given a runner that gains its command after construction', () { + late List trace; + late TracingRunner runner; + + setUp(() { + trace = []; + runner = TracingRunner(trace); + runner.addSubcommand( + RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + ), + ); + }); + + test( + 'when the added command is invoked ' + 'then that command runs', + () async { + await runner.run(['build']); + + expect(trace, ['build']); + }, + ); + }); + + group('Given a build command with an alias and a suggestion alias', () { + late List trace; + late TracingRunner runner; + + setUp(() { + trace = []; + runner = TracingRunner( + trace, + usageOutput: noUsageErrorOutput, + subcommands: [ + RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + aliases: ['b'], + suggestionAliases: ['bld'], + ), + ], + ); + }); + + test('when the alias is used then the build command runs', () async { + await runner.run(['b']); + + expect(trace, ['build']); + }); + + group('when a suggestion alias is used', () { + late UsageException? error; + + setUp(() async { + error = await _captureUsageError(() => runner.run(['bld'])); + }); + + test('then a usage exception is thrown', () { + expect(error, isA()); + }); + + test('then the build command does not run', () { + expect(trace, isEmpty); + }); + }); + }); + + group('Given a hidden command', () { + late List trace; + late TracingRunner runner; + + setUp(() { + trace = []; + runner = TracingRunner( + trace, + subcommands: [ + RecordingCommand( + name: 'secret', + description: 'Hidden command', + trace: trace, + hidden: true, + ), + ], + ); + }); + + test('when the command is invoked by name then it runs', () async { + await runner.run(['secret']); + + expect(trace, ['secret']); + }); + }); + + group('Given a branch command with a nested command', () { + late List trace; + late TracingRunner runner; + + setUp(() { + trace = []; + final child = RecordingCommand( + name: 'check', + description: 'Check the app', + trace: trace, + ); + final parent = RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + subcommands: [child], + ); + runner = TracingRunner( + trace, + usageOutput: noUsageErrorOutput, + subcommands: [parent], + ); + }); + + group('when the branch command is the last command', () { + late UsageException? error; + + setUp(() async { + error = await _captureUsageError(() => runner.run(['build'])); + }); + + test('then a subcommand is required', () { + expect(error?.message, 'build: A subcommand is required under build.'); + }); + + test('then no command runs', () { + expect(trace, isEmpty); + }); + }); + + group('when the nested command line is run', () { + late String? result; + + setUp(() async { + result = await runner.run(['build', 'check']); + }); + + test('then only the leaf command runs', () { + expect(trace, ['check']); + }); + + test('then the leaf result is returned', () { + expect(result, 'check'); + }); + }); + + test( + 'when the nested command is added with addSubcommand ' + 'then the leaf command runs', + () async { + final addedTrace = []; + final branch = RecordingCommand( + name: 'remote', + description: 'Manage remotes', + trace: addedTrace, + ); + final child = RecordingCommand( + name: 'add', + description: 'Add a remote', + trace: addedTrace, + ); + // ignore: deprecated_member_use_from_same_package + branch.addSubcommand(child); + final added = TracingRunner(addedTrace, subcommands: [branch]); + + await added.run(['remote', 'add']); + + expect(addedTrace, ['add']); + }, + ); + }); + + group('Given a branch defined by parameters that can run as a leaf', () { + late List trace; + late StringBuffer usageOut; + late Command remote; + late TracingRunner runner; + + setUp(() { + trace = []; + usageOut = StringBuffer(); + remote = CommandImpl.branch( + name: 'remote', + description: 'Manage remotes', + canRunAsLeafCommand: true, + subcommands: [ + RecordingCommand( + name: 'add', + description: 'Add a remote', + trace: trace, + ), + ], + ); + runner = TracingRunner( + trace, + usageOutput: UsageOutputHandler( + sinks: OutputSinks(out: usageOut, err: StringBuffer()), + ), + subcommands: [remote], + ); + }); + + group('when the branch command is the last command', () { + late String? result; + + setUp(() async { + result = await runner.run(['remote']); + }); + + test('then usage for the branch command is printed', () { + expect(usageOut.toString(), remote.usage); + }); + + test('then no result is returned', () { + expect(result, isNull); + }); + + test('then no command runs', () { + expect(trace, isEmpty); + }); + }); + + group('when the nested command line is run', () { + late String? result; + + setUp(() async { + result = await runner.run(['remote', 'add']); + }); + + test('then only the nested command runs', () { + expect(trace, ['add']); + }); + + test('then the nested command result is returned', () { + expect(result, 'add'); + }); + + test('then no usage is printed', () { + expect(usageOut.toString(), isEmpty); + }); + }); + }); + + group('Given a command that completes asynchronously', () { + late List trace; + late TracingRunner runner; + + setUp(() { + trace = []; + runner = TracingRunner( + trace, + subcommands: [ + RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + body: (final context) async { + await Future.delayed(Duration.zero); + return 'later'; + }, + ), + ], + ); + }); + + test( + 'when the command is invoked ' + 'then its future result is returned', + () async { + expect(await runner.run(['build']), 'later'); + }, + ); + }); +} + +Future _captureUsageError( + final FutureOr Function() body, +) async { + try { + await body(); + } on UsageException catch (error) { + return error; + } + return null; +} diff --git a/packages/config/test/command/command_middleware_test.dart b/packages/config/test/command/command_middleware_test.dart new file mode 100644 index 00000000..39577954 --- /dev/null +++ b/packages/config/test/command/command_middleware_test.dart @@ -0,0 +1,1342 @@ +import 'package:config/command.dart'; +import 'package:config/config.dart'; +import 'package:test/test.dart'; + +import 'command_fixtures.dart'; + +void main() { + group('Given a command with two middlewares', () { + late List trace; + late CommandRunner runner; + + setUp(() { + trace = []; + final command = RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + middlewares: [ + (final next) => (final context) async { + trace.add('outer-before'); + final result = await next(context); + trace.add('outer-after'); + return 'outer:$result'; + }, + (final next) => (final context) async { + trace.add('inner-before'); + final result = await next(context); + trace.add('inner-after'); + return 'inner:$result'; + }, + ], + ); + runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [command], + ); + }); + + group('when the command runs', () { + late String? result; + + setUp(() async { + result = await runner.run(['build']); + }); + + test('then the first middleware wraps the second', () { + expect(trace, [ + 'outer-before', + 'inner-before', + 'build', + 'inner-after', + 'outer-after', + ]); + }); + + test('then the runner returns the outer middleware result', () { + expect(result, 'outer:inner:build'); + }); + }); + }); + + group('Given a synchronous command middleware', () { + late List trace; + late CommandRunner runner; + + setUp(() { + trace = []; + final command = RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + middlewares: [ + (final next) => (final context) { + trace.add('before'); + final result = next(context); + trace.add('after:$result'); + return result; + }, + ], + ); + runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [command], + ); + }); + + group('when the command runs', () { + late String? result; + + setUp(() async { + result = await runner.run(['build']); + }); + + test('then the middleware runs around the command', () { + expect(trace, ['before', 'build', 'after:build']); + }); + + test('then the command result is returned', () { + expect(result, 'build'); + }); + }); + }); + + group('Given middleware added after the command is created', () { + test( + 'when the command runs ' + 'then that middleware wraps the result', + () async { + final trace = []; + final command = RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + ); + command.addMiddleware( + (final next) => (final context) async { + final result = await next(context); + return 'added:$result'; + }, + ); + final runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [command], + ); + + expect(await runner.run(['build']), 'added:build'); + }, + ); + }); + + group('Given command middleware that reads the run context', () { + test( + 'when the command line sets an option ' + 'then the middleware sees the resolved value', + () async { + const target = StringOption(argName: 'target'); + String? seen; + final command = + CommandImpl.leafWithRunFunction( + name: 'build', + description: 'Build the app', + options: [target], + middlewares: [ + (final next) => (final context) { + seen = context.config.optionalValue(target); + return next(context); + }, + ], + run: (final context) => 'build', + ); + final runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [command], + ); + + await runner.run(['build', '--target', 'wasm']); + + expect(seen, 'wasm'); + }, + ); + }); + + group('Given middleware that replaces the run context', () { + const marker = StringOption(argName: 'marker'); + + late CommandContext replaced; + late CommandContext? seenByCommand; + late String? result; + + setUp(() async { + seenByCommand = null; + final command = CommandImpl.leafWithRunFunction( + name: 'build', + description: 'Build the app', + middlewares: [ + (final next) => (final context) { + replaced = context.copyWith( + config: Configuration.fromValues( + values: {marker: 'from-middleware'}, + ), + ); + return next(replaced); + }, + ], + run: (final context) { + seenByCommand = context; + return context.config.optionalValue(marker); + }, + ); + final runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [command], + ); + result = await runner.run(['build']); + }); + + test( + 'when the command runs ' + 'then the command receives the replaced context', + () { + expect(seenByCommand, same(replaced)); + }, + ); + + test( + 'when the command runs ' + 'then the command result is returned', + () { + expect(result, 'from-middleware'); + }, + ); + }); + + group( + 'Given middleware that replaces the context passed to a following command', + () { + const marker = StringOption(argName: 'marker'); + + late _MarkerProvider originalProvider; + late _MarkerProvider replacedProvider; + late CommandContext replaced; + late CommandContext? seenByCheck; + late String? result; + + setUp(() async { + originalProvider = _MarkerProvider(); + replacedProvider = _MarkerProvider(); + seenByCheck = null; + final check = CommandImpl.leafWithRunFunction( + name: 'check', + description: 'Check the app', + middlewares: [ + (final next) => (final context) { + seenByCheck = context; + return next(context); + }, + ], + run: (final context) => 'check', + ); + final build = CommandImpl.branch( + name: 'build', + description: 'Build the app', + subcommands: [check], + middlewares: [ + (final next) => (final context) { + final following = context.next; + if (following == null) { + throw StateError('build has no following command.'); + } + replaced = following.copyWith( + config: Configuration.fromValues( + values: {marker: 'from-middleware'}, + ), + provider: replacedProvider, + ); + return next(context.copyWith(next: replaced)); + }, + ], + ); + final runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [build], + ); + result = await runner.run( + ['build', 'check'], + provider: originalProvider, + ); + }); + + test( + 'when the nested command line runs ' + 'then the following command receives the replaced context', + () { + expect(seenByCheck, same(replaced)); + }, + ); + + test( + 'when the nested command line runs ' + 'then the following command result is returned', + () { + expect(result, 'check'); + }, + ); + }, + ); + + group('Given command middleware that does not call the command', () { + late List trace; + late TracingRunner runner; + + setUp(() { + trace = []; + final command = RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + middlewares: [ + (final next) => + (final context) => 'stopped', + ], + ); + runner = TracingRunner(trace, subcommands: [command]); + }); + + group('when the command line is run', () { + late String? result; + + setUp(() async { + result = await runner.run(['build']); + }); + + test('then the command body does not run', () { + expect(trace, isEmpty); + }); + + test('then the middleware result is returned', () { + expect(result, 'stopped'); + }); + }); + }); + + group('Given a runner middleware and a command middleware', () { + late List trace; + late TracingRunner runner; + + setUp(() { + trace = []; + final command = RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + middlewares: [ + (final next) => (final context) async { + trace.add('cmd-before'); + final result = await next(context); + trace.add('cmd-after'); + return 'cmd:$result'; + }, + ], + ); + runner = TracingRunner( + trace, + middlewares: [ + (final next) => (final context) async { + trace.add('root-before'); + final result = await next(context); + trace.add('root-after:$result'); + return result; + }, + ], + subcommands: [command], + ); + }); + + group('when the command line is run', () { + late String? result; + + setUp(() async { + result = await runner.run(['build']); + }); + + test( + 'then the runner middleware wraps the root command and the subcommand', + () { + expect(trace, [ + 'root-before', + 'cmd-before', + 'build', + 'cmd-after', + 'root-after:cmd:build', + ]); + }, + ); + + test('then the runner returns the command middleware result', () { + expect(result, 'cmd:build'); + }); + }); + }); + + group('Given runner middleware that does not call the root command', () { + late List trace; + late TracingRunner runner; + + setUp(() { + trace = []; + runner = TracingRunner( + trace, + middlewares: [ + (final next) => + (final context) => 'skipped-root', + ], + subcommands: [ + RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + ), + ], + ); + }); + + group('when the command line is run', () { + late String? result; + + setUp(() async { + result = await runner.run(['build']); + }); + + test('then the root command and its subcommands do not run', () { + expect(trace, isEmpty); + }); + + test('then the middleware result is returned', () { + expect(result, 'skipped-root'); + }); + }); + }); + + group('Given runner middleware that throws', () { + late List trace; + late StringBuffer err; + late TracingRunner runner; + late Object? error; + + setUp(() async { + trace = []; + err = StringBuffer(); + error = null; + runner = TracingRunner( + trace, + usageOutput: UsageOutputHandler(sinks: OutputSinks(err: err)), + middlewares: [ + (final next) => + (final context) => throw StateError('stop'), + ], + subcommands: [ + RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + ), + ], + ); + try { + await runner.run(['build']); + } on StateError catch (e) { + error = e; + } + }); + + test('when the command line is run then the failure is reported', () { + expect( + error, + isA().having( + (final error) => error.message, + 'message', + 'stop', + ), + ); + }); + + test('when the command line is run then the subcommand does not run', () { + expect(trace, isEmpty); + }); + + test('when the command line is run then usage is not printed', () { + expect(err.toString(), isEmpty); + }); + }); + + group('Given a command whose body throws', () { + late List trace; + late StringBuffer err; + late Object? error; + + setUp(() async { + trace = []; + err = StringBuffer(); + error = null; + final command = RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + body: (final context) => throw StateError('boom'), + middlewares: [ + (final next) => (final context) async { + trace.add('before'); + final result = await next(context); + trace.add('after'); + return result; + }, + ], + ); + final runner = TracingRunner( + trace, + usageOutput: UsageOutputHandler(sinks: OutputSinks(err: err)), + subcommands: [command], + ); + try { + await runner.run(['build']); + } on StateError catch (e) { + error = e; + } + }); + + test( + 'when the command line is run then the failure reaches the caller', + () { + expect( + error, + isA().having( + (final error) => error.message, + 'message', + 'boom', + ), + ); + }, + ); + + test( + 'when the command line is run ' + 'then middleware does not continue after the command', + () { + expect(trace, ['before', 'build']); + }, + ); + + test('when the command line is run then usage is not printed', () { + expect(err.toString(), isEmpty); + }); + }); + + group('Given command middleware that handles a command failure', () { + late List trace; + late StringBuffer err; + late String? result; + + setUp(() async { + trace = []; + err = StringBuffer(); + final command = RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + body: (final context) => throw StateError('boom'), + middlewares: [ + (final next) => (final context) async { + trace.add('before'); + try { + return await next(context); + } on StateError { + trace.add('handled'); + return 'recovered'; + } + }, + ], + ); + final runner = TracingRunner( + trace, + usageOutput: UsageOutputHandler(sinks: OutputSinks(err: err)), + subcommands: [command], + ); + result = await runner.run(['build']); + }); + + test( + 'when the command line is run ' + 'then the middleware result is returned', + () { + expect(result, 'recovered'); + }, + ); + + test( + 'when the command line is run ' + 'then the middleware runs around the failure', + () { + expect(trace, ['before', 'build', 'handled']); + }, + ); + + test('when the command line is run then usage is not printed', () { + expect(err.toString(), isEmpty); + }); + }); + + group('Given middleware on the runner, a command, and a subcommand', () { + late List trace; + late String? result; + + setUp(() async { + trace = []; + final child = RecordingCommand( + name: 'check', + description: 'Check the app', + trace: trace, + middlewares: [ + (final next) => (final context) async { + trace.add('check-before'); + final value = await next(context); + trace.add('check-after'); + return 'check:$value'; + }, + ], + ); + final parent = RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + subcommands: [child], + middlewares: [ + (final next) => (final context) async { + trace.add('build-before'); + final value = await next(context); + trace.add('build-after'); + return 'build:$value'; + }, + ], + ); + final runner = TracingRunner( + trace, + middlewares: [ + (final next) => (final context) async { + trace.add('root-before'); + final value = await next(context); + trace.add('root-after'); + return 'root:$value'; + }, + ], + subcommands: [parent], + ); + result = await runner.run(['build', 'check']); + }); + + test('then each middleware wraps that command and its subcommands', () { + expect(trace, [ + 'root-before', + 'build-before', + 'check-before', + 'check', + 'check-after', + 'build-after', + 'root-after', + ]); + }); + + test('then the runner returns the outermost middleware result', () { + expect(result, 'root:build:check:check'); + }); + }); + + group('Given synchronous middleware on a command with a subcommand', () { + late List trace; + late String? result; + + setUp(() async { + trace = []; + final child = RecordingCommand( + name: 'check', + description: 'Check the app', + trace: trace, + ); + final parent = RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + subcommands: [child], + middlewares: [ + (final next) => (final context) { + trace.add('before'); + final value = next(context); + trace.add('after:$value'); + return value; + }, + ], + ); + final runner = TracingRunner(trace, subcommands: [parent]); + result = await runner.run(['build', 'check']); + }); + + test('then the middleware wraps the command and the subcommand', () { + expect(trace, ['before', 'check', 'after:check']); + }); + + test('then the subcommand result is returned', () { + expect(result, 'check'); + }); + }); + + group('Given command middleware that does not call the next handler', () { + late List trace; + late String? result; + + setUp(() async { + trace = []; + final child = RecordingCommand( + name: 'check', + description: 'Check the app', + trace: trace, + ); + final parent = RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + subcommands: [child], + middlewares: [ + (final next) => (final context) async { + trace.add('build-before'); + return 'stopped'; + }, + ], + ); + final runner = TracingRunner( + trace, + middlewares: [ + (final next) => (final context) async { + trace.add('root-before'); + final value = await next(context); + trace.add('root-after:$value'); + return value; + }, + ], + subcommands: [parent], + ); + result = await runner.run(['build', 'check']); + }); + + test('then that command and its subcommands do not run', () { + expect(trace, [ + 'root-before', + 'build-before', + 'root-after:stopped', + ]); + }); + + test('then the middleware result is returned', () { + expect(result, 'stopped'); + }); + }); + + group('Given a parent command whose body finishes asynchronously', () { + late List trace; + late String? result; + + setUp(() async { + trace = []; + final child = RecordingCommand( + name: 'check', + description: 'Check the app', + trace: trace, + ); + final parent = RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + subcommands: [child], + body: (final context) async { + trace.add('build-body-start'); + await Future.delayed(Duration.zero); + trace.add('build-body-end'); + return 'build-body'; + }, + ); + final runner = TracingRunner(trace, subcommands: [parent]); + result = await runner.run(['build', 'check']); + }); + + test('then the parent body does not run', () { + expect(trace, ['check']); + }); + + test('then the subcommand result is returned', () { + expect(result, 'check'); + }); + }); + + group('Given Middlewares.onBeforeRun with a synchronous callback', () { + late List trace; + late String? result; + + setUp(() async { + trace = []; + final command = RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + middlewares: [ + Middlewares.onBeforeRun((final _) { + trace.add('before'); + }), + ], + ); + final runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [command], + ); + result = await runner.run(['build']); + }); + + test( + 'when the command runs then the callback runs before the command', + () { + expect(trace, ['before', 'build']); + }, + ); + + test('when the command runs then the command result is returned', () { + expect(result, 'build'); + }); + }); + + group('Given Middlewares.onBeforeRun with an asynchronous callback', () { + late List trace; + late String? result; + + setUp(() async { + trace = []; + final command = RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + middlewares: [ + Middlewares.onBeforeRun((final _) async { + trace.add('before-start'); + await Future.delayed(Duration.zero); + trace.add('before-end'); + }), + ], + ); + final runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [command], + ); + result = await runner.run(['build']); + }); + + test( + 'when the command runs then the callback finishes before the command', + () { + expect(trace, ['before-start', 'before-end', 'build']); + }, + ); + + test('when the command runs then the command result is returned', () { + expect(result, 'build'); + }); + }); + + group('Given Middlewares.onRun with a synchronous callback', () { + const marker = StringOption(argName: 'marker'); + + late String? seen; + late String? result; + + setUp(() async { + seen = null; + final command = CommandImpl.leafWithRunFunction( + name: 'build', + description: 'Build the app', + middlewares: [ + Middlewares.onRun((final context) { + return context.copyWith( + config: Configuration.fromValues( + values: {marker: 'from-hook'}, + ), + ); + }), + ], + run: (final context) { + seen = context.config.optionalValue(marker); + return 'build'; + }, + ); + final runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [command], + ); + result = await runner.run(['build']); + }); + + test( + 'when the command runs ' + 'then the command receives the context from the callback', + () { + expect(seen, 'from-hook'); + }, + ); + + test('when the command runs then the command result is returned', () { + expect(result, 'build'); + }); + }); + + group('Given Middlewares.onRun with an asynchronous callback', () { + const marker = StringOption(argName: 'marker'); + + late String? seen; + late String? result; + + setUp(() async { + seen = null; + final command = CommandImpl.leafWithRunFunction( + name: 'build', + description: 'Build the app', + middlewares: [ + Middlewares.onRun((final context) async { + await Future.delayed(Duration.zero); + return context.copyWith( + config: Configuration.fromValues( + values: {marker: 'from-hook'}, + ), + ); + }), + ], + run: (final context) { + seen = context.config.optionalValue(marker); + return 'build'; + }, + ); + final runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [command], + ); + result = await runner.run(['build']); + }); + + test( + 'when the command runs ' + 'then the command receives the context from the callback', + () { + expect(seen, 'from-hook'); + }, + ); + + test('when the command runs then the command result is returned', () { + expect(result, 'build'); + }); + }); + + group('Given Middlewares.onReturn with a synchronous callback', () { + late List trace; + late String? result; + + setUp(() async { + trace = []; + final command = RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + middlewares: [ + Middlewares.onReturn((final _, final response) { + trace.add('onReturn'); + return 'hook:$response'; + }), + ], + ); + final runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [command], + ); + result = await runner.run(['build']); + }); + + test( + 'when the command runs then the callback runs after the command', + () { + expect(trace, ['build', 'onReturn']); + }, + ); + + test('when the command runs then the callback value is returned', () { + expect(result, 'hook:build'); + }); + }); + + group('Given Middlewares.onReturn with an asynchronous callback', () { + late List trace; + late String? result; + + setUp(() async { + trace = []; + final command = RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + middlewares: [ + Middlewares.onReturn((final _, final response) async { + trace.add('onReturn-start'); + await Future.delayed(Duration.zero); + trace.add('onReturn-end'); + return 'hook:$response'; + }), + ], + ); + final runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [command], + ); + result = await runner.run(['build']); + }); + + test( + 'when the command runs then the callback finishes after the command', + () { + expect(trace, ['build', 'onReturn-start', 'onReturn-end']); + }, + ); + + test('when the command runs then the callback value is returned', () { + expect(result, 'hook:build'); + }); + }); + + group('Given Middlewares.onError with a synchronous callback', () { + late List trace; + late String? result; + + setUp(() async { + trace = []; + final command = RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + body: (final _) => throw StateError('boom'), + middlewares: [ + Middlewares.onError((final error, final _, final _) { + trace.add('onError'); + return 'recovered:${(error as StateError).message}'; + }), + ], + ); + final runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [command], + ); + result = await runner.run(['build']); + }); + + test( + 'when the command fails then the callback runs after the command', + () { + expect(trace, ['build', 'onError']); + }, + ); + + test('when the command fails then the callback value is returned', () { + expect(result, 'recovered:boom'); + }); + }); + + group('Given Middlewares.onError with an asynchronous callback', () { + late List trace; + late String? result; + + setUp(() async { + trace = []; + final command = RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + body: (final _) => throw StateError('boom'), + middlewares: [ + Middlewares.onError((final error, final _, final _) async { + trace.add('onError-start'); + await Future.delayed(Duration.zero); + trace.add('onError-end'); + return 'recovered:${(error as StateError).message}'; + }), + ], + ); + final runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [command], + ); + result = await runner.run(['build']); + }); + + test( + 'when the command fails then the callback finishes after the command', + () { + expect(trace, ['build', 'onError-start', 'onError-end']); + }, + ); + + test('when the command fails then the callback value is returned', () { + expect(result, 'recovered:boom'); + }); + }); + + group('Given Middlewares.withHooks with synchronous callbacks', () { + const marker = StringOption(argName: 'marker'); + + late List trace; + late String? seen; + late String? result; + + setUp(() async { + trace = []; + seen = null; + final command = RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + middlewares: [ + Middlewares.withHooks( + onRun: (final context) { + trace.add('onRun'); + return context.copyWith( + config: Configuration.fromValues( + values: {marker: 'from-hook'}, + ), + ); + }, + onReturn: (final _, final response) { + trace.add('onReturn'); + return 'hook:$response'; + }, + ), + ], + body: (final context) { + seen = context.config.optionalValue(marker); + return 'build'; + }, + ); + final runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [command], + ); + result = await runner.run(['build']); + }); + + test('when the command runs then the hooks run around the command', () { + expect(trace, ['onRun', 'build', 'onReturn']); + }); + + test( + 'when the command runs ' + 'then the command receives the context from onRun', + () { + expect(seen, 'from-hook'); + }, + ); + + test('when the command runs then the onReturn value is returned', () { + expect(result, 'hook:build'); + }); + }); + + group('Given Middlewares.withHooks with asynchronous callbacks', () { + const marker = StringOption(argName: 'marker'); + + late List trace; + late String? seen; + late String? result; + + setUp(() async { + trace = []; + seen = null; + final command = RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + middlewares: [ + Middlewares.withHooks( + onRun: (final context) async { + await Future.delayed(Duration.zero); + trace.add('onRun'); + return context.copyWith( + config: Configuration.fromValues( + values: {marker: 'from-hook'}, + ), + ); + }, + onReturn: (final _, final response) async { + trace.add('onReturn-start'); + await Future.delayed(Duration.zero); + trace.add('onReturn-end'); + return 'hook:$response'; + }, + ), + ], + body: (final context) { + seen = context.config.optionalValue(marker); + return 'build'; + }, + ); + final runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [command], + ); + result = await runner.run(['build']); + }); + + test( + 'when the command runs then each hook finishes around the command', + () { + expect(trace, [ + 'onRun', + 'build', + 'onReturn-start', + 'onReturn-end', + ]); + }, + ); + + test( + 'when the command runs ' + 'then the command receives the context from onRun', + () { + expect(seen, 'from-hook'); + }, + ); + + test('when the command runs then the onReturn value is returned', () { + expect(result, 'hook:build'); + }); + }); + + group( + 'Given Middlewares.withHooks with a synchronous onError callback', + () { + late List trace; + late String? result; + + setUp(() async { + trace = []; + final command = RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + body: (final _) => throw StateError('boom'), + middlewares: [ + Middlewares.withHooks( + onError: (final error, final _, final _) { + trace.add('onError'); + return 'recovered:${(error as StateError).message}'; + }, + ), + ], + ); + final runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [command], + ); + result = await runner.run(['build']); + }); + + test( + 'when the command fails then the callback runs after the command', + () { + expect(trace, ['build', 'onError']); + }, + ); + + test('when the command fails then the callback value is returned', () { + expect(result, 'recovered:boom'); + }); + }, + ); + + group( + 'Given Middlewares.withHooks with an asynchronous onError callback', + () { + late List trace; + late String? result; + + setUp(() async { + trace = []; + final command = RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + body: (final _) => throw StateError('boom'), + middlewares: [ + Middlewares.withHooks( + onError: (final error, final _, final _) async { + trace.add('onError-start'); + await Future.delayed(Duration.zero); + trace.add('onError-end'); + return 'recovered:${(error as StateError).message}'; + }, + ), + ], + ); + final runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [command], + ); + result = await runner.run(['build']); + }); + + test( + 'when the command fails ' + 'then the callback finishes after the command', + () { + expect(trace, ['build', 'onError-start', 'onError-end']); + }, + ); + + test('when the command fails then the callback value is returned', () { + expect(result, 'recovered:boom'); + }); + }, + ); +} + +class _MarkerProvider implements ContextProvider { + @override + T fetch() => throw ContextValueNotFound(T); + + @override + T? maybeFetch() => null; + + @override + bool has() => false; + + @override + void store(final T value) {} + + @override + void remove() {} +} diff --git a/packages/config/test/command/command_run_context_test.dart b/packages/config/test/command/command_run_context_test.dart new file mode 100644 index 00000000..6165a248 --- /dev/null +++ b/packages/config/test/command/command_run_context_test.dart @@ -0,0 +1,994 @@ +import 'dart:async'; + +import 'package:config/command.dart'; +import 'package:config/config.dart'; +import 'package:config/middleware.dart'; +import 'package:test/test.dart'; + +import 'command_fixtures.dart'; + +enum BuildOption implements OptionDefinition { + target(StringOption(argName: 'target', argAbbrev: 't')), + jobs(IntOption(argName: 'jobs', defaultsTo: 1)), + release(FlagOption(argName: 'release', defaultsTo: false)), + path(StringOption(argPos: 0)); + + const BuildOption(this.option); + + @override + final ConfigOptionBase option; +} + +enum RequiredOption implements OptionDefinition { + name(StringOption(argName: 'name', mandatory: true)); + + const RequiredOption(this.option); + + @override + final ConfigOptionBase option; +} + +void main() { + group('Given a build command with named, flag, and positional options', () { + late CommandContext context; + + setUp(() async { + final command = CommandImpl.leafWithRunFunction( + name: 'build', + description: 'Build the app', + options: BuildOption.values, + run: (final runContext) { + context = runContext; + }, + ); + final runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [command], + ); + await runner.run([ + 'build', + '--target', + 'wasm', + '--jobs', + '4', + '--release', + 'lib/main.dart', + ]); + }); + + test('when those options are set then the named option is available', () { + expect(context.config.optionalValue(BuildOption.target), 'wasm'); + }); + + test('when those options are set then the integer option is available', () { + expect(context.config.value(BuildOption.jobs), 4); + }); + + test('when those options are set then the flag is set', () { + expect(context.config.value(BuildOption.release), isTrue); + }); + + test( + 'when those options are set ' + 'then the positional option receives the first positional word', + () { + expect(context.config.optionalValue(BuildOption.path), 'lib/main.dart'); + }, + ); + }); + + group('Given a build command whose options are omitted', () { + late CommandContext context; + + setUp(() async { + final command = CommandImpl.leafWithRunFunction( + name: 'build', + description: 'Build the app', + options: BuildOption.values, + run: (final runContext) { + context = runContext; + }, + ); + final runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [command], + ); + await runner.run(['build']); + }); + + test('when the command runs then a default integer is available', () { + expect(context.config.value(BuildOption.jobs), 1); + }); + + test('when the command runs then an omitted flag is false', () { + expect(context.config.value(BuildOption.release), isFalse); + }); + + test('when the command runs then an omitted named option is null', () { + expect(context.config.optionalValue(BuildOption.target), isNull); + }); + + test('when the command runs then an omitted positional option is null', () { + expect(context.config.optionalValue(BuildOption.path), isNull); + }); + }); + + group('Given a build command with a positional option', () { + late UsageException? error; + late bool ran; + + setUp(() async { + error = null; + ran = false; + final command = CommandImpl.leafWithRunFunction( + name: 'build', + description: 'Build the app', + options: BuildOption.values, + run: (final runContext) { + ran = true; + }, + ); + final runner = CommandRunner( + 'tool', + 'Tools', + usageOutput: noUsageErrorOutput, + subcommands: [command], + ); + try { + await runner.run(['build', 'lib/main.dart', 'extra']); + } on UsageException catch (e) { + error = e; + } + }); + + test( + 'when another positional word follows ' + 'then the extra word is reported', + () { + expect( + error?.message, + "build: Unexpected positional argument(s): 'extra'", + ); + }, + ); + + test( + 'when another positional word follows ' + 'then the command does not run', + () { + expect(ran, isFalse); + }, + ); + }); + + group('Given a command with a mandatory option', () { + late List trace; + late UsageException? error; + late StringBuffer err; + late String commandUsage; + + setUp(() async { + trace = []; + error = null; + err = StringBuffer(); + final command = CommandImpl.leafWithRunFunction( + name: 'greet', + description: 'Greet', + options: RequiredOption.values, + middlewares: [ + (final next) => (final context) { + trace.add('middleware'); + return next(context); + }, + ], + run: (final runContext) { + trace.add('run'); + }, + ); + final runner = CommandRunner( + 'tool', + 'Tools', + usageOutput: UsageOutputHandler(sinks: OutputSinks(err: err)), + subcommands: [command], + ); + commandUsage = command.usage; + try { + await runner.run(['greet']); + } on UsageException catch (e) { + error = e; + } + }); + + test('when the option is omitted then the missing option is reported', () { + expect(error?.message, 'greet: Option `name` is mandatory.'); + }); + + test( + 'when the option is omitted ' + "then the error and that command's usage are printed", + () { + expect(err.toString(), '${error!.message}\n\n$commandUsage'); + }, + ); + + test( + 'when the option is omitted ' + 'then the command and its middleware do not run', + () { + expect(trace, isEmpty); + }, + ); + }); + + group('Given a command that is missing a mandatory option', () { + late UsageException? error; + + setUp(() async { + error = null; + final command = CommandImpl.leafWithRunFunction( + name: 'greet', + description: 'Greet', + options: RequiredOption.values, + run: (final context) {}, + ); + final runner = CommandRunner( + 'tool', + 'Tools', + usageOutput: noUsageErrorOutput, + subcommands: [command], + ); + try { + await runner.run(['greet', '--missing']); + } on UsageException catch (e) { + error = e; + } + }); + + test( + 'when the command line also has an unknown option ' + 'then both problems are reported', + () { + expect( + error?.message, + 'greet: Unknown option: --missing.\n' + 'greet: Option `name` is mandatory.', + ); + }, + ); + }); + + group('Given a command with two mandatory options', () { + late UsageException? error; + + setUp(() async { + error = null; + const name = StringOption(argName: 'name', mandatory: true); + const target = StringOption(argName: 'target', mandatory: true); + final command = CommandImpl.leafWithRunFunction( + name: 'greet', + description: 'Greet', + options: [name, target], + run: (final context) {}, + ); + final runner = CommandRunner( + 'tool', + 'Tools', + usageOutput: noUsageErrorOutput, + subcommands: [command], + ); + try { + await runner.run(['greet']); + } on UsageException catch (e) { + error = e; + } + }); + + test('when both options are omitted then both errors are reported', () { + expect( + error?.message, + 'greet: Option `name` is mandatory.\n' + 'greet: Option `target` is mandatory.', + ); + }); + }); + + group('Given mandatory options on the root and on a command', () { + late List trace; + late UsageException? error; + late StringBuffer err; + late String runnerUsage; + + setUp(() async { + trace = []; + error = null; + err = StringBuffer(); + const verbose = StringOption(argName: 'verbose', mandatory: true); + const name = StringOption(argName: 'name', mandatory: true); + final command = CommandImpl.leafWithRunFunction( + name: 'greet', + description: 'Greet', + options: [name], + middlewares: [ + (final next) => (final context) { + trace.add('middleware'); + return next(context); + }, + ], + run: (final context) { + trace.add('greet'); + return null; + }, + ); + final runner = TracingRunner( + trace, + globalOptions: [ + verbose, + ], + usageOutput: UsageOutputHandler(sinks: OutputSinks(err: err)), + subcommands: [command], + ); + runnerUsage = runner.usage; + try { + await runner.run(['greet']); + } on UsageException catch (e) { + error = e; + } + }); + + test( + 'when both options are omitted ' + 'then both commands report their errors', + () { + expect( + error?.message, + 'tool: Option `verbose` is mandatory.\n' + 'greet: Option `name` is mandatory.', + ); + }, + ); + + test('when both options are omitted then nothing runs', () { + expect(trace, isEmpty); + }); + + test( + 'when both options are omitted ' + 'then usage for the first command with errors is printed', + () { + expect(err.toString(), '${error!.message}\n\n$runnerUsage'); + }, + ); + }); + + group('Given a command option added after the command is created', () { + test( + 'when the command line sets that option ' + 'then the command receives the value', + () async { + const target = StringOption(argName: 'target'); + final command = CommandImpl.leafWithRunFunction( + name: 'build', + description: 'Build the app', + run: (final context) => context.config.optionalValue(target), + ); + command.addOption(target); + final runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [command], + ); + + expect( + await runner.run(['build', '--target', 'wasm']), + 'wasm', + ); + }, + ); + }); + + group('Given global, parent, and leaf options', () { + const verbose = FlagOption(argName: 'verbose', defaultsTo: false); + const profile = StringOption(argName: 'profile'); + const target = StringOption(argName: 'target'); + + late CommandContext leaf; + + setUp(() async { + final trace = []; + final check = RecordingCommand( + name: 'check', + description: 'Check the app', + trace: trace, + body: (final context) { + leaf = context; + return 'check'; + }, + ); + final build = RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + options: [target], + subcommands: [check], + ); + final group = RecordingCommand( + name: 'group', + description: 'Group of commands', + trace: trace, + options: [profile], + subcommands: [build], + ); + final runner = CommandRunner( + 'tool', + 'Tools', + globalOptions: [ + verbose, + ], + subcommands: [group], + ); + await runner.run([ + '--verbose', + 'group', + '--profile', + 'app', + 'build', + '--target', + 'wasm', + 'check', + ]); + }); + + test( + 'when the nested command line is run ' + 'then the leaf sees the parent command', + () { + expect(leaf.prev?.command.name, 'build'); + }, + ); + + test( + 'when the nested command line is run ' + 'then the leaf sees the parent option', + () { + expect(leaf.prev?.config.optionalValue(target), 'wasm'); + }, + ); + + test( + 'when the nested command line is run ' + 'then the leaf sees the grandparent command', + () { + expect(leaf.prev?.prev?.command.name, 'group'); + }, + ); + + test( + 'when the nested command line is run ' + 'then the leaf sees the grandparent option', + () { + expect(leaf.prev?.prev?.config.optionalValue(profile), 'app'); + }, + ); + + test( + 'when the nested command line is run ' + 'then the leaf sees the root command', + () { + expect(leaf.prev?.prev?.prev?.command.name, 'tool'); + }, + ); + + test( + 'when the nested command line is run ' + 'then the leaf sees the global option', + () { + expect(leaf.root().config.value(verbose), isTrue); + }, + ); + + test( + 'when the nested command line is run ' + 'then a parent option is not part of the leaf configuration', + () { + expect(leaf.config.findOption(argName: 'target'), isNull); + }, + ); + }); + + group('Given a persistent option on a branch command', () { + const profile = StringOption(argName: 'profile'); + + late String? seenByBranch; + late CommandContext? childContext; + + setUp(() async { + seenByBranch = null; + childContext = null; + final trace = []; + final child = RecordingCommand( + name: 'check', + description: 'Check the app', + trace: trace, + body: (final context) { + childContext = context; + return 'check'; + }, + ); + final branch = RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + subcommands: [child], + body: (final context) { + seenByBranch = context.config.optionalValue(profile); + return 'build'; + }, + ); + branch.addOption(profile, persistent: true); + final runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [branch], + ); + await runner.run(['build', '--profile', 'ci', 'check']); + }); + + test( + 'when the option is set on the branch command ' + 'then the branch command run is not invoked', + () { + expect(seenByBranch, isNull); + }, + ); + + test( + 'when the option is set on the branch command ' + 'then the child reads it from the parent configuration', + () { + expect(childContext?.prev?.config.optionalValue(profile), 'ci'); + }, + ); + + test( + 'when the option is set on the branch command ' + 'then the child configuration does not own it', + () { + expect(childContext?.config.findOption(argName: 'profile'), isNull); + }, + ); + }); + + group('Given a global option written after a subcommand', () { + const verbose = FlagOption(argName: 'verbose', defaultsTo: false); + + late CommandContext context; + + setUp(() async { + final command = CommandImpl.leafWithRunFunction( + name: 'build', + description: 'Build the app', + run: (final runContext) { + context = runContext; + return 'build'; + }, + ); + final runner = CommandRunner( + 'tool', + 'Tools', + globalOptions: [ + verbose, + ], + subcommands: [command], + ); + await runner.run(['build', '--verbose']); + }); + + test( + 'when the command line is run ' + 'then the global configuration has the option', + () { + expect(context.root().config.value(verbose), isTrue); + }, + ); + }); + + group('Given a persistent option written after a nested command', () { + const profile = StringOption(argName: 'profile'); + + late CommandContext leaf; + + setUp(() async { + final trace = []; + final check = RecordingCommand( + name: 'check', + description: 'Check the app', + trace: trace, + body: (final context) { + leaf = context; + return 'check'; + }, + ); + final build = RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + subcommands: [check], + ); + final group = RecordingCommand( + name: 'group', + description: 'Group of commands', + trace: trace, + subcommands: [build], + ); + group.addOption(profile, persistent: true); + final runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [group], + ); + await runner.run([ + 'group', + 'build', + 'check', + '--profile', + 'app', + ]); + }); + + test( + 'when the command line is run ' + 'then the command that defines the option receives it', + () { + expect(leaf.prev?.prev?.config.optionalValue(profile), 'app'); + }, + ); + + test( + 'when the command line is run ' + 'then the leaf configuration does not own the option', + () { + expect(leaf.config.findOption(argName: 'profile'), isNull); + }, + ); + + test( + 'when the command line is run ' + 'then the intermediate command does not own the option', + () { + expect(leaf.prev?.config.findOption(argName: 'profile'), isNull); + }, + ); + }); + + group( + 'Given a global option written on the root and again after a subcommand', + () { + const verbose = FlagOption(argName: 'verbose', defaultsTo: false); + + late UsageException? error; + late bool ran; + + setUp(() async { + error = null; + ran = false; + final command = CommandImpl.leafWithRunFunction( + name: 'build', + description: 'Build the app', + run: (final runContext) { + ran = true; + }, + ); + final runner = CommandRunner( + 'tool', + 'Tools', + globalOptions: [ + verbose, + ], + usageOutput: noUsageErrorOutput, + subcommands: [command], + ); + try { + await runner.run(['--verbose', 'build', '--verbose']); + } on UsageException catch (e) { + error = e; + } + }); + + test( + 'when the command line is run ' + 'then the repeated option is reported', + () { + expect( + error?.message, + 'build: Option --verbose cannot be specified more than once.', + ); + }, + ); + + test('when the command line is run then the command does not run', () { + expect(ran, isFalse); + }); + }, + ); + + group('Given a command option backed by an environment variable', () { + const user = StringOption(argName: 'user', envName: 'APP_USER'); + + test( + 'when run is given that variable ' + 'then the command receives the environment value', + () async { + final command = CommandImpl.leafWithRunFunction( + name: 'greet', + description: 'Greet', + options: [user], + run: (final context) => context.config.optionalValue(user), + ); + final runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [command], + ); + + expect( + await runner.run(['greet'], env: {'APP_USER': 'ada'}), + 'ada', + ); + }, + ); + }); + + group( + 'Given a command option that only allows certain environment values', + () { + const user = StringOption( + argName: 'user', + envName: 'APP_USER', + allowedValues: ['ada', 'grace'], + ); + + late List trace; + late UsageException? error; + late StringBuffer err; + late String commandUsage; + + setUp(() async { + trace = []; + error = null; + err = StringBuffer(); + final command = CommandImpl.leafWithRunFunction( + name: 'greet', + description: 'Greet', + options: [user], + middlewares: [ + (final next) => (final context) { + trace.add('middleware'); + return next(context); + }, + ], + run: (final context) { + trace.add('run'); + }, + ); + final runner = CommandRunner( + 'tool', + 'Tools', + usageOutput: UsageOutputHandler(sinks: OutputSinks(err: err)), + subcommands: [command], + ); + commandUsage = command.usage; + try { + await runner.run(['greet'], env: {'APP_USER': 'nope'}); + } on UsageException catch (e) { + error = e; + } + }); + + test('when the variable is not allowed then the value is reported', () { + expect( + error?.message, + 'greet: Invalid value for option `user`: ' + '`nope` is not an allowed value for option `user`.', + ); + }); + + test( + 'when the variable is not allowed ' + "then the error and that command's usage are printed", + () { + expect(err.toString(), '${error!.message}\n\n$commandUsage'); + }, + ); + + test( + 'when the variable is not allowed ' + 'then the command and its middleware do not run', + () { + expect(trace, isEmpty); + }, + ); + }, + ); + + group('Given a command with a configuration broker', () { + const user = StringOption(argName: 'user', configKey: 'user'); + + test( + 'when the broker has a value for the command option ' + 'then the command receives that value', + () async { + final command = _BrokerCommand( + name: 'greet', + description: 'Greet', + options: [user], + broker: _MapBroker({'user': 'ada'}), + run: (final context) => context.config.optionalValue(user), + ); + final runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [command], + ); + expect(await runner.run(['greet']), 'ada'); + }, + ); + }); + + group('Given a command option read from configuration', () { + const jobs = IntOption(argName: 'jobs', configKey: 'jobs'); + + late List trace; + late UsageException? error; + late StringBuffer err; + late String commandUsage; + + setUp(() async { + trace = []; + error = null; + err = StringBuffer(); + final command = _BrokerCommand( + name: 'greet', + description: 'Greet', + options: [jobs], + broker: _ValueBroker(true), + middlewares: [ + (final next) => (final context) { + trace.add('middleware'); + return next(context); + }, + ], + run: (final context) { + trace.add('run'); + }, + ); + final runner = CommandRunner( + 'tool', + 'Tools', + usageOutput: UsageOutputHandler(sinks: OutputSinks(err: err)), + subcommands: [command], + ); + commandUsage = command.usage; + try { + await runner.run(['greet']); + } on UsageException catch (e) { + error = e; + } + }); + + test( + 'when the configured value has the wrong type ' + 'then the value is reported', + () { + expect( + error?.message, + 'greet: Option `jobs` value true is of type bool, not int.', + ); + }, + ); + + test( + 'when the configured value has the wrong type ' + "then the error and that command's usage are printed", + () { + expect(err.toString(), '${error!.message}\n\n$commandUsage'); + }, + ); + + test( + 'when the configured value has the wrong type ' + 'then the command and its middleware do not run', + () { + expect(trace, isEmpty); + }, + ); + }); + + group('Given a runner with result type Object?', () { + test( + 'when a null-returning command runs under a runner middleware ' + 'then the command runs', + () async { + var ran = false; + final runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [ + CommandImpl.leafWithRunFunction( + name: 'date', + description: 'Display the current date', + run: (final CommandContext runContext) { + ran = true; + return null; + }, + ), + ], + middlewares: [const _ResultMiddleware().middleware], + ); + + await runner.run(['date']); + + expect(ran, isTrue); + }, + ); + }); +} + +/// Middleware class whose type arguments are inferred from the runner. +class _ResultMiddleware + extends MiddlewareHooks> { + const _ResultMiddleware(); +} + +/// A command that resolves configuration through [broker]. +class _BrokerCommand extends CommandImpl { + _BrokerCommand({ + required super.name, + required super.description, + required this.broker, + required final CommandRunFunction run, + super.options, + super.middlewares, + }) : _run = run; + + final ConfigurationBroker broker; + + final CommandRunFunction _run; + + @override + ConfigurationBroker? configBroker( + final CommandContext? prevContext, + ) => broker; + + @override + FutureOr run(final CommandContext context) => _run(context); +} + +class _MapBroker implements ConfigurationBroker { + _MapBroker(this.values); + + final Map values; + + @override + String? valueOrNull( + final String key, + final Configuration cfg, + ) { + return values[key]; + } +} + +class _ValueBroker implements ConfigurationBroker { + _ValueBroker(this.value); + + final Object? value; + + @override + Object? valueOrNull( + final String key, + final Configuration cfg, + ) { + return value; + } +} diff --git a/packages/config/test/command/command_tree_test.dart b/packages/config/test/command/command_tree_test.dart new file mode 100644 index 00000000..b98a1d64 --- /dev/null +++ b/packages/config/test/command/command_tree_test.dart @@ -0,0 +1,327 @@ +import 'package:config/command.dart'; +import 'package:config/config.dart'; +import 'package:test/test.dart'; + +void main() { + group('Given a command runner named tool', () { + final runner = CommandRunner( + 'tool', + 'Builds artifacts', + rootFooter: 'See docs', + ); + + test('when reading its name then the executable name is returned', () { + expect(runner.name, 'tool'); + }); + + test( + 'when reading the executable name ' + 'then the name passed to the runner is returned', + () { + expect(runner.executableName, 'tool'); + }, + ); + + test('when reading usage then the description is available', () { + expect(runner.usageDefinition.description, 'Builds artifacts'); + }); + + test('when reading usage then the footer is available', () { + expect(runner.usageDefinition.usageFooter, 'See docs'); + }); + + test('when reading subcommands then the list is empty', () { + expect(runner.subcommands, isEmpty); + }); + + test('when reading canRunAsLeafCommand then it is false', () { + expect(runner.canRunAsLeafCommand, isFalse); + }); + + test('when reading global options then there are none', () { + expect(runner.globalOptions, isEmpty); + }); + + test( + 'when reading the built-in global options ' + 'then the help flag and the completion option are included ' + 'since there are no subcommands', + () { + expect( + runner.builtinPersistentOptions.map( + (final option) => option.option.argName, + ), + ['help', 'completion'], + ); + }, + ); + + test( + 'when a subcommand is added afterwards ' + 'then the completion option gives way to the completion command', + () { + final runner = CommandRunner('tool', 'Tools') + ..addSubcommand( + CommandImpl.leafWithRunFunction( + name: 'build', + description: 'Build', + run: (final _) => null, + ), + ); + expect(runner.builtinPersistentOptions, [BuiltinGlobalOption.help]); + expect(runner.subcommands.map((final c) => c.name), [ + 'build', + 'completion', + 'help', + ]); + }, + ); + }); + + group('Given a runner with completion disabled', () { + final runner = CommandRunner( + 'tool', + 'Tools', + completion: CompletionSettings.disabled, + ); + + test( + 'when reading the built-in global options ' + 'then only the help flag is included', + () { + expect( + runner.builtinPersistentOptions.map( + (final option) => option.option.argName, + ), + ['help'], + ); + }, + ); + }); + + group('Given a runner that can run as a leaf', () { + final runner = CommandRunner( + 'tool', + 'Tools', + canRunAsLeafCommand: true, + ); + + test('when reading canRunAsLeafCommand then it is true', () { + expect(runner.canRunAsLeafCommand, isTrue); + }); + }); + + group('Given a runner with a global option', () { + const verbose = FlagOption(argName: 'verbose', defaultsTo: false); + final runner = CommandRunner( + 'tool', + 'Tools', + globalOptions: [verbose], + ); + + test( + 'when reading global options ' + 'then only the user option is included', + () { + expect( + runner.globalOptions.map((final option) => option.option.argName), + ['verbose'], + ); + }, + ); + }); + + group('Given a runner with a build command', () { + late Command build; + late CommandRunner runner; + + setUp(() { + build = CommandImpl.leafWithRunFunction( + name: 'build', + description: 'Build the app', + run: (final context) {}, + ); + runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [build], + ); + }); + + test( + 'when reading subcommands ' + 'then the command is followed by the built-in completion and help', + () { + expect( + runner.subcommands.map((final command) => command.name), + ['build', 'completion', 'help'], + ); + }, + ); + + test( + 'when reading subcommands ' + 'then the injected help command is hidden', + () { + expect(runner.subcommands.last.usageDefinition.hidden, isTrue); + }, + ); + + test( + 'when reading subcommands ' + 'then the injected help command is a help command', + () { + expect(runner.subcommands.last, isA()); + }, + ); + + test('when another command is added then help stays last', () { + final Command testCommand = + CommandImpl.leafWithRunFunction( + name: 'test', + description: 'Test the app', + run: (final context) {}, + ); + runner.addSubcommand(testCommand); + + expect( + runner.subcommands.map((final command) => command.name), + ['build', 'test', 'completion', 'help'], + ); + }); + }); + + group('Given a branch command', () { + late Command parent; + late Command child; + + setUp(() { + child = CommandImpl.leafWithRunFunction( + name: 'check', + description: 'Check the app', + run: (final context) {}, + ); + parent = CommandImpl.leafWithRunFunction( + name: 'build', + description: 'Build the app', + run: (final context) {}, + ); + // ignore: deprecated_member_use_from_same_package + parent.addSubcommand(child); + }); + + test( + 'when reading the branch subcommands ' + 'then the child is followed by its own help command', + () { + expect( + parent.subcommands.map((final command) => command.name), + ['check', 'help'], + ); + }, + ); + + test( + 'when the branch is added to a runner ' + 'then the runner help command is separate', + () { + final runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [parent], + ); + + expect( + runner.subcommands.map((final command) => command.name), + ['build', 'completion', 'help'], + ); + }, + ); + }); + + group('Given a command that is a subcommand of a runner', () { + late Command build; + late CommandRunner runner; + + Command leaf(final String name) => + CommandImpl.leafWithRunFunction( + name: name, + description: 'The $name command', + run: (final context) {}, + ); + + setUp(() { + build = leaf('build'); + runner = CommandRunner('tool', 'Tools', subcommands: [build]); + }); + + test( + 'when it is passed to another runner then a state error is thrown', + () { + expect( + () => CommandRunner( + 'other', + 'Other tools', + subcommands: [build], + ), + throwsStateError, + ); + }, + ); + + group('when it is added to another command', () { + late Command other; + late Object? error; + + setUp(() { + other = leaf('other'); + error = null; + try { + other.addSubcommand(build); + } catch (e) { + error = e; + } + }); + + test('then a state error is thrown', () { + expect(error, isStateError); + }); + + test('then the other command gains no subcommand', () { + expect(other.subcommands, isEmpty); + }); + + test('then it remains a subcommand of the runner', () { + expect(build.parent, same(runner)); + }); + }); + + test('when its parent is set again then a state error is thrown', () { + expect(() => build.parent = leaf('other'), throwsStateError); + }); + }); + + group('Given a command that already has a help command', () { + late Command help; + + setUp(() { + help = CommandImpl.leafWithRunFunction( + name: 'help', + description: 'Custom help', + run: (final context) {}, + ); + }); + + test('when reading subcommands then the custom help command is kept', () { + final runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [help], + completion: CompletionSettings.disabled, + ); + + expect(runner.subcommands, hasLength(1)); + expect(identical(runner.subcommands.single, help), isTrue); + }); + }); +} diff --git a/packages/config/test/command/command_validation_test.dart b/packages/config/test/command/command_validation_test.dart new file mode 100644 index 00000000..8348b29d --- /dev/null +++ b/packages/config/test/command/command_validation_test.dart @@ -0,0 +1,221 @@ +import 'package:config/command.dart'; +import 'package:config/config.dart'; +import 'package:test/test.dart'; + +import 'command_fixtures.dart'; + +void main() { + group('Given two subcommands with the same name', () { + late List trace; + late StringBuffer out; + late StringBuffer err; + late int usageHandlerCalls; + late TracingRunner runner; + + setUp(() { + trace = []; + out = StringBuffer(); + err = StringBuffer(); + usageHandlerCalls = 0; + final first = RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + ); + final second = RecordingCommand( + name: 'build', + description: 'Build again', + trace: trace, + ); + runner = TracingRunner( + trace, + middlewares: [ + (final next) => (final context) { + trace.add('root'); + return next(context); + }, + ], + usageOutput: UsageOutputHandler( + sinks: OutputSinks(out: out, err: err), + addExceptionHandlers: [ + ( + final UsageException exception, + final UsageOutputHandler usageOutput, { + required final CommandDefinition? fromCommand, + }) { + usageHandlerCalls++; + return exception; + }, + ], + ), + subcommands: [first, second], + ); + }); + + group('when the command line would also be invalid', () { + late Object? error; + + setUp(() async { + error = null; + try { + await runner.run(['missing', '--missing']); + } catch (e) { + error = e; + } + }); + + test('then a definition error is thrown', () { + expect(error, isA()); + }); + + test('then the duplicate command name is reported', () { + expect( + error.toString(), + 'CommandDefinitionError: Invalid definition for command `build`: ' + 'Duplicate subcommand name: build for command tool', + ); + }); + + test('then usage is not printed', () { + expect(out.toString(), isEmpty); + expect(err.toString(), isEmpty); + }); + + test('then usage exception handlers are not called', () { + expect(usageHandlerCalls, 0); + }); + + test('then no command or middleware runs', () { + expect(trace, isEmpty); + }); + }); + }); + + group('Given a branch command with a positional option', () { + late List trace; + late StringBuffer err; + late Object? error; + + setUp(() async { + trace = []; + err = StringBuffer(); + error = null; + final child = RecordingCommand( + name: 'check', + description: 'Check the app', + trace: trace, + ); + final parent = RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + options: const [ + StringOption(argName: 'file', argPos: 0), + ], + subcommands: [child], + middlewares: [ + (final next) => (final context) { + trace.add('middleware'); + return next(context); + }, + ], + ); + final runner = TracingRunner( + trace, + usageOutput: UsageOutputHandler(sinks: OutputSinks(err: err)), + subcommands: [parent], + ); + try { + await runner.run(['build', 'check']); + } catch (e) { + error = e; + } + }); + + test('when the runner is started then a definition error is thrown', () { + expect( + error, + isA().having( + (final error) => error.toString(), + 'toString', + 'CommandDefinitionError: Invalid definition for command `build`: ' + 'Cannot define positional options on a command with subcommands: ' + 'option `file`.', + ), + ); + }); + + test('when the runner is started then usage is not printed', () { + expect(err.toString(), isEmpty); + }); + + test( + 'when the runner is started ' + 'then no command or middleware runs', + () { + expect(trace, isEmpty); + }, + ); + }); + + group('Given a command with two options of the same name', () { + late List trace; + late StringBuffer err; + late Object? error; + + setUp(() async { + trace = []; + err = StringBuffer(); + error = null; + final command = RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + options: const [ + StringOption(argName: 'target'), + StringOption(argName: 'target'), + ], + middlewares: [ + (final next) => (final context) { + trace.add('middleware'); + return next(context); + }, + ], + ); + final runner = TracingRunner( + trace, + usageOutput: UsageOutputHandler(sinks: OutputSinks(err: err)), + subcommands: [command], + ); + try { + await runner.run(['build', '--missing']); + } catch (e) { + error = e; + } + }); + + test('when the runner is started then a definition error is thrown', () { + expect( + error, + isA().having( + (final error) => error.toString(), + 'toString', + 'OptionDefinitionError: Invalid definition for option `target`: ' + 'Duplicate argument name: target for target', + ), + ); + }); + + test('when the runner is started then usage is not printed', () { + expect(err.toString(), isEmpty); + }); + + test( + 'when the runner is started ' + 'then no command or middleware runs', + () { + expect(trace, isEmpty); + }, + ); + }); +} diff --git a/packages/config/test/command/completion/completion_command_test.dart b/packages/config/test/command/completion/completion_command_test.dart new file mode 100644 index 00000000..dab78217 --- /dev/null +++ b/packages/config/test/command/completion/completion_command_test.dart @@ -0,0 +1,1154 @@ +import 'dart:io' show Directory, File, stderr, stdout; + +import 'package:config/command.dart'; +import 'package:config/config.dart'; +import 'package:path/path.dart' as p; +import 'package:test/test.dart'; + +import 'fixtures/completion_cli.dart'; + +/// The script of the leaf runner, requested via the `--completion` option. +String _leafScript(final CompletionShell shell) => + shell.script('leaftool', viaOption: true); + +void main() { + late StringBuffer out; + late StringBuffer err; + late List trace; + late CommandRunner runner; + + UsageOutputHandler usage() => UsageOutputHandler( + sinks: OutputSinks(out: out, err: err), + ); + + setUp(() { + out = StringBuffer(); + err = StringBuffer(); + trace = []; + runner = buildCompletionCli( + usageOutput: usage(), + trace: trace, + completionOutput: out, + completionError: err, + ); + }); + + group('Given a runner with subcommands and default completion settings', () { + test('when listing the subcommands ' + 'then the completion command is included before help', () { + expect(runner.subcommands.map((final c) => c.name), [ + 'build', + 'deploy', + 'export', + 'internal', + 'version', + 'db', + 'completion', + 'help', + ]); + }); + + test('when printing the usage ' + 'then the completion command is listed', () { + expect(runner.usage, contains('completion')); + expect(runner.usage, contains('Generate a shell completion script.')); + }); + + for (final shell in CompletionShell.values) { + test( + 'when running `completion --shell ${shell.name}` ' + 'then the ${shell.displayName} script for the executable ' + 'is written to the output sink and the runner middleware runs', + () async { + final result = await runner.run([ + 'completion', + '--shell', + shell.name, + ]); + expect(result, isNull); + expect( + out.toString(), + shell.script( + 'comptool', + description: runner.usageDefinition.description, + ), + ); + expect(err.toString(), isEmpty); + expect(trace, ['middleware:comptool']); + }, + ); + } + + test( + 'when running `completion` without a shell ' + 'then the script of the shell detected in this environment is printed', + () async { + await runner.run(['completion']); + expect( + out.toString(), + detectCompletionShell()?.script( + 'comptool', + description: runner.usageDefinition.description, + ), + ); + }, + skip: detectCompletionShell() == null + ? 'No shell is detected in this environment' + : null, + ); + test('when running `completion` with an unknown shell ' + 'then a usage error listing the shells is reported', () async { + await expectLater( + runner.run(['completion', '--shell', 'tcsh']), + throwsA(isA()), + ); + expect(err.toString(), contains('bash')); + expect(err.toString(), contains('carapace')); + }); + + test('when running `completion bash` with the shell as an argument ' + 'then it is reported as an unknown subcommand', () async { + await expectLater( + runner.run(['completion', 'bash']), + throwsA( + isA().having( + (final e) => e.message, + 'message', + contains('Unknown subcommand: "bash"'), + ), + ), + ); + expect(out.toString(), isEmpty); + }); + + test('when running `completion --help` ' + 'then the installation instructions name the executable ' + 'and are part of the description, before the usage line', () async { + await runner.run(['completion', '--help']); + final output = out.toString(); + for (final shell in CompletionShell.values) { + expect(output, contains(shell.installInstruction('comptool'))); + } + expect(output, contains('Usage: comptool completion')); + expect( + output.indexOf('Manual installation:'), + inInclusiveRange(0, output.indexOf('Usage: comptool completion')), + ); + }); + + test('when running `completion --help` ' + 'then the install subcommand is described and listed', () async { + await runner.run(['completion', '--help']); + final output = out.toString(); + expect(output, contains('run `comptool completion install`')); + expect( + output, + matches(RegExp(r'install +Install the shell completion script')), + ); + }); + + test('when running `completion --help` ' + 'then the usage has the persistent options, with and without ' + 'a subcommand', () async { + await runner.run(['completion', '--help']); + expect( + out.toString(), + contains( + 'Usage: comptool completion [--shell=] ' + '[--command=] [arguments]\n' + ' or: comptool completion [--shell=] ' + '[--command=]\n', + ), + ); + }); + + test('when running `completion install --help` ' + 'then the usage of the install subcommand is printed', () async { + await runner.run(['completion', 'install', '--help']); + expect( + out.toString(), + contains('Usage: comptool completion install [--dry-run]'), + ); + }); + + test('when running `help completion` ' + 'then its usage is printed', () async { + await runner.run(['help', 'completion']); + expect( + out.toString(), + contains('Usage: comptool completion [--shell=]'), + ); + expect(err.toString(), isEmpty); + }); + + test('when running `completion --shell zsh` ' + 'then the script header has the installation instructions ' + 'for the completion command', () async { + await runner.run(['completion', '--shell', 'zsh']); + final output = out.toString(); + expect( + output, + contains('# Generated by `comptool completion --shell zsh`.'), + ); + for (final line + in CompletionShell.zsh.installInstructions('comptool').split('\n')) { + expect(output, contains('# $line')); + } + expect(output, isNot(contains('--completion'))); + }); + + test('when running `completion --shell bash --command mywrap` ' + 'then the script completes the wrapper name ' + 'and sends the requests to the executable directly', () async { + await runner.run([ + 'completion', + '--shell', + 'bash', + '--command', + 'mywrap', + ]); + final output = out.toString(); + expect(output, contains('complete -F __mywrap_complete mywrap')); + expect(output, contains("local cmd='comptool' out")); + expect( + output, + contains( + '# Generated by ' + '`comptool completion --shell bash --command mywrap`.', + ), + ); + expect( + output, + contains( + '# source <(comptool completion --shell bash --command mywrap)', + ), + ); + expect(output, contains('/etc/bash_completion.d/mywrap')); + expect(output, contains('requested from comptool directly')); + expect(output, isNot(contains('comptool_complete'))); + }); + + for (final shell in CompletionShell.values) { + test('when running `completion --shell ${shell.name} --command mywrap` ' + 'then the ${shell.displayName} script is for the wrapper', () async { + await runner.run([ + 'completion', + '--shell', + shell.name, + '--command', + 'mywrap', + ]); + expect( + out.toString(), + CompletionShell.values + .byName(shell.name) + .script( + 'comptool', + description: runner.usageDefinition.description, + commandName: 'mywrap', + ), + ); + }); + } + + test('when running `completion --shell zsh` ' + 'then the script completes the executable as typed', () async { + await runner.run(['completion', '--shell', 'zsh']); + expect(out.toString(), contains(r'cmd=${(Q)words[1]}')); + expect(out.toString(), isNot(contains("cmd='comptool'"))); + }); + + test('when running `--completion zsh` ' + 'then it is an unknown option since the runner has subcommands ' + 'and the completion command instead', () async { + await expectLater( + runner.run(['--completion', 'zsh']), + throwsA( + isA().having( + (final e) => e.message, + 'message', + contains('Unknown option: --completion'), + ), + ), + ); + expect(out.toString(), isEmpty); + }); + + test('when reading the built-in global options ' + 'then the completion option is not included', () { + expect(runner.builtinPersistentOptions, [BuiltinGlobalOption.help]); + }); + + test('when printing the usage ' + 'then the completion option is not listed', () { + expect(runner.usage, isNot(contains('--completion'))); + }); + + test('when running a regular command ' + 'then it runs as usual', () async { + final result = await runner.run(['build']); + expect(result, 0); + expect(trace, ['middleware:comptool', 'build']); + }); + }); + + group('Given a runner with completion disabled', () { + setUp(() { + runner = buildCompletionCli( + usageOutput: usage(), + completion: CompletionSettings.disabled, + trace: trace, + ); + }); + + test('when listing the subcommands ' + 'then there is no completion command', () { + expect(runner.subcommands.map((final c) => c.name), [ + 'build', + 'deploy', + 'export', + 'internal', + 'version', + 'db', + 'help', + ]); + }); + + test('when running `completion --shell bash` ' + 'then it is an unknown subcommand', () async { + await expectLater( + runner.run(['completion', '--shell', 'bash']), + throwsA(isA()), + ); + expect(out.toString(), isEmpty); + }); + + test('when running `--completion bash` ' + 'then it is an unknown option', () async { + await expectLater( + runner.run(['--completion', 'bash']), + throwsA(isA()), + ); + expect(out.toString(), isEmpty); + }); + + test('when running `__complete` ' + 'then it is an unknown subcommand', () async { + await expectLater( + runner.run(['__complete', '']), + throwsA(isA()), + ); + expect(out.toString(), isEmpty); + }); + }); + + group('Given a runner with a hidden completion command', () { + setUp(() { + runner = buildCompletionCli( + usageOutput: usage(), + completion: const CompletionSettings(hideCommand: true), + completionOutput: out, + completionError: err, + ); + }); + + test('when printing the usage ' + 'then the completion command is not listed', () { + expect(runner.usage, isNot(contains('Generate a shell completion'))); + expect(runner.usage, contains('build')); + }); + + test('when running `completion --shell fish` ' + 'then the script is still printed', () async { + await runner.run(['completion', '--shell', 'fish']); + expect(out.toString(), CompletionShell.fish.script('comptool')); + }); + + test('when completing the first word ' + 'then the completion command is not offered', () async { + await runner.run(['__complete', '']); + expect(out.toString(), isNot(contains('completion'))); + }); + }); + + // The shell detection depends on the processes and the environment the + // tests are run in, so here the shell is given. The commands with a + // detected shell, or with none, are tested in the shell integration tests, + // which control the environment of the fixture executable. + group('Given a completion command that installs into a home directory', () { + late Directory home; + + String homePath( + final String part1, [ + final String? part2, + final String? part3, + final String? part4, + final String? part5, + ]) => p.join(home.path, part1, part2, part3, part4, part5); + + setUp(() { + home = Directory.systemTemp.createTempSync('completion_command_test_'); + runner = buildCompletionCli( + usageOutput: usage(), + trace: trace, + completionOutput: out, + completionError: err, + extraCommands: [ + CompletionCommand( + installer: CompletionInstaller(environment: {'HOME': home.path}), + ), + ], + ); + }); + + tearDown(() => home.deleteSync(recursive: true)); + + group('when running `completion install --shell fish`', () { + late String scriptPath; + late int? result; + + setUp(() async { + scriptPath = homePath( + '.config', + 'fish', + 'completions', + 'comptool.fish', + ); + result = await runner.run(['completion', 'install', '--shell', 'fish']); + }); + + test('then the script of the given shell is saved ' + 'where the shell loads it from', () { + expect( + File(scriptPath).readAsStringSync(), + CompletionShell.fish.script( + 'comptool', + description: runner.usageDefinition.description, + ), + ); + }); + + test('then the steps are printed, followed by how to activate ' + 'the completion', () { + expect( + out.toString(), + 'Installing the Fish completion for comptool:\n' + ' Create directory ${p.dirname(scriptPath)}\n' + ' Write $scriptPath\n' + 'Fish loads it automatically, no reload needed.\n', + ); + }); + + test('then nothing is printed to the error sink', () { + expect(err.toString(), isEmpty); + }); + + test('then the runner returns null after running its middleware', () { + expect(result, isNull); + expect(trace, ['middleware:comptool']); + }); + }); + + group('when running `completion install --shell fish --dry-run`', () { + setUp(() async { + await runner.run([ + 'completion', + 'install', + '--shell', + 'fish', + '--dry-run', + ]); + }); + + test('then the steps are printed as a dry run, ' + 'without how to activate the completion', () { + final scriptPath = homePath( + '.config', + 'fish', + 'completions', + 'comptool.fish', + ); + expect( + out.toString(), + 'Installing the Fish completion for comptool ' + '(dry run, nothing is changed):\n' + ' Create directory ${p.dirname(scriptPath)}\n' + ' Write $scriptPath\n', + ); + }); + + test('then nothing is created in the home directory', () { + expect(home.listSync(), isEmpty); + }); + }); + + group('when running `completion --shell zsh install`', () { + setUp(() async { + await runner.run(['completion', '--shell', 'zsh', 'install']); + }); + + test('then the script of the given shell is saved', () { + expect( + File( + homePath('.local', 'share', 'zsh', 'site-functions', '_comptool'), + ).readAsStringSync(), + startsWith('#compdef comptool'), + ); + }); + + test('then the startup file of the shell loads the script', () { + expect( + File(homePath('.zshrc')).readAsStringSync(), + contains(p.join('site-functions', '_comptool')), + ); + }); + + test('then the added startup file lines are printed', () { + expect( + out.toString(), + contains( + ' Create ${homePath('.zshrc')}:\n' + ' # comptool shell completion, ' + 'added by `comptool completion install`.\n', + ), + ); + }); + }); + + test('when running `completion install --shell zsh --dry-run` ' + 'with the persistent option after the subcommand ' + 'then the steps for the given shell are printed ' + 'and nothing is created', () async { + await runner.run([ + 'completion', + 'install', + '--shell', + 'zsh', + '--dry-run', + ]); + expect( + out.toString(), + startsWith( + 'Installing the Zsh completion for comptool ' + '(dry run, nothing is changed):\n', + ), + ); + expect(home.listSync(), isEmpty); + }); + + test('when running `completion --shell fish install --command mywrap` ' + 'then the script for the wrapper is saved under its name', () async { + await runner.run([ + 'completion', + '--shell', + 'fish', + 'install', + '--command', + 'mywrap', + ]); + expect( + File( + homePath('.config', 'fish', 'completions', 'mywrap.fish'), + ).readAsStringSync(), + CompletionShell.fish.script( + 'comptool', + description: runner.usageDefinition.description, + commandName: 'mywrap', + ), + ); + expect( + out.toString(), + startsWith('Installing the Fish completion for mywrap:\n'), + ); + }); + + group('when running `completion install --shell bash` ' + 'with the path of a wrapper as the command name', () { + const wrapperContent = '#!/bin/sh\nexec comptool "\$@"\n'; + late File wrapper; + late Object? error; + + setUp(() async { + wrapper = File(homePath('bin', 'mywrap')); + wrapper.parent.createSync(); + wrapper.writeAsStringSync(wrapperContent); + error = null; + try { + await runner.run([ + 'completion', + 'install', + '--shell', + 'bash', + '--command', + wrapper.path, + ]); + } on UsageException catch (e) { + error = e; + } + }); + + test('then a usage error tells to specify the name of the command', () { + expect( + error, + isA().having( + (final e) => e.message, + 'message', + 'install: Cannot install the completion for "${wrapper.path}". ' + 'Specify the name of the command with --command, ' + 'not its path.', + ), + ); + }); + + test('then the wrapper is not overwritten', () { + expect(wrapper.readAsStringSync(), wrapperContent); + }); + + test('then nothing is created', () { + expect(home.listSync(recursive: true).map((final e) => e.path), [ + wrapper.parent.path, + wrapper.path, + ]); + }); + + test('then no installation is printed', () { + expect(out.toString(), isEmpty); + }); + }); + + test('when running `completion install --shell zsh --dry-run` ' + 'with a parent directory in the command name ' + 'then a usage error is reported', () async { + await expectLater( + runner.run([ + 'completion', + 'install', + '--shell', + 'zsh', + '--dry-run', + '--command', + '../mywrap', + ]), + throwsA(isA()), + ); + }); + + test('when running `completion install --shell fish` twice ' + 'then the second run only writes the script again', () async { + await runner.run(['completion', 'install', '--shell', 'fish']); + out.clear(); + await runner.run(['completion', 'install', '--shell', 'fish']); + expect( + out.toString(), + 'Installing the Fish completion for comptool:\n' + ' Write ' + '${homePath('.config', 'fish', 'completions', 'comptool.fish')}\n' + 'Fish loads it automatically, no reload needed.\n', + ); + }); + + test('when running `completion install` with an unexpected argument ' + 'then a usage error is reported and nothing is created', () async { + await expectLater( + runner.run(['completion', 'install', 'fish']), + throwsA(isA()), + ); + expect(home.listSync(), isEmpty); + }); + }); + + group('Given a runner defining its own completion subcommand', () { + setUp(() { + runner = buildCompletionCli( + usageOutput: usage(), + trace: trace, + extraCommands: [ + CommandImpl.leafWithRunFunction( + name: 'completion', + description: 'My own completion.', + run: (final _) { + trace.add('own completion'); + return 7; + }, + ), + ], + ); + }); + + test('when running `completion` then the own command runs', () async { + final result = await runner.run(['completion']); + expect(result, 7); + expect(trace, contains('own completion')); + }); + + test('when listing the subcommands ' + 'then the completion command appears once', () { + final names = runner.subcommands.map((final c) => c.name); + expect(names.where((final n) => n == 'completion'), hasLength(1)); + }); + + test('when running `--completion bash` ' + 'then it is an unknown option as well', () async { + await expectLater( + runner.run(['--completion', 'bash']), + throwsA(isA()), + ); + expect(out.toString(), isEmpty); + }); + }); + + group('Given a runner without subcommands', () { + setUp(() { + runner = buildLeafCompletionCli( + usageOutput: usage(), + completionOutput: out, + completionError: err, + ); + }); + + test('when listing the subcommands then there are none', () { + expect(runner.subcommands, isEmpty); + }); + + test('when reading the built-in global options ' + 'then the completion option is included', () { + expect(runner.builtinPersistentOptions, [ + BuiltinGlobalOption.help, + BuiltinGlobalOption.completion, + ]); + }); + + test('when running `--completion bash` ' + 'then the script header has the installation instructions ' + 'for the completion option', () async { + await runner.run(['--completion', 'bash']); + final output = out.toString(); + expect(output, contains('# Generated by `leaftool --completion bash`.')); + expect(output, contains('# source <(leaftool --completion bash)')); + expect(output, isNot(contains('leaftool completion'))); + }); + + test('when printing the usage ' + 'then the completion option is listed among the global options ' + 'with the shells as its values', () { + expect(runner.usage, contains('Global options:')); + expect( + runner.usage, + matches(RegExp(r'--completion +Print the shell completion script')), + ); + expect( + runner.usage, + contains('values: [bash, zsh, fish, powershell, carapace]'), + ); + }); + + test('when running `--completion bash` ' + 'then the Bash script for the executable is printed', () async { + final result = await runner.run(['--completion', 'bash']); + expect(result, isNull); + expect(out.toString(), _leafScript(CompletionShell.bash)); + }); + + test('when running `--completion=powershell` ' + 'then the PowerShell script is printed', () async { + await runner.run(['--completion=powershell']); + expect(out.toString(), _leafScript(CompletionShell.powershell)); + }); + + test('when running `--completion` without a shell ' + 'then the missing value is reported ' + 'along with the other usage errors', () async { + await expectLater( + runner.run(['--completion']), + throwsA( + isA().having( + (final e) => e.message, + 'message', + allOf( + contains('Missing value for option: --completion'), + contains('`target` is mandatory'), + ), + ), + ), + ); + expect(err.toString(), contains('Missing value for option')); + }); + + test('when running `--completion=` with an empty shell ' + 'then the invalid value is reported listing the shells', () async { + await expectLater( + runner.run(['--completion=']), + throwsA( + isA().having( + (final e) => e.message, + 'message', + allOf( + contains('Invalid value for option `completion`: ""'), + contains('bash|zsh|fish|powershell|carapace'), + ), + ), + ), + ); + }); + + test('when `--help` is given with an invalid `--completion` shell ' + 'then the invalid shell is reported', () async { + await expectLater( + runner.run(['--help', '--completion', 'ksh']), + throwsA( + isA().having( + (final e) => e.message, + 'message', + contains('Invalid value for option `completion`: "ksh"'), + ), + ), + ); + }); + + test('when running `--completion` with an unknown shell ' + 'then the invalid value is reported', () async { + await expectLater( + runner.run(['--completion', 'ksh']), + throwsA( + isA().having( + (final e) => e.message, + 'message', + contains( + 'Invalid value for option `completion`: "ksh" ' + 'is not in bash|zsh|fish|powershell|carapace', + ), + ), + ), + ); + }); + + test( + 'when running `--completion` with a shell in the wrong case ' + 'then the invalid value is reported since names are case sensitive', + () async { + await expectLater( + runner.run(['--completion', 'Bash']), + throwsA( + isA().having( + (final e) => e.message, + 'message', + contains('Invalid value for option `completion`: "Bash"'), + ), + ), + ); + }, + ); + + test('when `--completion ` is given with other arguments ' + 'then the script is printed and the mandatory option is not ' + 'required, like with the help option', () async { + await runner.run(['--mode', 'debug', '--completion', 'bash']); + expect(out.toString(), _leafScript(CompletionShell.bash)); + expect(err.toString(), isEmpty); + }); + + test( + 'when `--completion ` is given with an unknown option ' + 'then the unknown option is reported', + () async { + await expectLater( + runner.run(['--completion', 'bash', '--bogus']), + throwsA( + isA().having( + (final e) => e.message, + 'message', + contains('Unknown option: --bogus'), + ), + ), + ); + expect(out.toString(), isEmpty); + expect(err.toString(), contains('Unknown option: --bogus')); + }, + ); + + test('when running `__complete` then the request is served', () async { + await runner.run(['__complete', '--mode', '']); + expect( + out.toString(), + 'debug\tDebug build\nprofile\n' + 'release\tOptimized build\n:4\n', + ); + }); + }); + + group('Given the completion settings', () { + test('when created with defaults then completion is enabled, ' + 'the command is visible and the runner returns after ' + 'completion output', () { + const settings = CompletionSettings(); + expect(settings.enabled, isTrue); + expect(settings.hideCommand, isFalse); + expect(settings.exitAfterResponse, isFalse); + expect(settings.sinks.out, same(stdout)); + expect(settings.sinks.err, same(stderr)); + }); + + test('when disabled then completion is not enabled', () { + expect(CompletionSettings.disabled.enabled, isFalse); + }); + }); + + group('Given the completion shells', () { + test('when creating a shell identifier ' + 'then only letters, digits and underscores remain', () { + expect(shellIdentifier('my-tool'), 'my_tool'); + expect(shellIdentifier('my.tool'), 'my_tool'); + expect(shellIdentifier('1tool'), '_1tool'); + expect(shellIdentifier(''), '_'); + expect(shellIdentifier('tool'), 'tool'); + }); + + for (final shell in CompletionShell.values) { + test('when generating the ${shell.displayName} script ' + 'then it mentions the executable and the request command', () { + final script = shell.script('my-tool', description: 'My tool.'); + expect(script, contains('my-tool')); + expect(script, contains('__complete')); + }); + + test('when generating the ${shell.displayName} install instructions ' + 'then the long form contains the install command ' + 'and the short form adds the location', () { + final command = shell.installCommand('my-tool'); + expect(command, contains('my-tool completion --shell ${shell.name}')); + expect(shell.installInstructions('my-tool'), contains(command)); + final short = shell.installInstruction('my-tool'); + expect(short, startsWith(command)); + final location = shell.installLocation; + if (location != null) expect(short, endsWith('# in $location')); + }); + + test('when generating the ${shell.displayName} install instructions ' + 'then they end with how to activate the completion', () { + expect( + shell.installInstructions('my-tool'), + endsWith(shell.activationInstruction), + ); + }); + + test('when generating the ${shell.displayName} script for a wrapper ' + 'then it is installed under the wrapper name ' + 'and generated with the command option', () { + final script = shell.script('my-tool', commandName: 'wrap'); + expect( + script, + contains( + 'Generated by `my-tool completion --shell ${shell.name} ' + '--command wrap`.', + ), + ); + expect( + shell.installCommand('my-tool', commandName: 'wrap'), + allOf( + contains( + 'my-tool completion --shell ${shell.name} --command wrap', + ), + isNot(contains('my-tool.')), + ), + ); + expect( + shell.installInstructions('my-tool', commandName: 'wrap'), + isNot(contains('_my-tool')), + ); + }); + } + + test('when generating a script for a wrapper name with a quote ' + 'then the executable is quoted for the shell', () { + expect(shellQuote("it's"), r"'it'\''s'"); + expect( + CompletionShell.bash.script("it's", commandName: 'wrap'), + contains(r"local cmd='it'\''s' out"), + ); + expect( + CompletionShell.powershell.script("it's", commandName: 'wrap'), + contains(r"$program = 'it''s'"), + ); + }); + + test('when making a shell word of a plain name or path ' + 'then it is unchanged', () { + expect(shellWord('my-tool'), 'my-tool'); + expect(shellWord('~/bin/my_tool.sh'), '~/bin/my_tool.sh'); + }); + + test('when making a shell word of a name the shell would split or expand ' + 'then it is quoted', () { + expect(shellWord('/opt/My Tools/tool'), "'/opt/My Tools/tool'"); + expect(shellWord(r'$tool'), r"'$tool'"); + expect(shellWord(''), "''"); + }); + + test('when generating the script command for an executable path ' + 'with a space then the path is quoted', () { + expect( + CompletionShell.bash.scriptCommand('/opt/My Tools/tool'), + "'/opt/My Tools/tool' completion --shell bash", + ); + expect( + CompletionShell.fish.scriptCommand( + '/opt/My Tools/tool', + viaOption: true, + ), + "'/opt/My Tools/tool' --completion fish", + ); + }); + + test('when generating the PowerShell script command for an executable ' + 'path with a space then the quoted path is run with the call ' + 'operator', () { + expect( + CompletionShell.powershell.scriptCommand("/opt/My Tool's/tool"), + "& '/opt/My Tool''s/tool' completion --shell powershell", + ); + }); + + test('when generating the script command for a wrapper name ' + 'with a space then the name is quoted', () { + expect( + CompletionShell.zsh.scriptCommand('my-tool', commandName: 'my wrap'), + "my-tool completion --shell zsh --command 'my wrap'", + ); + expect( + CompletionShell.powershell.scriptCommand( + 'my-tool', + commandName: 'my wrap', + ), + "my-tool completion --shell powershell --command 'my wrap'", + ); + }); + + test('when generating the Bash script for a wrapper path with a space ' + 'then the completion is registered for the path as one word', () { + expect( + CompletionShell.bash.script('my-tool', commandName: '/tmp/my wrapper'), + endsWith("complete -F ___tmp_my_wrapper_complete '/tmp/my wrapper'\n"), + ); + }); + + test('when generating the Bash and Zsh install instructions ' + 'then the shell is reloaded with exec', () { + expect(CompletionShell.bash.activationInstruction, contains('exec bash')); + expect(CompletionShell.zsh.activationInstruction, contains('exec zsh')); + }); + + test('when generating the installation overview ' + 'then every shell has one line', () { + final lines = completionInstallationOverview('my-tool').split('\n'); + expect(lines.first, 'Installation:'); + expect(lines.skip(1), hasLength(CompletionShell.values.length)); + for (final shell in CompletionShell.values) { + expect( + lines, + contains( + allOf( + startsWith(' ${shell.displayName}:'), + endsWith(shell.installInstruction('my-tool')), + ), + ), + ); + } + }); + }); + + group('Given the Bash completion script', () { + final script = CompletionShell.bash.script('my-tool'); + + test('then it registers a completion function for the executable', () { + expect(script, contains('complete -F __my_tool_complete my-tool')); + }); + + test('then compopt is guarded for old Bash versions', () { + expect(script, contains('type compopt')); + }); + + test('then it handles all directives', () { + expect(script, contains('directiveError=1')); + expect(script, contains('directiveNoSpace=2')); + expect(script, contains('directiveNoFiles=4')); + expect(script, contains('directiveFileExt=8')); + expect(script, contains('directiveDirs=16')); + expect(script, contains('directiveKeepOrder=32')); + }); + }); + + group('Given the Zsh completion script', () { + final script = CompletionShell.zsh.script('my-tool'); + + test('then it is an autoloadable compdef file', () { + expect(script, startsWith('#compdef my-tool')); + expect(script, contains('compdef _my-tool my-tool')); + }); + + test('then it also works when sourced directly', () { + expect(script, contains(r'$funcstack[1]')); + }); + + test('then it uses the standard completion helpers', () { + expect(script, contains('_describe')); + expect(script, contains('_files')); + }); + }); + + group('Given the Fish completion script', () { + final script = CompletionShell.fish.script('my-tool'); + + test('then it registers a completion for the executable', () { + expect( + script, + contains("complete -c my-tool -f -a '(__my_tool_complete)'"), + ); + }); + + test('then it clears previous completions first', () { + expect(script, contains('complete -c my-tool -e')); + }); + }); + + group('Given the PowerShell completion script', () { + final script = CompletionShell.powershell.script('my-tool'); + + test('then it registers a native argument completer', () { + expect( + script, + contains("Register-ArgumentCompleter -Native -CommandName 'my-tool'"), + ); + }); + + test('then it uses the Cobra request command', () { + expect(script, contains('__complete')); + }); + }); + + group('Given the Carapace completion spec', () { + test('then it bridges to the Cobra protocol with parsing disabled', () { + final spec = CompletionShell.carapace.script( + 'my-tool', + description: 'My tool.\nMore.', + ); + expect(spec, contains('name: "my-tool"')); + expect(spec, contains('description: "My tool."')); + expect(spec, contains('parsing: disabled')); + expect(spec, contains(r'"$carapace.bridge.Cobra([my-tool])"')); + }); + + test('when the description contains quotes ' + 'then they are escaped', () { + final spec = CompletionShell.carapace.script( + 'my-tool', + description: 'Say "hi" \\ bye', + ); + expect(spec, contains(r'description: "Say \"hi\" \\ bye"')); + }); + + test('when there is no description then none is written', () { + final spec = CompletionShell.carapace.script('my-tool'); + expect(spec, isNot(contains('description:'))); + }); + }); +} diff --git a/packages/config/test/command/completion/completion_engine_test.dart b/packages/config/test/command/completion/completion_engine_test.dart new file mode 100644 index 00000000..392a1d55 --- /dev/null +++ b/packages/config/test/command/completion/completion_engine_test.dart @@ -0,0 +1,1086 @@ +import 'package:config/command.dart'; +import 'package:config/config.dart'; +import 'package:test/test.dart'; + +import 'fixtures/completion_cli.dart'; + +/// The parsed response of a `__complete` request. +typedef Response = ({List lines, int directive}); + +/// Runs a `__complete` request on [runner] and parses the response. +Future complete( + final CommandRunner runner, + final StringBuffer out, + final List words, { + final Map? env, +}) async { + final result = await runner.run(['__complete', ...words], env: env); + expect(result, isNull, reason: 'a completion request runs no command'); + final lines = out.toString().split('\n'); + expect(lines.last, isEmpty, reason: 'the response ends with a newline'); + lines.removeLast(); + final footer = lines.removeLast(); + expect(footer, startsWith(':'), reason: 'the response ends with :'); + return (lines: lines, directive: int.parse(footer.substring(1))); +} + +/// The candidate values of a response, without descriptions. +List valuesOf(final Response response) => + response.lines.map((final line) => line.split('\t').first).toList(); + +void main() { + late StringBuffer out; + late StringBuffer err; + late CommandRunner runner; + late List trace; + + setUp(() { + out = StringBuffer(); + err = StringBuffer(); + trace = []; + runner = buildCompletionCli( + usageOutput: UsageOutputHandler( + sinks: OutputSinks(out: out, err: err), + ), + trace: trace, + completionOutput: out, + completionError: err, + ); + }); + + group('Given a completion request for the first word', () { + test('when the word is empty then the non-hidden subcommands ' + 'including the built-in completion command are offered ' + 'with the first line of their description', () async { + final response = await complete(runner, out, ['']); + expect(response.lines, [ + 'build\tBuild the project.', + 'deploy\tDeploy a bundle to a target.', + 'export\tExport data in one of the formats.', + 'version\tDisplay the version.', + 'db\tDatabase commands.', + 'completion\tGenerate a shell completion script.', + ]); + expect(response.directive, CompletionDirective.noFileCompletion); + }); + + test('when the word is a prefix then only matching subcommands ' + 'are offered', () async { + final response = await complete(runner, out, ['d']); + expect(valuesOf(response), ['deploy', 'db']); + }); + + test('when the word is a dash then the global options and the ' + 'option-like command aliases are offered', () async { + final response = await complete(runner, out, ['-']); + expect(response.lines, [ + '--help\tPrint this usage information.', + '-h\tPrint this usage information.', + '--config\tThe configuration file.', + '-c\tThe configuration file.', + '--verbose\tPrint more.', + '--no-verbose\tPrint more.', + '--version\tDisplay the version.', + ]); + expect(response.directive, CompletionDirective.noFileCompletion); + }); + + test('when the word is a double dash then short options ' + 'are not offered', () async { + final response = await complete(runner, out, ['--']); + expect(valuesOf(response), [ + '--help', + '--config', + '--verbose', + '--no-verbose', + '--version', + ]); + }); + + test('when the word is a long option prefix ' + 'then only matching options are offered', () async { + final response = await complete(runner, out, ['--ver']); + expect(valuesOf(response), ['--verbose', '--version']); + }); + + test('then no command and no middleware is run', () async { + await complete(runner, out, ['']); + expect(trace, isEmpty); + }); + + test('when completing an option value ' + 'then the middlewares of the resolved commands run ' + 'and the command does not', () async { + await complete(runner, out, ['build', '--mode', '']); + expect(trace, ['middleware:comptool']); + }); + + test('then nothing is written to the error sink', () async { + await complete(runner, out, ['']); + expect(err.toString(), isEmpty); + }); + }); + + group('Given a completion request within a subcommand', () { + test('when the word is a dash then the subcommand options, ' + 'and the global options, but not hidden options, ' + 'are offered', () async { + final response = await complete(runner, out, ['build', '-']); + expect(valuesOf(response), [ + '--help', + '-h', + '--config', + '-c', + '--verbose', + '--no-verbose', + '--mode', + '-m', + '--out', + '-o', + '--tags', + '--jobs', + '-j', + '--project', + '--env', + '-e', + '--spec', + ]); + }); + + test('when an option was already given ' + 'then it is no longer offered', () async { + final response = await complete(runner, out, [ + '--verbose', + 'build', + '--mode', + 'debug', + '-', + ]); + expect(valuesOf(response), isNot(contains('--mode'))); + expect(valuesOf(response), isNot(contains('-m'))); + expect(valuesOf(response), isNot(contains('--verbose'))); + expect(valuesOf(response), contains('--out')); + }); + + test('when a multi-option was already given ' + 'then it is still offered', () async { + final response = await complete(runner, out, [ + 'build', + '--tags', + 'fast', + '--', + ]); + expect(valuesOf(response), contains('--tags')); + }); + + test('when the subcommand has no positional options ' + 'and the word is not an option then nothing is offered', () async { + final response = await complete(runner, out, ['build', '']); + expect(response.lines, isEmpty); + expect(response.directive, CompletionDirective.noFileCompletion); + }); + + test('when the command is nested ' + 'then its subcommands are offered', () async { + final response = await complete(runner, out, ['db', '']); + expect(response.lines, [ + 'migrate\tRun the migrations.', + 'seed\tSeed the database.', + ]); + }); + + test('when the command is nested ' + 'then its options are completed', () async { + final response = await complete(runner, out, [ + 'db', + 'migrate', + '--steps', + '', + ]); + expect(valuesOf(response), ['1', '5', '10']); + }); + }); + + group('Given a completion request for an option value', () { + test('when the option is an enum then its values are offered ' + 'with allowed help descriptions', () async { + final response = await complete(runner, out, ['build', '--mode', '']); + expect(response.lines, [ + 'debug\tDebug build', + 'profile', + 'release\tOptimized build', + ]); + expect(response.directive, CompletionDirective.noFileCompletion); + }); + + test('when the option is given by abbreviation ' + 'then its values are offered', () async { + final response = await complete(runner, out, ['build', '-m', '']); + expect(valuesOf(response), ['debug', 'profile', 'release']); + }); + + test('when the value is attached with an equals sign ' + 'then the bare values are offered', () async { + final response = await complete(runner, out, ['build', '--mode=re']); + expect(valuesOf(response), ['debug', 'profile', 'release']); + expect(response.directive, CompletionDirective.noFileCompletion); + }); + + test('when the value is attached to a cluster of abbreviations ' + 'then the values of the last option are offered', () async { + runner = buildCompletionCli( + completionOutput: out, + completionError: err, + extraCommands: [ + CommandImpl.leafWithRunFunction( + name: 'pack', + description: 'Pack the project.', + options: const [ + FlagOption(argName: 'fast', argAbbrev: 'f', negatable: false), + modeOption, + ], + run: (final _) => 0, + ), + ], + ); + final response = await complete(runner, out, ['pack', '-fm=r']); + expect(valuesOf(response), ['debug', 'profile', 'release']); + expect(response.directive, CompletionDirective.noFileCompletion); + }); + + test('when the option is a directory option ' + 'then directory completion is requested', () async { + final response = await complete(runner, out, ['build', '--out', '']); + expect(response.lines, isEmpty); + expect(response.directive, CompletionDirective.filterDirectories); + }); + + test('when the option is a file option ' + 'then file completion is requested', () async { + final response = await complete(runner, out, ['--config', '']); + expect(response.lines, isEmpty); + expect(response.directive, CompletionDirective.defaultDirective); + }); + + test('when the option completes files with given extensions ' + 'then extension filtered file completion is requested', () async { + final response = await complete(runner, out, ['build', '--spec', '']); + expect(response.lines, ['yaml', 'yml']); + expect(response.directive, CompletionDirective.filterFileExtensions); + }); + + test('when the option is an int option without allowed values ' + 'then file completion is requested', () async { + final response = await complete(runner, out, ['build', '--jobs', '']); + expect(response.lines, isEmpty); + expect(response.directive, CompletionDirective.defaultDirective); + }); + + test('when the option is a multi-option with allowed values ' + 'then the values are offered', () async { + final response = await complete(runner, out, ['build', '--tags', '']); + expect(valuesOf(response), ['fast', 'slow', 'net']); + }); + + test('when completing a later element of a multi-option list ' + 'then the earlier elements are kept as prefix', () async { + final response = await complete(runner, out, [ + 'build', + '--tags', + 'fast,s', + ]); + expect(valuesOf(response), ['fast,fast', 'fast,slow', 'fast,net']); + }); + + test('when the preceding option is a flag ' + 'then the word is not treated as its value', () async { + final response = await complete(runner, out, ['--verbose', '']); + expect(valuesOf(response), contains('build')); + }); + + test('when the option is given twice ' + 'then the values are still offered', () async { + final response = await complete(runner, out, [ + 'build', + '--mode', + 'debug', + '--mode', + '', + ]); + expect(valuesOf(response), ['debug', 'profile', 'release']); + }); + + test('when the option is an alias ' + 'then the option is still recognized', () async { + final response = await complete(runner, out, [ + 'build', + '--proj', + 'p', + '--env', + '', + ]); + expect(valuesOf(response), ['p-dev', 'p-prod', '!']); + }); + }); + + group('Given a custom option type overriding complete', () { + test('when completing its value then the custom candidates are ' + 'offered unfiltered, with the raw values of preceding options ' + 'available in the context', () async { + final response = await complete(runner, out, [ + 'build', + '--project', + 'acme', + '--env', + 'x', + ]); + expect(response.lines, [ + 'acme-dev\tDevelopment', + 'acme-prod\tProduction', + 'x!\tEcho', + ]); + }); + + test('when the preceding option is not given ' + 'then the context reports it as not parsed', () async { + final response = await complete(runner, out, ['build', '-e', '']); + expect(valuesOf(response), ['default-dev', 'default-prod', '!']); + }); + + test('when the custom completion throws ' + 'then an error response is given ' + 'and the failure is reported on the error sink', () async { + final response = await complete(runner, out, [ + 'build', + '--project', + 'boom', + '--env', + '', + ]); + expect(response.lines, isEmpty); + expect(response.directive, CompletionDirective.error); + expect(err.toString(), contains('Completion failed')); + expect(err.toString(), contains('completion failure')); + }); + }); + + group('Given custom option types that read their own parsed value ' + 'when completing', () { + setUp(() { + runner = buildCompletionCli( + completionOutput: out, + completionError: err, + extraCommands: [ + CommandImpl.leafWithRunFunction( + name: 'probe', + description: 'Probe.', + options: const [_OwnValueOption(), _OwnValuesOption()], + run: (final _) => 0, + ), + ], + ); + }); + + test('when completing the value of the option ' + 'then the option is not reported as parsed', () async { + final response = await complete(runner, out, ['probe', '--own', '']); + expect(valuesOf(response), ['not parsed']); + }); + + test( + 'when completing the value of the option given earlier as well ' + 'then the option is reported as parsed with the earlier value', + () async { + final response = await complete(runner, out, [ + 'probe', + '--own', + 'first', + '--own', + '', + ]); + expect(valuesOf(response), ['parsed: first']); + }, + ); + + test('when completing the first value of the multi-option ' + 'then the option is not reported as parsed', () async { + final response = await complete(runner, out, ['probe', '--owns', '']); + expect(valuesOf(response), ['not parsed']); + }); + + test( + 'when completing a later value of the multi-option ' + 'then the option is reported as parsed with the earlier values', + () async { + final response = await complete(runner, out, [ + 'probe', + '--owns', + 'first', + '--owns', + '', + ]); + expect(valuesOf(response), ['parsed: first']); + }, + ); + }); + + group('Given a completion request for positional arguments', () { + test('when completing the first positional argument ' + 'then its allowed values are offered', () async { + final response = await complete(runner, out, ['deploy', '']); + expect(response.lines, [ + 'staging\tStaging servers', + 'production\tLive servers', + ]); + }); + + test('when completing the second positional argument ' + 'then file completion is requested for the file option', () async { + final response = await complete(runner, out, ['deploy', 'staging', '']); + expect(response.lines, isEmpty); + expect(response.directive, CompletionDirective.defaultDirective); + }); + + test('when options are interleaved ' + 'then the positional index is unaffected', () async { + final response = await complete(runner, out, [ + 'deploy', + '--verbose', + 'staging', + '-c', + 'x.yaml', + '', + ]); + expect(response.directive, CompletionDirective.defaultDirective); + }); + + test('when all positional arguments are given ' + 'then nothing is offered', () async { + final response = await complete(runner, out, [ + 'deploy', + 'staging', + 'b.zip', + '', + ]); + expect(response.lines, isEmpty); + expect(response.directive, CompletionDirective.noFileCompletion); + }); + + test('when all positional arguments are given ' + 'and unexpected positional arguments are ignored ' + 'then file completion is requested', () async { + runner = buildCompletionCli( + usageOutput: UsageOutputHandler(sinks: OutputSinks(out: out)), + ignoreUnexpectedPositionalArgs: true, + completionOutput: out, + ); + final response = await complete(runner, out, [ + 'deploy', + 'staging', + 'b.zip', + '', + ]); + expect(response.directive, CompletionDirective.defaultDirective); + }); + + test('when completing after a redirection operator ' + 'then file completion is requested ' + 'instead of the command arguments', () async { + final response = await complete(runner, out, ['deploy', '>', '']); + expect(response.lines, isEmpty); + expect(response.directive, CompletionDirective.defaultDirective); + }); + + test('when completing after > before any command ' + 'then subcommands are not offered', () async { + final response = await complete(runner, out, ['>', '']); + expect(response.lines, isEmpty); + expect(response.directive, CompletionDirective.defaultDirective); + }); + + test('when the cursor word is a redirection operator without a space ' + 'then file completion is requested', () async { + final response = await complete(runner, out, ['build', '>']); + expect(response.lines, isEmpty); + expect(response.directive, CompletionDirective.defaultDirective); + }); + + test('when a filename is glued to the redirection operator ' + 'then file completion is requested', () async { + final response = await complete(runner, out, ['deploy', '>>st']); + expect(response.lines, isEmpty); + expect(response.directive, CompletionDirective.defaultDirective); + }); + + test('when a redirection precedes the cursor word ' + 'then the redirection and its filename are ignored', () async { + final response = await complete(runner, out, [ + '>', + 'out.txt', + 'bu', + ]); + expect(valuesOf(response), ['build']); + }); + + test('when a redirection follows an option value ' + 'then later options are still completed', () async { + final response = await complete(runner, out, [ + 'build', + '--jobs', + '2', + '>', + 'out.txt', + '--mo', + ]); + expect(valuesOf(response), ['--mode']); + }); + + test('when the cursor is after a here-document operator ' + 'then it is not treated as a file redirection', () async { + final response = await complete(runner, out, ['build', '<<', '']); + expect(response.lines, isEmpty); + expect(response.directive, CompletionDirective.noFileCompletion); + }); + + test('when completing after a double dash ' + 'and unexpected positional arguments are ignored ' + 'then file completion is requested', () async { + runner = buildCompletionCli( + usageOutput: UsageOutputHandler(sinks: OutputSinks(out: out)), + ignoreUnexpectedPositionalArgs: true, + completionOutput: out, + ); + final response = await complete(runner, out, ['build', '--', '-']); + expect(response.lines, isEmpty); + expect(response.directive, CompletionDirective.defaultDirective); + }); + }); + + group('Given a completion request with usage errors so far', () { + test('when an unknown option precedes the word ' + 'then completion still works', () async { + final response = await complete(runner, out, [ + '--bogus', + 'build', + '--mode', + '', + ]); + expect(valuesOf(response), ['debug', 'profile', 'release']); + }); + + test('when an unknown subcommand precedes the word ' + 'then nothing is offered', () async { + final response = await complete(runner, out, ['bogus', '']); + expect(response.lines, isEmpty); + expect(response.directive, CompletionDirective.noFileCompletion); + }); + + test('when there are no words at all ' + 'then it is treated as an empty first word', () async { + final response = await complete(runner, out, []); + expect(valuesOf(response), contains('build')); + }); + }); + + group('Given a completion request for the built-in commands', () { + test('when completing the completion command argument ' + 'then the install subcommand is offered', () async { + final response = await complete(runner, out, ['completion', '']); + expect(valuesOf(response), ['install']); + }); + + test('when completing the shell option of the completion command ' + 'then the shell names are offered', () async { + final response = await complete(runner, out, [ + 'completion', + '--shell', + '', + ]); + expect(valuesOf(response), [ + 'bash', + 'zsh', + 'fish', + 'powershell', + 'carapace', + ]); + }); + + test( + 'when completing the shell option after the install subcommand ' + 'then the shell names are offered since the option is persistent', + () async { + final response = await complete(runner, out, [ + 'completion', + 'install', + '--shell', + '', + ]); + expect(valuesOf(response), [ + 'bash', + 'zsh', + 'fish', + 'powershell', + 'carapace', + ]); + }, + ); + + test( + 'when completing a dash after the install subcommand ' + 'then its dry-run flag and the persistent options are offered', + () async { + final response = await complete(runner, out, [ + 'completion', + 'install', + '-', + ]); + expect( + valuesOf(response), + containsAll(['--dry-run', '--shell', '--command']), + ); + }, + ); + + test('when completing the help command argument ' + 'then the non-hidden commands are offered', () async { + final response = await complete(runner, out, ['help', '']); + expect(valuesOf(response), [ + 'build', + 'deploy', + 'export', + 'version', + 'db', + 'completion', + ]); + }); + }); + + group('Given options in mutually exclusive groups', () { + test('when none of the group is given ' + 'then all options of the group are offered', () async { + final response = await complete(runner, out, ['export', '-']); + expect( + valuesOf(response), + containsAll(['--json', '--yaml', '--stdin']), + ); + }); + + test('when an option of the group is given ' + 'then the other options of the group are no longer offered ' + 'while other groups are unaffected', () async { + final response = await complete(runner, out, ['export', '--json', '-']); + expect(valuesOf(response), isNot(contains('--json'))); + expect(valuesOf(response), isNot(contains('--yaml'))); + expect(valuesOf(response), contains('--stdin')); + }); + + test('when a positional option is in the group ' + 'and no other option of the group is given ' + 'then the positional argument is completed', () async { + final response = await complete(runner, out, ['export', '--yaml', '']); + expect(response.directive, CompletionDirective.defaultDirective); + }); + + test('when a positional option is in the group ' + 'and another option of the group is given ' + 'then the positional argument is not completed', () async { + final response = await complete(runner, out, ['export', '--stdin', '']); + expect(response.lines, isEmpty); + expect(response.directive, CompletionDirective.noFileCompletion); + }); + + test('when the positional option of the group is given ' + 'then the other options of the group are no longer offered', () async { + final response = await complete(runner, out, ['export', 'in.txt', '-']); + expect(valuesOf(response), isNot(contains('--stdin'))); + expect(valuesOf(response), contains('--json')); + }); + }); + + group('Given a tool without subcommands', () { + setUp(() { + runner = buildLeafCompletionCli( + usageOutput: UsageOutputHandler( + sinks: OutputSinks(out: out, err: err), + ), + completionOutput: out, + completionError: err, + ); + }); + + test('when completing the first word ' + 'then the positional values are offered', () async { + final response = await complete(runner, out, ['']); + expect(valuesOf(response), ['staging', 'production']); + }); + + test('when completing a dash then the options, including the ' + 'completion option and the named positional options, are offered ' + 'and there is no completion command', () async { + final response = await complete(runner, out, ['-']); + expect(valuesOf(response), [ + '--help', + '-h', + '--completion', + '--mode', + '-m', + '--target', + '--bundle', + ]); + }); + + test('when completing the value of the completion option ' + 'then the shells are offered', () async { + final response = await complete(runner, out, ['--completion', '']); + expect( + valuesOf(response), + CompletionShell.values.map((final shell) => shell.name), + ); + }); + }); + + group('Given middleware that publishes a service while completing', () { + const tokenOption = StringOption( + argName: 'token', + helpText: 'The access token.', + mandatory: true, + ); + + late _CompletionProbe probe; + + setUp(() { + probe = _CompletionProbe(); + trace = []; + runner = CommandRunner( + 'worktool', + 'Completes with resolved context.', + globalOptions: [verboseOption, endpointOption], + usageOutput: UsageOutputHandler( + sinks: OutputSinks(out: out, err: err), + ), + completion: CompletionSettings( + sinks: OutputSinks(out: out, err: err), + ), + middlewares: [ + Middlewares.withHooks( + onRun: (final ctx) { + trace.add('${ctx.command.name}:onRun:${ctx.runMode.name}'); + if (ctx.isCompletion && + ctx.leaf().config.options.contains(projectOption)) { + final project = ctx.leaf().config.optionalValue(projectOption); + ctx.provider.store(_ProjectApi(project ?? 'none')); + } + return ctx; + }, + onReturn: (final ctx, final result) { + trace.add('${ctx.command.name}:onReturn:${ctx.runMode.name}'); + return result; + }, + ), + ], + subcommands: [ + CommandImpl.branch( + name: 'db', + description: 'Database commands.', + middlewares: [ + Middlewares.onBeforeRun((final ctx) { + trace.add('db:onRun:${ctx.runMode.name}'); + }), + ], + subcommands: [ + CommandImpl.leafWithRunFunction( + name: 'migrate', + description: 'Run the migrations.', + options: [stepsOption], + middlewares: [ + Middlewares.onBeforeRun((final ctx) { + trace.add('migrate:onRun:${ctx.runMode.name}'); + }), + ], + run: (final ctx) { + trace.add('run:${ctx.command.name}:${ctx.runMode.name}'); + return 0; + }, + ), + ], + ), + CommandImpl.leafWithRunFunction( + name: 'work', + description: 'Work on a resource.', + options: [ + projectOption, + tokenOption, + _ContextNameOption(probe), + ], + run: (final ctx) { + trace.add('run:${ctx.command.name}:${ctx.runMode.name}'); + return 0; + }, + ), + ], + ); + }); + + test('when completing an option value ' + 'then middleware runs inside out before completion ' + 'and the command does not run', () async { + await complete(runner, out, ['db', 'migrate', '--steps', '']); + expect(trace, [ + 'worktool:onRun:completion', + 'db:onRun:completion', + 'migrate:onRun:completion', + 'worktool:onReturn:completion', + ]); + }); + + test('when completing an option value ' + 'then complete reads the resolved configurations ' + 'and the service middleware stored', () async { + final response = await complete( + runner, + out, + ['--verbose', 'work', '--project', 'acme', '--name', ''], + env: {'ENDPOINT': 'https://example.test'}, + ); + expect(valuesOf(response), ['alpha', 'beta', 'seen']); + expect(probe.project, 'acme'); + expect(probe.endpoint, 'https://example.test'); + expect(probe.verbose, isTrue); + expect(probe.apiProject, 'acme'); + expect(probe.leafMode, CommandRunMode.completion); + expect(probe.leafCommand, 'work'); + expect(probe.rootCommand, 'worktool'); + }); + + test('when a mandatory option is still missing ' + 'then completion still offers the values', () async { + final response = await complete(runner, out, ['work', '--name', '']); + expect(valuesOf(response), ['alpha', 'beta', 'seen']); + expect(err.toString(), isEmpty); + }); + + test('when the command is run ' + 'then middleware sees execution mode and the command runs', () async { + await runner.run([ + '--verbose', + 'work', + '--project', + 'acme', + '--token', + 'secret', + '--name', + 'alpha', + ]); + expect(trace, [ + 'worktool:onRun:execution', + 'run:work:execution', + 'worktool:onReturn:execution', + ]); + }); + }); + + group('Given a CompletionEngine used directly', () { + test('when completing then a response object is returned', () async { + final engine = CompletionEngine(runner); + final response = await engine.complete(['build', '--mode', 'd']); + expect(response.candidates.map((final c) => c.value), [ + 'debug', + 'profile', + 'release', + ]); + expect(response.directive, CompletionDirective.noFileCompletion); + expect(response.allowsFileCompletion, isFalse); + }); + + test('when the environment is given ' + 'then it is passed on to the completion context', () async { + final seen = {}; + final probe = CommandImpl.leafWithRunFunction( + name: 'probe', + description: 'Probe.', + options: [_ProbeOption(seen)], + run: (final _) => 0, + ); + runner = buildCompletionCli(extraCommands: [probe]); + final engine = CompletionEngine(runner); + await engine.complete( + ['probe', '--probe', ''], + environment: {'HOME': '/home/x'}, + ); + expect(seen, {'HOME': '/home/x'}); + }); + + test('when the completion fails then the error is reported ' + 'to the callback', () async { + Object? reported; + final engine = CompletionEngine( + runner, + onError: (final error, final _) => reported = error, + ); + final response = await engine.complete([ + 'build', + '--project', + 'boom', + '--env', + '', + ]); + expect(response.directive, CompletionDirective.error); + expect(reported, isA()); + }); + }); + + group('Given a CompletionResponse', () { + test('when formatted then tabs and newlines in candidates ' + 'are replaced', () { + const response = CompletionResponse( + [CompletionCandidate('a\tb', description: 'line1\nline2')], + directive: CompletionDirective.noFileCompletion, + ); + expect(response.format(), 'a b\tline1 line2\n:4\n'); + }); + + test('when formatted then spaces at the ends of a candidate value ' + 'are kept', () { + const response = CompletionResponse( + [CompletionCandidate(' report.csv ', description: ' A report ')], + directive: CompletionDirective.noFileCompletion, + ); + expect(response.format(), ' report.csv \tA report\n:4\n'); + }); + + test('when formatted then tabs and newlines at the ends of a ' + 'candidate value are dropped', () { + const response = CompletionResponse( + [CompletionCandidate('\treport.csv\r\n')], + directive: CompletionDirective.noFileCompletion, + ); + expect(response.format(), 'report.csv\n:4\n'); + }); + + test('when formatted with an empty description ' + 'then no tab is written', () { + const response = CompletionResponse( + [CompletionCandidate('a', description: '')], + directive: CompletionDirective.defaultDirective, + ); + expect(response.format(), 'a\n:0\n'); + }); + + test('when created from a no-space result ' + 'then the no-space directive is combined', () { + final response = CompletionResponse.fromResult( + CompletionResult.strings(['host:'], noSpace: true), + ); + expect( + response.directive, + CompletionDirective.noFileCompletion | CompletionDirective.noSpace, + ); + }); + + test('when created from a file extensions result ' + 'then the extensions are the candidates', () { + final response = CompletionResponse.fromResult( + const CompletionResult.files(extensions: ['yaml', 'yml']), + ); + expect(response.candidates.map((final c) => c.value), ['yaml', 'yml']); + expect(response.directive, CompletionDirective.filterFileExtensions); + expect(response.allowsFileCompletion, isTrue); + }); + }); +} + +const endpointOption = StringOption( + argName: 'endpoint', + envName: 'ENDPOINT', + helpText: 'The service endpoint.', + defaultsTo: 'http://localhost', +); + +class _ProjectApi { + final String project; + + _ProjectApi(this.project); +} + +class _CompletionProbe { + String? project; + String? endpoint; + bool? verbose; + String? apiProject; + CommandRunMode? leafMode; + String? leafCommand; + String? rootCommand; +} + +class _ContextNameOption extends StringOption { + final _CompletionProbe probe; + + _ContextNameOption(this.probe) + : super( + argName: 'name', + helpText: 'The resource name.', + allowedValues: const ['alpha', 'beta'], + ); + + @override + CompletionResult complete(final CompletionContext context) { + final leaf = commandContextOf(context); + final root = leaf?.root(); + probe.project = leaf?.config.optionalValue(projectOption); + probe.endpoint = root?.config.optionalValue(endpointOption); + probe.verbose = root?.config.optionalValue(verboseOption); + probe.apiProject = leaf?.provider.maybeFetch<_ProjectApi>()?.project; + probe.leafMode = leaf?.runMode; + probe.leafCommand = leaf?.command.name; + probe.rootCommand = root?.command.name; + return CompletionResult.strings(['alpha', 'beta', 'seen']); + } +} + +/// Offers whether it was parsed, and if so the value it was given. +class _OwnValueOption extends StringOption { + const _OwnValueOption() : super(argName: 'own'); + + @override + CompletionResult complete(final CompletionContext context) { + final args = context.parsedArgs; + return CompletionResult.strings([ + if (args.wasParsed(this)) + 'parsed: ${args.option(this)}' + else + 'not parsed', + ]); + } +} + +/// Offers whether it was parsed, and if so the values it was given. +class _OwnValuesOption extends MultiStringOption { + const _OwnValuesOption() : super(argName: 'owns'); + + @override + CompletionResult complete(final CompletionContext context) { + final args = context.parsedArgs; + return CompletionResult.strings([ + if (args.wasParsed(this)) + 'parsed: ${args.multiOption(this).join(' ')}' + else + 'not parsed', + ]); + } +} + +class _ProbeOption extends StringOption { + final Map seen; + + const _ProbeOption(this.seen) : super(argName: 'probe'); + + @override + CompletionResult complete(final CompletionContext context) { + seen.addAll(context.environment); + expect(context.command.name, 'probe'); + expect(context.commands.first.name, 'comptool'); + expect(context.precedingWords, ['probe', '--probe']); + expect(context.wordToComplete, ''); + return const CompletionResult.none(); + } +} diff --git a/packages/config/test/command/completion/completion_installer_test.dart b/packages/config/test/command/completion/completion_installer_test.dart new file mode 100644 index 00000000..56c69f42 --- /dev/null +++ b/packages/config/test/command/completion/completion_installer_test.dart @@ -0,0 +1,673 @@ +import 'dart:convert' show utf8; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:config/command.dart'; +import 'package:path/path.dart' as p; +import 'package:test/test.dart'; + +const _script = '# the completion script\n'; + +/// A text encoding with code units of a fixed number of bytes. +class _FixedWidthEncoding { + final String name; + final int unitSize; + final Endian endian; + + const _FixedWidthEncoding(this.name, this.unitSize, this.endian); + + List encode(final String text) { + final units = unitSize == 2 ? text.codeUnits : text.runes.toList(); + final data = ByteData(units.length * unitSize); + for (final (index, unit) in units.indexed) { + if (unitSize == 2) { + data.setUint16(index * unitSize, unit, endian); + } else { + data.setUint32(index * unitSize, unit, endian); + } + } + return data.buffer.asUint8List(); + } + + String decode(final Uint8List bytes) { + expect(bytes.length % unitSize, 0, reason: 'whole code units'); + final data = ByteData.sublistView(bytes); + return String.fromCharCodes([ + for (var i = 0; i < bytes.length; i += unitSize) + unitSize == 2 ? data.getUint16(i, endian) : data.getUint32(i, endian), + ]); + } +} + +const _utf16LittleEndian = _FixedWidthEncoding('UTF-16LE', 2, Endian.little); + +/// The encodings that are recognized by their byte order mark. +const _markedEncodings = [ + _utf16LittleEndian, + _FixedWidthEncoding('UTF-16BE', 2, Endian.big), + _FixedWidthEncoding('UTF-32LE', 4, Endian.little), + _FixedWidthEncoding('UTF-32BE', 4, Endian.big), +]; + +void main() { + late Directory home; + + /// A path below the home directory, in POSIX style like the installers + /// under test, which install for Linux or macOS. + String inHome(final String relativePath) => '${home.path}/$relativePath'; + + CompletionInstaller newInstaller({ + final Map environment = const {}, + final String operatingSystem = 'linux', + }) { + return CompletionInstaller( + environment: {'HOME': home.path, ...environment}, + operatingSystem: operatingSystem, + ); + } + + List plan( + final CompletionInstaller installer, + final CompletionShell shell, { + final String name = 'mytool', + }) { + return installer.plan( + shell, + name: name, + script: _script, + executableName: 'mytool', + ); + } + + void install( + final CompletionInstaller installer, + final CompletionShell shell, + ) { + for (final step in plan(installer, shell)) { + step.perform(); + } + } + + List descriptions(final List steps) => [ + for (final step in steps) step.description, + ]; + + setUp(() { + home = Directory.systemTemp.createTempSync('completion_installertest_'); + }); + + tearDown(() => home.deleteSync(recursive: true)); + + group('Given an installer for an empty home directory on Linux', () { + test('when planning the Bash installation ' + 'then the script is written to the bash-completion user directory ' + 'and sourced from a new .bashrc', () { + final script = inHome('.local/share/bash-completion/completions/mytool'); + expect(descriptions(plan(newInstaller(), CompletionShell.bash)), [ + 'Create directory ${p.posix.dirname(script)}', + 'Write $script', + 'Create ${inHome('.bashrc')}:\n' + ' # mytool shell completion, ' + 'added by `mytool completion install`.\n' + " [ -r '$script' ] && source '$script'", + ]); + }); + + test('when planning the Zsh installation ' + 'then the script is written as a function file ' + 'and sourced from a new .zshrc after ensuring compinit', () { + final script = inHome('.local/share/zsh/site-functions/_mytool'); + expect(descriptions(plan(newInstaller(), CompletionShell.zsh)), [ + 'Create directory ${p.posix.dirname(script)}', + 'Write $script', + 'Create ${inHome('.zshrc')}:\n' + ' # mytool shell completion, ' + 'added by `mytool completion install`.\n' + r' (( $+functions[compdef] )) || ' + '{ autoload -Uz compinit && compinit; }\n' + " [[ -r '$script' ]] && source '$script'", + ]); + }); + + test('when planning the Fish installation ' + 'then the script is written to the Fish completions directory ' + 'and no startup file is changed', () { + final script = inHome('.config/fish/completions/mytool.fish'); + expect(descriptions(plan(newInstaller(), CompletionShell.fish)), [ + 'Create directory ${p.posix.dirname(script)}', + 'Write $script', + ]); + }); + + test('when planning the PowerShell installation ' + 'then the script is written next to the profile, which loads it, ' + 'and their directory is created once', () { + final script = inHome('.config/powershell/Completions/mytool.ps1'); + final profile = inHome( + '.config/powershell/Microsoft.PowerShell_profile.ps1', + ); + expect(descriptions(plan(newInstaller(), CompletionShell.powershell)), [ + 'Create directory ${p.posix.dirname(script)}', + 'Write $script', + 'Create $profile:\n' + ' # mytool shell completion, ' + 'added by `mytool completion install`.\n' + " if (Test-Path -LiteralPath '$script') { . '$script' }", + ]); + }); + + test('when planning the Carapace installation ' + 'then the spec is written to the Carapace specs directory ' + 'and no startup file is changed', () { + final spec = inHome('.config/carapace/specs/mytool.yaml'); + expect(descriptions(plan(newInstaller(), CompletionShell.carapace)), [ + 'Create directory ${p.posix.dirname(spec)}', + 'Write $spec', + ]); + }); + + test('when planning an installation for another command name ' + 'then the script is named after that command', () { + final steps = plan(newInstaller(), CompletionShell.zsh, name: 'mywrap'); + expect( + descriptions(steps), + contains( + 'Write ${inHome('.local/share/zsh/site-functions/_mywrap')}', + ), + ); + expect( + descriptions(steps).last, + contains( + '# mywrap shell completion, added by `mytool completion install`.', + ), + ); + }); + + for (final shell in CompletionShell.values) { + test('when planning the ${shell.displayName} installation ' + 'then nothing is created', () { + plan(newInstaller(), shell); + expect(home.listSync(), isEmpty); + }); + + test('when performing the ${shell.displayName} installation ' + 'then the script is at the script path', () { + final installer = newInstaller(); + install(installer, shell); + expect( + File(installer.scriptPath(shell, 'mytool')).readAsStringSync(), + _script, + ); + }); + } + + test('when performing the Bash installation ' + 'then the startup file has the comment and the line that sources ' + 'the script', () { + install(newInstaller(), CompletionShell.bash); + final script = inHome('.local/share/bash-completion/completions/mytool'); + expect( + File(inHome('.bashrc')).readAsStringSync(), + '# mytool shell completion, added by `mytool completion install`.\n' + "[ -r '$script' ] && source '$script'\n", + ); + }); + + test('when the home directory has a quote in its path ' + 'then the script path is quoted for the shell', () { + final quoted = Directory("${home.path}/it's")..createSync(); + final installer = CompletionInstaller( + environment: {'HOME': quoted.path}, + operatingSystem: 'linux', + ); + install(installer, CompletionShell.bash); + expect( + File('${quoted.path}/.bashrc').readAsStringSync(), + contains( + r"[ -r '" + '${home.path}' + r"/it'\''s/.local/", + ), + ); + }); + }); + + group('Given an installer for a home directory with startup files', () { + test('when the startup file ends with a newline ' + 'then the lines are appended after an empty line', () { + File(inHome('.bashrc')).writeAsStringSync('alias ll="ls -l"\n'); + final steps = plan(newInstaller(), CompletionShell.bash); + expect(steps.last.description, startsWith('Append to ')); + for (final step in steps) { + step.perform(); + } + expect( + File(inHome('.bashrc')).readAsStringSync(), + startsWith('alias ll="ls -l"\n\n# mytool shell completion, '), + ); + }); + + test('when the startup file does not end with a newline ' + 'then the lines are appended after an empty line', () { + File(inHome('.zshrc')).writeAsStringSync('alias ll="ls -l"'); + install(newInstaller(), CompletionShell.zsh); + expect( + File(inHome('.zshrc')).readAsStringSync(), + startsWith('alias ll="ls -l"\n\n# mytool shell completion, '), + ); + }); + + test('when the startup file is empty ' + 'then the lines are written from its start', () { + File(inHome('.zshrc')).writeAsStringSync(''); + install(newInstaller(), CompletionShell.zsh); + expect( + File(inHome('.zshrc')).readAsStringSync(), + startsWith('# mytool shell completion, '), + ); + }); + + test('when the startup file is not valid UTF-8 ' + 'then the lines are appended and its content is kept', () { + File(inHome('.bashrc')).writeAsBytesSync([0x23, 0xff, 0xfe, 0x0a]); + install(newInstaller(), CompletionShell.bash); + final bytes = File(inHome('.bashrc')).readAsBytesSync(); + expect(bytes.sublist(0, 4), [0x23, 0xff, 0xfe, 0x0a]); + expect(String.fromCharCodes(bytes.sublist(4)), contains('source')); + }); + + test('when the startup file is UTF-8 with a byte order mark ' + 'then the lines are appended as UTF-8 after its content', () { + const content = [0xef, 0xbb, 0xbf, 0x23, 0x0a]; + File(inHome('.bashrc')).writeAsBytesSync(content); + install(newInstaller(), CompletionShell.bash); + final bytes = File(inHome('.bashrc')).readAsBytesSync(); + expect(bytes.sublist(0, content.length), content); + expect( + utf8.decode(bytes.sublist(content.length)), + startsWith('\n# mytool shell completion, '), + ); + }); + + group('when the installation has been performed already', () { + late CompletionInstaller installer; + late String startupFileContent; + + setUp(() { + installer = newInstaller(); + File(inHome('.zshrc')).writeAsStringSync('alias ll="ls -l"\n'); + install(installer, CompletionShell.zsh); + startupFileContent = File(inHome('.zshrc')).readAsStringSync(); + }); + + test('then the plan only writes the script ' + 'and notes that the startup file is kept', () { + expect(descriptions(plan(installer, CompletionShell.zsh)), [ + 'Write ${inHome('.local/share/zsh/site-functions/_mytool')}', + 'Keep ${inHome('.zshrc')}, it already loads the script', + ]); + }); + + test('then performing it again leaves the startup file unchanged', () { + install(installer, CompletionShell.zsh); + expect(File(inHome('.zshrc')).readAsStringSync(), startupFileContent); + }); + + test('then installing for another command name appends its lines', () { + final steps = plan(installer, CompletionShell.zsh, name: 'mywrap'); + expect(steps.last.description, startsWith('Append to ')); + }); + }); + }); + + // Windows PowerShell writes UTF-16 with a byte order mark by default, + // and PowerShell reads any of these encodings by their byte order mark. + for (final encoding in _markedEncodings) { + group('Given a PowerShell profile ' + 'in ${encoding.name} with a byte order mark', () { + const existing = "# Ã…ke's profile\r\n"; + const script = '.config/powershell/Completions/mytool.ps1'; + late File profile; + + setUp(() { + profile = File( + inHome('.config/powershell/Microsoft.PowerShell_profile.ps1'), + ); + profile.parent.createSync(recursive: true); + profile.writeAsBytesSync(encoding.encode('\ufeff$existing')); + }); + + test('when performing the PowerShell installation ' + 'then the lines are appended in the encoding of the profile', () { + install(newInstaller(), CompletionShell.powershell); + final path = inHome(script); + expect( + encoding.decode(profile.readAsBytesSync()), + '\ufeff$existing\n' + '# mytool shell completion, added by `mytool completion install`.\n' + "if (Test-Path -LiteralPath '$path') { . '$path' }\n", + ); + }); + + test('when planning the installation after it has been performed ' + 'then the profile is kept', () { + install(newInstaller(), CompletionShell.powershell); + expect( + descriptions(plan(newInstaller(), CompletionShell.powershell)).last, + 'Keep ${profile.path}, it already loads the script', + ); + }); + }); + } + + group('Given a PowerShell profile ' + 'with only the UTF-16 byte order mark', () { + test('when performing the PowerShell installation ' + 'then the lines follow the byte order mark directly', () { + final profile = File( + inHome('.config/powershell/Microsoft.PowerShell_profile.ps1'), + ); + profile.parent.createSync(recursive: true); + profile.writeAsBytesSync([0xff, 0xfe]); + install(newInstaller(), CompletionShell.powershell); + expect( + _utf16LittleEndian.decode(profile.readAsBytesSync()), + startsWith('\ufeff# mytool shell completion, '), + ); + }); + }); + + group('Given an installer and a name that is not a command name', () { + const names = { + 'an absolute path': '/home/me/bin/mywrap', + 'a relative path': 'bin/mywrap', + 'a path to a parent directory': '../mywrap', + 'a Windows path': r'C:\bin\mywrap', + 'the current directory': '.', + 'the parent directory': '..', + 'empty': '', + 'a name with a newline': 'my\nwrap', + }; + + for (final MapEntry(key: description, value: name) in names.entries) { + test('when planning an installation for a name that is $description ' + 'then it fails with an argument error', () { + for (final shell in CompletionShell.values) { + expect( + () => plan(newInstaller(), shell, name: name), + throwsArgumentError, + reason: shell.displayName, + ); + } + }); + + test('when asking for the script path of a name that is $description ' + 'then it fails with an argument error', () { + expect( + () => newInstaller().scriptPath(CompletionShell.bash, name), + throwsArgumentError, + ); + }); + + test('when asking if a name that is $description is a command name ' + 'then it is not', () { + expect(CompletionInstaller.isCommandName(name), isFalse); + }); + } + + for (final name in ['mytool', 'my-tool.sh', 'my tool', '_my:tool', '...']) { + test('when asking if "$name" is a command name then it is', () { + expect(CompletionInstaller.isCommandName(name), isTrue); + }); + } + }); + + group('Given an installer with XDG and shell directory variables', () { + test('when XDG_DATA_HOME is set ' + 'then the Bash and Zsh scripts are installed below it', () { + final installer = newInstaller(environment: {'XDG_DATA_HOME': '/data'}); + expect( + installer.scriptPath(CompletionShell.bash, 'mytool'), + '/data/bash-completion/completions/mytool', + ); + expect( + installer.scriptPath(CompletionShell.zsh, 'mytool'), + '/data/zsh/site-functions/_mytool', + ); + }); + + test('when BASH_COMPLETION_USER_DIR is set ' + 'then the Bash script is installed below it', () { + final installer = newInstaller( + environment: { + 'XDG_DATA_HOME': '/data', + 'BASH_COMPLETION_USER_DIR': '/bash-completion', + }, + ); + expect( + installer.scriptPath(CompletionShell.bash, 'mytool'), + '/bash-completion/completions/mytool', + ); + }); + + test('when XDG_CONFIG_HOME is set ' + 'then the Fish script, the Carapace spec and the PowerShell profile ' + 'are below it', () { + final installer = newInstaller( + environment: {'XDG_CONFIG_HOME': '/config'}, + ); + expect( + installer.scriptPath(CompletionShell.fish, 'mytool'), + '/config/fish/completions/mytool.fish', + ); + expect( + installer.scriptPath(CompletionShell.carapace, 'mytool'), + '/config/carapace/specs/mytool.yaml', + ); + expect( + installer.startupFilePath(CompletionShell.powershell), + '/config/powershell/Microsoft.PowerShell_profile.ps1', + ); + }); + + test('when an XDG variable is empty then it is ignored', () { + final installer = newInstaller(environment: {'XDG_CONFIG_HOME': ''}); + expect( + installer.scriptPath(CompletionShell.fish, 'mytool'), + inHome('.config/fish/completions/mytool.fish'), + ); + }); + + test('when ZDOTDIR is set then its .zshrc is the Zsh startup file', () { + final installer = newInstaller(environment: {'ZDOTDIR': '/zdotdir'}); + expect( + installer.startupFilePath(CompletionShell.zsh), + '/zdotdir/.zshrc', + ); + }); + + test('when asking for the startup file of Fish and Carapace ' + 'then there is none', () { + expect(newInstaller().startupFilePath(CompletionShell.fish), isNull); + expect(newInstaller().startupFilePath(CompletionShell.carapace), isNull); + }); + }); + + group('Given an installer for macOS', () { + CompletionInstaller macInstaller() => + newInstaller(operatingSystem: 'macos'); + + test('when the home directory has no Bash startup file ' + 'then .bash_profile is the Bash startup file', () { + expect( + macInstaller().startupFilePath(CompletionShell.bash), + inHome('.bash_profile'), + ); + }); + + test('when the home directory has a .profile but no .bash_profile ' + 'then .profile is the Bash startup file, since a new .bash_profile ' + 'would replace it', () { + File(inHome('.profile')).createSync(); + File(inHome('.bashrc')).createSync(); + expect( + macInstaller().startupFilePath(CompletionShell.bash), + inHome('.profile'), + ); + }); + + test('when the home directory has a .bash_login and a .profile ' + 'then .bash_login is the Bash startup file', () { + File(inHome('.profile')).createSync(); + File(inHome('.bash_login')).createSync(); + expect( + macInstaller().startupFilePath(CompletionShell.bash), + inHome('.bash_login'), + ); + }); + + test('when asking for the Carapace spec path ' + 'then it is in the Application Support directory', () { + expect( + macInstaller().scriptPath(CompletionShell.carapace, 'mytool'), + inHome('Library/Application Support/carapace/specs/mytool.yaml'), + ); + }); + }); + + group('Given an installer for Windows', () { + CompletionInstaller windowsInstaller({ + final Map environment = const { + 'USERPROFILE': r'C:\Users\me', + }, + final String? profile, + }) { + return CompletionInstaller( + environment: environment, + operatingSystem: 'windows', + powerShellProfile: () => profile, + ); + } + + test('when PowerShell reports its profile ' + 'then the profile is the startup file ' + 'and the script is installed next to it', () { + const profile = + r'C:\Users\me\OneDrive\Documents\PowerShell' + r'\Microsoft.PowerShell_profile.ps1'; + final installer = windowsInstaller(profile: profile); + expect(installer.startupFilePath(CompletionShell.powershell), profile); + expect( + installer.scriptPath(CompletionShell.powershell, 'mytool'), + r'C:\Users\me\OneDrive\Documents\PowerShell\Completions\mytool.ps1', + ); + }); + + test('when PowerShell does not report its profile ' + 'then the default profile of PowerShell is the startup file', () { + expect( + windowsInstaller().startupFilePath(CompletionShell.powershell), + r'C:\Users\me\Documents\PowerShell\Microsoft.PowerShell_profile.ps1', + ); + }); + + test('when the script path has a quote ' + 'then it is quoted for PowerShell in the profile', () { + final steps = + windowsInstaller( + profile: r"C:\Users\O'Hara\Documents\PowerShell\profile.ps1", + ).plan( + CompletionShell.powershell, + name: 'mytool', + script: _script, + executableName: 'mytool', + ); + expect( + steps.last.description, + contains( + r"if (Test-Path -LiteralPath 'C:\Users\O''Hara\Documents" + r"\PowerShell\Completions\mytool.ps1') " + r"{ . 'C:\Users\O''Hara\Documents" + r"\PowerShell\Completions\mytool.ps1' }", + ), + ); + }); + + test('when asking for the Carapace spec path ' + 'then it is in the roaming application data directory', () { + expect( + windowsInstaller( + environment: const { + 'USERPROFILE': r'C:\Users\me', + 'APPDATA': r'D:\Roaming', + }, + ).scriptPath(CompletionShell.carapace, 'mytool'), + r'D:\Roaming\carapace\specs\mytool.yaml', + ); + }); + + test('when HOME is set, as in Git Bash, ' + 'then the Bash startup file is in that directory', () { + expect( + windowsInstaller( + environment: const { + 'HOME': r'C:\Users\gitbash', + 'USERPROFILE': r'C:\Users\me', + }, + ).startupFilePath(CompletionShell.bash), + r'C:\Users\gitbash\.bashrc', + ); + }); + }); + + group('Given an installer without a home directory', () { + test('when planning an installation on Linux ' + 'then it fails naming the HOME variable', () { + final installer = CompletionInstaller( + environment: const {}, + operatingSystem: 'linux', + ); + expect( + () => plan(installer, CompletionShell.zsh), + throwsA( + isA().having( + (final e) => e.message, + 'message', + contains('HOME is not set'), + ), + ), + ); + }); + + test('when planning an installation on Windows ' + 'then it fails naming the USERPROFILE variable', () { + final installer = CompletionInstaller( + environment: const {}, + operatingSystem: 'windows', + powerShellProfile: () => null, + ); + expect( + () => plan(installer, CompletionShell.powershell), + throwsA( + isA().having( + (final e) => e.message, + 'message', + contains('USERPROFILE is not set'), + ), + ), + ); + }); + + test('when all locations are given by other variables ' + 'then the home directory is not needed', () { + final installer = CompletionInstaller( + environment: const {'XDG_CONFIG_HOME': '/config'}, + operatingSystem: 'linux', + ); + expect( + installer.scriptPath(CompletionShell.fish, 'mytool'), + '/config/fish/completions/mytool.fish', + ); + }); + }); +} diff --git a/packages/config/test/command/completion/completion_shell_detection_test.dart b/packages/config/test/command/completion/completion_shell_detection_test.dart new file mode 100644 index 00000000..932c1be5 --- /dev/null +++ b/packages/config/test/command/completion/completion_shell_detection_test.dart @@ -0,0 +1,179 @@ +import 'package:config/command.dart'; +import 'package:test/test.dart'; + +/// Detects the shell from [ancestors], the command lines of the ancestor +/// processes (nearest first), and the login shell. +CompletionShell? _detect( + final List> ancestors, { + final String? loginShell, + final bool isWindows = false, +}) { + return detectCompletionShell( + environment: {'SHELL': ?loginShell}, + ancestorCommandLines: ancestors, + isWindows: isWindows, + ); +} + +void main() { + group('Given a program started from a shell the user types in', () { + const shells = <(List, CompletionShell)>[ + (['bash'], CompletionShell.bash), + (['-bash'], CompletionShell.bash), + (['/opt/homebrew/bin/bash'], CompletionShell.bash), + (['-/opt/homebrew/bin/bash', '--posix'], CompletionShell.bash), + (['bash', '--login', '-i'], CompletionShell.bash), + (['-zsh'], CompletionShell.zsh), + (['/bin/zsh', '-l'], CompletionShell.zsh), + (['/usr/bin/zsh-5.9'], CompletionShell.zsh), + (['fish'], CompletionShell.fish), + (['/usr/local/bin/fish', '--private'], CompletionShell.fish), + (['pwsh'], CompletionShell.powershell), + (['/usr/bin/pwsh', '-NoLogo'], CompletionShell.powershell), + ([r'C:\Program Files\PowerShell\7\pwsh.exe'], CompletionShell.powershell), + (['PowerShell.EXE', '-NoProfile'], CompletionShell.powershell), + ]; + for (final (commandLine, shell) in shells) { + test('when the parent process is `${commandLine.join(' ')}` ' + 'then ${shell.displayName} is detected', () { + expect(_detect([commandLine]), shell); + }); + } + + test('when the login shell is another shell ' + 'then the shell the program is started from is detected', () { + expect( + _detect([ + ['fish'], + ], loginShell: '/bin/zsh'), + CompletionShell.fish, + ); + }); + + test('when that shell was started from another shell ' + 'then the nearest one is detected', () { + expect( + _detect([ + ['fish'], + ['-zsh'], + ]), + CompletionShell.fish, + ); + }); + }); + + group('Given a program started through other processes', () { + test('when the parent process is not a shell ' + 'then the shell above it is detected', () { + expect( + _detect([ + ['dart', 'run', 'bin/mytool.dart'], + ['-zsh'], + ]), + CompletionShell.zsh, + ); + }); + + test('when the parent process is a shell running a wrapper script ' + 'then the shell above it is detected', () { + expect( + _detect([ + ['bash', '/usr/local/bin/mywrap', 'completion'], + ['fish'], + ]), + CompletionShell.fish, + ); + }); + + test('when the parent process is a shell running a command ' + 'then the shell above it is detected', () { + expect( + _detect([ + ['zsh', '-c', 'mytool', 'completion'], + ['-bash'], + ]), + CompletionShell.bash, + ); + }); + + test('when the parent process is a shell without completion support ' + 'then the shell above it is detected', () { + expect( + _detect([ + ['/bin/sh', '/usr/local/bin/mywrap'], + ['tcsh'], + ['-zsh'], + ]), + CompletionShell.zsh, + ); + }); + + test('when a process has no command line ' + 'then the shell above it is detected', () { + expect( + _detect([ + [], + ['-zsh'], + ]), + CompletionShell.zsh, + ); + }); + }); + + group('Given a program without a shell the user types in above it', () { + const ancestors = [ + ['dart', 'test'], + ['bash', '-c', 'dart test'], + ['/sbin/launchd'], + ]; + + for (final MapEntry(key: loginShell, value: shell) in { + '/bin/bash': CompletionShell.bash, + '/bin/zsh': CompletionShell.zsh, + '/opt/homebrew/bin/fish': CompletionShell.fish, + '/usr/bin/pwsh': CompletionShell.powershell, + }.entries) { + test('when the login shell is $loginShell ' + 'then ${shell.displayName} is detected', () { + expect(_detect(ancestors, loginShell: loginShell), shell); + }); + } + + test('when the login shell has no completion support ' + 'then no shell is detected', () { + expect(_detect(ancestors, loginShell: '/bin/tcsh'), isNull); + }); + + test('when there is no login shell then no shell is detected', () { + expect(_detect(ancestors), isNull); + }); + }); + + group('Given a program on Windows', () { + test('when there is no login shell then PowerShell is detected', () { + expect(_detect([], isWindows: true), CompletionShell.powershell); + }); + + test('when the login shell is Bash, as in Git Bash, ' + 'then Bash is detected', () { + expect( + _detect([], loginShell: r'C:\Program Files\Git\usr\bin\bash.exe'), + CompletionShell.bash, + ); + }); + + test('when the login shell has no completion support ' + 'then PowerShell is detected', () { + expect( + _detect([], loginShell: '/usr/bin/sh', isWindows: true), + CompletionShell.powershell, + ); + }); + }); + + group('Given the environment and the processes of the test', () { + test('when detecting the shell then it completes normally', () { + expect(detectCompletionShell, returnsNormally); + }); + }); +} diff --git a/packages/config/test/command/completion/fixtures/completion_cli.dart b/packages/config/test/command/completion/fixtures/completion_cli.dart new file mode 100644 index 00000000..55d81d1f --- /dev/null +++ b/packages/config/test/command/completion/fixtures/completion_cli.dart @@ -0,0 +1,332 @@ +/// A command line tool exercising the completion support. +/// +/// Used in-process by the completion unit tests, and compiled to an +/// executable named `comptool` by the shell integration tests. +library; + +import 'dart:async' show FutureOr; +import 'dart:io' show Platform, exitCode; + +import 'package:config/command.dart'; +import 'package:config/config.dart'; + +enum BuildMode { debug, profile, release } + +const configOption = FileOption( + argName: 'config', + argAbbrev: 'c', + helpText: 'The configuration file.', +); + +const verboseOption = FlagOption( + argName: 'verbose', + helpText: 'Print more.\nSecond line of the help text.', + negatable: true, + defaultsTo: false, +); + +const modeOption = EnumOption( + enumParser: EnumParser(BuildMode.values), + argName: 'mode', + argAbbrev: 'm', + helpText: 'The build mode.', + allowedHelp: { + 'debug': 'Debug build', + 'release': 'Optimized build', + }, +); + +const outOption = DirOption( + argName: 'out', + argAbbrev: 'o', + helpText: 'The output directory.', +); + +const tagsOption = MultiStringOption( + argName: 'tags', + helpText: 'The tags.', + allowedValues: ['fast', 'slow', 'net'], +); + +const jobsOption = IntOption( + argName: 'jobs', + argAbbrev: 'j', + helpText: 'The number of jobs.', +); + +const secretOption = StringOption( + argName: 'secret', + helpText: 'Not shown.', + hide: true, +); + +const projectOption = StringOption( + argName: 'project', + argAliases: ['proj'], + helpText: 'The project.', +); + +/// A custom option type with a custom, context dependent completion list. +class EnvironmentOption extends StringOption { + const EnvironmentOption({super.argName, super.argAbbrev, super.helpText}); + + @override + FutureOr complete(final CompletionContext context) async { + final args = context.parsedArgs; + final project = args.wasParsed(projectOption) + ? args.option(projectOption) + : 'default'; + if (project == 'boom') throw StateError('completion failure'); + await Future.delayed(Duration.zero); + return CompletionResult.values([ + CompletionCandidate('$project-dev', description: 'Development'), + CompletionCandidate('$project-prod', description: 'Production'), + CompletionCandidate('${context.wordToComplete}!', description: 'Echo'), + ]); + } +} + +const envOption = EnvironmentOption( + argName: 'env', + argAbbrev: 'e', + helpText: 'The environment.', +); + +/// A custom file option type completing only files with given extensions. +class YamlFileOption extends FileOption { + const YamlFileOption({super.argName, super.helpText}); + + @override + CompletionResult complete(final CompletionContext context) { + return const CompletionResult.files(extensions: ['yaml', 'yml']); + } +} + +const specOption = YamlFileOption( + argName: 'spec', + helpText: 'The build specification file.', +); + +const targetOption = StringOption( + argName: 'target', + argPos: 0, + mandatory: true, + helpText: 'The deployment target.', + allowedValues: ['staging', 'production'], + allowedHelp: {'staging': 'Staging servers', 'production': 'Live servers'}, +); + +const bundleOption = FileOption( + argName: 'bundle', + argPos: 1, + helpText: 'The bundle to deploy.', +); + +const stepsOption = IntOption( + argName: 'steps', + helpText: 'The number of migration steps.', + allowedValues: [1, 5, 10], +); + +const formatGroup = MutuallyExclusive( + 'Output format', + mode: MutuallyExclusiveMode.mandatory, +); + +const jsonOption = FlagOption( + argName: 'json', + helpText: 'Output JSON.', + negatable: false, + group: formatGroup, +); + +const yamlOption = FlagOption( + argName: 'yaml', + helpText: 'Output YAML.', + negatable: false, + group: formatGroup, +); + +const inputGroup = MutuallyExclusive('Input'); + +const stdinOption = FlagOption( + argName: 'stdin', + helpText: 'Read standard input.', + negatable: false, + group: inputGroup, +); + +const inputOption = FileOption( + argName: 'input', + argPos: 0, + helpText: 'The input file.', + group: inputGroup, +); + +/// The default settings for the in-process tests: completion output must not +/// exit the test process. +const inProcessCompletion = CompletionSettings(exitAfterResponse: false); + +/// [settings] with the test capture sinks, when those sinks are given. +CompletionSettings _withCompletionSinks( + final CompletionSettings settings, { + final StringSink? output, + final StringSink? errorOutput, +}) { + if (output == null && errorOutput == null) return settings; + return CompletionSettings( + enabled: settings.enabled, + hideCommand: settings.hideCommand, + exitAfterResponse: settings.exitAfterResponse, + sinks: OutputSinks(out: output, err: errorOutput), + ); +} + +CommandRunner buildCompletionCli({ + final UsageOutputHandler? usageOutput, + final CompletionSettings completion = inProcessCompletion, + final StringSink? completionOutput, + final StringSink? completionError, + final bool ignoreUnexpectedPositionalArgs = false, + final List? trace, + final List> extraCommands = const [], +}) { + int? run(final CommandContext context) { + trace?.add(context.command.name); + return 0; + } + + return CommandRunner( + 'comptool', + 'A tool for testing command line completion.\nMore description.', + globalOptions: [ + configOption, + verboseOption, + ], + usageOutput: usageOutput, + completion: _withCompletionSinks( + completion, + output: completionOutput, + errorOutput: completionError, + ), + ignoreUnexpectedPositionalArgs: ignoreUnexpectedPositionalArgs, + middlewares: [ + Middlewares.onBeforeRun((final ctx) { + trace?.add('middleware:${ctx.command.name}'); + }), + ], + subcommands: [ + CommandImpl.leafWithRunFunction( + name: 'build', + description: 'Build the project.\nIn one of the build modes.', + options: [ + modeOption, + outOption, + tagsOption, + jobsOption, + secretOption, + projectOption, + envOption, + specOption, + ], + run: run, + ), + CommandImpl.leafWithRunFunction( + name: 'deploy', + description: 'Deploy a bundle to a target.', + options: [targetOption, bundleOption], + run: run, + ), + CommandImpl.leafWithRunFunction( + name: 'export', + description: 'Export data in one of the formats.', + options: [jsonOption, yamlOption, stdinOption, inputOption], + run: run, + ), + CommandImpl.leafWithRunFunction( + name: 'internal', + description: 'A hidden command.', + hidden: true, + run: run, + ), + CommandImpl.leafWithRunFunction( + name: 'version', + aliases: ['--version'], + description: 'Display the version.', + run: run, + ), + CommandImpl.branch( + name: 'db', + description: 'Database commands.', + subcommands: [ + CommandImpl.leafWithRunFunction( + name: 'migrate', + description: 'Run the migrations.', + options: [stepsOption], + run: run, + ), + CommandImpl.leafWithRunFunction( + name: 'seed', + description: 'Seed the database.', + run: run, + ), + ], + ), + ...extraCommands, + ], + ); +} + +/// A tool without subcommands: options and positional arguments only. +CommandRunner buildLeafCompletionCli({ + final UsageOutputHandler? usageOutput, + final CompletionSettings completion = inProcessCompletion, + final StringSink? completionOutput, + final StringSink? completionError, + final bool ignoreUnexpectedPositionalArgs = false, +}) { + return CommandRunner( + 'leaftool', + 'A tool without subcommands.', + globalOptions: const [modeOption], + usageOutput: usageOutput, + completion: _withCompletionSinks( + completion, + output: completionOutput, + errorOutput: completionError, + ), + canRunAsLeafCommand: true, + ignoreUnexpectedPositionalArgs: ignoreUnexpectedPositionalArgs, + ) + // Positional options can't be persistent, add them as regular options. + ..addOption(targetOption) + ..addOption(bundleOption); +} + +/// Printed after the runner returns, as a program might do. The fixture +/// exits after completion output, so this never follows a completion +/// response or script. +const afterRunnerMarker = '>>> result:'; + +/// The environment variable that, when set, makes the compiled fixture +/// report usage errors without throwing a [UsageException]. +const noUsageExceptionVariable = 'COMPTOOL_NO_USAGE_EXCEPTION'; + +Future main(final List args) async { + try { + final result = await buildCompletionCli( + usageOutput: Platform.environment.containsKey(noUsageExceptionVariable) + ? UsageOutputHandler( + exceptionSettings: const UsageExceptionSettings( + noUsageException: true, + ), + ) + : null, + completion: const CompletionSettings(exitAfterResponse: true), + ).run(args); + print('$afterRunnerMarker $result'); + exitCode = result ?? 0; + } on UsageException { + exitCode = 64; + } +} diff --git a/packages/config/test/command/completion/shell_integration_test.dart b/packages/config/test/command/completion/shell_integration_test.dart new file mode 100644 index 00000000..cdbbfd84 --- /dev/null +++ b/packages/config/test/command/completion/shell_integration_test.dart @@ -0,0 +1,1748 @@ +/// Integration tests running the fixture CLI compiled to an executable: +/// the completion protocol as a process, and the generated completion +/// scripts in the real shells. +/// +/// Each shell's tests run only if the shell is installed. To make them +/// mandatory (as in CI), list the shells in the environment variable +/// `CLI_COMPLETION_SHELLS`, e.g. `CLI_COMPLETION_SHELLS=bash,zsh,fish`; +/// the tests for a listed shell that is not installed then fail. +/// The shell executables are looked up on the PATH, or can be given +/// explicitly as `CLI_COMPLETION_BASH`, `CLI_COMPLETION_ZSH`, +/// `CLI_COMPLETION_FISH`, `CLI_COMPLETION_PWSH` and `CLI_COMPLETION_CARAPACE`. +/// +/// On Windows, only the process-level tests and the PowerShell tests run; +/// the other shells' harnesses are POSIX scripts. +@Timeout(Duration(minutes: 5)) +library; + +import 'dart:convert' show jsonDecode, utf8; +import 'dart:io'; + +import 'package:config/command.dart' show CompletionShell; +import 'package:path/path.dart' as p; +import 'package:test/test.dart'; + +import 'fixtures/completion_cli.dart' + show afterRunnerMarker, buildCompletionCli, noUsageExceptionVariable; + +const _exeName = 'comptool'; + +/// A wrapper script of the executable, for which completion is installed +/// with `completion --shell --command mywrap`. +const _wrapperName = 'mywrap'; + +/// The shells (and completion frameworks) under test, by executable name. +const _shells = ['bash', 'zsh', 'fish', 'pwsh', 'carapace']; + +/// The shells whose harnesses run on this platform. +final _platformShells = Platform.isWindows ? const ['pwsh'] : _shells; + +void main() { + final required = (Platform.environment['CLI_COMPLETION_SHELLS'] ?? '') + .split(',') + .map((final s) => s.trim()) + .where((final s) => s.isNotEmpty) + .toSet(); + final installed = { + for (final shell in _platformShells) shell: _findShell(shell), + }; + for (final shell in required) { + if (installed[shell] == null) { + test('Given $shell is required by CLI_COMPLETION_SHELLS ' + 'then it is installed and tested on this platform', () { + fail( + _platformShells.contains(shell) + ? '$shell is not installed or not on the PATH' + : '$shell is not tested on ${Platform.operatingSystem}', + ); + }); + } + } + + final env = _Environment(); + + setUpAll(() async { + await env.setUp(); + }); + + tearDownAll(() { + env.tearDown(); + }); + + _executableTests(env); + + String? skipUnless(final String shell) { + if (!_platformShells.contains(shell)) { + return '$shell is not tested on ${Platform.operatingSystem}'; + } + return installed[shell] == null ? '$shell is not installed' : null; + } + + // On macOS, /bin/bash is version 3.2 while a newer Bash is usually + // installed elsewhere; test both when they differ. + final bashes = { + if (installed['bash'] case final String bash) bash, + if (Platform.isMacOS && File('/bin/bash').existsSync()) '/bin/bash', + }; + for (final bash in bashes) { + _bashTests(env, bash, skip: skipUnless('bash')); + } + _zshTests(env, installed['zsh'], skip: skipUnless('zsh')); + _fishTests(env, installed['fish'], skip: skipUnless('fish')); + _powershellTests(env, installed['pwsh'], skip: skipUnless('pwsh')); + _carapaceTests(env, installed['carapace'], skip: skipUnless('carapace')); +} + +/// The completion protocol at the process level: the executable prints after +/// `runner()` returns (see the fixture's `main`), which must not reach the +/// completion output. +void _executableTests(final _Environment env) { + group('Given the fixture CLI compiled to an executable ' + 'that prints after the runner returns', () { + final description = buildCompletionCli().usageDefinition.description; + + test('when running a regular command ' + 'then the output after the runner is printed', () async { + final result = await env.run(env.exePath, ['build']); + expect(result.stdout, contains(afterRunnerMarker)); + }); + + test('when a completion request goes through the wrapper ' + 'then the response is corrupted, which is why the scripts ' + 'generated for the wrapper bypass it', () async { + final result = await env.run( + _wrapperName, + ['__complete', 'bu'], + expectSuccess: false, + ); + expect(result.stdout, startsWith('wrapper noise\n')); + expect(result.stdout, isNot(contains('build\t'))); + }, skip: Platform.isWindows ? 'the wrapper is a POSIX script' : null); + + test( + 'when serving a completion request ' + 'then the process exits with code 0 right after the response', + () async { + final result = await env.run(env.exePath, ['__complete', 'bu']); + expect(result.stdout, 'build\tBuild the project.\n:4\n'); + expect(result.exitCode, 0); + }, + ); + + test('when a completion request fails ' + 'then the process exits with code 0 right after the error response ' + 'and the failure is reported on stderr', () async { + final result = await env.run(env.exePath, [ + '__complete', + 'build', + '--project', + 'boom', + '--env', + '', + ]); + expect(result.stdout, ':1\n'); + expect(result.exitCode, 0); + expect(result.stderr, contains('Completion failed')); + }); + + test('when printing a completion script with the completion command ' + 'then the process exits right after the script', () async { + final result = await env.run(env.exePath, [ + 'completion', + '--shell', + 'bash', + ]); + expect( + result.stdout, + CompletionShell.bash.script(_exeName, description: description), + ); + expect(result.exitCode, 0); + }); + + test('when installing the completion with `completion install` ' + 'then the script is saved, the steps are printed ' + 'and the program continues after the runner', () async { + final environment = env.installEnvironment(); + final result = await env.run( + env.exePath, + ['completion', 'install', '--shell', 'fish'], + environment: environment, + ); + final script = p.join( + environment['XDG_CONFIG_HOME']!, + 'fish', + 'completions', + '$_exeName.fish', + ); + expect( + File(script).readAsStringSync(), + CompletionShell.fish.script(_exeName, description: description), + ); + expect( + result.stdout, + 'Installing the Fish completion for $_exeName:\n' + ' Create directory ${p.dirname(script)}\n' + ' Write $script\n' + 'Fish loads it automatically, no reload needed.\n' + '$afterRunnerMarker null\n', + ); + }); + + test('when installing the completion with `completion install --dry-run` ' + 'then the steps are printed and nothing is created', () async { + final environment = env.installEnvironment(); + final result = await env.run( + env.exePath, + ['completion', 'install', '--shell', 'zsh', '--dry-run'], + environment: environment, + ); + expect( + result.stdout, + startsWith( + 'Installing the Zsh completion for $_exeName ' + '(dry run, nothing is changed):\n' + ' Create directory ', + ), + ); + expect(Directory(environment['HOME']!).listSync(), isEmpty); + }); + + test('when the completion script request is invalid ' + 'then the usage error is reported and the process does not exit ' + 'early', () async { + final result = await env.run( + env.exePath, + ['completion', '--shell', 'tcsh'], + expectSuccess: false, + ); + expect(result.exitCode, 64); + expect(result.stderr, contains('"tcsh"')); + expect(result.stdout, isNot(contains(afterRunnerMarker))); + }); + }); + + group('Given the fixture CLI run with Fish as the login shell ' + 'where the ancestor processes cannot be inspected', () { + final description = buildCompletionCli().usageDefinition.description; + // Lazy: the environment is set up after the tests are declared. + late final detection = env.detectionEnvironment( + loginShell: '/usr/bin/fish', + ); + + test('when running `completion` without the shell option ' + 'then the script of the detected shell is printed', () async { + final result = await env.run( + env.exePath, + ['completion'], + environment: detection, + ); + expect( + result.stdout, + CompletionShell.fish.script(_exeName, description: description), + ); + }); + + test('when running `completion --shell zsh` ' + 'then the script of the given shell is printed', () async { + final result = await env.run( + env.exePath, + ['completion', '--shell', 'zsh'], + environment: detection, + ); + expect( + result.stdout, + CompletionShell.zsh.script(_exeName, description: description), + ); + }); + + test('when running `completion --command $_wrapperName` ' + 'without the shell option ' + 'then the script of the detected shell is for the wrapper', () async { + final result = await env.run( + env.exePath, + ['completion', '--command', _wrapperName], + environment: detection, + ); + expect( + result.stdout, + CompletionShell.fish.script( + _exeName, + description: description, + commandName: _wrapperName, + ), + ); + }); + + group('when running `completion install` without the shell option', () { + late Map environment; + late String script; + late _ProcessOutput result; + + setUp(() async { + environment = {...env.installEnvironment(), ...detection}; + script = p.join( + environment['XDG_CONFIG_HOME']!, + 'fish', + 'completions', + '$_exeName.fish', + ); + result = await env.run( + env.exePath, + ['completion', 'install'], + environment: environment, + ); + }); + + test('then the script of the detected shell is saved ' + 'where the shell loads it from', () { + expect( + File(script).readAsStringSync(), + CompletionShell.fish.script(_exeName, description: description), + ); + }); + + test('then the steps for the detected shell are printed', () { + expect( + result.stdout, + startsWith( + 'Installing the Fish completion for $_exeName:\n' + ' Create directory ${p.dirname(script)}\n' + ' Write $script\n', + ), + ); + }); + }); + + test('when running `completion install --dry-run` ' + 'without the shell option ' + 'then the steps for the detected shell are printed ' + 'and nothing is created', () async { + final environment = {...env.installEnvironment(), ...detection}; + final result = await env.run( + env.exePath, + ['completion', 'install', '--dry-run'], + environment: environment, + ); + expect( + result.stdout, + startsWith( + 'Installing the Fish completion for $_exeName ' + '(dry run, nothing is changed):\n', + ), + ); + expect(Directory(environment['HOME']!).listSync(), isEmpty); + }); + }); + + group( + 'Given the fixture CLI run without a login shell ' + 'where the ancestor processes cannot be inspected', + () { + late final detection = env.detectionEnvironment(loginShell: ''); + + group('when running `completion` without the shell option', () { + late _ProcessOutput result; + + setUp(() async { + result = await env.run( + env.exePath, + ['completion'], + environment: detection, + expectSuccess: false, + ); + }); + + test('then a usage error asks for the shell option', () { + expect( + result.stderr, + contains( + 'completion: Could not detect the shell. ' + 'Specify it with --shell.', + ), + ); + expect(result.exitCode, 64); + }); + + test('then the usage of the command is printed with the error', () { + expect(result.stderr, contains('Usage: $_exeName completion')); + }); + + test('then no script is printed', () { + expect(result.stdout, isEmpty); + }); + }); + + test('when running `completion install` without the shell option ' + 'then a usage error asks for the shell option ' + 'and nothing is installed', () async { + final environment = {...env.installEnvironment(), ...detection}; + final result = await env.run( + env.exePath, + ['completion', 'install'], + environment: environment, + expectSuccess: false, + ); + expect( + result.stderr, + contains( + 'install: Could not detect the shell. Specify it with --shell.', + ), + ); + expect(result.exitCode, 64); + expect(Directory(environment['HOME']!).listSync(), isEmpty); + }); + + test('when running `completion --shell bash` ' + 'then the script of the given shell is printed', () async { + final result = await env.run( + env.exePath, + ['completion', '--shell', 'bash'], + environment: detection, + ); + expect( + result.stdout, + contains('complete -F __${_exeName}_complete $_exeName'), + ); + }); + + test('when running `completion --help` ' + 'then the usage is printed without requiring a shell', () async { + final result = await env.run( + env.exePath, + ['completion', '--help'], + environment: detection, + ); + expect(result.stdout, contains('Usage: $_exeName completion')); + expect(result.stderr, isEmpty); + }); + + test('when running `completion` without the shell option ' + 'in a runner that does not throw usage exceptions ' + 'then the error is printed and the runner returns null', () async { + final result = await env.run( + env.exePath, + ['completion'], + environment: {...detection, noUsageExceptionVariable: '1'}, + ); + expect(result.stderr, contains('Could not detect the shell.')); + expect(result.stdout, '$afterRunnerMarker null\n'); + }); + }, + skip: Platform.isWindows + ? 'PowerShell is always detected on Windows' + : null, + ); +} + +void _bashTests( + final _Environment env, + final String bash, { + required final String? skip, +}) { + group('Given the Bash completion script sourced in $bash', () { + /// Completes the last of [words]. The equals sign is a word break, + /// as it is by default in Bash, unless [breakAtEquals] is false. + Future> complete( + final List words, { + final bool breakAtEquals = true, + }) async { + final result = await env.run( + bash, + [ + env.harnessPath('bash_harness.sh'), + env.scriptPath('bash'), + ...words, + ], + environment: {if (!breakAtEquals) 'COMPLETION_NO_EQUALS_BREAK': '1'}, + ); + return result.lines; + } + + test('when sourced then a completion function is registered ' + 'for the executable', () async { + final result = await env.run(bash, [ + '-c', + 'source "\$1" && complete -p $_exeName', + 'bash', + env.scriptPath('bash'), + ]); + expect( + result.stdout.trim(), + 'complete -F __${_exeName}_complete $_exeName', + ); + }); + + test('when completing the first word ' + 'then the non-hidden subcommands are offered', () async { + expect(await complete(['']), [ + 'build', + 'deploy', + 'export', + 'version', + 'db', + 'completion', + ]); + }); + + test('when completing a subcommand prefix ' + 'then only the matching subcommand is offered', () async { + expect(await complete(['bu']), ['build']); + }); + + test('when completing a dash then the options are offered', () async { + expect( + await complete(['-']), + containsAll(['--config', '-c', '--verbose', '--no-verbose', '-h']), + ); + }); + + test('when completing an enum option value ' + 'then its values are offered', () async { + expect(await complete(['build', '--mode', '']), [ + 'debug', + 'profile', + 'release', + ]); + }); + + test('when completing an option value attached with an equals sign ' + 'then the value part is completed', () async { + // Bash splits the word at '=' by default. + expect(await complete(['build', '--mode', '=', 're']), ['release']); + }); + + group('when the equals sign is not a word break', () { + test('and completing an enum option value attached with an equals sign ' + 'then the option is kept in the offered value', () async { + expect( + await complete(['build', '--mode=re'], breakAtEquals: false), + ['--mode=release'], + ); + }); + + test('and completing a file option value attached with an equals sign ' + 'then the option is kept in the offered file', () async { + expect( + await complete(['--config=f'], breakAtEquals: false), + ['--config=f.txt'], + ); + }); + + test( + 'and completing a directory option value attached with an ' + 'equals sign then the option is kept in the offered directory', + () async { + expect( + await complete(['build', '--out=s'], breakAtEquals: false), + ['--out=sub'], + ); + }, + ); + + test('and completing a file option value with extensions attached ' + 'with an equals sign then the option is kept in the offered ' + 'files', () async { + expect( + await complete(['build', '--spec=a'], breakAtEquals: false), + ['--spec=a.yaml'], + ); + }); + }); + + test('when completing a later list element of a multi-option ' + 'then the earlier elements are kept', () async { + expect(await complete(['build', '--tags', 'fast,s']), [r'fast\,slow']); + }); + + test('when completing a directory option ' + 'then only directories are offered', () async { + expect(await complete(['build', '--out', '']), ['sub']); + }); + + test('when completing a file option ' + 'then files are offered', () async { + expect(await complete(['--config', 'f']), ['f.txt']); + }); + + test('when completing a file option with extensions ' + 'then only matching files and directories are offered', () async { + expect( + await complete(['build', '--spec', '']), + unorderedEquals(['sub', 'a.yaml', 'b.yml']), + ); + }); + + group('when file and directory names have wildcard characters ' + 'that match other names', () { + // `w[1]` as a wildcard pattern matches `w1`. + late List entities; + + setUp(() { + entities = [ + File(p.join(env.workDir.path, 'w[1].yaml'))..createSync(), + File(p.join(env.workDir.path, 'w1.yaml'))..createSync(), + Directory(p.join(env.workDir.path, 'w[1]dir'))..createSync(), + Directory(p.join(env.workDir.path, 'w1dir'))..createSync(), + ]; + }); + + tearDown(() { + for (final entity in entities) { + entity.deleteSync(); + } + }); + + test('and completing a file option ' + 'then each name is offered as it is', () async { + expect( + await complete(['--config', 'w']), + unorderedEquals(['w[1].yaml', 'w1.yaml', 'w[1]dir', 'w1dir']), + ); + }); + + test('and completing a file option with extensions ' + 'then each name is offered as it is', () async { + expect( + await complete(['build', '--spec', 'w']), + unorderedEquals(['w[1].yaml', 'w1.yaml', 'w[1]dir', 'w1dir']), + ); + }); + + test('and completing a directory option ' + 'then each name is offered as it is', () async { + expect( + await complete(['build', '--out', 'w']), + unorderedEquals(['w[1]dir', 'w1dir']), + ); + }); + }); + + test('when completing a positional argument ' + 'then its allowed values are offered', () async { + expect(await complete(['deploy', '']), ['staging', 'production']); + }); + + test('when nothing can be completed then nothing is offered', () async { + expect(await complete(['build', '']), isEmpty); + }); + + test('when completing after a redirection operator ' + 'then files are offered instead of command arguments', () async { + expect( + await complete(['>', '']), + unorderedEquals(['f.txt', 'a.yaml', 'b.yml', 'sub']), + ); + }); + + test('when completing the redirection operator itself ' + 'then files are offered', () async { + expect( + await complete(['>']), + unorderedEquals(['f.txt', 'a.yaml', 'b.yml', 'sub']), + ); + }); + + test('when completing a command word after a redirected file ' + 'then the redirection is ignored', () async { + expect(await complete(['>', 'out.txt', 'bu']), ['build']); + }); + + test('when the script is generated for a wrapper of the executable ' + 'then completing the wrapper asks the executable directly', () async { + final result = await env.run( + bash, + [ + env.harnessPath('bash_harness.sh'), + env.wrapperScriptPath('bash'), + 'bu', + ], + environment: {'COMPLETION_CMD': _wrapperName}, + ); + expect(result.lines, ['build']); + }); + + test('when the script is generated for a wrapper path with a space ' + 'then the completion is registered for that path', () async { + const wrapper = '/tmp/my wrapper'; + final script = await env.run(env.exePath, [ + 'completion', + '--shell', + 'bash', + '--command', + wrapper, + ]); + final scriptFile = File(p.join(env.scriptDir.path, 'spaced.bash')) + ..writeAsStringSync(script.stdout); + final result = await env.run(bash, [ + '-c', + 'source "\$1" && complete -p "\$2"', + 'bash', + scriptFile.path, + wrapper, + ]); + expect( + result.stdout.trim(), + startsWith('complete -F ___tmp_my_wrapper_complete '), + ); + }); + }, skip: skip); + + group('Given an interactive $bash', () { + test( + 'when running `completion` without the shell option ' + 'then the Bash script is printed, whatever the login shell is', + () async { + final result = await env.run( + bash, + ['--noprofile', '--norc', '-i'], + stdin: '$_exeName completion\n', + environment: {'SHELL': '/bin/zsh'}, + ); + expect( + result.stdout, + contains('complete -F __${_exeName}_complete $_exeName'), + ); + }, + skip: _skipUnlessProcessesCanBeInspected, + ); + + test('when the completion is installed with `completion install` ' + 'then a new shell that reads its startup file ' + 'has the completion function registered', () async { + final environment = env.installEnvironment(); + await env.run( + env.exePath, + ['completion', 'install', '--shell', 'bash'], + environment: environment, + ); + // The startup file is the one of login shells on macOS, + // and the one of interactive shells elsewhere. + final result = await env.run( + bash, + [Platform.isMacOS ? '-l' : '-i', '-c', 'complete -p $_exeName'], + environment: environment, + ); + expect( + result.lines, + contains('complete -F __${_exeName}_complete $_exeName'), + ); + }); + }, skip: skip); +} + +void _zshTests( + final _Environment env, + final String? zsh, { + required final String? skip, +}) { + group('Given the Zsh completion script in an interactive Zsh', () { + /// Types [line] followed by TAB in an interactive zsh, returning the + /// resulting command line buffer and the raw terminal output. + Future<({String buffer, String output})> completeLine( + final String line, { + final bool installInFpath = false, + final String? script, + }) async { + final result = await env.run( + zsh!, + ['-f', env.harnessPath('zsh_harness.zsh'), line], + environment: { + // The interactive Zsh under test is the same one as the harness. + 'ZSH_BIN': zsh, + 'ZSH_INIT': env.harnessPath('zsh_init.zsh'), + 'ZSH_COMPDUMP': p.join(env.root.path, 'zcompdump'), + 'ZSH_BUFFER_FILE': p.join(env.root.path, 'zsh_buffer.txt'), + 'COMPLETION_SCRIPT': script ?? env.scriptPath('zsh'), + 'COMPLETION_INSTALL': installInFpath ? 'fpath' : 'source', + 'COMPLETION_FPATH': env.fpathDir.path, + }, + ); + final buffer = result.lines.firstWhere( + (final l) => l.startsWith('BUFFER:'), + orElse: () => fail('no buffer in harness output:\n${result.stdout}'), + ); + return ( + buffer: buffer.substring('BUFFER:'.length), + output: result.stdout, + ); + } + + test('when sourced after compinit ' + 'then the completion function is registered', () async { + final result = await env.run(zsh!, [ + '-f', + '-c', + 'autoload -Uz compinit && compinit -u -d "\$1" && source "\$2" && ' + 'print -r -- "\${_comps[$_exeName]}"', + 'zsh', + p.join(env.root.path, 'zcompdump_check'), + env.scriptPath('zsh'), + ]); + expect(result.stdout.trim(), '_$_exeName'); + }); + + test('when completing a unique subcommand prefix ' + 'then the subcommand is inserted', () async { + final result = await completeLine('$_exeName bu'); + expect(result.buffer, '$_exeName build '); + }); + + test('when installed in fpath and completing a unique subcommand prefix ' + 'then the subcommand is inserted', () async { + final result = await completeLine('$_exeName bu', installInFpath: true); + expect(result.buffer, '$_exeName build '); + }); + + test('when completing the first word ' + 'then the subcommands are listed with descriptions', () async { + final result = await completeLine('$_exeName '); + expect(result.output, contains('build')); + expect(result.output, contains('Build the project.')); + expect(result.output, contains('deploy')); + expect(result.output, contains('completion')); + expect(result.output, isNot(contains('internal'))); + }); + + test('when completing an enum option value ' + 'then the values are listed with descriptions', () async { + final result = await completeLine('$_exeName build --mode '); + expect(result.buffer, '$_exeName build --mode '); + expect(result.output, contains('debug')); + expect(result.output, contains('Debug build')); + expect(result.output, contains('profile')); + expect(result.output, contains('release')); + }); + + test('when completing a unique enum option value ' + 'then it is inserted', () async { + final result = await completeLine('$_exeName build --mode re'); + expect(result.buffer, '$_exeName build --mode release '); + }); + + test('when completing an option value attached with an equals sign ' + 'then the value is inserted after the option', () async { + final result = await completeLine('$_exeName build --mode=re'); + expect(result.buffer, '$_exeName build --mode=release '); + }); + + test('when completing a later list element of a multi-option ' + 'then the earlier elements are kept', () async { + final result = await completeLine('$_exeName build --tags fast,s'); + expect(result.buffer, '$_exeName build --tags fast,slow '); + }); + + test('when completing a value that contains a backslash and a colon ' + 'then the value is inserted whole', () async { + // The typed word is `a\:b`, which the fixture offers as `a\:b!`. + final result = await completeLine('$_exeName build --env a\\\\:b'); + expect(result.buffer, '$_exeName build --env a\\\\:b\\! '); + }); + + test('when completing a directory option ' + 'then the directory is inserted', () async { + final result = await completeLine('$_exeName build --out su'); + expect(result.buffer, '$_exeName build --out sub/'); + }); + + test('when completing a file option then the file is inserted', () async { + final result = await completeLine('$_exeName --config f.t'); + expect(result.buffer, '$_exeName --config f.txt '); + }); + + test('when completing a file option with extensions ' + 'then the matching file is inserted', () async { + final result = await completeLine('$_exeName build --spec a.'); + expect(result.buffer, '$_exeName build --spec a.yaml '); + }); + + test('when completing a positional argument ' + 'then its allowed values are listed', () async { + final result = await completeLine('$_exeName deploy '); + expect(result.output, contains('staging')); + expect(result.output, contains('production')); + }); + + test('when nothing can be completed ' + 'then no files are offered', () async { + final result = await completeLine('$_exeName build '); + expect(result.buffer, '$_exeName build '); + expect(result.output, isNot(contains('f.txt'))); + }); + + test('when the script is generated for a wrapper of the executable ' + 'then completing the wrapper asks the executable directly', () async { + final result = await completeLine( + '$_wrapperName bu', + script: env.wrapperScriptPath('zsh'), + ); + expect(result.buffer, '$_wrapperName build '); + }); + }, skip: skip); + + group('Given an interactive Zsh', () { + /// Expects that a new interactive Zsh with the [environment] has the + /// completion function registered for the executable. + /// + /// Zsh does not initialize its completion system if a directory it + /// loads functions from is writable by other users (see `compaudit`) + /// and it cannot ask the user: its error output tells if that is so. + Future expectCompletionRegistered( + final Map environment, + ) async { + final result = await env.run( + zsh!, + ['-i', '-c', 'print -r -- "registered:\${_comps[$_exeName]}"'], + environment: environment, + ); + expect( + result.lines.last, + 'registered:_$_exeName', + reason: 'Error output of Zsh:\n${result.stderr}', + ); + } + + test( + 'when running `completion` without the shell option ' + 'then the Zsh script is printed, whatever the login shell is', + () async { + final result = await env.run( + zsh!, + ['-f', '-i'], + stdin: '$_exeName completion\n', + environment: {'SHELL': '/bin/bash'}, + ); + expect(result.stdout, contains('#compdef $_exeName')); + }, + skip: _skipUnlessProcessesCanBeInspected, + ); + + test( + 'when running `completion` without the shell option ' + 'through a wrapper that is a Bash script ' + 'then the Zsh script is printed', + () async { + final wrapper = File(p.join(env.binDir.path, 'bashwrap')) + ..writeAsStringSync('#!/bin/bash\n$_exeName "\$@"\n'); + await env.run('chmod', ['+x', wrapper.path]); + final result = await env.run( + zsh!, + ['-f', '-i'], + stdin: 'bashwrap completion\n', + environment: {'SHELL': '/bin/bash'}, + ); + expect(result.stdout, contains('#compdef $_exeName')); + }, + skip: + _skipUnlessProcessesCanBeInspected ?? + (File('/bin/bash').existsSync() ? null : '/bin/bash is missing'), + ); + + test('when the completion is installed with `completion install` ' + 'in a home directory without a startup file ' + 'then a new shell has the completion registered', () async { + final environment = env.installEnvironment(); + await env.run( + env.exePath, + ['completion', 'install', '--shell', 'zsh'], + environment: environment, + ); + await expectCompletionRegistered(environment); + }); + + test('when the completion is installed with `completion install` ' + 'and the startup file initializes the completion system ' + 'then a new shell has the completion registered', () async { + final environment = env.installEnvironment(); + final home = environment['HOME']!; + File(p.join(home, '.zshrc')).writeAsStringSync( + 'autoload -Uz compinit\n' + 'compinit -u -d ${p.join(home, 'zcompdump')}', + ); + await env.run( + env.exePath, + ['completion', 'install', '--shell', 'zsh'], + environment: environment, + ); + await expectCompletionRegistered(environment); + }); + }, skip: skip); +} + +void _fishTests( + final _Environment env, + final String? fish, { + required final String? skip, +}) { + group('Given the Fish completion script sourced in Fish', () { + /// Completes [line] with fish's `complete -C`, + /// returning the candidates as `valuedescription` lines. + Future> complete( + final String line, { + final String? script, + }) async { + final result = await env.run(fish!, [ + '--no-config', + '-c', + 'source "\$argv[1]"; complete -C "\$argv[2]"', + script ?? env.scriptPath('fish'), + line, + ]); + return result.lines; + } + + test('when the script is generated for a wrapper of the executable ' + 'then completing the wrapper asks the executable directly', () async { + expect( + await complete( + '$_wrapperName bu', + script: env.wrapperScriptPath('fish'), + ), + ['build\tBuild the project.'], + ); + }); + + test('when completing the first word ' + 'then the subcommands are offered with descriptions', () async { + final lines = await complete('$_exeName '); + expect( + lines, + containsAll([ + 'build\tBuild the project.', + 'deploy\tDeploy a bundle to a target.', + 'completion\tGenerate a shell completion script.', + ]), + ); + expect(_values(lines), isNot(contains('internal'))); + }); + + test('when completing a subcommand prefix ' + 'then only the matching subcommand is offered', () async { + expect(_values(await complete('$_exeName bu')), ['build']); + }); + + test('when completing a dash then the options are offered', () async { + expect( + _values(await complete('$_exeName build -')), + containsAll(['-m', '--mode', '--no-verbose', '--config']), + ); + }); + + test('when completing an enum option value ' + 'then its values are offered with descriptions', () async { + expect(await complete('$_exeName build --mode '), [ + 'debug\tDebug build', + 'profile', + 'release\tOptimized build', + ]); + }); + + test('when completing an option value attached with an equals sign ' + 'then the option prefix is kept', () async { + expect(_values(await complete('$_exeName build --mode=re')), [ + '--mode=release', + ]); + }); + + test('when completing a later list element of a multi-option ' + 'then the earlier elements are kept', () async { + expect(_values(await complete('$_exeName build --tags fast,s')), [ + 'fast,slow', + ]); + }); + + test('when completing a directory option ' + 'then only directories are offered', () async { + expect(_values(await complete('$_exeName build --out ')), ['sub/']); + }); + + test('when completing a file option then files are offered', () async { + expect(_values(await complete('$_exeName --config f')), ['f.txt']); + }); + + test('when completing a file option with extensions ' + 'then only matching files and directories are offered', () async { + expect( + _values(await complete('$_exeName build --spec ')), + unorderedEquals(['a.yaml', 'b.yml', 'sub/']), + ); + }); + + test('when completing a positional argument ' + 'then its allowed values are offered', () async { + expect( + _values(await complete('$_exeName deploy ')), + unorderedEquals(['staging', 'production']), + ); + }); + + test('when nothing can be completed then nothing is offered', () async { + expect(await complete('$_exeName build '), isEmpty); + }); + }, skip: skip); + + group('Given an interactive Fish', () { + test('when the completion is installed with `completion install` ' + 'then completing a subcommand prefix in a new shell ' + 'loads the script and offers the subcommand', () async { + final environment = env.installEnvironment(); + await env.run( + env.exePath, + ['completion', 'install', '--shell', 'fish'], + environment: environment, + ); + final result = await env.run( + fish!, + ['-c', 'complete -C "$_exeName bu"'], + environment: environment, + ); + expect(_values(result.lines), ['build']); + }); + + test( + 'when running `completion` without the shell option ' + 'then the Fish script is printed, whatever the login shell is', + () async { + final result = await env.run( + fish!, + ['--no-config', '-i'], + stdin: '$_exeName completion\n', + environment: {'SHELL': '/bin/bash'}, + ); + expect(result.stdout, contains('complete -c $_exeName')); + }, + skip: _skipUnlessProcessesCanBeInspected, + ); + }, skip: skip); +} + +void _powershellTests( + final _Environment env, + final String? pwsh, { + required final String? skip, +}) { + group('Given the PowerShell completion script loaded in PowerShell', () { + /// Completes [line] with `TabExpansion2`, returning the completion + /// results as (text, listItem, type, toolTip) records. + Future> + complete(final String line) async { + final result = await env.run(pwsh!, [ + '-NoProfile', + '-NonInteractive', + '-File', + env.harnessPath('ps_harness.ps1'), + '-Script', + env.scriptPath('powershell'), + '-Line', + line, + ]); + return [ + for (final l in result.lines) + if (l.split('\t') case [ + final text, + final item, + final type, + final tip, + ]) + (text: text, item: item, type: type, tip: tip), + ]; + } + + test('when completing the first word ' + 'then the subcommands are offered with tool tips', () async { + final results = await complete('$_exeName '); + final items = results.map((final r) => r.item); + expect(items, containsAll(['build', 'deploy', 'db', 'completion'])); + expect(items, isNot(contains('internal'))); + final build = results.firstWhere((final r) => r.item == 'build'); + expect(build.tip, 'Build the project.'); + expect(build.type, 'ParameterValue'); + }); + + test('when completing a subcommand prefix ' + 'then only the matching subcommand is offered', () async { + final results = await complete('$_exeName bu'); + expect(results.map((final r) => r.text.trim()), ['build']); + }); + + test('when completing an enum option value ' + 'then its values are offered', () async { + final results = await complete('$_exeName build --mode '); + expect(results.map((final r) => r.item), ['debug', 'profile', 'release']); + expect(results.last.tip, 'Optimized build'); + }); + + test('when completing an option value attached with an equals sign ' + 'then the option prefix is kept', () async { + final results = await complete('$_exeName build --mode=re'); + expect(results.map((final r) => r.text.trim()), ['--mode=release']); + }); + + test('when completing a later list element of a multi-option ' + 'then the earlier elements are kept', () async { + final results = await complete('$_exeName build --tags fast,s'); + expect(results.map((final r) => r.item), ['fast,slow']); + }); + + test('when completing a directory option ' + 'then only directories are offered', () async { + final results = await complete('$_exeName build --out '); + expect(results.map((final r) => r.item), ['sub']); + expect(results.single.type, 'ProviderContainer'); + }); + + test('when completing a file option then files are offered', () async { + final results = await complete('$_exeName --config f'); + expect(results.map((final r) => r.item), ['f.txt']); + }); + + test('when completing a file option with extensions ' + 'then only matching files and directories are offered', () async { + final results = await complete('$_exeName build --spec '); + expect( + results.map((final r) => r.item), + unorderedEquals(['sub', 'a.yaml', 'b.yml']), + ); + }); + + test('when completing a path that contains a space ' + 'then the space is escaped in the inserted text', () async { + final dir = 'sub${p.separator}'; + final results = await complete('$_exeName build --spec $dir'); + expect(results.map((final r) => r.item), ['my spec.yaml']); + expect(results.map((final r) => r.text), ['${dir}my` spec.yaml']); + }); + + test('when completing a positional argument ' + 'then its allowed values are offered', () async { + final results = await complete('$_exeName deploy '); + expect( + results.map((final r) => r.item), + unorderedEquals(['staging', 'production']), + ); + }); + + test('when nothing can be completed then no files are offered', () async { + final results = await complete('$_exeName build '); + expect(results.map((final r) => r.item.trim()), isNot(contains('f.txt'))); + expect(results.map((final r) => r.text.trim()), everyElement(isEmpty)); + }); + + test('when the completion fails then no files are offered', () async { + final results = await complete('$_exeName build --project boom --env '); + expect(results.map((final r) => r.item.trim()), isNot(contains('f.txt'))); + expect(results.map((final r) => r.text.trim()), everyElement(isEmpty)); + }); + + test('when completing a directory option and no directory matches ' + 'then no files are offered', () async { + final results = await complete('$_exeName build --out f'); + expect(results.map((final r) => r.item.trim()), isNot(contains('f.txt'))); + expect(results.map((final r) => r.text.trim()), everyElement(isEmpty)); + }); + + test('when completing a file option with extensions and no file ' + 'or directory matches then no files are offered', () async { + final results = await complete('$_exeName build --spec f'); + expect(results.map((final r) => r.item.trim()), isNot(contains('f.txt'))); + expect(results.map((final r) => r.text.trim()), everyElement(isEmpty)); + }); + + test('when completing a path with wildcard characters ' + 'then the path is taken literally', () async { + // `lit[1]` as a wildcard pattern matches the directory `lit1`. + // They are in the working directory, to complete a relative path: + // the path of the directory may have a space. + final dir = Directory(p.join(env.workDir.path, 'lit[1]'))..createSync(); + final decoy = Directory(p.join(env.workDir.path, 'lit1'))..createSync(); + addTearDown(() { + dir.deleteSync(recursive: true); + decoy.deleteSync(recursive: true); + }); + File(p.join(dir.path, 'c.yaml')).createSync(); + File(p.join(decoy.path, 'c-decoy.yaml')).createSync(); + final results = await complete( + '$_exeName build --spec lit[1]${p.separator}c', + ); + expect(results.map((final r) => r.item), ['c.yaml']); + }); + }, skip: skip); + + group('Given the PowerShell completion installed ' + 'with `completion install`', () { + test( + 'when completing a subcommand prefix in a new shell ' + 'then the profile loads the script and the subcommand is offered', + () async { + const line = '$_exeName bu'; + final environment = env.installEnvironment(); + await env.run( + env.exePath, + ['completion', 'install', '--shell', 'powershell'], + environment: environment, + ); + final result = await env.run( + pwsh!, + [ + '-NonInteractive', + '-Command', + "(TabExpansion2 -inputScript '$line' -cursorColumn ${line.length})" + '.CompletionMatches | ' + r'ForEach-Object { $_.CompletionText.Trim() }', + ], + environment: environment, + ); + expect(result.lines, ['build']); + }, + // On Windows the profile is in the documents folder of the user, + // wherever the environment says the home directory is. + skip: Platform.isWindows + ? 'it would change the profile of the user' + : null, + ); + }, skip: skip); +} + +void _carapaceTests( + final _Environment env, + final String? carapace, { + required final String? skip, +}) { + group( + 'Given the Carapace spec installed in the Carapace specs directory', + () { + /// Completes [words] via `carapace export`, + /// returning the values with their descriptions. + Future> complete( + final List words, { + final Map environment = const {}, + }) async { + final result = await env.run( + carapace!, + [_exeName, 'export', _exeName, ...words], + environment: environment, + ); + final json = jsonDecode(result.stdout) as Map; + return [ + for (final value in json['values'] as List) + ( + value: (value as Map)['value'] as String, + description: (value['description'] as String?) ?? '', + ), + ]; + } + + test('when detecting the completion framework of the executable ' + 'then Cobra is detected', () async { + final result = await env.run(carapace!, ['--detect', _exeName]); + // Carapace reports the detected framework on stderr. + expect('${result.stdout}${result.stderr}'.trim(), 'cobra'); + }); + + test('when completing the first word ' + 'then the subcommands are offered with descriptions', () async { + final results = await complete(['']); + expect( + results.map((final r) => r.value), + containsAll(['build', 'deploy', 'db', 'version', 'completion']), + ); + expect(results.map((final r) => r.value), isNot(contains('internal'))); + final build = results.firstWhere((final r) => r.value == 'build'); + expect(build.description, 'Build the project.'); + }); + + test('when completing a subcommand prefix ' + 'then only the matching subcommand is offered', () async { + final results = await complete(['bu']); + expect(results.map((final r) => r.value), ['build']); + }); + + test('when completing an enum option value ' + 'then its values are offered', () async { + final results = await complete(['build', '--mode', '']); + expect( + results.map((final r) => r.value), + unorderedEquals(['debug', 'profile', 'release']), + ); + }); + + test('when completing a later list element of a multi-option ' + 'then the earlier elements are kept', () async { + final results = await complete(['build', '--tags', 'fast,s']); + expect(results.map((final r) => r.value), ['fast,slow']); + }); + + test('when completing a directory option ' + 'then only directories are offered', () async { + final results = await complete(['build', '--out', '']); + expect(results.map((final r) => r.value), ['sub/']); + }); + + test('when completing a file option then files are offered', () async { + final results = await complete(['--config', 'f']); + expect(results.map((final r) => r.value), ['f.txt']); + }); + + test('when completing a file option with extensions ' + 'then only matching files and directories are offered', () async { + final results = await complete(['build', '--spec', '']); + expect( + results.map((final r) => r.value), + unorderedEquals(['a.yaml', 'b.yml', 'sub/']), + ); + }); + + test('when nothing can be completed then nothing is offered', () async { + expect(await complete(['build', '']), isEmpty); + }); + + test('when the spec is installed with `completion install` instead ' + 'then Carapace completes with it', () async { + final environment = env.installEnvironment(); + await env.run( + env.exePath, + ['completion', 'install', '--shell', 'carapace'], + environment: environment, + ); + final results = await complete(['bu'], environment: environment); + expect(results.map((final r) => r.value), ['build']); + }); + }, + skip: skip, + ); +} + +/// The values of `valuedescription` lines. +List _values(final List lines) => [ + for (final line in lines) line.split('\t').first, +]; + +/// The reason to skip a test of the shell detection, or null if the +/// ancestor processes can be inspected with `ps` (which a sandbox may deny). +final String? _skipUnlessProcessesCanBeInspected = () { + if (!Platform.isWindows) { + try { + final result = Process.runSync('ps', ['-o', 'ppid=', '-p', '$pid']); + if (result.exitCode == 0) return null; + } on ProcessException { + // Not installed. + } + } + return 'the ancestor processes cannot be inspected with ps'; +}(); + +/// Looks up the executable of [shell] via `CLI_COMPLETION_` +/// or on the PATH. +String? _findShell(final String shell) { + final explicit = + Platform.environment['CLI_COMPLETION_${shell.toUpperCase()}']; + if (explicit != null && explicit.isNotEmpty) { + return File(explicit).existsSync() ? explicit : null; + } + final path = Platform.environment['PATH'] ?? ''; + final extensions = Platform.isWindows ? ['.exe', ''] : ['']; + for (final dir in path.split(Platform.isWindows ? ';' : ':')) { + if (dir.isEmpty) continue; + for (final ext in extensions) { + final candidate = p.join(dir, '$shell$ext'); + if (File(candidate).existsSync()) return candidate; + } + } + return null; +} + +class _ProcessOutput { + final String stdout; + final String stderr; + final int exitCode; + + _ProcessOutput(this.stdout, this.stderr, this.exitCode); + + /// The non-empty lines of [stdout], without line terminators. + List get lines => [ + for (final line in stdout.split('\n')) + if (line.trim().isNotEmpty) + line.endsWith('\r') ? line.substring(0, line.length - 1) : line, + ]; +} + +/// The compiled fixture executable, the generated completion scripts, the +/// shell harness scripts, and a working directory with files to complete. +class _Environment { + late final Directory root; + late final Directory binDir; + late final Directory scriptDir; + late final Directory harnessDir; + late final Directory workDir; + late final Directory fpathDir; + late final Directory xdgConfigDir; + late final Directory homeDir; + + String get exePath => + p.join(binDir.path, Platform.isWindows ? '$_exeName.exe' : _exeName); + + /// The generated script for [shell]; PowerShell requires a `.ps1` file. + String scriptPath(final String shell) => p.join( + scriptDir.path, + shell == 'powershell' ? '$_exeName.ps1' : '$_exeName.$shell', + ); + + /// The script for [shell] generated for the wrapper of the executable, + /// see [_wrapperName]. POSIX shells only. + String wrapperScriptPath(final String shell) => + p.join(scriptDir.path, '$_wrapperName.$shell'); + + String harnessPath(final String name) => p.join(harnessDir.path, name); + + Future setUp() async { + root = Directory.systemTemp.createTempSync('completion_shell_test_'); + binDir = Directory(p.join(root.path, 'bin'))..createSync(); + scriptDir = Directory(p.join(root.path, 'scripts'))..createSync(); + harnessDir = Directory(p.join(root.path, 'harness'))..createSync(); + workDir = Directory(p.join(root.path, 'work'))..createSync(); + fpathDir = Directory(p.join(root.path, 'fpath'))..createSync(); + homeDir = Directory(p.join(root.path, 'home'))..createSync(); + xdgConfigDir = Directory(p.join(root.path, 'xdg_config'))..createSync(); + + Directory(p.join(workDir.path, 'sub')).createSync(); + for (final name in ['f.txt', 'a.yaml', 'b.yml']) { + File(p.join(workDir.path, name)).createSync(); + } + File(p.join(workDir.path, 'sub', 'my spec.yaml')).createSync(); + + await _compileFixture(); + if (!Platform.isWindows) await _writeWrapper(); + await _generateScripts(); + _writeHarnesses(); + } + + /// Writes a wrapper script of the executable to the bin directory that + /// prints to stdout and inserts an argument: completion requests that + /// went through it would fail. + Future _writeWrapper() async { + final wrapper = File(p.join(binDir.path, _wrapperName)) + ..writeAsStringSync( + '#!/bin/sh\n' + 'echo "wrapper noise"\n' + 'exec $_exeName --verbose "\$@"\n', + ); + final result = await Process.run('chmod', ['+x', wrapper.path]); + if (result.exitCode != 0) fail('chmod failed: ${result.stderr}'); + } + + void tearDown() { + try { + root.deleteSync(recursive: true); + } on FileSystemException { + // Best effort. + } + } + + Future _compileFixture() async { + final fixture = p.join( + p.dirname(Platform.script.toFilePath()), + 'fixtures', + 'completion_cli.dart', + ); + final source = File(fixture).existsSync() + ? fixture + : p.join( + Directory.current.path, + 'test', + 'command', + 'completion', + 'fixtures', + 'completion_cli.dart', + ); + final result = await Process.run(Platform.resolvedExecutable, [ + 'compile', + 'exe', + source, + '-o', + exePath, + ]); + if (result.exitCode != 0) { + fail('Compiling the fixture failed:\n${result.stdout}\n${result.stderr}'); + } + } + + Future _generateScripts() async { + for (final shell in ['bash', 'zsh', 'fish', 'powershell']) { + final result = await run(exePath, ['completion', '--shell', shell]); + File(scriptPath(shell)).writeAsStringSync(result.stdout); + } + if (!Platform.isWindows) { + for (final shell in ['bash', 'zsh', 'fish']) { + final result = await run(exePath, [ + 'completion', + '--shell', + shell, + '--command', + _wrapperName, + ]); + File(wrapperScriptPath(shell)).writeAsStringSync(result.stdout); + } + } + File(p.join(fpathDir.path, '_$_exeName')).writeAsStringSync( + File(scriptPath('zsh')).readAsStringSync(), + ); + final specs = Directory(p.join(xdgConfigDir.path, 'carapace', 'specs')) + ..createSync(recursive: true); + final spec = await run(exePath, ['completion', '--shell', 'carapace']); + File(p.join(specs.path, '$_exeName.yaml')).writeAsStringSync(spec.stdout); + } + + void _writeHarnesses() { + File(harnessPath('bash_harness.sh')).writeAsStringSync(_bashHarness); + File(harnessPath('zsh_harness.zsh')).writeAsStringSync(_zshHarness); + File(harnessPath('zsh_init.zsh')).writeAsStringSync(_zshInit); + File(harnessPath('ps_harness.ps1')).writeAsStringSync(_powershellHarness); + } + + /// Creates an empty home directory to install a completion in, and + /// returns the environment variables that locate the installation there, + /// whatever they are in the environment of the test. + Map installEnvironment() { + final home = root.createTempSync('home_').path; + final dataHome = p.join(home, '.local', 'share'); + return { + 'HOME': home, + 'ZDOTDIR': home, + 'XDG_CONFIG_HOME': p.join(home, '.config'), + 'XDG_DATA_HOME': dataHome, + 'BASH_COMPLETION_USER_DIR': p.join(dataHome, 'bash-completion'), + }; + } + + /// The environment variables that make the shell detection of the fixture + /// executable independent of where the tests are run from: `ps` is not on + /// the PATH, so the ancestor processes are not inspected, which leaves + /// the [loginShell] to detect. An empty [loginShell] is no shell. + /// + /// (On Windows the ancestor processes are never inspected.) + Map detectionEnvironment({ + required final String loginShell, + }) => { + if (!Platform.isWindows) 'PATH': p.join(root.path, 'no_ps'), + 'SHELL': loginShell, + }; + + /// Runs [executable] in the working directory with the fixture + /// executable on the PATH, failing the test on a non-zero exit code + /// when [expectSuccess] is set. [stdin] is written to its standard input, + /// which is then closed. + Future<_ProcessOutput> run( + final String executable, + final List arguments, { + final Map environment = const {}, + final String? stdin, + final bool expectSuccess = true, + }) async { + final separator = Platform.isWindows ? ';' : ':'; + final path = '${binDir.path}$separator${Platform.environment['PATH']}'; + // On Windows the variable may be spelled `Path`; replace it rather than + // adding a second, differently cased entry. + final processEnvironment = {...Platform.environment} + ..removeWhere((final key, final _) => key.toUpperCase() == 'PATH') + ..addAll({ + 'PATH': path, + 'HOME': homeDir.path, + 'TERM': 'xterm', + 'XDG_CONFIG_HOME': xdgConfigDir.path, + 'XDG_CACHE_HOME': p.join(root.path, 'xdg_cache'), + ...environment, + }); + final process = await Process.start( + executable, + arguments, + workingDirectory: workDir.path, + environment: processEnvironment, + ); + if (stdin != null) { + process.stdin.write(stdin); + await process.stdin.close(); + } + final stdout = process.stdout.transform(utf8.decoder).join(); + final stderr = process.stderr.transform(utf8.decoder).join(); + final exitCode = await process.exitCode.timeout( + const Duration(seconds: 60), + onTimeout: () { + process.kill(); + fail('$executable ${arguments.join(' ')} timed out'); + }, + ); + final output = _ProcessOutput(await stdout, await stderr, exitCode); + if (expectSuccess && exitCode != 0) { + fail( + '$executable ${arguments.join(' ')} failed with exit code $exitCode:\n' + '${output.stdout}\n${output.stderr}', + ); + } + return output; + } +} + +/// Sources the script and calls the completion function the way Bash does, +/// printing COMPREPLY one entry per line. +/// Arguments: the script, then the words after the command name; +/// the last word is the one being completed. The command name is +/// `$COMPLETION_CMD`, or comptool. With `$COMPLETION_NO_EQUALS_BREAK` set, +/// the equals sign is not a word break. +const _bashHarness = r''' +script=$1; shift +cmd=${COMPLETION_CMD:-comptool} +source "$script" || exit 1 +[[ -n $COMPLETION_NO_EQUALS_BREAK ]] && COMP_WORDBREAKS=${COMP_WORDBREAKS//=/} +COMP_WORDS=("$cmd" "$@") +COMP_CWORD=$(( ${#COMP_WORDS[@]} - 1 )) +COMP_LINE="${COMP_WORDS[*]}" +COMP_POINT=${#COMP_LINE} +"__${cmd}_complete" "$cmd" "${COMP_WORDS[COMP_CWORD]}" "${COMP_WORDS[COMP_CWORD-1]}" +printf '%s\n' "${COMPREPLY[@]}" +'''; + +/// Sourced in the interactive Zsh under test: sets up the completion system +/// with the script either sourced or autoloaded from fpath, and binds a key +/// that saves the command line buffer to a file. +const _zshInit = r''' +if [[ $COMPLETION_INSTALL == fpath ]]; then fpath=("$COMPLETION_FPATH" $fpath); fi +autoload -Uz compinit +compinit -u -d "$ZSH_COMPDUMP" +if [[ $COMPLETION_INSTALL != fpath ]]; then source "$COMPLETION_SCRIPT"; fi +stty columns 200 rows 50 +LISTMAX=10000 +zstyle ':completion:*' menu no +zstyle ':completion:*' list-colors '' +__dump() { print -r -- "$BUFFER" > "$ZSH_BUFFER_FILE"; zle kill-whole-line; zle accept-line } +zle -N __dump +bindkey '^X^P' __dump +'''; + +/// Runs an interactive Zsh (`$ZSH_BIN`) in a pseudo terminal, types the +/// given line followed by TAB, and prints the resulting buffer and terminal +/// output. +const _zshHarness = r''' +zmodload zsh/zpty || { print 'zsh/zpty unavailable'; exit 2 } +export PS1='PROMPT> ' +rm -f "$ZSH_BUFFER_FILE" +zpty z "${(q)ZSH_BIN} -f -i" +zpty -r z log '*PROMPT>*' || { print 'no prompt'; exit 1 } +zpty -w z "source '$ZSH_INIT'" +zpty -r z log '*PROMPT>*' || { print 'no prompt after init'; exit 1 } +zpty -n -w z "$1"$'\t'$'\C-x\C-p' +zpty -r z log '*PROMPT>*' || { print 'no prompt after completion'; exit 1 } +zpty -d z +print -r -- "BUFFER:$(cat "$ZSH_BUFFER_FILE" 2>/dev/null)" +print -r -- "LOG:$log" +'''; + +/// Loads the script and completes the line with TabExpansion2, +/// printing one tab-separated line per completion result. +const _powershellHarness = r''' +param([string]$Script, [string]$Line) +$ErrorActionPreference = 'Stop' +. $Script +$result = TabExpansion2 -inputScript $Line -cursorColumn $Line.Length +foreach ($m in $result.CompletionMatches) { + "$($m.CompletionText)`t$($m.ListItemText)`t$($m.ResultType)`t$($m.ToolTip)" +} +'''; diff --git a/packages/config/test/command/context_provider_test.dart b/packages/config/test/command/context_provider_test.dart new file mode 100644 index 00000000..3b4a7e7e --- /dev/null +++ b/packages/config/test/command/context_provider_test.dart @@ -0,0 +1,452 @@ +import 'package:config/command.dart'; +import 'package:config/config.dart'; +import 'package:test/test.dart'; + +void main() { + group('Given a context provider and middleware on a command', () { + late ContextProvider provider; + late UserSession? sessionSeenByCommand; + late CommandReport? reportSeenByMiddleware; + + setUp(() async { + provider = ContextProvider(); + sessionSeenByCommand = null; + reportSeenByMiddleware = null; + final command = CommandImpl.leafWithRunFunction( + name: 'build', + description: 'Build the app', + middlewares: [ + (final next) => (final context) { + context.provider.store(const UserSession('ada')); + final result = next(context); + reportSeenByMiddleware = context.provider.fetch(); + return result; + }, + ], + run: (final context) { + sessionSeenByCommand = context.provider.fetch(); + context.provider.store(const CommandReport('built')); + return 'build'; + }, + ); + final runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [command], + ); + await runner.run(['build'], provider: provider); + }); + + test( + 'when the middleware stores a session before the command ' + 'then the command retrieves that session', + () { + expect(sessionSeenByCommand?.name, 'ada'); + }, + ); + + test( + 'when the command stores a report ' + 'then the middleware retrieves that report after the command returns', + () { + expect(reportSeenByMiddleware?.summary, 'built'); + }, + ); + + test( + 'when the command line finishes ' + 'then the caller retrieves the report stored by the command', + () { + expect(provider.fetch().summary, 'built'); + }, + ); + }); + + group( + 'Given a context provider shared by nested commands and middleware', + () { + late ContextProvider provider; + late UserSession? sessionSeenByBranch; + late UserSession? sessionSeenByLeaf; + late CommandReport? reportSeenByBranch; + + setUp(() async { + provider = ContextProvider(); + sessionSeenByBranch = null; + sessionSeenByLeaf = null; + reportSeenByBranch = null; + final check = CommandImpl.leafWithRunFunction( + name: 'check', + description: 'Check the app', + run: (final context) { + sessionSeenByLeaf = context.provider.fetch(); + context.provider.store(const CommandReport('checked')); + return 'check'; + }, + ); + final build = CommandImpl.branch( + name: 'build', + description: 'Build the app', + subcommands: [check], + middlewares: [ + (final next) => (final context) { + sessionSeenByBranch = context.provider.fetch(); + final result = next(context); + reportSeenByBranch = context.provider.fetch(); + return result; + }, + ], + ); + final runner = CommandRunner( + 'tool', + 'Tools', + middlewares: [ + (final next) => (final context) { + context.provider.store(const UserSession('ada')); + return next(context); + }, + ], + subcommands: [build], + ); + await runner.run(['build', 'check'], provider: provider); + }); + + test( + 'when runner middleware stores a session ' + 'then a branch command middleware retrieves that session', + () { + expect(sessionSeenByBranch?.name, 'ada'); + }, + ); + + test( + 'when runner middleware stores a session ' + 'then the leaf command retrieves that session', + () { + expect(sessionSeenByLeaf?.name, 'ada'); + }, + ); + + test( + 'when the leaf command stores a report ' + 'then the branch middleware retrieves that report', + () { + expect(reportSeenByBranch?.summary, 'checked'); + }, + ); + + test( + 'when the command line finishes ' + 'then the caller retrieves the report stored by the leaf command', + () { + expect(provider.fetch().summary, 'checked'); + }, + ); + }, + ); + + group('Given no context provider', () { + late ContextProvider? seen; + + setUp(() async { + final command = CommandImpl.leafWithRunFunction( + name: 'build', + description: 'Build the app', + run: (final context) { + seen = context.provider; + }, + ); + final runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [command], + ); + await runner.run(['build']); + }); + + test('when a command runs then its run context has a default provider', () { + expect(seen, isNotNull); + }); + }); + + group('Given a context provider that holds a session and a report', () { + late ContextProvider provider; + + setUp(() async { + provider = ContextProvider() + ..store(const UserSession('ada')) + ..store(const CommandReport('built')); + final command = CommandImpl.leafWithRunFunction( + name: 'logout', + description: 'Log out', + run: (final context) { + context.provider.remove(); + }, + ); + final runner = CommandRunner( + 'tool', + 'Tools', + subcommands: [command], + ); + await runner.run(['logout'], provider: provider); + }); + + test( + 'when a command removes the session ' + 'then the caller still retrieves the report', + () { + expect(provider.fetch().summary, 'built'); + }, + ); + + test( + 'when a command removes the session ' + 'then the caller cannot retrieve that session', + () { + expect( + () => provider.fetch(), + throwsA( + isA().having( + (final error) => error.type, + 'type', + UserSession, + ), + ), + ); + }, + ); + }); + + group('Given an empty context provider', () { + late ContextProvider provider; + + setUp(() { + provider = ContextProvider(); + }); + + test( + 'when a missing session is fetched ' + 'then the error names that type', + () { + expect( + () => provider.fetch(), + throwsA( + isA().having( + (final error) => error.type, + 'type', + UserSession, + ), + ), + ); + }, + ); + + test( + 'when a missing session is maybe-fetched ' + 'then null is returned', + () { + expect(provider.maybeFetch(), isNull); + }, + ); + + test('when a missing session is checked then has is false', () { + expect(provider.has(), isFalse); + }); + + test('when a missing session is removed then the provider stays empty', () { + provider.remove(); + expect(provider.has(), isFalse); + }); + }); + + group('Given a context provider', () { + late ContextProvider provider; + + setUp(() { + provider = ContextProvider(); + }); + + test('when a session is stored then fetch returns that session', () { + provider.store(const UserSession('ada')); + expect(provider.fetch().name, 'ada'); + }); + + test( + 'when a session is stored then maybeFetch returns that session', + () { + provider.store(const UserSession('ada')); + expect(provider.maybeFetch()?.name, 'ada'); + }, + ); + + test('when a session is stored then has is true', () { + provider.store(const UserSession('ada')); + expect(provider.has(), isTrue); + }); + + test( + 'when a session is stored again ' + 'then fetch returns the new session', + () { + provider + ..store(const UserSession('ada')) + ..store(const UserSession('grace')); + expect(provider.fetch().name, 'grace'); + }, + ); + + test( + 'when a session and a report are stored ' + 'then fetch returns the session', + () { + provider + ..store(const UserSession('ada')) + ..store(const CommandReport('built')); + expect(provider.fetch().name, 'ada'); + }, + ); + + test( + 'when a session and a report are stored ' + 'then fetch returns the report', + () { + provider + ..store(const UserSession('ada')) + ..store(const CommandReport('built')); + expect(provider.fetch().summary, 'built'); + }, + ); + + test( + 'when a session is removed ' + 'then that session is gone', + () { + provider + ..store(const UserSession('ada')) + ..remove(); + expect(provider.maybeFetch(), isNull); + }, + ); + + test( + 'when a session is removed ' + 'then the report stored beside it remains', + () { + provider + ..store(const UserSession('ada')) + ..store(const CommandReport('built')) + ..remove(); + expect(provider.fetch().summary, 'built'); + }, + ); + }); + + group('Given a session stored under Object', () { + late Object session; + late ContextProvider provider; + + setUp(() { + session = const UserSession('ada'); + provider = ContextProvider()..store(session); + }); + + test('when Object is fetched then that session is returned', () { + expect(provider.fetch(), same(session)); + }); + + test('when UserSession is maybe-fetched then null is returned', () { + expect(provider.maybeFetch(), isNull); + }); + + test('when UserSession is checked then has is false', () { + expect(provider.has(), isFalse); + }); + }); + + group('Given a context provider seeded from a type map', () { + test( + 'when the map keys a session under UserSession ' + 'then fetch returns that session', + () { + const session = UserSession('ada'); + final provider = ContextProvider({UserSession: session}); + expect(provider.fetch(), same(session)); + }, + ); + + test( + 'when the map keys a session under Object ' + 'then fetch Object returns that session', + () { + const session = UserSession('ada'); + final provider = ContextProvider({Object: session}); + expect(provider.fetch(), same(session)); + }, + ); + + test( + 'when the map keys a session under Object ' + 'then the UserSession slot is empty', + () { + final provider = ContextProvider({ + Object: const UserSession('ada'), + }); + expect(provider.has(), isFalse); + }, + ); + + test( + 'when the caller changes the map ' + 'then the provider still returns the original session', + () { + const session = UserSession('ada'); + final values = {UserSession: session}; + final provider = ContextProvider(values); + values[UserSession] = const UserSession('grace'); + expect(provider.fetch().name, 'ada'); + }, + ); + }); + + group( + 'Given a context provider whose map stores a string under UserSession', + () { + late ContextProvider provider; + + setUp(() { + provider = ContextProvider({UserSession: 'ada'}); + }); + + test( + 'when the session is fetched ' + 'then it throws ContextValueNotFound', + () { + expect( + () => provider.fetch(), + throwsA(isA()), + ); + }, + ); + + test('when the session is maybe-fetched then null is returned', () { + expect(provider.maybeFetch(), isNull); + }); + + test('when the session is checked then has is false', () { + expect(provider.has(), isFalse); + }); + }, + ); +} + +class UserSession { + const UserSession(this.name); + + final String name; +} + +class CommandReport { + const CommandReport(this.summary); + + final String summary; +} diff --git a/packages/config/test/command/help_command_test.dart b/packages/config/test/command/help_command_test.dart new file mode 100644 index 00000000..cad83600 --- /dev/null +++ b/packages/config/test/command/help_command_test.dart @@ -0,0 +1,1077 @@ +import 'dart:async'; + +import 'package:config/command.dart'; +import 'package:config/config.dart'; +import 'package:test/test.dart'; + +import 'command_fixtures.dart'; + +void main() { + group('Given a runner with no subcommands', () { + late List trace; + late TracingRunner runner; + late _CapturedUsage usage; + + setUp(() { + trace = []; + usage = _CapturedUsage(); + runner = TracingRunner( + trace, + usageOutput: usage.handler, + ); + }); + + group('when --help is passed', () { + late String? result; + + setUp(() async { + result = await runner.run(['--help']); + }); + + test('then usage for the runner is printed to standard output', () { + expect(usage.out.toString(), runner.usage); + expect(usage.err.toString(), isEmpty); + }); + + test('then no command runs', () { + expect(trace, isEmpty); + }); + + test('then no command result is returned', () { + expect(result, isNull); + }); + }); + + group('when -h is passed', () { + setUp(() async { + await runner.run(['-h']); + }); + + test('then the same runner usage is printed to standard output', () { + expect(usage.out.toString(), runner.usage); + expect(usage.err.toString(), isEmpty); + }); + }); + + group('when the command line is the word help', () { + late UsageException? error; + + setUp(() async { + error = await _captureUsageError(() => runner.run(['help'])); + }); + + test('then the unexpected word is reported', () { + expect( + error?.message, + "tool: Unexpected positional argument(s): 'help'", + ); + }); + + test('then the error and runner usage are printed to standard error', () { + expect( + usage.err.toString(), + _errorThenUsage( + "tool: Unexpected positional argument(s): 'help'", + runner.usage, + ), + ); + expect(usage.out.toString(), isEmpty); + }); + }); + }); + + group('Given a runner that can run as a leaf', () { + late List trace; + late TracingRunner runner; + late _CapturedUsage usage; + + setUp(() { + trace = []; + usage = _CapturedUsage(); + runner = TracingRunner( + trace, + canRunAsLeafCommand: true, + usageOutput: usage.handler, + subcommands: [_buildCommand(trace)], + ); + }); + + group('when --help is passed', () { + setUp(() async { + await runner.run(['--help']); + }); + + test('then usage for the runner lists the command and help', () { + expect(usage.out.toString(), runner.usage); + expect(usage.err.toString(), isEmpty); + }); + + test('then no command runs', () { + expect(trace, isEmpty); + }); + }); + }); + + group('Given a runner with a build command', () { + late List trace; + late TracingRunner runner; + late RecordingCommand build; + late _CapturedUsage usage; + + setUp(() { + trace = []; + usage = _CapturedUsage(); + build = _buildCommand(trace); + runner = TracingRunner( + trace, + usageOutput: usage.handler, + subcommands: [build], + ); + }); + + group('when --help is passed', () { + setUp(() async { + await runner.run(['--help']); + }); + + test( + 'then usage for the runner is printed to standard output', + () { + expect(usage.out.toString(), runner.usage); + expect(usage.err.toString(), isEmpty); + }, + ); + + test('then no command runs', () { + expect(trace, isEmpty); + }); + }); + + group('when --help precedes the build command', () { + setUp(() async { + await runner.run(['--help', 'build']); + }); + + test( + 'then usage for the build command is printed to standard output', + () { + expect(usage.out.toString(), build.usage); + expect(usage.err.toString(), isEmpty); + }, + ); + + test('then the build command does not run', () { + expect(trace, isEmpty); + }); + }); + + group('when --help follows the build command', () { + setUp(() async { + await runner.run(['build', '--help']); + }); + + test( + 'then usage for the build command is printed to standard output', + () { + expect(usage.out.toString(), build.usage); + expect(usage.err.toString(), isEmpty); + }, + ); + + test('then the build command does not run', () { + expect(trace, isEmpty); + }); + }); + + group('when help is asked for the build command', () { + setUp(() async { + await runner.run(['help', 'build']); + }); + + test( + 'then usage for the build command is printed to standard output', + () { + expect(usage.out.toString(), build.usage); + expect(usage.err.toString(), isEmpty); + }, + ); + + test('then the build command does not run', () { + expect(trace, isEmpty); + }); + }); + + group('when the command line is the word help', () { + setUp(() async { + await runner.run(['help']); + }); + + test( + 'then usage for the runner is printed to standard output', + () { + expect(usage.out.toString(), runner.usage); + expect(usage.err.toString(), isEmpty); + }, + ); + }); + + group('when help is asked for the help command', () { + setUp(() async { + await runner.run(['help', 'help']); + }); + + test( + 'then usage for the help command is printed to standard output', + () { + expect(usage.out.toString(), _helpCommand(runner).usage); + expect(usage.err.toString(), isEmpty); + }, + ); + }); + + group('when help command and --help option are passed', () { + setUp(() async { + await runner.run(['help', '--help']); + }); + + test( + 'then usage for the help command is printed to standard output', + () { + expect(usage.out.toString(), _helpCommand(runner).usage); + expect(usage.err.toString(), isEmpty); + }, + ); + }); + }); + + group('Given a command that takes no positional arguments', () { + late List trace; + late TracingRunner runner; + late RecordingCommand lint; + late _CapturedUsage usage; + + setUp(() { + trace = []; + usage = _CapturedUsage(); + lint = RecordingCommand( + name: 'lint', + description: 'Lint the app', + trace: trace, + ); + runner = TracingRunner( + trace, + usageOutput: usage.handler, + subcommands: [lint], + ); + }); + + group('when help is appended to the command', () { + setUp(() async { + await _captureUsageError(() => runner.run(['lint', 'help'])); + }); + + test( + 'then "help" is an unexpected positional argument ' + 'and reported along with the command usage', + () { + expect( + usage.err.toString(), + _errorThenUsage( + "lint: Unexpected positional argument(s): 'help'", + lint.usage, + ), + ); + expect(usage.out.toString(), isEmpty); + }, + ); + + test('then the command does not run', () { + expect(trace, isEmpty); + }); + }); + }); + + group('Given a branch command', () { + late List trace; + late TracingRunner runner; + late RecordingCommand remote; + late _CapturedUsage usage; + + setUp(() { + trace = []; + usage = _CapturedUsage(); + remote = _remoteCommand(trace); + runner = TracingRunner( + trace, + usageOutput: usage.handler, + subcommands: [remote], + ); + }); + + group('when help is asked for the branch', () { + late UsageException? error; + + setUp(() async { + error = await _captureUsageError( + () => runner.run(['help', 'remote']), + ); + }); + + test('then the missing subcommand is not an error', () { + expect(error, isNull); + }); + + test( + 'then usage for the remote command is printed to standard output', + () { + expect(usage.out.toString(), remote.usage); + expect(usage.err.toString(), isEmpty); + }, + ); + + test('then the branch command does not run', () { + expect(trace, isEmpty); + }); + }); + + group('when help is asked for the nested command', () { + setUp(() async { + await runner.run(['help', 'remote', 'add']); + }); + + test( + 'then usage for the nested command is printed to standard output', + () { + final add = remote.subcommands.firstWhere( + (final command) => command.name == 'add', + ); + expect(usage.out.toString(), add.usage); + expect(usage.err.toString(), isEmpty); + }, + ); + + test('then the nested command does not run', () { + expect(trace, isEmpty); + }); + }); + + group('when help is asked for an unknown nested command', () { + late UsageException? error; + + setUp(() async { + error = await _captureUsageError( + () => runner.run(['help', 'remote', 'bogus']), + ); + }); + + test('then the unknown subcommand is reported ' + 'along with the remote usage', () { + expect(error?.message, 'remote: Unknown subcommand: "bogus"'); + expect( + usage.err.toString(), + _errorThenUsage('remote: Unknown subcommand: "bogus"', remote.usage), + ); + expect(usage.out.toString(), isEmpty); + }); + }); + + group('when --help follows the branch', () { + late UsageException? error; + + setUp(() async { + error = await _captureUsageError( + () => runner.run(['remote', '--help']), + ); + }); + + test('then the missing subcommand is not an error', () { + expect(error, isNull); + }); + + test( + 'then usage for the remote command is printed to standard output', + () { + expect(usage.out.toString(), remote.usage); + expect(usage.err.toString(), isEmpty); + }, + ); + + test('then the branch command does not run', () { + expect(trace, isEmpty); + }); + }); + + group('when --help precedes the branch', () { + late UsageException? error; + + setUp(() async { + error = await _captureUsageError( + () => runner.run(['--help', 'remote']), + ); + }); + + test('then the missing subcommand is not an error', () { + expect(error, isNull); + }); + + test( + 'then usage for the remote command is printed to standard output', + () { + expect(usage.out.toString(), remote.usage); + expect(usage.err.toString(), isEmpty); + }, + ); + }); + + group('when --help follows the branch with an unknown option', () { + late UsageException? error; + + setUp(() async { + error = await _captureUsageError( + () => runner.run(['remote', '--bogus', '--help']), + ); + }); + + test('then the unknown option is reported along with the usage', () { + expect(error?.message, 'remote: Unknown option: --bogus.'); + expect( + usage.err.toString(), + _errorThenUsage('remote: Unknown option: --bogus.', remote.usage), + ); + expect(usage.out.toString(), isEmpty); + }); + + test('then the branch command does not run', () { + expect(trace, isEmpty); + }); + }); + + group('when help is the last command', () { + setUp(() async { + await runner.run(['remote', 'help']); + }); + + test( + 'then usage for the remote command is printed to standard output', + () { + expect(usage.out.toString(), remote.usage); + expect(usage.err.toString(), isEmpty); + }, + ); + + test('then the branch command does not run', () { + expect(trace, isEmpty); + }); + }); + }); + + group('Given a command with mandatory options', () { + late List trace; + late TracingRunner runner; + late RecordingCommand deploy; + late _CapturedUsage usage; + + setUp(() { + trace = []; + usage = _CapturedUsage(); + deploy = RecordingCommand( + name: 'deploy', + description: 'Deploy the app', + trace: trace, + options: const [ + StringOption(argName: 'target', argPos: 0, mandatory: true), + FlagOption(argName: 'json', group: _format, negatable: false), + FlagOption(argName: 'yaml', group: _format, negatable: false), + ], + ); + runner = TracingRunner( + trace, + usageOutput: usage.handler, + subcommands: [deploy], + ); + }); + + group('when help is asked for the command', () { + late UsageException? error; + + setUp(() async { + error = await _captureUsageError( + () => runner.run(['help', 'deploy']), + ); + }); + + test('then the missing mandatory option and mandatory group ' + 'are not errors', () { + expect(error, isNull); + }); + + test('then usage for the command is printed to standard output', () { + expect(usage.out.toString(), deploy.usage); + expect(usage.err.toString(), isEmpty); + }); + + test('then the command does not run', () { + expect(trace, isEmpty); + }); + }); + + group('when help is asked for the command with an invalid value', () { + late UsageException? error; + + setUp(() async { + error = await _captureUsageError( + () => runner.run(['help', 'deploy', '--json', '--yaml']), + ); + }); + + test('then the mutually exclusive options are reported ' + 'along with the usage', () { + expect( + error?.message, + 'deploy: These options are mutually exclusive: json, yaml.', + ); + expect( + usage.err.toString(), + _errorThenUsage( + 'deploy: These options are mutually exclusive: json, yaml.', + deploy.usage, + ), + ); + expect(usage.out.toString(), isEmpty); + }); + }); + + group('when help is asked for the command with an unknown option', () { + late UsageException? error; + + setUp(() async { + error = await _captureUsageError( + () => runner.run(['help', 'deploy', '--bogus']), + ); + }); + + test('then the unknown option is reported along with the usage', () { + expect(error?.message, 'deploy: Unknown option: --bogus.'); + expect( + usage.err.toString(), + _errorThenUsage('deploy: Unknown option: --bogus.', deploy.usage), + ); + expect(usage.out.toString(), isEmpty); + }); + }); + + group('when --help is passed without the mandatory options', () { + late UsageException? error; + + setUp(() async { + error = await _captureUsageError( + () => runner.run(['deploy', '--help']), + ); + }); + + test('then the missing mandatory option and mandatory group ' + 'are not errors', () { + expect(error, isNull); + }); + + test('then usage for the command is printed to standard output', () { + expect(usage.out.toString(), deploy.usage); + expect(usage.err.toString(), isEmpty); + }); + + test('then the command does not run', () { + expect(trace, isEmpty); + }); + }); + + group('when --help is passed with an invalid value', () { + late UsageException? error; + + setUp(() async { + error = await _captureUsageError( + () => runner.run(['deploy', '--json', '--yaml', '--help']), + ); + }); + + test('then the mutually exclusive options are reported ' + 'along with the usage', () { + expect( + error?.message, + 'deploy: These options are mutually exclusive: json, yaml.', + ); + expect( + usage.err.toString(), + _errorThenUsage( + 'deploy: These options are mutually exclusive: json, yaml.', + deploy.usage, + ), + ); + expect(usage.out.toString(), isEmpty); + }); + }); + + group('when --help is passed with an option that has no value', () { + late UsageException? error; + + setUp(() async { + error = await _captureUsageError( + () => runner.run(['deploy', '--help', '--target']), + ); + }); + + test( + 'then the missing option value is reported along with the usage', + () { + expect(error?.message, 'deploy: Missing value for option: --target.'); + expect( + usage.err.toString(), + _errorThenUsage( + 'deploy: Missing value for option: --target.', + deploy.usage, + ), + ); + expect(usage.out.toString(), isEmpty); + }, + ); + }); + + group( + 'when help is asked for the command with an option that has no value', + () { + late UsageException? error; + + setUp(() async { + error = await _captureUsageError( + () => runner.run(['help', 'deploy', '--target']), + ); + }); + + test( + 'then the missing option value is reported along with the usage', + () { + expect( + error?.message, + 'deploy: Missing value for option: --target.', + ); + expect( + usage.err.toString(), + _errorThenUsage( + 'deploy: Missing value for option: --target.', + deploy.usage, + ), + ); + expect(usage.out.toString(), isEmpty); + }, + ); + }, + ); + + group('when --help is passed with an unknown option', () { + late UsageException? error; + + setUp(() async { + error = await _captureUsageError( + () => runner.run(['deploy', '--bogus', '--help']), + ); + }); + + test('then the unknown option is reported along with the usage', () { + expect(error?.message, 'deploy: Unknown option: --bogus.'); + expect( + usage.err.toString(), + _errorThenUsage('deploy: Unknown option: --bogus.', deploy.usage), + ); + expect(usage.out.toString(), isEmpty); + }); + }); + + group('when the command is run without its mandatory options', () { + late UsageException? error; + + setUp(() async { + error = await _captureUsageError(() => runner.run(['deploy'])); + }); + + test('then the usage error is still reported', () { + expect(error?.message, contains('mandatory')); + expect(trace, isEmpty); + }); + }); + }); + + group('Given a runner with a mandatory global option', () { + late List trace; + late TracingRunner runner; + late _CapturedUsage usage; + + setUp(() { + trace = []; + usage = _CapturedUsage(); + runner = TracingRunner( + trace, + usageOutput: usage.handler, + globalOptions: const [ + StringOption(argName: 'account', mandatory: true), + ], + subcommands: [_buildCommand(trace)], + ); + }); + + test('when the command line is the word help ' + 'then usage for the runner is printed without an error', () async { + final error = await _captureUsageError(() => runner.run(['help'])); + expect(error, isNull); + expect(usage.out.toString(), runner.usage); + expect(usage.err.toString(), isEmpty); + }); + + test('when help is asked for the build command ' + 'then its usage is printed without an error', () async { + final error = await _captureUsageError( + () => runner.run(['help', 'build']), + ); + expect(error, isNull); + expect(usage.out.toString(), contains('Usage: tool build')); + expect(usage.err.toString(), isEmpty); + }); + + test('when the runner has an unknown option before help ' + 'then the unknown option is reported', () async { + final error = await _captureUsageError( + () => runner.run(['--bogus', 'help']), + ); + expect(error?.message, 'tool: Unknown option: --bogus.'); + }); + + test('when --help is passed ' + 'then usage for the runner is printed without an error', () async { + final error = await _captureUsageError(() => runner.run(['--help'])); + expect(error, isNull); + expect(usage.out.toString(), runner.usage); + expect(usage.err.toString(), isEmpty); + }); + + test('when --help is passed with an unknown option ' + 'then the unknown option is reported', () async { + final error = await _captureUsageError( + () => runner.run(['--bogus', '--help']), + ); + expect(error?.message, 'tool: Unknown option: --bogus.'); + }); + }); + + group('Given a visible command and a hidden command', () { + late List trace; + late TracingRunner runner; + late _CapturedUsage usage; + + setUp(() { + trace = []; + usage = _CapturedUsage(); + runner = TracingRunner( + trace, + usageOutput: usage.handler, + subcommands: [ + _buildCommand(trace), + RecordingCommand( + name: 'secret', + description: 'Hidden command', + trace: trace, + hidden: true, + ), + ], + ); + }); + + group('when help describes itself', () { + setUp(() async { + await runner.run(['--help', 'help']); + }); + + test( + 'then usage for the help command is printed to standard output', + () { + expect(usage.out.toString(), _helpCommand(runner).usage); + expect(usage.err.toString(), isEmpty); + }, + ); + + test('then no command runs', () { + expect(trace, isEmpty); + }); + }); + + group('when help is asked for the hidden command', () { + late UsageException? error; + + setUp(() async { + error = await _captureUsageError( + () => runner.run(['help', 'secret']), + ); + }); + + test('then a usage exception is thrown', () { + expect(error, isA()); + }); + + test( + 'then the error and help usage are printed to standard error', + () { + expect( + usage.err.toString(), + _errorThenUsage( + 'help: Unknown subcommand: "secret"', + _helpCommand(runner).usage, + ), + ); + expect(usage.out.toString(), isEmpty); + }, + ); + }); + }); + + group('Given a custom command named help', () { + late List trace; + late TracingRunner runner; + + setUp(() { + trace = []; + final help = RecordingCommand( + name: 'help', + description: 'Custom help', + trace: trace, + ); + final build = RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + ); + runner = TracingRunner(trace, subcommands: [build, help]); + }); + + test( + 'when help is invoked ' + 'then only the custom command runs', + () async { + await runner.run(['help']); + + expect(trace, ['help']); + }, + ); + }); + + group('Given a help command with a custom run method', () { + late List trace; + late TracingRunner runner; + + setUp(() { + trace = []; + runner = TracingRunner( + trace, + subcommands: [ + RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + ), + _GuideCommand(trace), + ], + ); + }); + + group('when help is invoked', () { + late String? result; + + setUp(() async { + result = await runner.run(['help']); + }); + + test('then only the custom help command runs', () { + expect(trace, ['guide']); + }); + + test('then its result is returned', () { + expect(result, 'guided'); + }); + }); + }); + + group('Given runner middleware and a help request', () { + late List trace; + late _CapturedUsage usage; + late CommandRunner runner; + + setUp(() async { + trace = []; + usage = _CapturedUsage(); + runner = CommandRunner( + 'tool', + 'Tools', + usageOutput: usage.handler, + middlewares: [ + (final next) => (final context) { + trace.add('root'); + return next(context); + }, + ], + subcommands: [_buildCommand(trace)], + ); + await runner.run(['--help']); + }); + + test( + 'when --help is passed ' + 'then usage for the runner is printed to standard output', + () { + expect(usage.out.toString(), runner.usage); + expect(usage.err.toString(), isEmpty); + }, + ); + + test('when --help is passed then middleware does not run', () { + expect(trace, isEmpty); + }); + }); + + group('Given middleware on the runner and its subcommands', () { + late List trace; + late _CapturedUsage usage; + late CommandRunner runner; + late RecordingCommand list; + + setUp(() async { + trace = []; + usage = _CapturedUsage(); + list = RecordingCommand( + name: 'list', + description: 'List projects', + trace: trace, + middlewares: [ + (final next) => (final context) { + trace.add('list-middleware'); + return next(context); + }, + ], + ); + final project = RecordingCommand( + name: 'project', + description: 'Manage projects', + trace: trace, + middlewares: [ + (final next) => (final context) { + trace.add('project-middleware'); + return next(context); + }, + ], + subcommands: [list], + ); + runner = CommandRunner( + 'tool', + 'Tools', + usageOutput: usage.handler, + middlewares: [ + (final next) => (final context) { + trace.add('root-middleware'); + return next(context); + }, + ], + subcommands: [project], + ); + await runner.run(['project', 'list', '--help']); + }); + + test( + 'when --help follows the subcommand ' + 'then usage for that command is printed to standard output', + () { + expect(usage.out.toString(), list.usage); + expect(usage.err.toString(), isEmpty); + }, + ); + + test( + 'when --help follows the subcommand ' + 'then no middleware runs', + () { + expect(trace, isEmpty); + }, + ); + }); +} + +const _format = MutuallyExclusive( + 'Format', + mode: MutuallyExclusiveMode.mandatory, +); + +Future _captureUsageError( + final FutureOr Function() body, +) async { + try { + await body(); + } on UsageException catch (error) { + return error; + } + return null; +} + +/// Buffers passed to [UsageOutputHandler] so tests can read usage text. +class _CapturedUsage { + final out = StringBuffer(); + final err = StringBuffer(); + + late final UsageOutputHandler handler = UsageOutputHandler( + sinks: OutputSinks(out: out, err: err), + ); +} + +RecordingCommand _buildCommand(final List trace) { + return RecordingCommand( + name: 'build', + description: 'Build the app', + trace: trace, + aliases: ['b'], + options: const [ + StringOption(argName: 'target', argAbbrev: 't'), + FlagOption(argName: 'release', defaultsTo: false), + StringOption(argPos: 0), + ], + ); +} + +RecordingCommand _remoteCommand(final List trace) { + return RecordingCommand( + name: 'remote', + description: 'Manage remotes', + trace: trace, + aliases: ['r'], + options: const [ + StringOption(argName: 'env', argAbbrev: 'e'), + ], + subcommands: [ + RecordingCommand( + name: 'add', + description: 'Add a remote', + trace: trace, + ), + ], + ); +} + +class _GuideCommand extends HelpCommand { + _GuideCommand(this.trace); + + final List trace; + + @override + String? run(final CommandContext context) { + trace.add('guide'); + return 'guided'; + } +} + +CommandDefinition _helpCommand(final CommandDefinition command) => + command.subcommands.firstWhere((final sub) => sub.name == 'help'); + +String _errorThenUsage(final String message, final String usage) => + '$message\n\n$usage'; diff --git a/packages/config/test/command/usage_formatting_test.dart b/packages/config/test/command/usage_formatting_test.dart new file mode 100644 index 00000000..2c99a6f4 --- /dev/null +++ b/packages/config/test/command/usage_formatting_test.dart @@ -0,0 +1,1385 @@ +import 'package:config/command.dart'; +import 'package:config/config.dart'; +import 'package:test/test.dart'; + +void main() { + group('Given a command with no options', () { + late Command command; + + setUp(() { + command = _command(name: 'version', description: 'Show the version'); + _runner(subcommands: [command]); + }); + + test('when reading usage then the formatted usage is produced', () { + expect( + command.usage, + _usage(const [ + 'Show the version', + '', + 'Usage: tool version', + '', + 'Run "tool help" to see global options.', + ]), + ); + }); + }); + + group('Given a command with a mandatory named option', () { + late Command command; + + setUp(() { + command = _command( + name: 'greet', + description: 'Greet', + options: const [ + StringOption(argName: 'name', mandatory: true), + ], + ); + _runner(subcommands: [command]); + }); + + test('when reading usage then the formatted usage is produced', () { + expect( + command.usage, + _usage(const [ + 'Greet', + '', + 'Usage: tool greet --name=', + '', + 'Options:', + '--name ', + ' (mandatory)', + '', + 'Run "tool help" to see global options.', + ]), + ); + }); + }); + + group( + 'Given a command with an abbreviation, a flag, and a positional option', + () { + late Command command; + + setUp(() { + command = _command( + name: 'build', + description: 'Build the app', + aliases: const ['b'], + options: const [ + StringOption(argName: 'target', argAbbrev: 't'), + FlagOption(argName: 'release', defaultsTo: false), + StringOption(argPos: 0), + ], + ); + _runner(subcommands: [command]); + }); + + test('when reading usage then the formatted usage is produced', () { + expect( + command.usage, + _usage(const [ + 'Build the app', + '', + 'Usage: tool build [] [--target=] [--[no-]release]', + '', + 'Options:', + '-t, --target ', + '--[no-]release ', + ' (defaults to false)', + '{0} ', + '', + 'Run "tool help" to see global options.', + ]), + ); + }); + }, + ); + + group('Given a command with an option and a subcommand', () { + late Command command; + + setUp(() { + command = _command( + name: 'remote', + description: 'Manage remotes', + aliases: const ['r'], + options: const [ + StringOption(argName: 'env', argAbbrev: 'e'), + ], + subcommands: [ + _command(name: 'add', description: 'Add a remote'), + ], + ); + _runner(subcommands: [command]); + }); + + test('when reading usage then the formatted usage is produced', () { + expect( + command.usage, + _usage(const [ + 'Manage remotes', + '', + 'Usage: tool remote [--env=] [arguments]', + '', + 'Options:', + '-e, --env ', + '', + 'Available subcommands:', + ' add Add a remote', + '', + 'Run "tool help" to see global options.', + ]), + ); + }); + }); + + group('Given a command with a mandatory option and a subcommand', () { + late Command command; + + setUp(() { + command = _command( + name: 'build', + description: 'Build the app', + options: const [ + StringOption(argName: 'target', mandatory: true), + ], + subcommands: [ + _command(name: 'version', description: 'Show the version'), + ], + ); + _runner(subcommands: [command]); + }); + + test('when reading usage then the formatted usage is produced', () { + expect( + command.usage, + _usage(const [ + 'Build the app', + '', + 'Usage: tool build --target= [arguments]', + '', + 'Options:', + '--target ', + ' (mandatory)', + '', + 'Available subcommands:', + ' version Show the version', + '', + 'Run "tool help" to see global options.', + ]), + ); + }); + }); + + group('Given a runner with no subcommands', () { + late CommandRunner runner; + + setUp(() { + runner = _runner(); + }); + + test('when reading usage then the formatted usage is produced', () { + expect( + runner.usage, + _usage(const [ + 'Tools', + '', + 'Usage: tool [global-options]', + '', + 'Global options:', + '-h, --help Print this usage information.', + '', + ]), + ); + }); + }); + + group('Given a runner with a subcommand', () { + late CommandRunner runner; + + setUp(() { + runner = _runner( + subcommands: [ + _command(name: 'greet', description: 'Greet'), + ], + ); + }); + + test('when reading usage then the formatted usage is produced', () { + expect( + runner.usage, + _usage(const [ + 'Tools', + '', + 'Usage: tool [global-options] [arguments]', + '', + 'Global options:', + '-h, --help Print this usage information.', + '', + 'Available commands:', + ' greet Greet', + '', + 'Run "tool help " for more information about a command.', + ]), + ); + }); + }); + + group('Given a runner with a build command', () { + late CommandRunner runner; + + setUp(() { + runner = _runner( + subcommands: [ + _command(name: 'build', description: 'Build the app'), + ], + ); + }); + + test('when reading usage then the formatted usage is produced', () { + expect( + runner.usage, + _usage(const [ + 'Tools', + '', + 'Usage: tool [global-options] [arguments]', + '', + 'Global options:', + '-h, --help Print this usage information.', + '', + 'Available commands:', + ' build Build the app', + '', + 'Run "tool help " for more information about a command.', + ]), + ); + }); + }); + + group('Given a runner with a mandatory global option', () { + late CommandRunner runner; + + setUp(() { + runner = _runner( + globalOptions: const [ + StringOption(argName: 'verbose', mandatory: true), + ], + subcommands: [ + _command(name: 'greet', description: 'Greet'), + ], + ); + }); + + test('when reading usage then the formatted usage is produced', () { + expect( + runner.usage, + _usage(const [ + 'Tools', + '', + 'Usage: tool [global-options] [arguments]', + '', + 'Global options:', + '-h, --help Print this usage information.', + '--verbose ', + ' (mandatory)', + '', + 'Available commands:', + ' greet Greet', + '', + 'Run "tool help " for more information about a command.', + ]), + ); + }); + }); + + group('Given a help command for a runner with a hidden command', () { + late CommandDefinition help; + + setUp(() { + final runner = _runner( + subcommands: [ + _command(name: 'build', description: 'Build the app'), + _command( + name: 'secret', + description: 'Hidden command', + hidden: true, + ), + ], + ); + help = runner.subcommands.firstWhere( + (final command) => command.name == 'help', + ); + }); + + test('when reading usage then the formatted usage is produced', () { + expect( + help.usage, + _usage(const [ + 'Show help for a command.', + '', + 'Usage: tool help []', + '', + 'Available subcommands:', + ' build Build the app', + '', + 'Run "tool help" to see global options.', + ]), + ); + }); + }); + + group('Given a subcommand with a flag', () { + late Command command; + + setUp(() { + command = _command( + name: 'date', + description: 'Show the date', + options: const [ + FlagOption(argName: 'utc', negatable: false), + ], + ); + _runner(subcommands: [command]); + }); + + test( + 'when reading usage then the synopsis includes the parent command', + () { + expect( + command.usage, + contains('Usage: tool date [--utc]'), + ); + }, + ); + }); + + group('Given persistent, positional, and named options', () { + late Command command; + + setUp(() { + command = _command( + name: 'copy', + description: 'Copy a file', + persistentOptions: const [ + FlagOption(argName: 'verbose', negatable: false), + ], + options: const [ + StringOption(argPos: 0, valueHelp: 'file', mandatory: true), + StringOption( + argName: 'file', + argPos: 1, + valueHelp: 'dest', + mandatory: true, + ), + StringOption(argName: 'target'), + FlagOption(argName: 'color', hideNegatedUsage: true), + FlagOption(argName: 'force', negatable: false, mandatory: true), + MultiStringOption(argName: 'include', valueHelp: 'path'), + MultiStringOption(argName: 'tag', mandatory: true), + StringOption(argName: 'secret', hide: true), + StringOption(envName: 'COPY_MODE'), + ], + ); + _runner(subcommands: [command]); + }); + + test( + 'when reading usage then the synopsis orders positionals before names', + () { + expect( + command.usage, + contains( + 'Usage: tool copy [--verbose] [--target=] ' + '[--color] --force [--include=]... --tag=...', + ), + ); + }, + ); + }); + + group('Given a mandatory exclusive group', () { + late Command command; + late CommandRunner runner; + + setUp(() { + const format = MutuallyExclusive( + 'format', + mode: MutuallyExclusiveMode.mandatory, + ); + const input = MutuallyExclusive( + 'input', + mode: MutuallyExclusiveMode.mandatory, + ); + command = _command( + name: 'render', + description: 'Render', + persistentOptions: const [ + StringOption(argName: 'stdin', group: input), + ], + // The positional member of a group is the last positional: when the + // named member is given instead, no later positional takes its place. + options: const [ + StringOption(argPos: 0, valueHelp: 'dest', mandatory: true), + StringOption(argPos: 1, valueHelp: 'file', group: input), + FlagOption(argName: 'verbose', negatable: false), + StringOption(argName: 'json', group: format), + StringOption(argName: 'text', valueHelp: 'file', group: format), + ], + ); + runner = _runner(subcommands: [command]); + }); + + test( + 'when reading usage then the group is one required choice', + () { + expect( + command.usage, + contains( + 'Usage: tool render ( | --stdin=) [--verbose] ' + '(--json= | --text=)', + ), + ); + }, + ); + + test('when running with the positional member of the group ' + 'then the command line is accepted', () async { + await expectLater( + runner.run(['render', 'destination', 'source', '--json=value']), + completes, + ); + }); + + test('when running with the named member of the group ' + 'then the command line is accepted', () async { + await expectLater( + runner.run(['render', 'destination', '--stdin=source', '--text=value']), + completes, + ); + }); + }); + + group('Given an optional exclusive group', () { + late Command command; + + setUp(() { + const format = MutuallyExclusive('format'); + command = _command( + name: 'render', + description: 'Render', + options: const [ + FlagOption(argName: 'json', negatable: false, group: format), + FlagOption(argName: 'text', negatable: false, group: format), + ], + ); + _runner(subcommands: [command]); + }); + + test( + 'when reading usage then the group is one optional choice', + () { + expect( + command.usage, + contains('Usage: tool render [--json | --text]'), + ); + }, + ); + }); + + group('Given a runner with long usage text', () { + late CommandRunner runner; + + setUp(() { + runner = _longUsageRunner(); + }); + + test('when reading usage then the text is not wrapped', () { + expect( + runner.usage, + _usage(const [ + 'A command line tool that builds and deploys applications.', + '', + 'Usage: tool [global-options] [arguments]', + '', + 'Global options:', + '-h, --help Print this usage information.', + '--verbose Print extra information while the command is running.', + '', + 'Available commands:', + ' build Build the application from the current sources.', + '', + 'Run "tool help " for more information about a command.', + '', + 'See the documentation for more details about this tool.', + ]), + ); + }); + }); + + group('Given a runner with a usage line length', () { + late CommandRunner runner; + + setUp(() { + runner = _longUsageRunner(usageLineLength: 40); + }); + + test('when reading usage then the text is wrapped to that length', () { + expect( + runner.usage, + _usage(const [ + 'A command line tool that builds and', + 'deploys applications.', + '', + 'Usage: tool [global-options] ', + ' [arguments]', + '', + 'Global options:', + '-h, --help Print this usage', + ' information.', + '--verbose Print extra information', + ' while the command is', + ' running.', + '', + 'Available commands:', + ' build Build the application from the', + ' current sources.', + '', + 'Run "tool help " for more', + 'information about a command.', + '', + 'See the documentation for more details', + 'about this tool.', + ]), + ); + }); + }); + + group('Given a subcommand of a runner with a usage line length', () { + late Command command; + + setUp(() { + final runner = _longUsageRunner(usageLineLength: 40); + command = runner.subcommands.firstWhere( + (final subcommand) => subcommand.name == 'build', + ); + }); + + test( + 'when reading usage then the text is wrapped to the runner length', + () { + expect( + command.usage, + _usage(const [ + 'Build the application from the current', + 'sources.', + '', + 'Usage: tool build [--release]', + '', + 'Options:', + '--release Compile with optimizations', + ' for a production release.', + '', + 'Run "tool help" to see global options.', + ]), + ); + }, + ); + }); + + group('Given a subcommand whose synopsis fits the usage line length ' + 'only without the usage prefix', () { + late Command command; + + setUp(() { + command = _command( + name: 'copy', + description: 'Copy', + options: const [ + StringOption(argName: 'from'), + StringOption(argName: 'to'), + ], + ); + _runner(subcommands: [command], usageLineLength: 40); + }); + + test('when reading usage ' + 'then the first synopsis line leaves room for the prefix', () { + expect( + command.usage, + contains( + 'Usage: tool copy [--from=]\n' + ' [--to=]\n', + ), + ); + }); + + test('when reading usage ' + 'then no line is longer than the line length', () { + expect( + command.usage.split('\n').map((final line) => line.length), + everyElement(lessThanOrEqualTo(40)), + ); + }); + }); + + group('Given a usage line length shorter than ten columns', () { + late CommandRunner runner; + + setUp(() { + runner = _runner( + description: 'abcdefghijabcdefghijab', + usageLineLength: 1, + ); + }); + + test( + 'when reading usage then a long word is split every ten characters', + () { + expect( + runner.usage, + startsWith('abcdefghij\nabcdefghij\nab\n\n'), + ); + }, + ); + }); + + group('Given a command that can run as a leaf and has a subcommand', () { + late Command command; + + setUp(() { + command = _command( + name: 'build', + description: 'Build', + canRunAsLeafCommand: true, + options: const [ + FlagOption(argName: 'force', negatable: false), + ], + subcommands: [ + _command(name: 'version', description: 'Show the version'), + ], + ); + _runner(subcommands: [command]); + }); + + test( + 'when reading usage then the synopsis has a leaf alternative', + () { + expect( + command.usage, + contains( + 'Usage: tool build [--force] [arguments]\n' + ' or: tool build [--force]\n', + ), + ); + }, + ); + }); + + group('Given a command with only hidden options', () { + late Command command; + + setUp(() { + command = _command( + name: 'login', + description: 'Log in', + persistentOptions: const [ + FlagOption(argName: 'trace', negatable: false, hide: true), + ], + options: const [ + StringOption(argName: 'token', hide: true), + ], + ); + _runner(subcommands: [command]); + }); + + test('when reading usage then no option sections are shown', () { + expect( + command.usage, + _usage(const [ + 'Log in', + '', + 'Usage: tool login', + '', + 'Run "tool help" to see global options.', + ]), + ); + }); + }); + + group('Given an option set only by a single configuration key', () { + late Command command; + + setUp(() { + command = _command( + name: 'deploy', + description: 'Deploy', + options: const [ + StringOption(configKey: 'endpoint', helpText: 'Server endpoint'), + ], + ); + _runner(subcommands: [command]); + }); + + test('when reading usage then the option is listed by its key', () { + expect( + command.usage, + _usage(const [ + 'Deploy', + '', + 'Usage: tool deploy', + '', + 'Options:', + '{endpoint} Server endpoint', + ' key "endpoint"', + '', + 'Run "tool help" to see global options.', + ]), + ); + }); + }); + + group('Given an option with a single and several configuration keys', () { + late Command command; + + setUp(() { + command = _command( + name: 'deploy', + description: 'Deploy', + options: const [ + StringOption( + argName: 'endpoint', + configKey: 'endpoint', + configKeys: ['server.endpoint'], + ), + ], + ); + _runner(subcommands: [command]); + }); + + test('when reading usage then all keys are listed, the single first', () { + expect( + command.usage, + _usage(const [ + 'Deploy', + '', + 'Usage: tool deploy [--endpoint=]', + '', + 'Options:', + '--endpoint ', + ' key "endpoint"', + ' key "server.endpoint"', + '', + 'Run "tool help" to see global options.', + ]), + ); + }); + }); + + group('Given options declared out of alphabetical order', () { + late Command command; + + setUp(() { + command = _command( + name: 'build', + description: 'Build', + options: const [ + FlagOption(argName: 'zebra', negatable: false), + FlagOption(argName: 'alpha', negatable: false), + FlagOption(argName: 'middle', negatable: false), + ], + ); + _runner(subcommands: [command]); + }); + + test( + 'when reading usage then the options stay in declaration order', + () { + expect( + command.usage, + _usage(const [ + 'Build', + '', + 'Usage: tool build [--zebra] [--alpha] [--middle]', + '', + 'Options:', + '--zebra ', + '--alpha ', + '--middle ', + '', + 'Run "tool help" to see global options.', + ]), + ); + }, + ); + }); + + group('Given options assigned to option groups', () { + late Command command; + + setUp(() { + const logging = OptionGroup('Logging'); + const output = OptionGroup('Output'); + command = _command( + name: 'build', + description: 'Build', + options: const [ + FlagOption(argName: 'zebra', negatable: false), + FlagOption(argName: 'verbose', negatable: false, group: logging), + FlagOption(argName: 'alpha', negatable: false), + FlagOption(argName: 'json', negatable: false, group: output), + FlagOption(argName: 'quiet', negatable: false, group: logging), + FlagOption(argName: 'text', negatable: false, group: output), + ], + ); + _runner(subcommands: [command]); + }); + + test( + 'when reading usage then each group is a headline above its options', + () { + expect( + command.usage, + _usage(const [ + 'Build', + '', + 'Usage: tool build [--zebra] [--verbose] [--alpha] [--json] ' + '[--quiet] [--text]', + '', + 'Options:', + '--zebra ', + '--alpha ', + '', + 'Logging', + '--verbose ', + '--quiet ', + '', + 'Output', + '--json ', + '--text ', + '', + 'Run "tool help" to see global options.', + ]), + ); + }, + ); + }); + + group('Given an enum option', () { + late Command command; + + setUp(() { + command = _command( + name: 'go', + description: 'Go somewhere', + options: const [ + EnumOption( + enumParser: EnumParser(_Pace.values), + argName: 'pace', + helpText: 'How fast to go', + defaultsTo: _Pace.slow, + ), + ], + ); + _runner(subcommands: [command]); + }); + + test( + 'when reading usage then the enum values are listed without an allow-list', + () { + expect( + command.usage, + _usage(const [ + 'Go somewhere', + '', + 'Usage: tool go [--pace=]', + '', + 'Options:', + '--pace How fast to go', + ' values: [fast, slow (default)]', + '', + 'Run "tool help" to see global options.', + ]), + ); + }, + ); + }); + + group('Given an enum option restricted to a subset', () { + late Command command; + + setUp(() { + command = _command( + name: 'go', + description: 'Go somewhere', + options: const [ + EnumOption( + enumParser: EnumParser(_Pace.values), + argName: 'pace', + helpText: 'How fast to go', + allowedValues: [_Pace.fast], + ), + ], + ); + _runner(subcommands: [command]); + }); + + test('when reading usage then only the allowed values are listed', () { + expect( + command.usage, + contains('values: [fast]'), + ); + expect(command.usage, isNot(contains('slow'))); + }); + }); + + group('Given an option with allowed values and a default', () { + late Command command; + + setUp(() { + command = _command( + name: 'play', + description: 'Play a card', + options: const [ + StringOption( + argName: 'suit', + helpText: 'Like in cards', + defaultsTo: 'clubs', + allowedValues: ['spades', 'clubs', 'hearts', 'diamonds'], + ), + ], + ); + _runner(subcommands: [command]); + }); + + test( + 'when reading usage then the default value is marked in the list', + () { + expect( + command.usage, + _usage(const [ + 'Play a card', + '', + 'Usage: tool play [--suit=]', + '', + 'Options:', + '--suit Like in cards', + ' values: [spades, clubs (default), hearts, diamonds]', + '', + 'Run "tool help" to see global options.', + ]), + ); + }, + ); + }); + + group('Given a multi-option with allowed values and a default', () { + late Command command; + + setUp(() { + command = _command( + name: 'play', + description: 'Play cards', + options: const [ + MultiStringOption( + argName: 'suits', + helpText: 'Like in cards', + defaultsTo: ['clubs', 'hearts'], + allowedValues: ['spades', 'clubs', 'hearts', 'diamonds'], + ), + ], + ); + _runner(subcommands: [command]); + }); + + test('when reading usage then the allowed values are listed ' + 'with each default value marked', () { + expect( + command.usage, + contains( + 'values: [spades, clubs (default), hearts (default), diamonds]', + ), + ); + }); + + test('when reading usage then the default is not listed on its own', () { + expect(command.usage, isNot(contains('defaults to'))); + }); + }); + + group('Given an option with allowed help and a default', () { + late Command command; + + setUp(() { + command = _command( + name: 'play', + description: 'Play a card', + options: const [ + StringOption( + argName: 'suit', + helpText: 'Like in cards', + defaultsTo: 'clubs', + allowedValues: ['spades', 'clubs', 'diamonds', 'hearts'], + allowedHelp: { + 'spades': 'Swords of a soldier', + 'clubs': 'Weapons of war', + 'diamonds': 'Money for this art', + 'hearts': 'The shape of my heart', + }, + ), + ], + ); + _runner(subcommands: [command]); + }); + + test( + 'when reading usage then (default) is appended to its description', + () { + expect( + command.usage, + _usage(const [ + 'Play a card', + '', + 'Usage: tool play [--suit=]', + '', + 'Options:', + '--suit Like in cards', + ' [spades] Swords of a soldier', + ' [clubs] Weapons of war (default)', + ' [diamonds] Money for this art', + ' [hearts] The shape of my heart', + '', + 'Run "tool help" to see global options.', + ]), + ); + }, + ); + }); + + group('Given a multi option with several defaults', () { + late Command command; + + setUp(() { + command = _command( + name: 'play', + description: 'Play a card', + options: const [ + MultiStringOption( + argName: 'suit', + helpText: 'Like in cards', + defaultsTo: ['clubs', 'hearts'], + allowedHelp: { + 'spades': 'Swords of a soldier', + 'clubs': 'Weapons of war', + 'diamonds': 'Money for this art', + 'hearts': 'The shape of my heart', + }, + ), + ], + ); + _runner(subcommands: [command]); + }); + + test( + 'when reading usage then (default) is appended to each description', + () { + expect( + command.usage, + _usage(const [ + 'Play a card', + '', + 'Usage: tool play [--suit=]...', + '', + 'Options:', + '--suit Like in cards', + ' [spades] Swords of a soldier', + ' [clubs] Weapons of war (default)', + ' [diamonds] Money for this art', + ' [hearts] The shape of my heart (default)', + '', + 'Run "tool help" to see global options.', + ]), + ); + }, + ); + }); + + group('Given an option with a range and a default', () { + late Command command; + + setUp(() { + command = _command( + name: 'play', + description: 'Play a card', + options: const [ + IntOption( + argName: 'count', + helpText: 'How many', + defaultsTo: 2, + min: 1, + max: 10, + ), + ], + ); + _runner(subcommands: [command]); + }); + + test( + 'when reading usage then the range includes the default', + () { + expect( + command.usage, + _usage(const [ + 'Play a card', + '', + 'Usage: tool play [--count=]', + '', + 'Options:', + '--count How many', + ' integer', + ' values: [1 - 10] (defaults to 2)', + '', + 'Run "tool help" to see global options.', + ]), + ); + }, + ); + }); + + group('Given a command with a custom summary and invocation', () { + late Command command; + late CommandRunner runner; + + setUp(() { + command = _OverrideUsageCommand( + name: 'get', + usageDefinition: const CommandUsageDefinition( + description: 'Download packages.\nMore detail here.', + summary: 'Download packages', + invocation: 'get ', + ), + ); + runner = _runner(subcommands: [command]); + }); + + test('when reading the parent usage then the custom summary is shown', () { + expect( + runner.usage, + _usage(const [ + 'Tools', + '', + 'Usage: tool [global-options] [arguments]', + '', + 'Global options:', + '-h, --help Print this usage information.', + '', + 'Available commands:', + ' get Download packages', + '', + 'Run "tool help " for more information about a command.', + ]), + ); + }); + + test( + 'when reading the command usage then the custom invocation is shown', + () { + expect( + command.usage, + _usage(const [ + 'Download packages.', + 'More detail here.', + '', + 'Usage: tool get ', + '', + 'Run "tool help" to see global options.', + ]), + ); + }, + ); + }); + + group('Given a nested command with a custom invocation', () { + late Command command; + + setUp(() { + command = _OverrideUsageCommand( + name: 'add', + usageDefinition: const CommandUsageDefinition( + description: 'Add a remote', + invocation: 'add ', + ), + ); + final branch = _command( + name: 'remote', + description: 'Manage remotes', + subcommands: [command], + ); + _runner(subcommands: [branch]); + }); + + test( + 'when reading usage then the invocation replaces only this command', + () { + expect( + command.usage, + _usage(const [ + 'Add a remote', + '', + 'Usage: tool remote add ', + '', + 'Run "tool help" to see global options.', + ]), + ); + }, + ); + }); + + group('Given an option with allowed values, a range, and a default', () { + late Command command; + + setUp(() { + command = _command( + name: 'play', + description: 'Play a card', + options: const [ + IntOption( + argName: 'count', + helpText: 'How many', + defaultsTo: 2, + min: 1, + max: 10, + allowedValues: [1, 2, 5], + ), + ], + ); + _runner(subcommands: [command]); + }); + + test( + 'when reading usage then only the allowed values are shown', + () { + expect( + command.usage, + _usage(const [ + 'Play a card', + '', + 'Usage: tool play [--count=]', + '', + 'Options:', + '--count How many', + ' integer', + ' values: [1, 2 (default), 5]', + '', + 'Run "tool help" to see global options.', + ]), + ); + }, + ); + }); +} + +Command _command({ + required final String name, + required final String description, + final List? aliases, + final bool? hidden, + final bool canRunAsLeafCommand = false, + final List? persistentOptions, + final List? options, + final List>? subcommands, +}) { + return _UsageCommand( + name: name, + description: description, + aliases: aliases, + hidden: hidden, + canRunAsLeafCommand: canRunAsLeafCommand, + persistentOptions: persistentOptions, + options: options, + subcommands: subcommands, + ); +} + +enum _Pace { fast, slow } + +class _OverrideUsageCommand extends Command { + @override + final String name; + + _OverrideUsageCommand({ + required this.name, + required final CommandUsageDefinition usageDefinition, + }) : super(usageDefinition: usageDefinition); + + @override + void run(final CommandContext context) {} +} + +class _UsageCommand extends CommandImpl { + _UsageCommand({ + required super.name, + required super.description, + super.aliases, + super.hidden, + super.canRunAsLeafCommand, + super.persistentOptions, + super.options, + super.subcommands, + }); + + @override + void run(final CommandContext context) {} +} + +CommandRunner _runner({ + final String description = 'Tools', + final List? globalOptions, + final List>? subcommands, + final int? usageLineLength, + final String? rootFooter, +}) { + return CommandRunner( + 'tool', + description, + globalOptions: globalOptions, + subcommands: subcommands, + usageLineLength: usageLineLength, + rootFooter: rootFooter, + // The built-in completion command is covered by the completion tests. + completion: CompletionSettings.disabled, + ); +} + +CommandRunner _longUsageRunner({ + final int? usageLineLength, +}) { + return _runner( + description: 'A command line tool that builds and deploys applications.', + usageLineLength: usageLineLength, + rootFooter: 'See the documentation for more details about this tool.', + globalOptions: const [ + FlagOption( + argName: 'verbose', + negatable: false, + helpText: 'Print extra information while the command is running.', + ), + ], + subcommands: [ + _command( + name: 'build', + description: 'Build the application from the current sources.', + options: const [ + FlagOption( + argName: 'release', + negatable: false, + helpText: 'Compile with optimizations for a production release.', + ), + ], + ), + ], + ); +} + +String _usage(final Iterable lines) => '${lines.join('\n')}\n'; diff --git a/packages/config/test/command/usage_output_test.dart b/packages/config/test/command/usage_output_test.dart new file mode 100644 index 00000000..c73ce857 --- /dev/null +++ b/packages/config/test/command/usage_output_test.dart @@ -0,0 +1,1171 @@ +import 'dart:async'; + +import 'package:config/command.dart'; +import 'package:config/config.dart'; +import 'package:test/test.dart'; + +import 'command_fixtures.dart'; + +void main() { + group( + 'Given a usage handler constructed without exception handlers and one is added', + () { + late UsageOutputHandler output; + late UsageException? seen; + + setUp(() { + output = UsageOutputHandler( + exceptionSettings: const UsageExceptionSettings( + noUsageExceptionOutput: true, + ), + ); + seen = null; + output.addUsageExceptionHandler(( + final exception, + final _, { + required final fromCommand, + }) { + seen = exception; + return exception; + }); + }); + + test('when a usage exception is handled then the added handler runs', () { + final exception = UsageException('bad', 'usage'); + + output.onUsageException(exception, fromCommand: null); + + expect(seen, same(exception)); + }); + }, + ); + + group('Given a usage handler with captured sinks', () { + late _CapturedUsage usage; + late RecordingCommand greet; + late _DelegateHandler handler; + + setUp(() { + usage = _CapturedUsage(); + greet = _greet([]); + handler = _DelegateHandler( + (final exception, final _, final _) => exception, + ); + }); + + group('when usage is printed', () { + setUp(() { + usage + .output(addExceptionHandlers: [handler.onUsageException]) + .printUsage(greet); + }); + + test('then that command is written to standard output', () { + expect(usage.out.toString(), greet.usage); + }); + + test('then standard error stays empty', () { + expect(usage.err.toString(), isEmpty); + }); + + test('then exception handlers are not called', () { + expect(handler.calls, 0); + }); + }); + }); + + group('Given a command usage exception', () { + late _CapturedUsage usage; + late RecordingCommand greet; + late TracingRunner tool; + late CommandUsageException exception; + late UsageException? result; + + setUp(() { + usage = _CapturedUsage(); + greet = _greet([]); + tool = _tool([]); + exception = CommandUsageException(_missingName, greet); + result = usage.output().onUsageException( + exception, + fromCommand: tool, + ); + }); + + test('when it is handled then that same exception is returned', () { + expect(result, same(exception)); + }); + + test( + 'when it is handled ' + "then the error and that command's usage are printed", + () { + expect( + usage.err.toString(), + _errorThenUsage(_missingName, greet.usage), + ); + }, + ); + + test('when it is handled then standard output stays empty', () { + expect(usage.out.toString(), isEmpty); + }); + }); + + group('Given a usage exception that carries usage text', () { + late _CapturedUsage usage; + late TracingRunner tool; + late UsageException exception; + + setUp(() { + usage = _CapturedUsage(); + tool = _tool([]); + exception = UsageException('bad input', 'Try --help'); + }); + + group('when no command is attached', () { + setUp(() { + usage.output().onUsageException(exception, fromCommand: null); + }); + + test('then the message and usage text are printed', () { + expect( + usage.err.toString(), + _errorThenUsage('bad input', 'Try --help\n'), + ); + }); + }); + + group('when an originating command is attached', () { + late UsageException? result; + + setUp(() { + result = usage.output().onUsageException( + exception, + fromCommand: tool, + ); + }); + + test('then the usage text is followed by that command', () { + expect( + usage.err.toString(), + _errorUsageAndCommand('bad input', 'Try --help', tool.usage), + ); + }); + + test('then the exception is returned', () { + expect(result, same(exception)); + }); + }); + + group('when the usage text is empty and a command is attached', () { + setUp(() { + usage.output().onUsageException( + UsageException('bad input', ''), + fromCommand: tool, + ); + }); + + test('then that command is printed without a separator', () { + expect( + usage.err.toString(), + _errorThenUsage('bad input', tool.usage), + ); + }); + }); + + group('when the usage text is empty and no command is attached', () { + setUp(() { + usage.output().onUsageException( + UsageException('bad input', ''), + fromCommand: null, + ); + }); + + test('then only the message is printed', () { + expect(usage.err.toString(), 'bad input\n\n'); + }); + }); + }); + + group('Given usage exception output is disabled', () { + late _CapturedUsage usage; + late UsageException exception; + late UsageException? result; + + setUp(() { + usage = _CapturedUsage(); + exception = CommandUsageException(_missingName, _greet([])); + result = usage + .output( + exceptionSettings: const UsageExceptionSettings( + noUsageExceptionOutput: true, + ), + ) + .onUsageException(exception, fromCommand: _tool([])); + }); + + test( + 'when a command usage exception is handled then nothing is printed', + () { + expect(usage.err.toString(), isEmpty); + expect(usage.out.toString(), isEmpty); + }, + ); + + test( + 'when a command usage exception is handled ' + 'then the exception is still returned', + () { + expect(result, same(exception)); + }, + ); + }); + + group('Given usage exceptions are not thrown', () { + late _CapturedUsage usage; + late RecordingCommand greet; + late UsageException? result; + + setUp(() { + usage = _CapturedUsage(); + greet = _greet([]); + result = usage + .output( + exceptionSettings: const UsageExceptionSettings( + noUsageException: true, + ), + ) + .onUsageException( + CommandUsageException(_missingName, greet), + fromCommand: null, + ); + }); + + test( + 'when a command usage exception is handled ' + 'then the error and command usage are still printed', + () { + expect( + usage.err.toString(), + _errorThenUsage(_missingName, greet.usage), + ); + }, + ); + + test( + 'when a command usage exception is handled ' + 'then no exception is returned', + () { + expect(result, isNull); + }, + ); + }); + + group('Given usage exceptions are neither printed nor thrown', () { + late _CapturedUsage usage; + late UsageException? result; + + setUp(() { + usage = _CapturedUsage(); + result = usage + .output( + exceptionSettings: const UsageExceptionSettings( + noUsageException: true, + noUsageExceptionOutput: true, + ), + ) + .onUsageException( + CommandUsageException(_missingName, _greet([])), + fromCommand: null, + ); + }); + + test( + 'when a command usage exception is handled then nothing is printed', + () { + expect(usage.err.toString(), isEmpty); + }, + ); + + test( + 'when a command usage exception is handled ' + 'then no exception is returned', + () { + expect(result, isNull); + }, + ); + }); + + group('Given additional exception handlers', () { + late _CapturedUsage usage; + late UsageException original; + + setUp(() { + usage = _CapturedUsage(); + original = CommandUsageException(_missingName, _greet([])); + }); + + group('when an earlier handler rewrites the exception', () { + late _DelegateHandler first; + late _DelegateHandler second; + late TracingRunner tool; + late UsageException? result; + + setUp(() { + tool = _tool([]); + first = _DelegateHandler( + (final _, final _, final _) => + UsageException('rewritten', 'Try --help'), + ); + second = _DelegateHandler( + (final exception, final _, final _) => exception, + ); + result = usage + .output( + addExceptionHandlers: [ + first.onUsageException, + second.onUsageException, + ], + ) + .onUsageException(original, fromCommand: tool); + }); + + test('then each handler sees the exception from the previous one', () { + expect(first.messages, [_missingName]); + expect(second.messages, ['rewritten']); + }); + + test( + 'then the rewritten usage text and originating command are printed', + () { + expect( + usage.err.toString(), + _errorUsageAndCommand('rewritten', 'Try --help', tool.usage), + ); + }, + ); + + test('then the rewritten exception is returned', () { + expect(result?.message, 'rewritten'); + expect(result, isNot(isA())); + }); + }); + + group('when an earlier handler stops the exception', () { + late _DelegateHandler first; + late _DelegateHandler second; + late UsageException? result; + + setUp(() { + first = _DelegateHandler((final _, final _, final _) => null); + second = _DelegateHandler( + (final exception, final _, final _) => exception, + ); + result = usage + .output( + addExceptionHandlers: [ + first.onUsageException, + second.onUsageException, + ], + ) + .onUsageException(original, fromCommand: null); + }); + + test('then later handlers do not run', () { + expect(first.calls, 1); + expect(second.calls, 0); + }); + + test('then nothing is printed', () { + expect(usage.err.toString(), isEmpty); + }); + + test('then no exception is returned', () { + expect(result, isNull); + }); + }); + + group('when a handler rewrites the exception and throwing is disabled', () { + late UsageException? result; + + setUp(() { + result = usage + .output( + exceptionSettings: const UsageExceptionSettings( + noUsageException: true, + ), + addExceptionHandlers: [ + _DelegateHandler( + (final _, final _, final _) => + UsageException('rewritten', ''), + ).onUsageException, + ], + ) + .onUsageException(original, fromCommand: null); + }); + + test('then the rewritten message is printed', () { + expect(usage.err.toString(), 'rewritten\n\n'); + }); + + test('then no exception is returned', () { + expect(result, isNull); + }); + }); + }); + + group('Given a simple exception handler', () { + late _CapturedUsage usage; + late RecordingCommand greet; + late TracingRunner tool; + late UsageException exception; + + setUp(() { + usage = _CapturedUsage(); + greet = _greet([]); + tool = _tool([]); + exception = CommandUsageException(_missingName, greet); + }); + + group('when a command usage exception is handled', () { + late UsageOutputHandler output; + late List messages; + late UsageOutputHandler? seenOutput; + late CommandDefinition? seenCommand; + late UsageException? result; + + setUp(() { + messages = []; + seenOutput = null; + seenCommand = null; + output = usage.output( + addExceptionHandlers: [ + UsageExceptions.simpleHandler(( + final error, + final usageOutput, + final fromCommand, + ) { + messages.add(error.message); + seenOutput = usageOutput; + seenCommand = fromCommand; + }), + ], + ); + result = output.onUsageException(exception, fromCommand: tool); + }); + + test('then the callback receives that exception', () { + expect(messages, [_missingName]); + }); + + test('then the callback receives the usage output', () { + expect(seenOutput, same(output)); + }); + + test('then the callback receives the originating command', () { + expect(seenCommand, same(tool)); + }); + + test('then the error and command usage are still printed', () { + expect( + usage.err.toString(), + _errorThenUsage(_missingName, greet.usage), + ); + }); + + test('then the original exception is returned', () { + expect(result, same(exception)); + }); + }); + + group('when another handler follows it', () { + late _DelegateHandler follower; + late UsageException? result; + + setUp(() { + follower = _DelegateHandler( + (final error, final _, final _) => error, + ); + result = usage + .output( + addExceptionHandlers: [ + UsageExceptions.simpleHandler((final _, final _, final _) {}), + follower.onUsageException, + ], + ) + .onUsageException(exception, fromCommand: tool); + }); + + test('then the following handler sees the original exception', () { + expect(follower.messages, [_missingName]); + }); + + test('then the original exception is returned', () { + expect(result, same(exception)); + }); + }); + + group('when it replaces the standard handler', () { + late List messages; + late UsageException? result; + + setUp(() { + messages = []; + result = usage + .outputReplacing([ + UsageExceptions.simpleHandler(( + final error, + final _, + final _, + ) { + messages.add(error.message); + }), + ]) + .onUsageException(exception, fromCommand: tool); + }); + + test('then the callback still runs', () { + expect(messages, [_missingName]); + }); + + test('then nothing is printed', () { + expect(usage.err.toString(), isEmpty); + expect(usage.out.toString(), isEmpty); + }); + + test('then the original exception is returned', () { + expect(result, same(exception)); + }); + }); + }); + + group('Given the standard exception handler is replaced', () { + late _CapturedUsage usage; + late UsageException exception; + + setUp(() { + usage = _CapturedUsage(); + exception = CommandUsageException(_missingName, _greet([])); + }); + + group('when the replacement returns the exception', () { + late UsageException? result; + + setUp(() { + result = usage + .outputReplacing([ + _DelegateHandler( + (final error, final _, final _) => error, + ).onUsageException, + ]) + .onUsageException(exception, fromCommand: _tool([])); + }); + + test('then the standard usage text is not printed', () { + expect(usage.err.toString(), isEmpty); + }); + + test('then the exception is returned', () { + expect(result, same(exception)); + }); + }); + + group('when no handlers are installed', () { + late UsageException? result; + + setUp(() { + result = usage + .outputReplacing(const []) + .onUsageException( + exception, + fromCommand: null, + ); + }); + + test('then nothing is printed', () { + expect(usage.err.toString(), isEmpty); + }); + + test('then the exception is returned unchanged', () { + expect(result, same(exception)); + }); + }); + }); + + group('Given a custom exception printer', () { + late _CapturedUsage usage; + late UsageException exception; + late _CapturePrinter printer; + + setUp(() { + usage = _CapturedUsage(); + exception = CommandUsageException(_missingName, _greet([])); + printer = _CapturePrinter(); + }); + + group('when a command usage exception is handled', () { + late TracingRunner tool; + late UsageException? result; + + setUp(() { + tool = _tool([]); + result = usage + .output( + exceptionSettings: UsageExceptionSettings( + exceptionPrinter: printer, + ), + ) + .onUsageException(exception, fromCommand: tool); + }); + + test( + 'then the printer receives the exception and originating command', + () { + expect(printer.exception, same(exception)); + expect(printer.fromCommand, same(tool)); + }, + ); + + test('then the exception is returned', () { + expect(result, same(exception)); + }); + + test('then the error sink stays empty', () { + expect(usage.err.toString(), isEmpty); + }); + }); + + group('when output is disabled', () { + setUp(() { + usage + .output( + exceptionSettings: UsageExceptionSettings( + noUsageExceptionOutput: true, + exceptionPrinter: printer, + ), + ) + .onUsageException(exception, fromCommand: null); + }); + + test('then the printer is not called', () { + expect(printer.calls, 0); + }); + }); + }); + + group('Given commands that supply their own usage text', () { + late _CapturedUsage usage; + late _NamedUsageCommand greet; + late _NamedUsageCommand tool; + late UsageOutputHandler output; + + setUp(() { + usage = _CapturedUsage(); + greet = _NamedUsageCommand('greet'); + tool = _NamedUsageCommand('tool'); + output = usage.output(); + }); + + group('when usage is printed', () { + setUp(() => output.printUsage(greet)); + + test('then that usage is written to standard output', () { + expect(usage.out.toString(), greet.usage); + }); + }); + + group('when a command usage exception is handled', () { + setUp(() { + output.onUsageException( + CommandUsageException(_missingName, greet), + fromCommand: tool, + ); + }); + + test("then that exception's command usage is written", () { + expect( + usage.err.toString(), + _errorThenUsage(_missingName, greet.usage), + ); + }); + }); + + group('when a plain usage exception has an originating command', () { + setUp(() { + output.onUsageException( + UsageException('bad input', 'Try --help'), + fromCommand: tool, + ); + }); + + test('then the originating command usage is written', () { + expect( + usage.err.toString(), + _errorUsageAndCommand('bad input', 'Try --help', tool.usage), + ); + }); + }); + }); + + group('Given a runner that does not throw usage exceptions', () { + late List trace; + late _CapturedUsage usage; + late TracingRunner runner; + + setUp(() { + trace = []; + usage = _CapturedUsage(); + runner = _runner( + trace, + usage.output( + exceptionSettings: const UsageExceptionSettings( + noUsageException: true, + ), + ), + ); + }); + + group('when a mandatory option is omitted', () { + late Object? result; + + setUp(() async { + result = await runner.run(['greet']); + }); + + test('then the runner returns null', () { + expect(result, isNull); + }); + + test('then the error and command usage are still printed', () { + expect( + usage.err.toString(), + _errorThenUsage(_missingName, _subcommandUsage(runner, 'greet')), + ); + }); + + test('then the command does not run', () { + expect(trace, isEmpty); + }); + }); + }); + + group('Given a runner that does not print usage exceptions', () { + late _CapturedUsage usage; + late UsageException? error; + + setUp(() async { + usage = _CapturedUsage(); + final runner = _runner( + [], + usage.output( + exceptionSettings: const UsageExceptionSettings( + noUsageExceptionOutput: true, + ), + ), + ); + error = await _captureUsageError(() => runner.run(['greet'])); + }); + + test( + 'when a mandatory option is omitted ' + 'then a usage exception is thrown', + () { + expect( + error, + isA().having( + (final exception) => exception.command.name, + 'command', + 'greet', + ), + ); + }, + ); + + test( + 'when a mandatory option is omitted ' + 'then nothing is printed', + () { + expect(usage.err.toString(), isEmpty); + expect(usage.out.toString(), isEmpty); + }, + ); + }); + + group('Given a runner that neither prints nor throws usage exceptions', () { + late List trace; + late _CapturedUsage usage; + late TracingRunner runner; + + setUp(() { + trace = []; + usage = _CapturedUsage(); + runner = _runner( + trace, + usage.output( + exceptionSettings: const UsageExceptionSettings( + noUsageException: true, + noUsageExceptionOutput: true, + ), + ), + ); + }); + + group('when a mandatory option is omitted', () { + late Object? result; + + setUp(() async { + result = await runner.run(['greet']); + }); + + test('then the runner returns null', () { + expect(result, isNull); + }); + + test('then nothing is printed', () { + expect(usage.err.toString(), isEmpty); + }); + + test('then the command does not run', () { + expect(trace, isEmpty); + }); + }); + + group('when --help is passed', () { + late Object? result; + + setUp(() async { + result = await runner.run(['--help']); + }); + + test('then usage for the runner is printed to standard output', () { + expect(usage.out.toString(), runner.usage); + }); + + test('then standard error stays empty', () { + expect(usage.err.toString(), isEmpty); + }); + + test('then no command runs', () { + expect(trace, isEmpty); + }); + + test('then no command result is returned', () { + expect(result, isNull); + }); + }); + }); + + group('Given a runner with an additional exception handler', () { + late List trace; + late _CapturedUsage usage; + late _DelegateHandler handler; + late TracingRunner runner; + + setUp(() { + trace = []; + usage = _CapturedUsage(); + handler = _DelegateHandler( + (final exception, final _, final _) => exception, + ); + runner = _runner( + trace, + usage.output(addExceptionHandlers: [handler.onUsageException]), + ); + }); + + group('when a mandatory option is omitted', () { + late UsageException? error; + + setUp(() async { + error = await _captureUsageError(() => runner.run(['greet'])); + }); + + test('then the handler receives the runner and its usage output', () { + expect(handler.fromCommand, same(runner)); + expect(handler.usageOutput, same(runner.usageOutput)); + }); + + test('then the handler sees the original error', () { + expect(handler.messages, [_missingName]); + }); + + test('then the original exception is thrown', () { + expect(error?.message, _missingName); + }); + + test('then the error and command usage are printed', () { + expect( + usage.err.toString(), + _errorThenUsage(_missingName, _subcommandUsage(runner, 'greet')), + ); + }); + }); + + group('when the handler replaces the exception', () { + late UsageException replacement; + late UsageException? error; + + setUp(() async { + replacement = UsageException('replaced', 'custom usage'); + handler = _DelegateHandler( + (final _, final _, final _) => replacement, + ); + runner = _runner( + trace, + usage.output(addExceptionHandlers: [handler.onUsageException]), + ); + error = await _captureUsageError(() => runner.run(['greet'])); + }); + + test('then the replacement is thrown', () { + expect(error, same(replacement)); + }); + + test( + 'then the replacement usage is printed ' + 'with the runner usage after it', + () { + expect( + usage.err.toString(), + _errorUsageAndCommand('replaced', 'custom usage', runner.usage), + ); + }, + ); + + test('then the command does not run', () { + expect(trace, isEmpty); + }); + }); + + group('when the handler stops the exception', () { + late Object? result; + + setUp(() async { + handler = _DelegateHandler( + (final exception, final output, final _) { + output.sinks.err.writeln('logged ${exception.message}'); + return null; + }, + ); + runner = _runner( + trace, + usage.output(addExceptionHandlers: [handler.onUsageException]), + ); + result = await runner.run(['greet']); + }); + + test('then the runner returns null', () { + expect(result, isNull); + }); + + test('then only the handler output is printed', () { + expect(usage.err.toString(), 'logged $_missingName\n'); + }); + + test('then the command does not run', () { + expect(trace, isEmpty); + }); + }); + }); + + group('Given a runner whose standard exception handler is replaced', () { + late List trace; + late _CapturedUsage usage; + late _DelegateHandler handler; + late UsageException? error; + + setUp(() async { + trace = []; + usage = _CapturedUsage(); + handler = _DelegateHandler( + (final exception, final _, final _) => exception, + ); + final runner = _runner( + trace, + usage.outputReplacing([handler.onUsageException]), + ); + error = await _captureUsageError(() => runner.run(['greet'])); + }); + + test( + 'when a mandatory option is omitted ' + 'then the replacement handler runs', + () { + expect(handler.messages, [_missingName]); + }, + ); + + test( + 'when a mandatory option is omitted ' + 'then the standard usage text is not printed', + () { + expect(usage.err.toString(), isEmpty); + }, + ); + + test( + 'when a mandatory option is omitted ' + 'then the exception is still thrown', + () { + expect(error?.message, _missingName); + }, + ); + + test( + 'when a mandatory option is omitted ' + 'then the command does not run', + () { + expect(trace, isEmpty); + }, + ); + }); +} + +TracingRunner _runner( + final List trace, + final UsageOutputHandler usageOutput, +) { + return TracingRunner( + trace, + usageOutput: usageOutput, + subcommands: [_greetCommand(trace)], + ); +} + +/// A greet command attached to a runner, so that its usage can be rendered. +RecordingCommand _greet(final List trace) { + final greet = _greetCommand(trace); + TracingRunner(trace, subcommands: [greet]); + return greet; +} + +RecordingCommand _greetCommand(final List trace) { + return RecordingCommand( + name: 'greet', + description: 'Greet', + trace: trace, + options: const [ + StringOption(argName: 'name', mandatory: true), + ], + ); +} + +TracingRunner _tool(final List trace) => TracingRunner(trace); + +Future _captureUsageError( + final FutureOr Function() body, +) async { + try { + await body(); + } on UsageException catch (error) { + return error; + } + return null; +} + +String _subcommandUsage(final CommandDefinition command, final String name) => + command.subcommands.firstWhere((final sub) => sub.name == name).usage; + +String _errorThenUsage(final String message, final String usage) => + '$message\n\n$usage'; + +String _errorUsageAndCommand( + final String message, + final String usage, + final String commandUsage, +) => '$message\n\n$usage\n---\n$commandUsage'; + +const _missingName = 'greet: Option `name` is mandatory.'; + +class _CapturedUsage { + final out = StringBuffer(); + final err = StringBuffer(); + + OutputSinks get sinks => OutputSinks(out: out, err: err); + + UsageOutputHandler output({ + final UsageExceptionSettings? exceptionSettings, + final List? addExceptionHandlers, + }) { + return UsageOutputHandler( + sinks: sinks, + exceptionSettings: exceptionSettings ?? const UsageExceptionSettings(), + addExceptionHandlers: addExceptionHandlers, + ); + } + + UsageOutputHandler outputReplacing( + final List exceptionHandlers, { + final UsageExceptionSettings? exceptionSettings, + }) { + return UsageOutputHandler.replace( + sinks: sinks, + exceptionSettings: exceptionSettings ?? const UsageExceptionSettings(), + exceptionHandlers: exceptionHandlers, + ); + } +} + +class _DelegateHandler { + _DelegateHandler(this._handle); + + final UsageException? Function( + UsageException exception, + UsageOutputHandler usageOutput, + CommandDefinition? fromCommand, + ) + _handle; + + final List messages = []; + CommandDefinition? fromCommand; + UsageOutputHandler? usageOutput; + int calls = 0; + + UsageException? onUsageException( + final UsageException exception, + final UsageOutputHandler usageOutput, { + required final CommandDefinition? fromCommand, + }) { + calls++; + messages.add(exception.message); + this.fromCommand = fromCommand; + this.usageOutput = usageOutput; + return _handle(exception, usageOutput, fromCommand); + } +} + +class _NamedUsageCommand extends Command { + _NamedUsageCommand(this.name) + : super(usageGenerator: const _NamedGenerator()); + + @override + final String name; + + @override + String? run(final CommandContext context) => null; +} + +class _NamedGenerator implements UsageGenerator { + const _NamedGenerator(); + + @override + String generate(final CommandDefinition command) => 'usage:${command.name}\n'; +} + +class _CapturePrinter implements UsageExceptionPrinter { + UsageException? exception; + CommandDefinition? fromCommand; + int calls = 0; + + @override + void printException( + final UsageException exception, { + required final UsageOutputHandler usageOutput, + required final CommandDefinition? fromCommand, + }) { + calls++; + this.exception = exception; + this.fromCommand = fromCommand; + } +} diff --git a/packages/config/test/middleware/middleware_hooks_test.dart b/packages/config/test/middleware/middleware_hooks_test.dart new file mode 100644 index 00000000..e81e9e65 --- /dev/null +++ b/packages/config/test/middleware/middleware_hooks_test.dart @@ -0,0 +1,401 @@ +import 'package:config/src/middleware/middleware_hooks.dart'; +import 'package:test/test.dart'; + +void main() { + group('Given default middleware hooks', () { + const hooks = MiddlewareHooks(); + + test( + 'when onRun is left unchanged ' + 'then the next handler receives the original argument', + () async { + String? received; + final handler = hooks.middleware((final arg) { + received = arg; + return 'ok'; + }); + + await handler('original'); + + expect(received, 'original'); + }, + ); + + test( + 'when the next handler returns a value ' + 'then that value is returned', + () async { + final handler = hooks.middleware((final arg) => 'from-next'); + + expect(await handler('original'), 'from-next'); + }, + ); + + test( + 'when the next handler throws ' + 'then the exception propagates', + () { + final handler = hooks.middleware( + (final arg) => throw StateError('boom'), + ); + + expect(handler('original'), throwsA(isA())); + }, + ); + }); + + group('Given hooks whose onRun returns null', () { + const hooks = _NullOnRun(); + + test( + 'when the handler runs ' + 'then the next handler receives null', + () async { + // Not null, to tell a null argument from a skipped handler. + String? received = 'not called'; + final handler = hooks.middleware((final arg) { + received = arg; + return 'ok'; + }); + + await handler('original'); + + expect(received, isNull); + }, + ); + }); + + group('Given a MiddlewareComposer with no onRun hook', () { + const composer = MiddlewareComposer(); + + test( + 'when the handler runs ' + 'then the next handler receives the original argument', + () async { + String? received; + final handler = composer.middleware((final arg) { + received = arg; + return 'ok'; + }); + + await handler('original'); + + expect(received, 'original'); + }, + ); + }); + + group('Given a MiddlewareComposer whose onRun returns null', () { + final composer = MiddlewareComposer( + onRun: (final arg) => null, + ); + + test( + 'when the handler runs ' + 'then the next handler receives null', + () async { + // Not null, to tell a null argument from a skipped handler. + String? received = 'not called'; + final handler = composer.middleware((final arg) { + received = arg; + return 'ok'; + }); + + await handler('original'); + + expect(received, isNull); + }, + ); + }); + + group( + 'Given a MiddlewareComposer whose onRun asynchronously returns null', + () { + final composer = MiddlewareComposer( + onRun: (final arg) async => null, + ); + + test( + 'when the handler runs ' + 'then the next handler receives null', + () async { + // Not null, to tell a null argument from a skipped handler. + String? received = 'not called'; + final handler = composer.middleware((final arg) { + received = arg; + return 'ok'; + }); + + await handler('original'); + + expect(received, isNull); + }, + ); + }, + ); + + group('Given hooks that replace the argument and the response', () { + const hooks = _ReplacingHooks(); + + test( + 'when the handler runs ' + 'then the next handler receives the replacement argument', + () async { + String? received; + final handler = hooks.middleware((final arg) { + received = arg; + return 'from-next'; + }); + + await handler('original'); + + expect(received, 'replaced-arg'); + }, + ); + + test( + 'when the handler runs ' + 'then the result is built from the replacement and the next response', + () async { + final handler = hooks.middleware((final arg) => 'from-next'); + + expect(await handler('original'), 'replaced-arg/from-next'); + }, + ); + }); + + group('Given hooks whose onReturn returns null', () { + const hooks = _NullOnReturn(); + + test( + 'when the handler runs ' + 'then the result is null', + () async { + final handler = hooks.middleware((final arg) => 'from-next'); + + expect(await handler('original'), isNull); + }, + ); + }); + + group('Given hooks that recover from a thrown error', () { + late _RecoveringHooks hooks; + late String result; + + group('when the next handler throws', () { + setUp(() async { + hooks = _RecoveringHooks(); + final handler = hooks.middleware( + (final arg) => throw StateError('boom'), + ); + result = await handler('original'); + }); + + test('then the handler returns the onError value', () { + expect(result, 'recovered:original'); + }); + + test('then onReturn is not called', () { + expect(hooks.onReturnCalled, isFalse); + }); + }); + }); + + group('Given hooks whose onRun throws', () { + late bool nextCalled; + late Object? error; + + group('when the handler runs', () { + setUp(() async { + nextCalled = false; + final handler = const _ThrowingOnRun().middleware((final arg) { + nextCalled = true; + return 'ok'; + }); + try { + await handler('original'); + error = null; + } catch (thrown) { + error = thrown; + } + }); + + test('then the next handler is not called', () { + expect(nextCalled, isFalse); + }); + + test('then the exception propagates', () { + expect(error, isA()); + }); + }); + }); + + group('Given hooks whose onReturn throws', () { + const hooks = _ThrowingOnReturn(); + + test( + 'when the handler runs ' + 'then the exception propagates', + () { + final handler = hooks.middleware((final arg) => 'from-next'); + + expect(handler('original'), throwsA(isA())); + }, + ); + }); + + group('Given a MiddlewareComposer with no onReturn hook', () { + const composer = MiddlewareComposer(); + + test( + 'when the next handler returns a value ' + 'then that value is returned', + () async { + final handler = composer.middleware((final arg) => 'from-next'); + + expect(await handler('original'), 'from-next'); + }, + ); + }); + + group('Given a MiddlewareComposer whose onReturn returns null', () { + final composer = MiddlewareComposer( + onReturn: (final arg, final response) => null, + ); + + test( + 'when the handler runs ' + 'then the result is null', + () async { + final handler = composer.middleware((final arg) => 'from-next'); + + expect(await handler('original'), isNull); + }, + ); + }); + + group('Given a MiddlewareComposer whose onReturn replaces the response', () { + final composer = MiddlewareComposer( + onReturn: (final arg, final response) async => 'async:$response', + ); + + test( + 'when the handler runs ' + 'then the result is the awaited hook value', + () async { + final handler = composer.middleware((final arg) => 'from-next'); + + expect(await handler('original'), 'async:from-next'); + }, + ); + }); + + group('Given a MiddlewareComposer with no onError hook', () { + const composer = MiddlewareComposer(); + + test( + 'when the next handler throws ' + 'then the exception propagates', + () { + final handler = composer.middleware( + (final arg) => throw StateError('boom'), + ); + + expect(handler('original'), throwsA(isA())); + }, + ); + }); + + group('Given a MiddlewareComposer whose onError recovers', () { + final composer = MiddlewareComposer( + onRun: (final arg) => 'replaced', + onError: (final error, final stackTrace, final arg) => 'err:$arg', + ); + + test( + 'when the next handler throws ' + 'then the result is the onError value for the replaced argument', + () async { + final handler = composer.middleware( + (final arg) => throw StateError('boom'), + ); + + expect(await handler('original'), 'err:replaced'); + }, + ); + }); + + group('Given a MiddlewareComposer whose onError returns null', () { + final composer = MiddlewareComposer( + onError: (final error, final stackTrace, final arg) async => null, + ); + + test( + 'when the next handler throws ' + 'then the result is null', + () async { + final handler = composer.middleware( + (final arg) => throw StateError('boom'), + ); + + expect(await handler('original'), isNull); + }, + ); + }); +} + +class _NullOnRun extends MiddlewareHooks { + const _NullOnRun(); + + @override + String? onRun(final String? arg) => null; +} + +class _ReplacingHooks extends MiddlewareHooks { + const _ReplacingHooks(); + + @override + String onRun(final String arg) => 'replaced-arg'; + + @override + String onReturn(final String arg, final String response) => '$arg/$response'; +} + +class _NullOnReturn extends MiddlewareHooks { + const _NullOnReturn(); + + @override + String? onReturn(final String arg, final String? response) => null; +} + +class _RecoveringHooks extends MiddlewareHooks { + bool onReturnCalled = false; + + @override + String onReturn(final String arg, final String response) { + onReturnCalled = true; + return response; + } + + @override + String onError( + final Object error, + final StackTrace stackTrace, + final String arg, + ) => 'recovered:$arg'; +} + +class _ThrowingOnRun extends MiddlewareHooks { + const _ThrowingOnRun(); + + @override + String onRun(final String arg) => throw StateError('onRun'); +} + +class _ThrowingOnReturn extends MiddlewareHooks { + const _ThrowingOnReturn(); + + @override + String onReturn(final String arg, final String response) => + throw StateError('onReturn'); +} diff --git a/packages/config/test/middleware/middleware_test.dart b/packages/config/test/middleware/middleware_test.dart new file mode 100644 index 00000000..e0f89fae --- /dev/null +++ b/packages/config/test/middleware/middleware_test.dart @@ -0,0 +1,220 @@ +import 'package:config/src/middleware/middleware.dart'; +import 'package:test/test.dart'; + +void main() { + group('Given an empty MiddlewareChain', () { + final chain = MiddlewareChain(); + + test( + 'when invoking the handler chain ' + 'then the terminal handler receives the argument and its result is returned', + () { + final handler = chain.handlerChain((final arg) => 'terminal:$arg'); + + expect(handler('input'), 'terminal:input'); + }, + ); + }); + + group('Given a MiddlewareChain with one middleware', () { + final chain = MiddlewareChain([ + (final next) => + (final arg) => 'wrapped:${next('inner:$arg')}', + ]); + + test( + 'when invoking the handler chain ' + 'then the middleware runs around the terminal handler', + () { + final handler = chain.handlerChain((final arg) => 'terminal:$arg'); + + expect(handler('input'), 'wrapped:terminal:inner:input'); + }, + ); + }); + + group('Given a MiddlewareChain with two middlewares', () { + late List trace; + late String result; + + setUp(() { + trace = []; + final chain = MiddlewareChain([ + (final next) => (final arg) { + trace.add('first-in:$arg'); + final value = next('from-first:$arg'); + trace.add('first-out:$value'); + return 'first:$value'; + }, + (final next) => (final arg) { + trace.add('second-in:$arg'); + final value = next(arg); + trace.add('second-out:$value'); + return 'second:$value'; + }, + ]); + final handler = chain.handlerChain((final arg) { + trace.add('terminal:$arg'); + return 'terminal:$arg'; + }); + result = handler('input'); + }); + + test( + 'when invoking the handler chain ' + 'then middlewares run first-to-last and unwind last-to-first', + () { + expect(trace, [ + 'first-in:input', + 'second-in:from-first:input', + 'terminal:from-first:input', + 'second-out:terminal:from-first:input', + 'first-out:second:terminal:from-first:input', + ]); + }, + ); + + test( + 'when invoking the handler chain ' + 'then the result is the value returned by the first middleware', + () { + expect(result, 'first:second:terminal:from-first:input'); + }, + ); + }); + + group('Given a middleware that does not call the next handler', () { + test( + 'when invoking the handler chain ' + 'then later middlewares and the terminal handler are skipped', + () { + final trace = []; + final chain = MiddlewareChain([ + (final next) => (final arg) { + trace.add('short-circuit:$arg'); + return 'stopped'; + }, + (final next) => (final arg) { + trace.add('later:$arg'); + return next(arg); + }, + ]); + final handler = chain.handlerChain((final arg) { + trace.add('terminal:$arg'); + return 'terminal:$arg'; + }); + + expect(handler('input'), 'stopped'); + expect(trace, ['short-circuit:input']); + }, + ); + }); + + group('Given a MiddlewareChain with a growable middleware list', () { + test( + 'when adding a middleware to a chain created with the default list ' + 'then that middleware runs', + () { + final trace = []; + final chain = MiddlewareChain(); + chain.addMiddleware( + (final next) => (final arg) { + trace.add(arg); + return next(arg); + }, + ); + + chain.handlerChain((final arg) => arg)('input'); + + expect(trace, ['input']); + }, + ); + + test( + 'when adding a middleware ' + 'then it runs after the middlewares passed to the constructor', + () { + final trace = []; + final chain = MiddlewareChain([ + (final next) => (final arg) { + trace.add('initial:$arg'); + return next(arg); + }, + ]); + chain.addMiddleware( + (final next) => (final arg) { + trace.add('added:$arg'); + return next(arg); + }, + ); + + chain.handlerChain((final arg) { + trace.add('terminal:$arg'); + return arg; + })('input'); + + expect(trace, ['initial:input', 'added:input', 'terminal:input']); + }, + ); + + test( + 'when a middleware is added after the handler is built ' + 'then the existing handler does not run the new middleware', + () { + final trace = []; + final chain = MiddlewareChain(); + final handler = chain.handlerChain((final arg) { + trace.add('terminal:$arg'); + return arg; + }); + chain.addMiddleware( + (final next) => (final arg) { + trace.add('late:$arg'); + return next(arg); + }, + ); + + handler('input'); + + expect(trace, ['terminal:input']); + }, + ); + }); + + group('Given a composed handler', () { + test( + 'when the handler is invoked twice ' + 'then each invocation runs the full chain', + () { + var terminalCalls = 0; + final chain = MiddlewareChain([ + (final next) => + (final arg) => next(arg + 1), + ]); + final handler = chain.handlerChain((final arg) { + terminalCalls++; + return arg * 2; + }); + + expect([handler(1), handler(1)], [4, 4]); + expect(terminalCalls, 2); + }, + ); + + test( + 'when the terminal handler throws ' + 'then the exception propagates to the caller', + () { + final chain = MiddlewareChain([ + (final next) => + (final arg) => next(arg), + ]); + final handler = chain.handlerChain((final arg) { + throw StateError('boom'); + }); + + expect(() => handler(1), throwsA(isA())); + }, + ); + }); +}