diff --git a/packages/config/lib/src/config/arg_parser/arg_parser.dart b/packages/config/lib/src/config/arg_parser/arg_parser.dart index 5acb655a..cafcaf44 100644 --- a/packages/config/lib/src/config/arg_parser/arg_parser.dart +++ b/packages/config/lib/src/config/arg_parser/arg_parser.dart @@ -7,5 +7,7 @@ export 'parser.dart' ArgParseResult, scanAndParseArgs, scanAndParseCommands, + subcommandRequiredErrorPrefix, unknownSubcommandErrorPrefix; -export 'scanner.dart' show DoubleDashHandling, ScanMode, optionAwaitingValue; +export 'parser_settings.dart'; +export 'scanner.dart' show optionAwaitingValue; diff --git a/packages/config/lib/src/config/arg_parser/command_definition.dart b/packages/config/lib/src/config/arg_parser/command_definition.dart index 8bae8f6c..cbb9ef7b 100644 --- a/packages/config/lib/src/config/arg_parser/command_definition.dart +++ b/packages/config/lib/src/config/arg_parser/command_definition.dart @@ -35,9 +35,6 @@ abstract interface class CommandDefinition { } class CommandUsageDefinition { - // TODO: Support overriding `summary` and `invocation` of the formatted usage - // like the old Command did. - /// A description of this command, included in usage. final String description; @@ -46,7 +43,7 @@ class CommandUsageDefinition { /// The command's category. /// - /// Displayed in [parent]'s [CommandRunner.usage]. Commands with categories + /// Displayed in [parent]'s usage. Commands with categories /// will be grouped together, and displayed after commands without a category. final String? category; @@ -56,11 +53,25 @@ class CommandUsageDefinition { /// as long as any of their leaf commands are visible. final bool hidden; + /// A short description of this command, included in [parent]'s usage. + /// If null, the default is used which is typically the first line of [description]. + final String? summary; + + /// A custom template for this command's own invocation, replacing its name + /// and argument synopsis. + /// + /// Parent command names are prepended. If the default synopsis would be + /// `executable branch leaf `, this string replaces `leaf ` + /// (for example `"leaf "`). If null, the synopsis is generated. + final String? invocation; + const CommandUsageDefinition({ final String? description, this.usageFooter, this.category, final bool? hidden, + this.summary, + this.invocation, }) : description = description ?? '', hidden = hidden ?? false; } @@ -78,18 +89,9 @@ class CommandAliasesDefinition { /// A name does not have to be repeated both here and in [aliases]. final List suggestionAliases; - /// The maximum edit distance allowed when suggesting possible intended - /// commands. - /// - /// Set to `0` in order to disable suggestions, defaults to `2`. - // TODO: Make this global on the CommandRunner instead? - final int suggestionDistanceLimit; - const CommandAliasesDefinition({ final List? aliases, final List? suggestionAliases, - final int? suggestionDistanceLimit, }) : aliases = aliases ?? const [], - suggestionAliases = suggestionAliases ?? const [], - suggestionDistanceLimit = suggestionDistanceLimit ?? 2; + suggestionAliases = suggestionAliases ?? const []; } diff --git a/packages/config/lib/src/config/arg_parser/parser.dart b/packages/config/lib/src/config/arg_parser/parser.dart index c604a1b9..3d9e460c 100644 --- a/packages/config/lib/src/config/arg_parser/parser.dart +++ b/packages/config/lib/src/config/arg_parser/parser.dart @@ -7,12 +7,18 @@ import '../config.dart' CommandDefinitionError, validateOptions; import 'command_definition.dart'; +import 'parser_settings.dart'; import 'scanner.dart'; +import 'suggestions.dart'; /// The start of the [ArgParseResult.errors] message recorded when a word /// is not a known subcommand of a command that has subcommands. const String unknownSubcommandErrorPrefix = 'Unknown subcommand: '; +/// The start of the [ArgParseResult.errors] message recorded when a command +/// that cannot run on its own is invoked without a subcommand. +const String subcommandRequiredErrorPrefix = 'A subcommand is required under '; + /// Scans the arguments and parses them into an [ArgParseResult] /// corresponding to a single set of options. /// @@ -22,7 +28,7 @@ const String unknownSubcommandErrorPrefix = 'Unknown subcommand: '; ArgParseResult scanAndParseArgs( final Iterable args, { required final Iterable options, - final ScanMode scanMode = const ScanMode(), + final ParserSettings settings = const ParserSettings(), }) { validateOptions(options); @@ -31,7 +37,7 @@ ArgParseResult scanAndParseArgs( return _parseArgs( _ArgCursor(scannedArgs), options: options, - scanMode: scanMode, + settings: settings, ); } @@ -48,7 +54,7 @@ ArgParseResult scanAndParseArgs( ArgParseResult scanAndParseCommands( final Iterable args, { required final CommandDefinition rootCommand, - final ScanMode scanMode = const ScanMode(), + final ParserSettings settings = const ParserSettings(), }) { _validateCommandsAndOptions(rootCommand); @@ -57,7 +63,7 @@ ArgParseResult scanAndParseCommands( return _parseArgs( _ArgCursor(scannedArgs), command: rootCommand, - scanMode: scanMode, + settings: settings, ); } @@ -200,7 +206,7 @@ ArgParseResult _parseArgs( final Iterable? options, final ArgParseResult? parent, final Map>? inheritedPersistentOwners, - required final ScanMode scanMode, + required final ParserSettings settings, }) { final result = ArgParseResult(command: command, parent: parent); var rejectedSubcommand = false; @@ -263,7 +269,7 @@ ArgParseResult _parseArgs( scannedArgs: scannedArgs, command: command, persistentOwners: persistentOwners, - scanMode: scanMode, + settings: settings, name: '--${arg.string}', )) { return result; @@ -288,7 +294,7 @@ ArgParseResult _parseArgs( scannedArgs: scannedArgs, command: command, persistentOwners: persistentOwners, - scanMode: scanMode, + settings: settings, name: '-${arg.string}', )) { return result; @@ -296,7 +302,7 @@ ArgParseResult _parseArgs( result.errors.add('Unknown option: -${arg.string}'); case DoubleDashToken(): - if (scanMode.doubleDashHandling != DoubleDashHandling.passThroughRest) { + if (settings.doubleDashHandling != DoubleDashHandling.passThroughRest) { result.errors.add('Unexpected value: ${arg.string}'); break; } @@ -305,7 +311,9 @@ ArgParseResult _parseArgs( case SingleDashToken(): if (command != null && command.subcommands.isNotEmpty) { rejectedSubcommand = true; - result.errors.add('$unknownSubcommandErrorPrefix"${arg.string}"'); + result.errors.add( + _unknownSubcommandError(arg.string, command, settings), + ); } else { result.positionalWords.add(arg.string); } @@ -319,14 +327,16 @@ ArgParseResult _parseArgs( scannedArgs: scannedArgs, command: command, persistentOwners: persistentOwners, - scanMode: scanMode, + settings: settings, name: arg.string, )) { return result; } if (command != null && command.subcommands.isNotEmpty) { rejectedSubcommand = true; - result.errors.add('$unknownSubcommandErrorPrefix"${arg.string}"'); + result.errors.add( + _unknownSubcommandError(arg.string, command, settings), + ); } else { result.positionalWords.add(arg.string); } @@ -338,12 +348,25 @@ ArgParseResult _parseArgs( !command.canRunAsLeafCommand && result.child == null && !rejectedSubcommand) { - result.errors.add('A subcommand is required under ${command.name}'); + result.errors.add('$subcommandRequiredErrorPrefix${command.name}'); } return result; } +String _unknownSubcommandError( + final String name, + final CommandDefinition command, + final ParserSettings settings, +) { + final suggestions = similarCommandSuggestions( + name, + command.subcommands, + settings.suggestionDistanceLimit, + ); + return '$unknownSubcommandErrorPrefix"$name"$suggestions'; +} + void _assignOption({ required final ArgParseResult result, required final ArgParseResult target, @@ -577,7 +600,7 @@ bool _enterMatchedSubcommand({ required final _ArgCursor scannedArgs, required final CommandDefinition? command, required final Map> persistentOwners, - required final ScanMode scanMode, + required final ParserSettings settings, required final String name, }) { final subcommands = command?.subcommands; @@ -589,7 +612,7 @@ bool _enterMatchedSubcommand({ command: subcommand, parent: result, inheritedPersistentOwners: persistentOwners, - scanMode: scanMode, + settings: settings, ); return true; } diff --git a/packages/config/lib/src/config/arg_parser/parser_settings.dart b/packages/config/lib/src/config/arg_parser/parser_settings.dart new file mode 100644 index 00000000..66c001d1 --- /dev/null +++ b/packages/config/lib/src/config/arg_parser/parser_settings.dart @@ -0,0 +1,25 @@ +enum DoubleDashHandling { + /// No special handling means it is treated as any other word. + noSpecialHandling, + + /// When `--` is not taken as an option value, leave the following + /// arguments unparsed. A `--` used as a value does not start this, + /// so a later `--` still can. + passThroughRest, +} + +class ParserSettings { + /// How to handle a standalone `--`. + final DoubleDashHandling doubleDashHandling; + + /// The maximum edit distance allowed when suggesting possible intended + /// commands. + /// + /// Set to `0` in order to disable suggestions, defaults to `2`. + final int suggestionDistanceLimit; + + const ParserSettings({ + this.doubleDashHandling = DoubleDashHandling.noSpecialHandling, + this.suggestionDistanceLimit = 2, + }); +} diff --git a/packages/config/lib/src/config/arg_parser/scanner.dart b/packages/config/lib/src/config/arg_parser/scanner.dart index 0a4febf3..5acca841 100644 --- a/packages/config/lib/src/config/arg_parser/scanner.dart +++ b/packages/config/lib/src/config/arg_parser/scanner.dart @@ -50,24 +50,6 @@ final class ScannedArg { const ScannedArg(this.raw, this.tokens); } -enum DoubleDashHandling { - /// No special handling means it is treated as any other word. - noSpecialHandling, - - /// When `--` is not taken as an option value, leave the following - /// arguments unparsed. A `--` used as a value does not start this, - /// so a later `--` still can. - passThroughRest, -} - -class ScanMode { - final DoubleDashHandling doubleDashHandling; - - const ScanMode({ - this.doubleDashHandling = DoubleDashHandling.noSpecialHandling, - }); -} - /// Scans command-line arguments into one [ScannedArg] per argument. /// /// Does not validate and does not throw [Exception]s. diff --git a/packages/config/lib/src/config/arg_parser/suggestions.dart b/packages/config/lib/src/config/arg_parser/suggestions.dart new file mode 100644 index 00000000..10de2811 --- /dev/null +++ b/packages/config/lib/src/config/arg_parser/suggestions.dart @@ -0,0 +1,88 @@ +// Returns help text for commands similar to `name`, in sorted order. +import 'dart:collection' show SplayTreeSet; +import 'dart:math' as math; + +import 'command_definition.dart'; + +String similarCommandSuggestions( + final String name, + final Iterable commands, + final int suggestionDistanceLimit, +) { + final candidates = similarCommands(name, commands, suggestionDistanceLimit); + if (candidates.isEmpty) return ''; + return ' (Did you mean ${candidates.map((final command) => command.name).join(', ')}?)'; +} + +List similarCommands( + final String name, + final Iterable commands, + final int suggestionDistanceLimit, +) { + if (suggestionDistanceLimit <= 0) return []; + final distances = {}; + final candidates = SplayTreeSet((final a, final b) { + final byDistance = distances[a]! - distances[b]!; + if (byDistance != 0) return byDistance; + return a.name.compareTo(b.name); + }); + for (final command in commands) { + if (command.usageDefinition.hidden) continue; + int? bestDistance; + for (final alias in [ + command.name, + ...command.aliasesDefinition.aliases, + ...command.aliasesDefinition.suggestionAliases, + ]) { + final distance = _editDistance(name, alias); + if (distance <= suggestionDistanceLimit) { + bestDistance = math.min(bestDistance ?? distance, distance); + } + } + if (bestDistance == null) continue; + distances[command] = bestDistance; + candidates.add(command); + } + return candidates.toList(); +} + +/// Returns the edit distance between `from` and `to`. +// +/// Allows for edits, deletes, substitutions, and swaps all as single cost. +/// +/// See https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance#Optimal_string_alignment_distance +int _editDistance(String from, String to) { + // Add a space in front to mimic indexing by 1 instead of 0. + from = ' $from'; + to = ' $to'; + final distances = [ + for (var i = 0; i < from.length; i++) + [ + for (var j = 0; j < to.length; j++) + if (i == 0) j else if (j == 0) i else 0, + ], + ]; + + for (var i = 1; i < from.length; i++) { + for (var j = 1; j < to.length; j++) { + // Removals from `from`. + var min = distances[i - 1][j] + 1; + // Additions to `from`. + min = math.min(min, distances[i][j - 1] + 1); + // Substitutions (and equality). + min = math.min( + min, + distances[i - 1][j - 1] + + // Cost is zero if substitution was not actually necessary. + (from[i] == to[j] ? 0 : 1), + ); + // Allows for basic swaps, but no additional edits of swapped regions. + if (i > 1 && j > 1 && from[i] == to[j - 1] && from[i - 1] == to[j]) { + min = math.min(min, distances[i - 2][j - 2] + 1); + } + distances[i][j] = min; + } + } + + return distances.last.last; +} diff --git a/packages/config/lib/src/config/completion.dart b/packages/config/lib/src/config/completion.dart new file mode 100644 index 00000000..66be3dd8 --- /dev/null +++ b/packages/config/lib/src/config/completion.dart @@ -0,0 +1,162 @@ +import 'arg_parser/arg_parser.dart' show CommandDefinition; +import 'arg_parser_facade.dart' show ParsedArgs; + +/// A single command line completion alternative. +/// +/// [value] is the text inserted on the command line. +/// [description] is shown next to the value by shells that support it +/// (zsh, fish, PowerShell, Carapace). Bash ignores it. +class CompletionCandidate { + final String value; + final String? description; + + const CompletionCandidate(this.value, {this.description}); + + @override + bool operator ==(final Object other) { + if (identical(this, other)) return true; + return other is CompletionCandidate && + other.value == value && + other.description == description; + } + + @override + int get hashCode => Object.hash(value, description); + + @override + String toString() { + final desc = description; + return desc == null + ? 'CompletionCandidate($value)' + : 'CompletionCandidate($value: $desc)'; + } +} + +/// How the shell should complete file system paths. +enum CompletionPathMode { + /// No file system completion. + none, + + /// Complete files (and directories, to allow navigating into them). + files, + + /// Complete directories only. + directories, +} + +/// What to offer when completing the value of an option. +/// +/// Either a list of [candidates], or a request for the shell to perform its +/// native file system completion (which handles quoting, `~` expansion, and +/// relative paths much better than a program can). +/// +/// Use the named constructors: +/// - [CompletionResult.values] for an explicit list of alternatives +/// - [CompletionResult.strings] for an explicit list of plain string values +/// - [CompletionResult.files] for native file completion +/// - [CompletionResult.directories] for native directory completion +/// - [CompletionResult.none] to offer nothing +class CompletionResult { + /// The explicit completion alternatives. Empty for path completion. + final List candidates; + + /// Whether, and how, the shell should complete file system paths. + final CompletionPathMode pathMode; + + /// File name extensions (without the leading dot) to restrict + /// [CompletionPathMode.files] completion to. Empty means all files. + final List fileExtensions; + + /// If true, the shell is asked not to append a space after inserting a + /// single matching candidate. Useful for candidates that are prefixes of + /// longer values, e.g. `host:`. + final bool noSpace; + + /// Offers the given [candidates]. + const CompletionResult.values( + this.candidates, { + this.noSpace = false, + }) : pathMode = CompletionPathMode.none, + fileExtensions = const []; + + /// Offers the given plain string [values], without descriptions. + CompletionResult.strings( + final Iterable values, { + this.noSpace = false, + }) : candidates = [for (final value in values) CompletionCandidate(value)], + pathMode = CompletionPathMode.none, + fileExtensions = const []; + + /// Requests native file completion from the shell, + /// optionally restricted to the given file name [extensions] + /// (without the leading dot). + const CompletionResult.files({ + final List? extensions, + }) : candidates = const [], + pathMode = CompletionPathMode.files, + fileExtensions = extensions ?? const [], + noSpace = false; + + /// Requests native directory completion from the shell. + const CompletionResult.directories() + : candidates = const [], + pathMode = CompletionPathMode.directories, + fileExtensions = const [], + noSpace = false; + + /// Offers nothing. + const CompletionResult.none() + : candidates = const [], + pathMode = CompletionPathMode.none, + fileExtensions = const [], + noSpace = false; + + @override + String toString() => + 'CompletionResult(candidates: $candidates, pathMode: $pathMode, ' + 'fileExtensions: $fileExtensions, noSpace: $noSpace)'; +} + +/// 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. +class CompletionContext { + /// The partial text of the value being completed. May be empty. + /// + /// For a multi-value option with a separator, this is the text after the + /// last separator. + final String wordToComplete; + + /// The complete words preceding the word being completed, + /// not including the executable name. + final List precedingWords; + + /// The commands on the command line so far, root command first. + final List commands; + + /// The raw command line arguments parsed so far, for all commands on the + /// command line. Option values are the strings as typed, unvalidated. + final ParsedArgs parsedArgs; + + /// The environment variables of the completion request, i.e. of the shell + /// asking for completion. Not used by the built-in completions; available + /// for custom `complete` implementations, e.g. to find a server URL. + final Map environment; + + const CompletionContext({ + required this.wordToComplete, + required this.precedingWords, + required this.commands, + required this.parsedArgs, + required this.environment, + }); + + /// The command the completed option belongs to on this command line, + /// i.e. the last command. + CommandDefinition get command => commands.last; +} diff --git a/packages/config/lib/src/config/config.dart b/packages/config/lib/src/config/config.dart index 7b3d6d85..b30c7ef1 100644 --- a/packages/config/lib/src/config/config.dart +++ b/packages/config/lib/src/config/config.dart @@ -10,6 +10,7 @@ export 'arg_parser_facade.dart' NewParsedArgs, OptionReceiver, ParsedArgs; +export 'completion.dart'; export 'config_source.dart'; export 'config_source_provider.dart'; export 'configuration.dart'; diff --git a/packages/config/lib/src/config/exceptions.dart b/packages/config/lib/src/config/exceptions.dart index 1efb9928..903c99a2 100644 --- a/packages/config/lib/src/config/exceptions.dart +++ b/packages/config/lib/src/config/exceptions.dart @@ -59,3 +59,15 @@ class InvalidValueException implements Exception { return '$runtimeType: $message'; } } + +class CommandUsageException extends UsageException { + final CommandDefinition command; + + CommandUsageException(final String message, this.command) + : super(message, ''); + + @override + String toString() { + return 'Usage error for command: ${command.name}\n$message'; + } +} diff --git a/packages/config/lib/src/config/file_system_options.dart b/packages/config/lib/src/config/file_system_options.dart index 20587569..93ffd810 100644 --- a/packages/config/lib/src/config/file_system_options.dart +++ b/packages/config/lib/src/config/file_system_options.dart @@ -1,7 +1,9 @@ +import 'dart:async' show FutureOr; import 'dart:io'; import 'package:path/path.dart' as p; +import 'completion.dart'; import 'exceptions.dart'; import 'options.dart'; @@ -86,6 +88,12 @@ class DirOption extends ConfigOptionBase { break; } } + + /// Offers native directory completion from the shell. + @override + FutureOr complete(final CompletionContext context) { + return const CompletionResult.directories(); + } } class FileParser extends ValueParser { @@ -156,4 +164,10 @@ class FileOption extends ConfigOptionBase { break; } } + + /// Offers native file completion from the shell. + @override + FutureOr complete(final CompletionContext context) { + return const CompletionResult.files(); + } } diff --git a/packages/config/lib/src/config/option_types.dart b/packages/config/lib/src/config/option_types.dart index 3b94f9e0..b83d8470 100644 --- a/packages/config/lib/src/config/option_types.dart +++ b/packages/config/lib/src/config/option_types.dart @@ -1,5 +1,8 @@ +import 'dart:async' show FutureOr; + import 'package:meta/meta.dart'; +import 'completion.dart'; import 'options.dart'; /// ValueParser that returns the input string unchanged. @@ -158,6 +161,14 @@ class EnumOption extends ConfigOptionBase { // if no other value help is provided, auto-generate it with the enum names return (valueParser as EnumParser).valueHelpString(); } + + /// Offers the enum names, restricted to [allowedValues] when set, + /// with descriptions from [allowedHelp]. + @override + FutureOr complete(final CompletionContext context) { + final values = allowedValues ?? (valueParser as EnumParser).enumValues; + return CompletionResult.values(candidatesForValues(values)); + } } /// Base class for configuration options that diff --git a/packages/config/lib/src/config/options.dart b/packages/config/lib/src/config/options.dart index c1915d7d..d74916f7 100644 --- a/packages/config/lib/src/config/options.dart +++ b/packages/config/lib/src/config/options.dart @@ -1,8 +1,11 @@ +import 'dart:async' show FutureOr; + import 'package:collection/collection.dart'; import 'package:meta/meta.dart'; import 'arg_parser_bridge.dart'; import 'arg_parser_facade.dart'; +import 'completion.dart'; import 'configuration.dart' show Configuration; import 'configuration_broker.dart'; import 'exceptions.dart'; @@ -340,6 +343,67 @@ abstract class ConfigOptionBase implements OptionDefinition { @override ConfigOptionBase get option => this; + ///////////////////// + // Command line completion + + /// Returns the command line completion alternatives for a value of this + /// option. + /// + /// Invoked by the command runner when the shell requests completion of a + /// value for this option. [context] describes the command line typed so far, + /// including the partial [CompletionContext.wordToComplete]. + /// + /// The default implementation offers [allowedValues] when set, with + /// descriptions from [allowedHelp]; otherwise the keys of [allowedHelp] + /// when set; otherwise it requests native file completion from the shell. + /// + /// Subclasses override this for type-specific behavior, for example + /// [EnumOption] offers the enum names and [DirOption] offers directories. + /// A custom option type can override this to offer any alternatives, + /// for example names fetched from a server. The implementation may be + /// asynchronous, but must be fast and should not throw. If it throws, + /// nothing is offered. + /// + /// The candidates need not be filtered by [CompletionContext.wordToComplete] + /// since the shells do that; filtering is still recommended for large sets. + FutureOr complete(final CompletionContext context) { + final candidates = allowedValueCandidates(); + if (candidates != null) return CompletionResult.values(candidates); + return const CompletionResult.files(); + } + + /// Returns completion candidates for [allowedValues] with descriptions + /// from [allowedHelp], or for the keys of [allowedHelp] alone, + /// or null if neither is set. + @protected + List? allowedValueCandidates() { + final allowed = allowedValues; + if (allowed != null) return candidatesForValues(allowed); + + final help = allowedHelp; + if (help != null) { + return [ + for (final entry in help.entries) + CompletionCandidate(entry.key, description: entry.value), + ]; + } + return null; + } + + /// Returns completion candidates for [values], formatted with + /// [valueParser] and described by [allowedHelp] when available. + @protected + List candidatesForValues(final Iterable values) { + final help = allowedHelp; + return [ + for (final value in values) + if (valueParser.format(value) case final formatted) + CompletionCandidate(formatted, description: help?[formatted]), + ]; + } + + // TODO: Present arg options including the '--' prefix, + // and {position 0} for positional arguments without a name. @override String toString() => argName ?? envName ?? ''; @@ -630,6 +694,12 @@ class FlagOption extends ConfigOptionBase { source: ValueSourceType.arg, ); } + + /// A flag takes no value on the command line, so there is nothing to offer. + @override + FutureOr complete(final CompletionContext context) { + return const CompletionResult.none(); + } } /// Parses a list of values from a comma-separated string. @@ -730,6 +800,26 @@ class MultiOption extends ConfigOptionBase> { } } } + + /// Offers the [allowedElementValues] when set, with descriptions from + /// [allowedHelp]; otherwise the keys of [allowedHelp] when set; + /// otherwise native file completion. + /// + /// The command runner completes the element after the last separator, + /// when the [MultiParser.separator] is a string. + @override + FutureOr complete(final CompletionContext context) { + final allowed = allowedElementValues; + if (allowed != null) { + final help = allowedHelp; + return CompletionResult.values([ + for (final value in allowed) + if (multiParser.elementParser.format(value) case final formatted) + CompletionCandidate(formatted, description: help?[formatted]), + ]); + } + return super.complete(context); + } } /// Extension to add a [qualifiedString] shorthand method to [OptionDefinition]. diff --git a/packages/config/test/config/arg_parser/scan_and_parse_args_test.dart b/packages/config/test/config/arg_parser/scan_and_parse_args_test.dart index 3b7f175e..dcd8d5ad 100644 --- a/packages/config/test/config/arg_parser/scan_and_parse_args_test.dart +++ b/packages/config/test/config/arg_parser/scan_and_parse_args_test.dart @@ -840,7 +840,7 @@ void main() { const name = StringOption(argName: 'name', argAbbrev: 'n'); const file = StringOption(argName: 'file', argAbbrev: 'f'); - const passThroughRest = ScanMode( + const passThroughRest = ParserSettings( doubleDashHandling: DoubleDashHandling.passThroughRest, ); @@ -848,7 +848,7 @@ void main() { return scanAndParseArgs( args, options: [verbose, name, file], - scanMode: passThroughRest, + settings: passThroughRest, ); } diff --git a/packages/config/test/config/arg_parser/scan_and_parse_commands_test.dart b/packages/config/test/config/arg_parser/scan_and_parse_commands_test.dart index ef9603f9..e32f7121 100644 --- a/packages/config/test/config/arg_parser/scan_and_parse_commands_test.dart +++ b/packages/config/test/config/arg_parser/scan_and_parse_commands_test.dart @@ -209,10 +209,10 @@ void main() { expect(childResult(childResult(result)).command, same(leaf)); }); - test('when a suggestion alias is used then the error is recorded', () { + test('when a suggestion alias is used then that command is suggested', () { expect( childResult(parse(['mid', 'leave'])).errors, - ['Unknown subcommand: "leave"'], + ['Unknown subcommand: "leave" (Did you mean leaf?)'], ); }); @@ -231,9 +231,14 @@ void main() { expect(parse(['tool']).errors, ['Unknown subcommand: "tool"']); }); - test('when the first word is empty then the error is recorded', () { - expect(parse(['']).errors, ['Unknown subcommand: ""']); - }); + test( + 'when the first word is empty then the closest command is suggested', + () { + expect(parse(['']).errors, [ + 'Unknown subcommand: "" (Did you mean mid?)', + ]); + }, + ); test('when a branch command receives a positional word ' 'then the error is recorded', () { @@ -367,7 +372,7 @@ void main() { 'then that option and the following word are recorded', () { expect(childResult(parse(['mid', '-o', 'x'])).errors, [ 'Unknown option: -o', - 'Unknown subcommand: "x"', + 'Unknown subcommand: "x" (Did you mean leaf?)', ]); }); @@ -375,7 +380,7 @@ void main() { 'then that option and its value word are recorded', () { expect(childResult(parse(['mid', '--root-only', 'r'])).errors, [ 'Unknown option: --root-only', - 'Unknown subcommand: "r"', + 'Unknown subcommand: "r" (Did you mean leaf?)', ]); }); @@ -393,7 +398,7 @@ void main() { 'then the option and the following word are recorded', () { expect(parse(['--output', 'o', 'mid']).errors, [ 'Unknown option: --output', - 'Unknown subcommand: "o"', + 'Unknown subcommand: "o" (Did you mean mid?)', ]); }); @@ -433,8 +438,10 @@ void main() { ]); }); - test('when - is parsed then it is an unknown subcommand', () { - expect(parse(['-']).errors, ['Unknown subcommand: "-"']); + test('when - is parsed then the closest command is suggested', () { + expect(parse(['-']).errors, [ + 'Unknown subcommand: "-" (Did you mean mid?)', + ]); }); test('when the leaf receives - then it stays positional', () { @@ -445,6 +452,135 @@ void main() { }); }); + group('Given commands close to a mistyped name', () { + final build = TestCommand( + name: 'build', + aliasesDefinition: const CommandAliasesDefinition( + aliases: ['compile'], + suggestionAliases: ['bld'], + ), + ); + final built = TestCommand(name: 'built'); + final hidden = TestCommand( + name: 'secret', + usageDefinition: const CommandUsageDefinition(hidden: true), + ); + final root = TestCommand( + name: 'tool', + subcommands: [build, built, hidden], + ); + + ArgParseResult parse( + final List args, { + final int suggestionDistanceLimit = 2, + }) { + return scanAndParseCommands( + args, + rootCommand: root, + settings: ParserSettings( + suggestionDistanceLimit: suggestionDistanceLimit, + ), + ); + } + + test('when the name is close to several commands ' + 'then they are suggested in order of distance', () { + expect(parse(['biuld']).errors, [ + 'Unknown subcommand: "biuld" (Did you mean build, built?)', + ]); + }); + + test('when the name is one edit from an alias ' + 'then that command is suggested', () { + expect(parse(['compil']).errors, [ + 'Unknown subcommand: "compil" (Did you mean build?)', + ]); + }); + + test('when the name matches a suggestion alias ' + 'then that command is suggested', () { + expect(parse(['bld']).errors, [ + 'Unknown subcommand: "bld" (Did you mean build?)', + ]); + }); + + test('when the name is only close to a hidden command ' + 'then no suggestion is included', () { + expect(parse(['secre']).errors, ['Unknown subcommand: "secre"']); + }); + + test('when suggestions are disabled ' + 'then no suggestion is included', () { + expect( + parse(['biuld'], suggestionDistanceLimit: 0).errors, + ['Unknown subcommand: "biuld"'], + ); + }); + + test('when the name is farther than the limit ' + 'then no suggestion is included', () { + expect( + parse(['bxxld'], suggestionDistanceLimit: 1).errors, + ['Unknown subcommand: "bxxld"'], + ); + }); + + test('when the limit is raised ' + 'then a farther command is suggested', () { + expect( + parse(['qqqbuild'], suggestionDistanceLimit: 3).errors, + ['Unknown subcommand: "qqqbuild" (Did you mean build?)'], + ); + }); + }); + + group('Given a command whose alias is closer than its name', () { + final bata = TestCommand(name: 'bata'); + final zeta = TestCommand( + name: 'zeta', + aliasesDefinition: const CommandAliasesDefinition( + suggestionAliases: ['beta'], + ), + ); + final root = TestCommand( + name: 'tool', + subcommands: [bata, zeta], + ); + + test('when the input matches that alias ' + 'then suggestions follow the final distance', () { + final result = scanAndParseCommands( + ['beta'], + rootCommand: root, + ); + + expect(result.errors, [ + 'Unknown subcommand: "beta" (Did you mean zeta, bata?)', + ]); + }); + }); + + group('Given commands at the same edit distance', () { + final cut = TestCommand(name: 'cut'); + final bat = TestCommand(name: 'bat'); + final root = TestCommand( + name: 'tool', + subcommands: [cut, bat], + ); + + test('when the input is equally close to both ' + 'then both commands are suggested', () { + final result = scanAndParseCommands( + ['cat'], + rootCommand: root, + ); + + expect(result.errors, [ + 'Unknown subcommand: "cat" (Did you mean bat, cut?)', + ]); + }); + }); + group('Given a root and subcommand with different option types', () { final build = _EnumCommand<_BuildOption>( name: 'build', @@ -986,7 +1122,7 @@ void main() { usageDefinition: const CommandUsageDefinition(description: 'root usage'), ); - const passThroughRest = ScanMode( + const passThroughRest = ParserSettings( doubleDashHandling: DoubleDashHandling.passThroughRest, ); @@ -994,7 +1130,7 @@ void main() { return scanAndParseCommands( args, rootCommand: root, - scanMode: passThroughRest, + settings: passThroughRest, ); } @@ -1455,7 +1591,7 @@ void main() { final result = scanAndParseCommands( ['--', 'leaf'], rootCommand: root, - scanMode: const ScanMode( + settings: const ParserSettings( doubleDashHandling: DoubleDashHandling.passThroughRest, ), ); @@ -1469,7 +1605,7 @@ void main() { final result = scanAndParseCommands( ['--', 'leaf'], rootCommand: root, - scanMode: const ScanMode( + settings: const ParserSettings( doubleDashHandling: DoubleDashHandling.passThroughRest, ), ); @@ -1524,7 +1660,9 @@ void main() { test( 'when the word version is parsed then it is an unknown subcommand', () { - expect(parse(['version']).errors, ['Unknown subcommand: "version"']); + expect(parse(['version']).errors, [ + 'Unknown subcommand: "version" (Did you mean --version?)', + ]); }, ); diff --git a/packages/config/test/config/completion_test.dart b/packages/config/test/config/completion_test.dart new file mode 100644 index 00000000..b247fc70 --- /dev/null +++ b/packages/config/test/config/completion_test.dart @@ -0,0 +1,218 @@ +import 'dart:async' show FutureOr; +import 'dart:io' show Directory; + +import 'package:config/config.dart'; +import 'package:test/test.dart'; + +enum Color { red, green, blue } + +class ServerOption extends StringOption { + const ServerOption({super.argName}); + + @override + FutureOr complete(final CompletionContext context) async { + await Future.delayed(Duration.zero); + return CompletionResult.strings(['alpha', 'beta'], noSpace: true); + } +} + +const _context = CompletionContext( + wordToComplete: '', + precedingWords: [], + commands: [], + parsedArgs: _NoParsedArgs(), + environment: {}, +); + +class _NoParsedArgs implements ParsedArgs { + const _NoParsedArgs(); + + @override + bool wasParsed(final ConfigOptionBase option) => false; + + @override + bool flag(final FlagOption option) => throw StateError('not parsed'); + + @override + String option(final ConfigOptionBase option) => + throw StateError('not parsed'); + + @override + List multiOption(final MultiOption option) => + throw StateError('not parsed'); + + @override + List get rest => const []; + + @override + List get parseErrors => const []; +} + +Future complete(final OptionDefinition option) async { + return option.option.complete(_context); +} + +void main() { + group('Given a StringOption without allowed values', () { + const option = StringOption(argName: 'name'); + + test('when completing then native file completion is requested', () async { + final result = await complete(option); + expect(result.pathMode, CompletionPathMode.files); + expect(result.candidates, isEmpty); + }); + }); + + group('Given a StringOption with allowed values and allowed help', () { + const option = StringOption( + argName: 'name', + allowedValues: ['a', 'b'], + allowedHelp: {'a': 'The A', 'b': 'The B'}, + ); + + test('when completing then the allowed values are offered ' + 'with their help as description', () async { + final result = await complete(option); + expect(result.pathMode, CompletionPathMode.none); + expect(result.candidates, [ + const CompletionCandidate('a', description: 'The A'), + const CompletionCandidate('b', description: 'The B'), + ]); + }); + }); + + group('Given an IntOption with allowed help only', () { + const option = IntOption( + argName: 'size', + allowedHelp: {'1024': '1KB', '2048': '2KB'}, + ); + + test('when completing then the allowed help keys are offered', () async { + final result = await complete(option); + expect(result.candidates, [ + const CompletionCandidate('1024', description: '1KB'), + const CompletionCandidate('2048', description: '2KB'), + ]); + }); + }); + + group('Given an IntOption with allowed values', () { + const option = IntOption(argName: 'size', allowedValues: [1, 2]); + + test('when completing then the formatted values are offered', () async { + final result = await complete(option); + expect(result.candidates.map((final c) => c.value), ['1', '2']); + }); + }); + + group('Given an EnumOption', () { + const option = EnumOption( + enumParser: EnumParser(Color.values), + argName: 'color', + allowedHelp: {'red': 'Like roses'}, + ); + + test('when completing then all enum names are offered, ' + 'described by allowed help when present', () async { + final result = await complete(option); + expect(result.candidates, [ + const CompletionCandidate('red', description: 'Like roses'), + const CompletionCandidate('green'), + const CompletionCandidate('blue'), + ]); + }); + + test('when completing an option restricted by allowed values ' + 'then only those enum names are offered', () async { + const restricted = EnumOption( + enumParser: EnumParser(Color.values), + argName: 'color', + allowedValues: [Color.green, Color.blue], + ); + final result = await complete(restricted); + expect(result.candidates.map((final c) => c.value), ['green', 'blue']); + }); + }); + + group('Given a FlagOption', () { + const option = FlagOption(argName: 'force'); + + test('when completing then nothing is offered', () async { + final result = await complete(option); + expect(result.candidates, isEmpty); + expect(result.pathMode, CompletionPathMode.none); + }); + }); + + group('Given a MultiStringOption', () { + test('when completing with allowed values ' + 'then the allowed element values are offered', () async { + const option = MultiStringOption( + argName: 'tags', + allowedValues: ['x', 'y'], + allowedHelp: {'x': 'The X'}, + ); + final result = await complete(option); + expect(result.candidates, [ + const CompletionCandidate('x', description: 'The X'), + const CompletionCandidate('y'), + ]); + }); + + test('when completing without allowed values ' + 'then native file completion is requested', () async { + const option = MultiStringOption(argName: 'tags'); + final result = await complete(option); + expect(result.pathMode, CompletionPathMode.files); + }); + }); + + group('Given file system options', () { + test('when completing a DirOption ' + 'then native directory completion is requested', () async { + const option = DirOption(argName: 'dir'); + final result = await complete(option); + expect(result.pathMode, CompletionPathMode.directories); + }); + + test('when completing a FileOption ' + 'then native file completion is requested', () async { + const option = FileOption(argName: 'file'); + final result = await complete(option); + expect(result.pathMode, CompletionPathMode.files); + }); + + test('when completing a DirOption with a default value ' + 'then the default does not affect the completion', () async { + final option = DirOption(argName: 'dir', defaultsTo: Directory('x')); + final result = await complete(option); + expect(result.pathMode, CompletionPathMode.directories); + }); + }); + + group('Given a custom option type overriding complete', () { + const option = ServerOption(argName: 'server'); + + test('when completing then its asynchronous result is used', () async { + final result = await complete(option); + expect(result.candidates.map((final c) => c.value), ['alpha', 'beta']); + expect(result.noSpace, isTrue); + }); + }); + + group('Given a CompletionResult', () { + test('when created for files with extensions ' + 'then the extensions are kept without the path mode changing', () { + const result = CompletionResult.files(extensions: ['yaml', 'json']); + expect(result.pathMode, CompletionPathMode.files); + expect(result.fileExtensions, ['yaml', 'json']); + expect(result.candidates, isEmpty); + }); + + test('when created as none then nothing is offered', () { + const result = CompletionResult.none(); + expect(result.pathMode, CompletionPathMode.none); + expect(result.candidates, isEmpty); + }); + }); +}