diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ac1baae0..dc02ad64 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -46,11 +46,8 @@ jobs: - isolated_object - serverpod_logging - serverpod_logging_cli - platform: [ubuntu-latest] + platform: [ubuntu-latest, windows-latest] include: - - package: cli_tools - platform: windows-latest - dart: 3.9 - package: cli_tools platform: macos-latest dart: 3.9 diff --git a/packages/cli_tools/analysis_options.yaml b/packages/cli_tools/analysis_options.yaml index 3ce6aff5..b2be8bc1 100644 --- a/packages/cli_tools/analysis_options.yaml +++ b/packages/cli_tools/analysis_options.yaml @@ -10,3 +10,4 @@ analyzer: linter: rules: prefer_relative_imports: true + avoid_final_parameters: false diff --git a/packages/cli_tools/lib/src/better_command_runner/better_command.dart b/packages/cli_tools/lib/src/better_command_runner/better_command.dart index e502278e..e955deb8 100644 --- a/packages/cli_tools/lib/src/better_command_runner/better_command.dart +++ b/packages/cli_tools/lib/src/better_command_runner/better_command.dart @@ -123,6 +123,7 @@ abstract class BetterCommand extends Command { Configuration resolveConfiguration(final ArgResults? argResults) { return Configuration.resolveNoExcept( options: options, + // ignore: deprecated_member_use argResults: argResults, env: envVariables, ); diff --git a/packages/cli_tools/lib/src/better_command_runner/better_command_runner.dart b/packages/cli_tools/lib/src/better_command_runner/better_command_runner.dart index a259de22..37c120cd 100644 --- a/packages/cli_tools/lib/src/better_command_runner/better_command_runner.dart +++ b/packages/cli_tools/lib/src/better_command_runner/better_command_runner.dart @@ -386,6 +386,7 @@ class BetterCommandRunner Configuration resolveConfiguration(final ArgResults? argResults) { return Configuration.resolveNoExcept( options: _globalOptions, + // ignore: deprecated_member_use argResults: argResults, env: envVariables, ignoreUnexpectedPositionalArgs: true, diff --git a/packages/config/analysis_options.yaml b/packages/config/analysis_options.yaml index 29b3ba4a..62bbab7e 100644 --- a/packages/config/analysis_options.yaml +++ b/packages/config/analysis_options.yaml @@ -11,3 +11,4 @@ analyzer: linter: rules: prefer_relative_imports: true + avoid_final_parameters: false diff --git a/packages/config/lib/src/args_compatibility/config_parser.dart b/packages/config/lib/src/args_compatibility/config_parser.dart index 1eb0927e..4be3ad6f 100644 --- a/packages/config/lib/src/args_compatibility/config_parser.dart +++ b/packages/config/lib/src/args_compatibility/config_parser.dart @@ -2,6 +2,8 @@ import 'dart:io' show Platform; import 'package:args/args.dart'; +import '../config/arg_parser_bridge.dart'; +import '../config/arg_parser_facade.dart'; import '../config/configuration.dart'; import '../config/configuration_broker.dart'; import '../config/option_types.dart'; @@ -246,11 +248,15 @@ class ConfigParser implements ArgParser { }) { validateOptions(_optionDefinitions); - final argResults = parser.parse(args); + final parsedArgs = legacyParsedArgs( + _optionDefinitions, + args, + allowTrailingOptions: allowTrailingOptions, + ); final configuration = Configuration.resolve( options: _optionDefinitions, - argResults: argResults, + parsedArgs: parsedArgs, env: env ?? Platform.environment, configBroker: configBroker, presetValues: presetValues, @@ -261,8 +267,8 @@ class ConfigParser implements ArgParser { return ConfigResults( configuration, - argResults.arguments, - argResults.rest, + parsedArgs.argResults.arguments, + parsedArgs.argResults.rest, ); } diff --git a/packages/config/lib/src/config/arg_parser/arg_parser.dart b/packages/config/lib/src/config/arg_parser/arg_parser.dart new file mode 100644 index 00000000..5acb655a --- /dev/null +++ b/packages/config/lib/src/config/arg_parser/arg_parser.dart @@ -0,0 +1,11 @@ +/// Command line scanning and parsing. +library; + +export 'command_definition.dart'; +export 'parser.dart' + show + ArgParseResult, + scanAndParseArgs, + scanAndParseCommands, + unknownSubcommandErrorPrefix; +export 'scanner.dart' show DoubleDashHandling, ScanMode, 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 new file mode 100644 index 00000000..8bae8f6c --- /dev/null +++ b/packages/config/lib/src/config/arg_parser/command_definition.dart @@ -0,0 +1,95 @@ +import '../options.dart' show OptionDefinition; + +abstract interface class CommandDefinition { + /// The name of this command. + String get name; + + /// Generates a formatted string with usage information for this command. + String get usage; + + /// Describes usage documentation and visibility for this command. + CommandUsageDefinition get usageDefinition; + + /// Describes alternate names resolution for this command. + CommandAliasesDefinition get aliasesDefinition; + + /// Persistent options - the options of the current command that continue to + /// be available for all subcommands. + /// On the root command, this is the global options. + List get persistentOptions; + + /// Regular options - the options of the current command that are not + /// persistent. + List get options; + + /// All the defined options of this command, depending on the passed flag. + List allOptions({final bool onlyPersistent = false}); + + List get subcommands; + + /// Whether this command can be run as the last command on the command line + /// even if it has subcommands registered. Default is false. + /// If false and this command is the last command found on the command line, + /// the command line parser will yield an error. + bool get canRunAsLeafCommand => false; +} + +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; + + /// An optional footer which is added to the end of the usage. + final String? usageFooter; + + /// The command's category. + /// + /// Displayed in [parent]'s [CommandRunner.usage]. Commands with categories + /// will be grouped together, and displayed after commands without a category. + final String? category; + + /// Whether or not this command should be hidden from help listings. + /// + /// By default, leaf commands are always visible. Branch commands are visible + /// as long as any of their leaf commands are visible. + final bool hidden; + + const CommandUsageDefinition({ + final String? description, + this.usageFooter, + this.category, + final bool? hidden, + }) : description = description ?? '', + hidden = hidden ?? false; +} + +class CommandAliasesDefinition { + /// Alternate names for this command. + final List aliases; + + /// Alternate non-functional names for this command. + /// + /// These names won't be used in the documentation, and also they won't work + /// when invoked on the command line. But if an unknown command is used it + /// will be matched against this when creating suggestions. + /// + /// 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; +} diff --git a/packages/config/lib/src/config/arg_parser/parser.dart b/packages/config/lib/src/config/arg_parser/parser.dart new file mode 100644 index 00000000..c604a1b9 --- /dev/null +++ b/packages/config/lib/src/config/arg_parser/parser.dart @@ -0,0 +1,610 @@ +import '../config.dart' + show + ConfigOptionBase, + FlagOption, + MultiOption, + OptionDefinition, + CommandDefinitionError, + validateOptions; +import 'command_definition.dart'; +import 'scanner.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: '; + +/// Scans the arguments and parses them into an [ArgParseResult] +/// corresponding to a single set of options. +/// +/// Does not handle subcommands. +/// Usage problems are recorded on [ArgParseResult.errors] and parsing +/// continues. Invalid option definitions still throw. +ArgParseResult scanAndParseArgs( + final Iterable args, { + required final Iterable options, + final ScanMode scanMode = const ScanMode(), +}) { + validateOptions(options); + + final scannedArgs = scanArgs(args); + + return _parseArgs( + _ArgCursor(scannedArgs), + options: options, + scanMode: scanMode, + ); +} + +/// Scans the arguments and parses them into an [ArgParseResult], +/// treating the args as a command line potentially containing subcommands. +/// +/// A subcommand whose name or alias uses option syntax (`--version`, `-v`) +/// is considered an "action option". It is run as a command although it has +/// the name syntax of an option. +/// +/// Usage problems are recorded on the [ArgParseResult] for the command +/// whose arguments contained them, and parsing continues. +/// Invalid command or option definitions still throw. +ArgParseResult scanAndParseCommands( + final Iterable args, { + required final CommandDefinition rootCommand, + final ScanMode scanMode = const ScanMode(), +}) { + _validateCommandsAndOptions(rootCommand); + + final scannedArgs = scanArgs(args); + + return _parseArgs( + _ArgCursor(scannedArgs), + command: rootCommand, + scanMode: scanMode, + ); +} + +/// Represents the parsed result for a command / subcommand on a command line. +/// +/// An instance is a node in a linked list of subcommands. +/// The first node is the "root" (typically the executed program). +/// The last node is the "leaf" (the last subcommand on the command line). +class ArgParseResult { + final CommandDefinition? command; + final ArgParseResult? parent; + ArgParseResult? child; + + final Map flagOptions = {}; + final Map regularOptions = + {}; + final Map> multiOptions = + >{}; + final List positionalWords = []; + final List unparsedArgs = []; + + /// Usage errors found while parsing this command's arguments. + final List errors = []; + + ArgParseResult({this.command, this.parent}); + + Iterator get iterator => _ArgParseResultIterator(this); + + List toList() => + Iterable.withIterator(() => iterator).toList(); +} + +class _ArgParseResultIterator implements Iterator { + bool _initial = true; + + _ArgParseResultIterator(final ArgParseResult initial) : current = initial; + + @override + ArgParseResult current; + + @override + bool moveNext() { + if (_initial) { + _initial = false; + return true; + } + final child = current.child; + if (child == null) return false; + current = child; + return true; + } +} + +/// Walks scanned arguments one token at a time. +class _ArgCursor { + final List _args; + int _argIndex = 0; + int _tokenIndex = -1; + + _ArgCursor(this._args); + + bool moveNext() { + if (_argIndex >= _args.length) return false; + + final nextToken = _tokenIndex + 1; + if (nextToken < _args[_argIndex].tokens.length) { + _tokenIndex = nextToken; + return true; + } + + final nextArg = _argIndex + 1; + if (nextArg >= _args.length) return false; + _argIndex = nextArg; + _tokenIndex = 0; + return true; + } + + Token get current => _args[_argIndex].tokens[_tokenIndex]; + + /// Whether the next token was cut from the same command-line argument. + bool get nextContinuesRaw => + _argIndex < _args.length && + _tokenIndex + 1 < _args[_argIndex].tokens.length; + + bool get hasNext => nextContinuesRaw || _argIndex + 1 < _args.length; + + Token get peek => nextContinuesRaw + ? _args[_argIndex].tokens[_tokenIndex + 1] + : _args[_argIndex + 1].tokens.first; + + /// Drops later tokens cut from the current command-line argument. + void skipFollowingRawContinuation() { + _tokenIndex = _args[_argIndex].tokens.length - 1; + } + + /// The original command-line argument for [current]. + String takeCurrentRaw() { + final raw = _args[_argIndex].raw; + skipFollowingRawContinuation(); + return raw; + } + + /// Each command-line argument after the current one, in order. + List takeRemainingRaw() { + final rest = [ + for (var i = _argIndex + 1; i < _args.length; i++) _args[i].raw, + ]; + _argIndex = _args.length; + return rest; + } +} + +/// Reads the value for an option that takes one. +/// +/// A separate following argument is taken whole, including values that start +/// with a hyphen (`--number -123`). A value attached with `=` is the attached +/// text only. +/// +/// Returns null when no value is present. A cluster tail that is not an +/// attached `=` value is skipped, because those letters are not separate +/// options and are not a value either. +String? _readOptionValue(final _ArgCursor scannedArgs) { + if (!scannedArgs.hasNext) return null; + final next = scannedArgs.peek; + if (scannedArgs.nextContinuesRaw) { + if (next is WordToken) { + scannedArgs.moveNext(); + return next.string; + } + scannedArgs.skipFollowingRawContinuation(); + return null; + } + scannedArgs.moveNext(); + return scannedArgs.takeCurrentRaw(); +} + +ArgParseResult _parseArgs( + final _ArgCursor scannedArgs, { + final CommandDefinition? command, + final Iterable? options, + final ArgParseResult? parent, + final Map>? inheritedPersistentOwners, + required final ScanMode scanMode, +}) { + final result = ArgParseResult(command: command, parent: parent); + var rejectedSubcommand = false; + + final persistentOwners = >{ + ...?inheritedPersistentOwners, + if (command != null) ...{ + for (final option in command.allOptions(onlyPersistent: true)) + option.option: result, + }, + }; + + final allOptions = [ + ...?command?.options, + ...?options, + ...persistentOwners.keys, + ]; + + final possibleOptionNames = {}; + final possibleOptionAbbrevs = {}; + for (final option in allOptions) { + if (option.option.argName case final String name) { + possibleOptionNames[name] = option.option; + if (option.option case final FlagOption flag) { + if (flag.negatable) { + possibleOptionNames['no-$name'] = option.option; + } + } + } + if (option.option.argAliases case final List aliases) { + for (final alias in aliases) { + possibleOptionNames[alias] = option.option; + } + } + + if (option.option.argAbbrev case final String abbrev) { + possibleOptionAbbrevs[abbrev] = option.option; + } + } + + while (scannedArgs.moveNext()) { + final arg = scannedArgs.current; + + switch (arg) { + case LongOptionToken(): + final option = possibleOptionNames[arg.string]; + if (option != null) { + _assignOption( + result: result, + target: persistentOwners[option] ?? result, + option: option, + scannedArgs: scannedArgs, + name: arg.string, + longOption: true, + ); + break; + } + if (_enterMatchedSubcommand( + result: result, + scannedArgs: scannedArgs, + command: command, + persistentOwners: persistentOwners, + scanMode: scanMode, + name: '--${arg.string}', + )) { + return result; + } + result.errors.add('Unknown option: --${arg.string}'); + + case ShortOptionToken(): + final option = possibleOptionAbbrevs[arg.string]; + if (option != null) { + _assignOption( + result: result, + target: persistentOwners[option] ?? result, + option: option, + scannedArgs: scannedArgs, + name: arg.string, + longOption: false, + ); + break; + } + if (_enterMatchedSubcommand( + result: result, + scannedArgs: scannedArgs, + command: command, + persistentOwners: persistentOwners, + scanMode: scanMode, + name: '-${arg.string}', + )) { + return result; + } + result.errors.add('Unknown option: -${arg.string}'); + + case DoubleDashToken(): + if (scanMode.doubleDashHandling != DoubleDashHandling.passThroughRest) { + result.errors.add('Unexpected value: ${arg.string}'); + break; + } + result.unparsedArgs.addAll(scannedArgs.takeRemainingRaw()); + + case SingleDashToken(): + if (command != null && command.subcommands.isNotEmpty) { + rejectedSubcommand = true; + result.errors.add('$unknownSubcommandErrorPrefix"${arg.string}"'); + } else { + result.positionalWords.add(arg.string); + } + + case ValueToken(): + result.errors.add('Unexpected value: ${arg.string}'); + + case WordToken(): + if (_enterMatchedSubcommand( + result: result, + scannedArgs: scannedArgs, + command: command, + persistentOwners: persistentOwners, + scanMode: scanMode, + name: arg.string, + )) { + return result; + } + if (command != null && command.subcommands.isNotEmpty) { + rejectedSubcommand = true; + result.errors.add('$unknownSubcommandErrorPrefix"${arg.string}"'); + } else { + result.positionalWords.add(arg.string); + } + } + } + + if (command != null && + command.subcommands.isNotEmpty && + !command.canRunAsLeafCommand && + result.child == null && + !rejectedSubcommand) { + result.errors.add('A subcommand is required under ${command.name}'); + } + + return result; +} + +void _assignOption({ + required final ArgParseResult result, + required final ArgParseResult target, + required final ConfigOptionBase option, + required final _ArgCursor scannedArgs, + required final String name, + required final bool longOption, +}) { + final written = '${longOption ? '--' : '-'}$name'; + switch (option.option) { + case final FlagOption flag: + if (_recordIfSpecifiedMoreThanOnce( + result, + option, + target.flagOptions.containsKey(option), + )) { + return; + } + target.flagOptions[flag] = longOption + ? !_isNegatedFlag(flag, name) + : true; + + case final MultiOption multiOption: + final value = _readOptionValue(scannedArgs); + if (value == null) { + result.errors.add('Missing value for option: $written'); + return; + } + final values = target.multiOptions[multiOption] ?? []; + values.add(value); + target.multiOptions[multiOption] = values; + + default: + final duplicate = _recordIfSpecifiedMoreThanOnce( + result, + option, + target.regularOptions.containsKey(option), + ); + final value = _readOptionValue(scannedArgs); + if (value == null) { + result.errors.add('Missing value for option: $written'); + return; + } + if (!duplicate) { + target.regularOptions[option] = value; + } + } +} + +bool _isNegatedFlag(final FlagOption flag, final String name) { + if (!flag.negatable) return false; + final argName = flag.argName; + return argName != null && name == 'no-$argName'; +} + +void _validateCommandsAndOptions( + final CommandDefinition command, { + final List inheritedPersistentOptions = const [], +}) { + final visibleOptions = [ + ...inheritedPersistentOptions, + ...command.allOptions(), + ]; + validateOptions(visibleOptions); + + _rejectPositionalPersistentOptions(command); + + final subcommands = command.subcommands; + if (subcommands.isNotEmpty) { + _rejectDuplicateSubcommandNames(command.name, subcommands); + _rejectPositionalOptionsOnBranch(command); + _rejectOptionLikeSubcommandCollisions( + command.name, + visibleOptions, + subcommands, + ); + } + + final persistentOptions = [ + ...inheritedPersistentOptions, + ...command.allOptions(onlyPersistent: true), + ]; + for (final subcommand in subcommands) { + _validateCommandsAndOptions( + subcommand, + inheritedPersistentOptions: persistentOptions, + ); + } +} + +void _rejectDuplicateSubcommandNames( + final String commandName, + final List subcommands, +) { + final names = {}; + for (final subcommand in subcommands) { + final name = subcommand.name; + if (!names.add(name)) { + throw CommandDefinitionError( + subcommand, + 'Duplicate subcommand name: $name for command $commandName', + ); + } + } +} + +/// Rejects a subcommand name or alias in option syntax that matches an +/// option visible on [commandName]. +/// +/// Visible options are the command's own options and every persistent option +/// inherited from its ancestors. A command may still define an option whose spelling +/// matches its own name: that option is parsed only after the command is +/// selected. +void _rejectOptionLikeSubcommandCollisions( + final String commandName, + final List options, + final List subcommands, +) { + final spellings = {}; + for (final option in options) { + final argName = option.option.argName; + if (argName != null) { + spellings['--$argName'] = option; + if (option.option case final FlagOption flag when flag.negatable) { + spellings['--no-$argName'] = option; + } + } + if (option.option.argAliases case final List aliases) { + for (final alias in aliases) { + spellings['--$alias'] = option; + } + } + if (option.option.argAbbrev case final String abbrev) { + spellings['-$abbrev'] = option; + } + } + if (spellings.isEmpty) return; + + for (final subcommand in subcommands) { + _rejectSubcommandSpelling( + commandName, + subcommand, + subcommand.name, + spellings, + isAlias: false, + ); + for (final alias in subcommand.aliasesDefinition.aliases) { + _rejectSubcommandSpelling( + commandName, + subcommand, + alias, + spellings, + isAlias: true, + ); + } + } +} + +void _rejectSubcommandSpelling( + final String commandName, + final CommandDefinition subcommand, + final String spelling, + final Map spellings, { + required final bool isAlias, +}) { + if (!_isOptionLikeCommandName(spelling)) return; + final option = spellings[spelling]; + if (option == null) return; + final kind = isAlias ? 'alias' : 'name'; + throw CommandDefinitionError( + subcommand, + 'Subcommand $kind `$spelling` collides with ${option.option.qualifiedString()} ' + 'for command $commandName', + ); +} + +/// Whether [name] is a long option (`--version`) or a one-character short +/// option (`-v`), the spellings the parser can select as action options. +bool _isOptionLikeCommandName(final String name) { + if (name.startsWith('--')) { + return name.length > 2 && !name.contains('='); + } + return name.length == 2 && name.startsWith('-') && name[1] != '='; +} + +void _rejectPositionalPersistentOptions( + final CommandDefinition command, +) { + for (final option in command.persistentOptions) { + if (option.option.argPos == null) continue; + throw CommandDefinitionError( + command, + 'Persistent options must not be positional: ' + '${option.option.qualifiedString()}.', + ); + } +} + +void _rejectPositionalOptionsOnBranch( + final CommandDefinition command, +) { + for (final option in command.options) { + if (option.option.argPos == null) continue; + throw CommandDefinitionError( + command, + 'Cannot define positional options on a command with subcommands: ' + '${option.option.qualifiedString()}.', + ); + } +} + +bool _recordIfSpecifiedMoreThanOnce( + final ArgParseResult result, + final ConfigOptionBase option, + final bool alreadySpecified, +) { + if (!alreadySpecified) return false; + + final name = option.argName; + final label = name != null ? '--$name' : '-${option.argAbbrev}'; + result.errors.add('Option $label cannot be specified more than once'); + return true; +} + +/// Selects the first subcommand whose name or alias is [name]. +/// +/// Action options call this with the option spelling (`--version`, `-v`) +/// after no defined option matched that spelling. +bool _enterMatchedSubcommand({ + required final ArgParseResult result, + required final _ArgCursor scannedArgs, + required final CommandDefinition? command, + required final Map> persistentOwners, + required final ScanMode scanMode, + required final String name, +}) { + final subcommands = command?.subcommands; + if (subcommands == null || subcommands.isEmpty) return false; + if (_matchSubcommand(subcommands, name) + case final CommandDefinition subcommand) { + result.child = _parseArgs( + scannedArgs, + command: subcommand, + parent: result, + inheritedPersistentOwners: persistentOwners, + scanMode: scanMode, + ); + return true; + } + return false; +} + +CommandDefinition? _matchSubcommand( + final Iterable> subcommands, + final String name, +) { + for (final subcommand in subcommands) { + if (subcommand.name == name || + subcommand.aliasesDefinition.aliases.contains(name)) { + return subcommand; + } + } + return null; +} diff --git a/packages/config/lib/src/config/arg_parser/scanner.dart b/packages/config/lib/src/config/arg_parser/scanner.dart new file mode 100644 index 00000000..0a4febf3 --- /dev/null +++ b/packages/config/lib/src/config/arg_parser/scanner.dart @@ -0,0 +1,158 @@ +import 'package:characters/characters.dart'; + +sealed class Token { + final String string; + + const Token(this.string); +} + +sealed class OptionToken extends Token { + const OptionToken(super.string); +} + +class ShortOptionToken extends OptionToken { + const ShortOptionToken(super.string); +} + +class LongOptionToken extends OptionToken { + const LongOptionToken(super.string); +} + +/// Maybe a value, maybe a command. +class WordToken extends Token { + const WordToken(super.string); +} + +/// A token that is definitely a value. +class ValueToken extends WordToken { + const ValueToken(super.string); +} + +/// Special case - the `--` double dash argument. +/// Often this is used to separate the following arguments, +/// for example not parse them and instead pass them to another program. +final class DoubleDashToken extends ValueToken { + const DoubleDashToken() : super('--'); +} + +/// Special case - the `-` single dash argument. +/// Some commands attribute special meaning to `-`, such as referring to +/// stdin/stdout. +final class SingleDashToken extends ValueToken { + const SingleDashToken() : super('-'); +} + +/// One command-line argument and the tokens the scanner cut from it. +final class ScannedArg { + final String raw; + final List tokens; + + 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. +/// +/// ### Argument syntaxes +/// +/// These are the possible argument syntaxes. +/// +/// "Chars" are one or more characters with each representing an option +/// abbreviation. +/// +/// "Word" can be a command or a value, this depends on the previous argument +/// and whether it is an option that actually takes a value, and also whether +/// positional argument values are accepted at this position. +/// +/// Note that a word/value may be an empty string. +/// ``` +/// word +/// -chars +/// --option +/// -chars value +/// --option value +/// -chars=value +/// --option=value +/// -- +/// - +/// ``` +/// +/// When an option takes a value, the following argument is that value even if +/// it starts with a hyphen, so `--number -123` yields `-123`. +/// Attached values use the `=` syntax (`--number=-123`). +/// +/// No escapes are supported. +/// +/// ### Assumptions +/// +/// These constraints apply to option names and abbreviations. They are not +/// checked by this scanner, but are assumed to be followed. +/// - Option names / abbreviations cannot contain '='. +/// - Option names / abbreviations cannot start with '-'. +/// +/// A command name may itself be option syntax (`--version`, `-v`). This +/// scanner still classifies that argument as an option, but the parser may +/// then select it as a subcommand when no option matches. +List scanArgs(final Iterable args) => [ + for (final arg in args) ScannedArg(arg, _scanTokens(arg)), +]; + +/// If [arg] is written as an option that would take its value from the +/// next argument, returns the spelling of that option: `--name` for a +/// long option or `-x` for a short option (the last one of a cluster +/// such as `-abx`). +/// +/// Returns null for words, for `--` and `-`, and for options with an +/// attached value (`--name=value`, `-x=value`), since those cannot take +/// the next argument as their value. Whether the option actually takes +/// a value is up to the caller. +String? optionAwaitingValue(final String arg) { + final tokens = _scanTokens(arg); + if (tokens.isEmpty) return null; + return switch (tokens.last) { + LongOptionToken(:final string) => '--$string', + ShortOptionToken(:final string) => '-$string', + _ => null, + }; +} + +List _scanTokens(final String arg) { + if (arg == '--') return const [DoubleDashToken()]; + if (arg == '-') return const [SingleDashToken()]; + + final equalIndex = arg.indexOf('='); + final hasValue = equalIndex != -1; + final nameEnd = hasValue ? equalIndex : arg.length; + final value = [if (hasValue) ValueToken(arg.substring(equalIndex + 1))]; + + if (arg.startsWith('--')) { + return [LongOptionToken(arg.substring(2, nameEnd)), ...value]; + } + if (arg.startsWith('-')) { + return [ + for (final ch in arg.substring(1, nameEnd).characters) + ShortOptionToken(ch), + ...value, + ]; + } + return [WordToken(arg)]; +} diff --git a/packages/config/lib/src/config/arg_parser_bridge.dart b/packages/config/lib/src/config/arg_parser_bridge.dart new file mode 100644 index 00000000..4139782c --- /dev/null +++ b/packages/config/lib/src/config/arg_parser_bridge.dart @@ -0,0 +1,174 @@ +import 'package:args/args.dart'; + +import 'arg_parser_facade.dart'; +import 'options.dart'; + +/// A ParsedArgs implementation for the old approach using ArgParser and ArgResults. +class OldParsedArgs implements ParsedArgs { + late final ArgResults argResults; + + /// Throws [FormatException] from [ArgParser.parse] if the argument parsing fails. + OldParsedArgs( + final List options, + final Iterable args, { + final bool allowTrailingOptions = false, + }) { + final parser = ArgParser(allowTrailingOptions: allowTrailingOptions); + addOptionsToParser(options, parser); + argResults = parser.parse(args); + } + + OldParsedArgs.fromArgResults(this.argResults); + + /// Returns `true` if the option with [name] was parsed from an actual + /// argument. + /// + /// Returns `false` if it wasn't provided and the default value or no default + /// value would be used instead. + /// + /// [name] must be a valid option name in the parser. + @override + bool wasParsed(final ConfigOptionBase option) { + return argResults.wasParsed(_optionArgName(option)); + } + + /// Returns the parsed or default command-line flag named [name]. + /// + /// [name] must be a valid flag name in the parser. + @override + bool flag(final FlagOption option) { + return argResults.flag(_optionArgName(option)); + } + + /// Returns the parsed string value of the argument option named [name]. + /// + /// [name] must be a valid option name in the parser. + /// + /// Throws [StateError] if the option was not parsed. + @override + String option(final OptionDefinition option) { + return argResults.option(_optionArgName(option))!; + } + + /// Returns the list of parsed (or default) command-line options for [name]. + /// + /// [name] must be a valid option name in the parser. + @override + List multiOption(final MultiOption option) { + return argResults.multiOption(_optionArgName(option)); + } + + String _optionArgName(final OptionDefinition option) { + final argName = option.option.argName; + if (argName == null) { + throw StateError('Option has no arg name: $option'); + } + return argName; + } + + /// The remaining command-line arguments that were not parsed as options or + /// flags. + /// + /// If `--` was used to separate the options from the remaining arguments, + /// it will not be included in this list unless parsing stopped before the + /// `--` was reached. + @override + List get rest { + return argResults.rest; + } + + /// The legacy parser throws instead of recording usage errors. + @override + List get parseErrors => const []; +} + +/// Returns the usage help text for these options. +String oldUsage(final Iterable options) { + final parser = ArgParser(); + final argOptions = options.where((final o) => o.option.argName != null); + addOptionsToParser(argOptions, parser, addGroupSeparators: true); + return parser.usage; +} + +void addOptionsToParser( + final Iterable argNameOpts, + final ArgParser argParser, { + final bool addGroupSeparators = false, +}) { + final receiver = _ArgParserOptionCollection(argParser); + addOptionsToReceiver( + argNameOpts, + receiver, + addGroupSeparators: addGroupSeparators, + ); +} + +class _ArgParserOptionCollection implements OptionReceiver { + final ArgParser argParser; + + _ArgParserOptionCollection(this.argParser); + + @override + void addSeparator(final String separator) { + argParser.addSeparator(separator); + } + + @override + void addOption(final OptionDefinition option) { + _addToArgParser(option, argParser); + } +} + +void _addToArgParser(final OptionDefinition option, final ArgParser argParser) { + final opt = option.option; + final argName = opt.argName; + if (argName == null) { + throw StateError("Can't add option without arg name to arg parser."); + } + + switch (opt) { + case FlagOption(): + argParser.addFlag( + argName, + abbr: opt.argAbbrev, + help: opt.helpText, + defaultsTo: opt.defaultValue(), + negatable: opt.negatable, + hideNegatedUsage: opt.hideNegatedUsage, + hide: opt.hide, + aliases: opt.argAliases ?? const [], + ); + + case MultiOption(): + argParser.addMultiOption( + argName, + abbr: opt.argAbbrev, + help: opt.helpText, + valueHelp: opt.valueHelpString(), + allowed: opt.allowedElementValues?.map( + opt.multiParser.elementParser.format, + ), + allowedHelp: opt.allowedHelp, + defaultsTo: opt.defaultValue()?.map( + opt.multiParser.elementParser.format, + ), + hide: opt.hide, + splitCommas: opt.multiParser.separator == ',', + aliases: opt.argAliases ?? const [], + ); + + default: + argParser.addOption( + argName, + abbr: opt.argAbbrev, + help: opt.helpText, + valueHelp: opt.valueHelpString(), + allowed: opt.allowedValues?.map(opt.valueParser.format), + allowedHelp: opt.allowedHelp, + defaultsTo: opt.defaultValueString(), + mandatory: opt.mandatory, + hide: opt.hide, + aliases: opt.argAliases ?? const [], + ); + } +} diff --git a/packages/config/lib/src/config/arg_parser_facade.dart b/packages/config/lib/src/config/arg_parser_facade.dart new file mode 100644 index 00000000..ed9a0ae2 --- /dev/null +++ b/packages/config/lib/src/config/arg_parser_facade.dart @@ -0,0 +1,205 @@ +import 'package:args/args.dart' show ArgResults, ArgParser; + +import 'arg_parser/arg_parser.dart' show scanAndParseArgs, ArgParseResult; +import 'arg_parser_bridge.dart' show OldParsedArgs, addOptionsToParser; +import 'options.dart' + show + OptionDefinition, + validateOptions, + ConfigOptionBase, + FlagOption, + MultiOption, + OptionGroup; + +/// Validates and prepares a set of options for a legacy [ArgParser]. +void prepareOptionsForParsing( + final Iterable options, + final ArgParser argParser, +) { + final argNameOpts = validateOptions(options); + addOptionsToParser(argNameOpts, argParser, addGroupSeparators: true); +} + +/// Throws [FormatException] from [ArgParser.parse] if the argument parsing fails. +OldParsedArgs legacyParsedArgs( + final List options, + final Iterable args, { + final bool allowTrailingOptions = false, +}) { + final argNameOpts = options + .where((final o) => o.option.argName != null) + .toList(); + + return OldParsedArgs( + argNameOpts, + args, + allowTrailingOptions: allowTrailingOptions, + ); +} + +OldParsedArgs legacyParsedArgsFromArgResults(final ArgResults argResults) { + return OldParsedArgs.fromArgResults(argResults); +} + +NewParsedArgs newParsedArgs( + final Iterable options, + final Iterable args, +) { + return NewParsedArgs(scanAndParseArgs(args, options: options)); +} + +/// A proxy (wrapper) for the parsed command-line arguments for an individual +/// command/subcommand. +abstract interface class ParsedArgs { + /// Returns `true` if the option was parsed from an actual argument. + bool wasParsed(final ConfigOptionBase option); + + /// Returns the value of the specified parsed command-line flag. + /// + /// [option] must be a successfully parsed flag option, + /// otherwise throws [StateError]. + bool flag(final FlagOption option); + + /// Returns the string value of the specified parsed command-line option. + /// + /// [option] must be a successfully parsed option, + /// otherwise throws [StateError]. + String option(final ConfigOptionBase option); + + /// Returns the value list of the specified parsed command-line multi-option. + /// + /// [option] must be a successfully parsed multi-option, + /// otherwise throws [StateError]. + List multiOption(final MultiOption option); + + /// The remaining command-line arguments that were not parsed as options or + /// flags. + /// + /// If `--` was used to separate the options from the remaining arguments, + /// it will not be included in this list unless parsing stopped before the + /// `--` was reached. + List get rest; + + /// Usage errors recorded while parsing these arguments, such as an unknown + /// option. Empty when parsing succeeded. + List get parseErrors; +} + +class NewParsedArgs implements ParsedArgs { + final ArgParseResult _result; + + NewParsedArgs(final ArgParseResult result) : _result = result; + + @override + bool wasParsed(final OptionDefinition option) { + return _result.flagOptions.containsKey(option) || + _result.regularOptions.containsKey(option) || + _result.multiOptions.containsKey(option); + } + + @override + bool flag(final FlagOption option) { + final value = _result.flagOptions[option]; + if (value == null) { + throw StateError('Flag ${option.option.argName} not found'); + } + return value; + } + + @override + String option(final OptionDefinition option) { + final value = _result.regularOptions[option]; + if (value == null) { + throw StateError('Option ${option.option.argName} not found'); + } + return value; + } + + @override + List multiOption(final MultiOption option) { + final value = _result.multiOptions[option]; + if (value == null) { + throw StateError('Multi-option ${option.option.argName} not found'); + } + return value; + } + + @override + List get rest { + return [..._result.positionalWords, ..._result.unparsedArgs]; + } + + @override + List get parseErrors => _result.errors; +} + +/// Adds [argNameOpts] to [argParser]. +/// +/// When [addGroupSeparators] is `true`, +/// - options are grouped by [OptionGroup] and a +/// - separator with the group name is inserted +/// - before each group that has at least one visible option. +/// - Note: +/// - groupless options are added first in their original order +/// - relative order of all options within a group is preserved +/// - relative order of all groups is preserved +/// +/// By default, +/// [addGroupSeparators] is `false` to ensure backwards compatibility. +void addOptionsToReceiver( + final Iterable argNameOpts, + final OptionReceiver receiver, { + final bool addGroupSeparators = false, +}) { + // plain option-addition without any group separator logic + if (!addGroupSeparators) { + for (final o in argNameOpts) { + receiver.addOption(o.option); + } + return; + } + + // the following containers are ordered by default i.e. + // preserves insertion-order: + // - Map : https://stackoverflow.com/q/79786585/10251345 + // - List : https://api.dart.dev/dart-core/List-class.html + final optionGroups = >{}; + final grouplessOptions = []; + + // gather all necessary option-group information + for (final opt in argNameOpts) { + final group = opt.option.group; + if (group != null) { + optionGroups.update( + group, + (final options) => options..add(opt), + ifAbsent: () => [opt], + ); + } else { + grouplessOptions.add(opt); + } + } + + // add all groupless-options first (in order) + for (final o in grouplessOptions) { + receiver.addOption(o.option); + } + + // add all explicit groups (in order) + optionGroups.forEach((final group, final groupedOptions) { + // add the group-name-separator only if it has at least one visible option + if (groupedOptions.any((final o) => !o.option.hide)) { + receiver.addSeparator(group.name); + } + // add all options within this group (in order) + for (final o in groupedOptions) { + receiver.addOption(o.option); + } + }); +} + +abstract interface class OptionReceiver { + void addSeparator(final String separator); + + void addOption(final OptionDefinition option); +} diff --git a/packages/config/lib/src/config/config.dart b/packages/config/lib/src/config/config.dart index 6f9839e9..7b3d6d85 100644 --- a/packages/config/lib/src/config/config.dart +++ b/packages/config/lib/src/config/config.dart @@ -1,3 +1,15 @@ +export 'arg_parser/arg_parser.dart'; + +export 'arg_parser_facade.dart' + show + addOptionsToReceiver, + prepareOptionsForParsing, + legacyParsedArgs, + legacyParsedArgsFromArgResults, + newParsedArgs, + NewParsedArgs, + OptionReceiver, + ParsedArgs; export 'config_source.dart'; export 'config_source_provider.dart'; export 'configuration.dart'; diff --git a/packages/config/lib/src/config/configuration.dart b/packages/config/lib/src/config/configuration.dart index 250bff5c..8674d8d8 100644 --- a/packages/config/lib/src/config/configuration.dart +++ b/packages/config/lib/src/config/configuration.dart @@ -1,6 +1,8 @@ -import 'package:args/args.dart'; +import 'package:args/args.dart' show ArgResults; import 'package:collection/collection.dart'; +import 'arg_parser_facade.dart' + show ParsedArgs, legacyParsedArgsFromArgResults, newParsedArgs; import 'configuration_broker.dart'; import 'exceptions.dart'; import 'option_resolution_impl.dart'; @@ -76,7 +78,11 @@ class Configuration { /// {@template Configuration.resolveNoExcept} /// Creates a configuration with option values resolved from the provided context. /// - /// [argResults] is used if provided. Otherwise [args] is used if provided. + /// [argResults] is used if provided, however it is deprecated and will be + /// removed in a future version, use [parsedArgs] or [args] instead. + /// If both [args] and [parsedArgs] are provided, [args] has precedence. + /// If neither [argResults], [parsedArgs], nor [args] are provided, the + /// configuration will be resolved without command line arguments. /// /// If [presetValues] is provided, the values present will override the other sources, /// including if they are null. @@ -86,7 +92,8 @@ class Configuration { /// instead the caller is responsible for checking if [errors] is non-empty. Configuration.resolveNoExcept({ required final Iterable options, - ArgResults? argResults, + @Deprecated('Use parsedArgs or args instead') final ArgResults? argResults, + ParsedArgs? parsedArgs, final Iterable? args, final Map? env, final ConfigurationBroker? configBroker, @@ -95,16 +102,14 @@ class Configuration { }) : _options = List.from(options), _config = {}, _errors = [] { - if (argResults == null && args != null) { - argResults = _prepareArgResults(args); - if (argResults == null) { - remainingPosArgs = []; - return; - } + if (argResults != null) { + parsedArgs = legacyParsedArgsFromArgResults(argResults); + } else if (args != null) { + parsedArgs = newParsedArgs(options, args); } _resolveWithArgResults( - args: argResults, + parsedArgs: parsedArgs, env: env, configBroker: configBroker, presetValues: presetValues, @@ -119,7 +124,8 @@ class Configuration { /// A caller can use [resolveNoExcept] instead to handle the errors themselves. Configuration.resolve({ required final Iterable options, - ArgResults? argResults, + @Deprecated('Use parsedArgs or args instead') final ArgResults? argResults, + ParsedArgs? parsedArgs, final Iterable? args, final Map? env, final ConfigurationBroker? configBroker, @@ -128,17 +134,14 @@ class Configuration { }) : _options = List.from(options), _config = {}, _errors = [] { - if (argResults == null && args != null) { - argResults = _prepareArgResults(args); - if (argResults == null) { - remainingPosArgs = []; - throwExceptionOnErrors(); - return; - } + if (argResults != null) { + parsedArgs = legacyParsedArgsFromArgResults(argResults); + } else if (args != null) { + parsedArgs = newParsedArgs(options, args); } _resolveWithArgResults( - args: argResults, + parsedArgs: parsedArgs, env: env, configBroker: configBroker, presetValues: presetValues, @@ -148,30 +151,13 @@ class Configuration { throwExceptionOnErrors(); } - ArgResults? _prepareArgResults(final Iterable args) { - final parser = ArgParser(); - _options.prepareForParsing(parser); - - try { - return parser.parse(args); - } on FormatException catch (e) { - _errors.add(e.message); - for (final o in _options) { - _config[o] = const OptionResolutionImpl.error( - 'Previous ArgParser error', - ); - } - return null; - } - } - /// Throws a [UsageException] with error and correct usage information /// if there were any errors during configuration resolution. /// Can be overridden to change the exception or its content. void throwExceptionOnErrors() { if (_errors.isNotEmpty) { final buffer = StringBuffer(); - final errors = _errors.map(formatConfigError); + final errors = formattedErrors; buffer.writeAll(errors, '\n'); throw UsageException(buffer.toString(), usage); } @@ -186,6 +172,9 @@ class Configuration { /// Gets the errors that occurred during configuration resolution. Iterable get errors => _errors; + /// Gets the errors that occurred during configuration resolution with regularized formatting. + Iterable get formattedErrors => _errors.map(formatConfigError); + /// Returns the option definition for the given enum name, /// or any provided argument name, position, /// environment variable name, or configuration key. @@ -311,13 +300,17 @@ class Configuration { } void _resolveWithArgResults({ - final ArgResults? args, + final ParsedArgs? parsedArgs, final Map? env, final ConfigurationBroker? configBroker, final Map? presetValues, final bool ignoreUnexpectedPositionalArgs = false, }) { - final posArgs = (args?.rest ?? []).iterator; + validateOptions(_options); + + _errors.addAll(parsedArgs?.parseErrors ?? []); + + final posArgs = (parsedArgs?.rest ?? []).iterator; final orderedOpts = _options.sorted( (final a, final b) => (a.option.argPos ?? -1).compareTo(b.option.argPos ?? -1), @@ -333,7 +326,7 @@ class Configuration { } else { resolution = opt.option.resolveValue( this, - args: args, + args: parsedArgs, posArgs: posArgs, env: env, configBroker: configBroker, diff --git a/packages/config/lib/src/config/exceptions.dart b/packages/config/lib/src/config/exceptions.dart index d016e716..1efb9928 100644 --- a/packages/config/lib/src/config/exceptions.dart +++ b/packages/config/lib/src/config/exceptions.dart @@ -1,9 +1,14 @@ +import 'package:args/command_runner.dart' show UsageException; + +import 'arg_parser/arg_parser.dart' show CommandDefinition; import 'options.dart'; export 'package:args/command_runner.dart' show UsageException; +sealed class ConfigDefinitionError extends Error {} + /// Indicates that the option definition is invalid. -class OptionDefinitionError extends Error { +class OptionDefinitionError extends ConfigDefinitionError { final OptionDefinition option; final String? message; @@ -12,8 +17,24 @@ class OptionDefinitionError extends Error { @override String toString() { return message != null - ? 'Invalid definition for ${option.qualifiedString()}: $message' - : 'Invalid definition for ${option.qualifiedString()}'; + ? '$runtimeType: Invalid definition for ${option.qualifiedString()}: $message' + : '$runtimeType: Invalid definition for ${option.qualifiedString()}'; + } +} + +/// Indicates that the command definition is invalid. +class CommandDefinitionError extends ConfigDefinitionError { + final CommandDefinition command; + final String? message; + + CommandDefinitionError(this.command, [this.message]); + + @override + String toString() { + final label = 'command `${command.name}`'; + return message != null + ? '$runtimeType: Invalid definition for $label: $message' + : '$runtimeType: Invalid definition for $label'; } } diff --git a/packages/config/lib/src/config/options.dart b/packages/config/lib/src/config/options.dart index 888567db..c1915d7d 100644 --- a/packages/config/lib/src/config/options.dart +++ b/packages/config/lib/src/config/options.dart @@ -1,7 +1,8 @@ -import 'package:args/args.dart'; import 'package:collection/collection.dart'; import 'package:meta/meta.dart'; +import 'arg_parser_bridge.dart'; +import 'arg_parser_facade.dart'; import 'configuration.dart' show Configuration; import 'configuration_broker.dart'; import 'exceptions.dart'; @@ -258,26 +259,6 @@ abstract class ConfigOptionBase implements OptionDefinition { return valueHelp; } - /// Adds this configuration option to the provided argument parser. - void _addToArgParser(final ArgParser argParser) { - final argName = this.argName; - if (argName == null) { - throw StateError("Can't add option without arg name to arg parser."); - } - argParser.addOption( - argName, - abbr: argAbbrev, - help: helpText, - valueHelp: valueHelpString(), - allowed: allowedValues?.map(valueParser.format), - allowedHelp: allowedHelp, - defaultsTo: defaultValueString(), - mandatory: mandatory, - hide: hide, - aliases: argAliases ?? const [], - ); - } - /// Validates the configuration option definition. /// /// This method is called by [validateOptions] to validate @@ -288,25 +269,34 @@ abstract class ConfigOptionBase implements OptionDefinition { /// If they do, they must also call the super implementation. @mustCallSuper void validateDefinition() { - if (argName == null && argAbbrev != null) { - throw OptionDefinitionError( - this, - "An argument option can't have an abbreviation but not a full name", - ); - } - - if (argName?.contains('=') == true || argAbbrev?.contains('=') == true) { - throw OptionDefinitionError( - this, - "An argument option name / abbreviation can't contain '='", - ); - } - if (argName?.startsWith('-') == true || - argAbbrev?.startsWith('-') == true) { - throw OptionDefinitionError( - this, - "An argument option name / abbreviation can't start with '-'", - ); + final fullName = argName; + if (fullName == null) { + if (argAbbrev != null) { + throw OptionDefinitionError( + this, + "An argument option can't have an abbreviation but not a full name", + ); + } + if (argAliases?.isNotEmpty == true) { + throw OptionDefinitionError( + this, + "An argument option can't have aliases but not a full name", + ); + } + } else { + if (fullName.contains('=') == true || argAbbrev?.contains('=') == true) { + throw OptionDefinitionError( + this, + "An argument option name / abbreviation can't contain '='", + ); + } + if (fullName.startsWith('-') == true || + argAbbrev?.startsWith('-') == true) { + throw OptionDefinitionError( + this, + "An argument option name / abbreviation can't start with '-'", + ); + } } if (argAliases?.any((final alias) => alias.contains('=')) == true) { throw OptionDefinitionError( @@ -386,7 +376,7 @@ abstract class ConfigOptionBase implements OptionDefinition { @internal OptionResolutionImpl resolveValue( final Configuration cfg, { - final ArgResults? args, + final ParsedArgs? args, final Iterator? posArgs, final Map? env, final ConfigurationBroker? configBroker, @@ -432,7 +422,7 @@ abstract class ConfigOptionBase implements OptionDefinition { OptionResolutionImpl _doResolve( final Configuration cfg, { - final ArgResults? args, + final ParsedArgs? args, final Iterator? posArgs, final Map? env, final ConfigurationBroker? configBroker, @@ -460,13 +450,12 @@ abstract class ConfigOptionBase implements OptionDefinition { return const OptionResolutionImpl.noValue(); } - OptionResolutionImpl? _resolveNamedArg(final ArgResults? args) { - final argOptName = argName; - if (argOptName == null || args == null || !args.wasParsed(argOptName)) { + OptionResolutionImpl? _resolveNamedArg(final ParsedArgs? args) { + if (argName == null || args == null || !args.wasParsed(this)) { return null; } return OptionResolutionImpl( - stringValue: args.option(argOptName), + stringValue: args.option(this), source: ValueSourceType.arg, ); } @@ -621,31 +610,23 @@ class FlagOption extends ConfigOptionBase { ); @override - void _addToArgParser(final ArgParser argParser) { - final argName = this.argName; - if (argName == null) { - throw StateError("Can't add flag without arg name to arg parser."); - } - argParser.addFlag( - argName, - abbr: argAbbrev, - help: helpText, - defaultsTo: defaultValue(), - negatable: negatable, - hideNegatedUsage: hideNegatedUsage, - hide: hide, - aliases: argAliases ?? const [], - ); + void validateDefinition() { + super.validateDefinition(); + if (negatable && argName?.startsWith('no-') == true) { + throw OptionDefinitionError( + this, + "A flag whose name starts with 'no-' can't be negatable", + ); + } } @override - OptionResolutionImpl? _resolveNamedArg(final ArgResults? args) { - final argOptName = argName; - if (argOptName == null || args == null || !args.wasParsed(argOptName)) { + OptionResolutionImpl? _resolveNamedArg(final ParsedArgs? args) { + if (argName == null || args == null || !args.wasParsed(this)) { return null; } return OptionResolutionImpl( - value: args.flag(argOptName), + value: args.flag(this), source: ValueSourceType.arg, ); } @@ -722,38 +703,13 @@ class MultiOption extends ConfigOptionBase> { } @override - void _addToArgParser(final ArgParser argParser) { - final argName = this.argName; - if (argName == null) { - throw StateError("Can't add option without arg name to arg parser."); - } - - argParser.addMultiOption( - argName, - abbr: argAbbrev, - help: helpText, - valueHelp: valueHelpString(), - allowed: allowedElementValues?.map(multiParser.elementParser.format), - allowedHelp: allowedHelp, - defaultsTo: defaultValue()?.map(multiParser.elementParser.format), - hide: hide, - splitCommas: multiParser.separator == ',', - aliases: argAliases ?? const [], - ); - } - - @override - OptionResolutionImpl>? _resolveNamedArg(final ArgResults? args) { - final argOptName = argName; - if (argOptName == null || args == null || !args.wasParsed(argOptName)) { + OptionResolutionImpl>? _resolveNamedArg(final ParsedArgs? args) { + if (argName == null || args == null || !args.wasParsed(this)) { return null; } final multiParser = valueParser as MultiParser; return OptionResolutionImpl( - value: args - .multiOption(argOptName) - .map(multiParser.elementParser.parse) - .toList(), + value: args.multiOption(this).expand(multiParser.parse).toList(), source: ValueSourceType.arg, ); } @@ -790,27 +746,20 @@ extension QualifiedString on OptionDefinition { } } -/// Validates and prepares a set of options for the provided argument parser. -void prepareOptionsForParsing( - final Iterable options, - final ArgParser argParser, -) { - final argNameOpts = validateOptions(options); - addOptionsToParser(argNameOpts, argParser, addGroupSeparators: true); -} - /// Validates a set of options. /// /// Throws an [OptionDefinitionError] if the options are invalid. /// /// Returns an iterable of the options that are specifyable with an argument /// name on the command line. -Iterable validateOptions( +List validateOptions( final Iterable options, ) { final argNameOpts = {}; final argPosOpts = {}; final envNameOpts = {}; + final claimedNames = {}; + final claimedAbbrevs = {}; final optionGroups = >{}; @@ -819,12 +768,7 @@ Iterable validateOptions( final argName = opt.option.argName; if (argName != null) { - if (argNameOpts.containsKey(opt.option.argName)) { - throw OptionDefinitionError( - opt, - 'Duplicate argument name: ${opt.option.argName} for $opt', - ); - } + _claimOptionArgs(opt, claimedNames, claimedAbbrevs); argNameOpts[argName] = opt; } @@ -884,87 +828,70 @@ Iterable validateOptions( } } - return argNameOpts.values; + return argNameOpts.values.toList(); } -/// Adds [argNameOpts] to [argParser]. -/// -/// When [addGroupSeparators] is `true`, -/// - options are grouped by [OptionGroup] and a -/// - separator with the group name is inserted -/// - before each group that has at least one visible option. -/// - Note: -/// - groupless options are added first in their original order -/// - relative order of all options within a group is preserved -/// - relative order of all groups is preserved -/// -/// By default, -/// [addGroupSeparators] is `false` to ensure backwards compatibility. -void addOptionsToParser( - final Iterable argNameOpts, - final ArgParser argParser, { - final bool addGroupSeparators = false, -}) { - // plain option-addition without any group separator logic - if (!addGroupSeparators) { - for (final o in argNameOpts) { - o.option._addToArgParser(argParser); - } - return; - } - - // the following containers are ordered by default i.e. - // preserves insertion-order: - // - Map : https://stackoverflow.com/q/79786585/10251345 - // - List : https://api.dart.dev/dart-core/List-class.html - final optionGroups = >{}; - final grouplessOptions = []; +void _claimOptionArgs( + final OptionDefinition opt, + final Map names, + final Map abbrevs, +) { + final argName = opt.option.argName; + if (argName == null) return; + + _claimArg( + names, + argName, + opt, + 'Duplicate argument name: $argName for $opt', + ); + if (opt.option case final FlagOption flag when flag.negatable) { + final negation = 'no-$argName'; + _claimArg( + names, + negation, + opt, + 'Duplicate argument name: $negation for $opt', + ); + } - // gather all necessary option-group information - for (final opt in argNameOpts) { - final group = opt.option.group; - if (group != null) { - optionGroups.update( - group, - (final options) => options..add(opt), - ifAbsent: () => [opt], + if (opt.option.argAliases case final List aliases) { + for (final alias in aliases) { + _claimArg( + names, + alias, + opt, + 'Duplicate argument name: $alias for $opt', ); - } else { - grouplessOptions.add(opt); } } - // add all groupless-options first (in order) - for (final o in grouplessOptions) { - o.option._addToArgParser(argParser); + if (opt.option.argAbbrev case final String abbrev) { + _claimArg( + abbrevs, + abbrev, + opt, + 'Duplicate argument abbreviation: $abbrev for $opt', + ); } +} - // add all explicit groups (in order) - optionGroups.forEach((final group, final groupedOptions) { - // add the group-name-separator only if it has at least one visible option - if (groupedOptions.any((final o) => !o.option.hide)) { - argParser.addSeparator(group.name); - } - // add all options within this group (in order) - for (final o in groupedOptions) { - o.option._addToArgParser(argParser); - } - }); +void _claimArg( + final Map claimed, + final String key, + final OptionDefinition opt, + final String message, +) { + if (claimed.containsKey(key)) { + throw OptionDefinitionError(opt, message); + } + claimed[key] = opt; } extension PrepareOptions on Iterable { - /// Validates and prepares these options for the provided argument parser. - void prepareForParsing(final ArgParser argParser) => - prepareOptionsForParsing(this, argParser); - - /// Validates these options. - void validate() => validateOptions(this); - /// Returns the usage help text for these options. String get usage { - final parser = ArgParser(); - prepareForParsing(parser); - return parser.usage; + return oldUsage(this); } /// Returns the option definition for the given enum name, diff --git a/packages/config/pubspec.yaml b/packages/config/pubspec.yaml index bdf7cae8..486447b0 100644 --- a/packages/config/pubspec.yaml +++ b/packages/config/pubspec.yaml @@ -19,6 +19,7 @@ environment: dependencies: args: ^2.7.0 + characters: ^1.4.1 collection: ^1.18.0 meta: ^1.11.0 path: ^1.8.2 diff --git a/packages/config/test/args_compatibility/parse_test.dart b/packages/config/test/args_compatibility/parse_test.dart index 228ec775..cdb2d03a 100644 --- a/packages/config/test/args_compatibility/parse_test.dart +++ b/packages/config/test/args_compatibility/parse_test.dart @@ -170,23 +170,30 @@ void main() { expect(args['verbose'], isFalse); }); - test('set the flag to true if the flag actually starts with "no-"', () { - var parser = ConfigParser(); - parser.addFlag('no-body'); + test( + 'set the flag to true if the flag actually starts with "no-"', + () { + var parser = ConfigParser(); + parser.addFlag('no-body', negatable: false); - var args = parser.parse(['--no-body']); - expect(args['no-body'], isTrue); - }); + var args = parser.parse(['--no-body']); + expect(args['no-body'], isTrue); + }, + ); - test('are not preferred over a colliding one without', () { - var parser = ConfigParser(); - parser.addFlag('no-strum'); - parser.addFlag('strum'); + test( + 'is prevented from colliding with a flag without "no-" prefix', + () { + var parser = ConfigParser(); + parser.addFlag('no-strum', negatable: false); + parser.addFlag('strum'); - var args = parser.parse(['--no-strum']); - expect(args['no-strum'], isTrue); - expect(args['strum'], isFalse); - }); + expectLater( + () => parser.parse(['--no-strum']), + throwsA(isA()), + ); + }, + ); test('fail for non-negatable flags', () { var parser = ConfigParser(); diff --git a/packages/config/test/config/arg_parser/arg_parser_test_support.dart b/packages/config/test/config/arg_parser/arg_parser_test_support.dart new file mode 100644 index 00000000..c1086753 --- /dev/null +++ b/packages/config/test/config/arg_parser/arg_parser_test_support.dart @@ -0,0 +1,49 @@ +import 'package:config/config.dart'; + +ArgParseResult childResult( + final ArgParseResult result, +) { + return result.child!; +} + +class TestCommand implements CommandDefinition { + TestCommand({ + required this.name, + this.usageDefinition = const CommandUsageDefinition(description: ''), + this.aliasesDefinition = const CommandAliasesDefinition(), + this.persistentOptions = const [], + this.options = const [], + this.subcommands = const [], + this.canRunAsLeafCommand = false, + }); + + @override + final String name; + + @override + String get usage => '$name: ${usageDefinition.description}'; + + @override + final CommandUsageDefinition usageDefinition; + + @override + final CommandAliasesDefinition aliasesDefinition; + + @override + final List persistentOptions; + + @override + List allOptions({final bool onlyPersistent = false}) => [ + ...persistentOptions, + if (!onlyPersistent) ...options, + ]; + + @override + final List options; + + @override + final List subcommands; + + @override + final bool canRunAsLeafCommand; +} 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 new file mode 100644 index 00000000..3b7f175e --- /dev/null +++ b/packages/config/test/config/arg_parser/scan_and_parse_args_test.dart @@ -0,0 +1,1060 @@ +import 'package:config/config.dart'; +import 'package:test/test.dart'; + +void main() { + group('Given no options and no arguments', () { + late ArgParseResult result; + + setUp(() { + result = scanAndParseArgs([], options: []); + }); + + test('then the result has no command', () { + expect(result.command, isNull); + }); + + test('then the result has no parent', () { + expect(result.parent, isNull); + }); + + test('then the result has no child', () { + expect(result.child, isNull); + }); + + test('then no flags are set', () { + expect(result.flagOptions, isEmpty); + }); + + test('then no regular options are set', () { + expect(result.regularOptions, isEmpty); + }); + + test('then no multi options are set', () { + expect(result.multiOptions, isEmpty); + }); + + test('then there are no positional words', () { + expect(result.positionalWords, isEmpty); + }); + + test('then there are no unparsed arguments', () { + expect(result.unparsedArgs, isEmpty); + }); + + test('then there are no errors', () { + expect(result.errors, isEmpty); + }); + + test('then toList returns that result alone', () { + expect(result.toList(), [result]); + }); + }); + + group('Given no options', () { + test('when words are parsed then they stay positional in order', () { + final ArgParseResult result = scanAndParseArgs( + ['alpha', '', 'gamma'], + options: [], + ); + + expect(result.positionalWords, ['alpha', '', 'gamma']); + }); + + test('when a word matches an option shape without dashes ' + 'then it stays positional', () { + const name = StringOption(argName: 'name'); + final result = scanAndParseArgs(['name', 'ada'], options: [name]); + + expect(result.positionalWords, ['name', 'ada']); + }); + + test('when -- is parsed then the error is recorded', () { + final result = scanAndParseArgs(['--'], options: []); + + expect(result.errors, ['Unexpected value: --']); + }); + + test('when - is parsed then it stays positional', () { + final result = scanAndParseArgs(['-'], options: []); + + expect(result.positionalWords, ['-']); + }); + + test('when - is parsed then there is no error', () { + final result = scanAndParseArgs(['-'], options: []); + + expect(result.errors, isEmpty); + }); + + test( + 'when an unknown long option is parsed then the error is recorded', + () { + final result = scanAndParseArgs( + ['--unknown'], + options: [], + ); + + expect(result.errors, ['Unknown option: --unknown']); + }, + ); + + test( + 'when an unknown short option is parsed then the error is recorded', + () { + final result = scanAndParseArgs(['-x'], options: []); + + expect(result.errors, ['Unknown option: -x']); + }, + ); + + test('when a long option name is empty ' + 'then the name and the attached value are recorded', () { + final result = scanAndParseArgs(['--='], options: []); + + expect(result.errors, ['Unknown option: --', 'Unexpected value: ']); + }); + + test('when a long option name starts with a dash ' + 'then the error is recorded', () { + final result = scanAndParseArgs(['---'], options: []); + + expect(result.errors, ['Unknown option: ---']); + }); + + test('when several arguments are invalid then every error is recorded', () { + const name = StringOption(argName: 'name'); + const verbose = FlagOption(argName: 'verbose'); + final result = scanAndParseArgs( + ['--missing', '-x', '--verbose', '--verbose', '--name'], + options: [name, verbose], + ); + + expect(result.errors, [ + 'Unknown option: --missing', + 'Unknown option: -x', + 'Option --verbose cannot be specified more than once', + 'Missing value for option: --name', + ]); + }); + + test('when several arguments are invalid ' + 'then the valid flag is still recorded', () { + const name = StringOption(argName: 'name'); + const verbose = FlagOption(argName: 'verbose'); + final result = scanAndParseArgs( + ['--missing', '-x', '--verbose', '--verbose', '--name'], + options: [name, verbose], + ); + + expect(result.flagOptions[verbose], isTrue); + }); + }); + + group('Given options that declare positional indexes', () { + const first = StringOption(argName: 'first', argPos: 0); + const second = StringOption(argPos: 1); + + group('when two words are parsed', () { + late ArgParseResult result; + + setUp(() { + result = scanAndParseArgs( + ['a', 'b'], + options: [first, second], + ); + }); + + test('then both words stay positional', () { + expect(result.positionalWords, ['a', 'b']); + }); + + test('then the indexed options are not assigned', () { + expect(result.regularOptions, isEmpty); + }); + }); + }); + + group('Given option metadata this parser does not apply', () { + test('when a mandatory option is omitted then it is absent', () { + const name = StringOption(argName: 'name', mandatory: true); + final result = scanAndParseArgs([], options: [name]); + + expect(result.regularOptions[name], isNull); + }); + + test( + 'when an option default is omitted then the default is not filled', + () { + const name = StringOption(argName: 'name', defaultsTo: 'fallback'); + final result = scanAndParseArgs([], options: [name]); + + expect(result.regularOptions[name], isNull); + }, + ); + }); + + group('Given a negatable flag with a name, abbreviation, and alias', () { + const verbose = FlagOption( + argName: 'verbose', + argAbbrev: 'v', + argAliases: ['verbose-mode'], + ); + + ArgParseResult parse(final List args) { + return scanAndParseArgs(args, options: [verbose]); + } + + test('when passed as --verbose then it is set', () { + expect(parse(['--verbose']).flagOptions[verbose], isTrue); + }); + + test('when passed as --no-verbose then it is cleared', () { + expect(parse(['--no-verbose']).flagOptions[verbose], isFalse); + }); + + test('when passed as -v then it is set', () { + expect(parse(['-v']).flagOptions[verbose], isTrue); + }); + + test('when - follows the flag then the flag is set', () { + expect(parse(['-v', '-']).flagOptions[verbose], isTrue); + }); + + test('when - follows the flag then - stays positional', () { + expect(parse(['-v', '-']).positionalWords, ['-']); + }); + + test('when passed by alias then it is set', () { + expect(parse(['--verbose-mode']).flagOptions[verbose], isTrue); + }); + + test('when omitted then it is absent', () { + expect(parse([]).flagOptions[verbose], isNull); + }); + + test('when a long value is attached then the error is recorded', () { + expect( + parse(['--verbose=true']).errors, + ['Unexpected value: true'], + ); + }); + + test('when a short value is attached then the error is recorded', () { + expect(parse(['-v=true']).errors, ['Unexpected value: true']); + }); + + test('when an empty long value is attached then the error is recorded', () { + expect(parse(['--verbose=']).errors, ['Unexpected value: ']); + }); + + test('when the alias is negated then the error is recorded', () { + expect( + parse(['--no-verbose-mode']).errors, + ['Unknown option: --no-verbose-mode'], + ); + }); + + test('when the long name is repeated then the error is recorded', () { + expect( + parse(['--verbose', '--verbose']).errors, + ['Option --verbose cannot be specified more than once'], + ); + }); + + test('when the long name is repeated then the first value is kept', () { + expect(parse(['--verbose', '--verbose']).flagOptions[verbose], isTrue); + }); + + test('when the long name and abbreviation are both passed ' + 'then the error is recorded', () { + expect( + parse(['--verbose', '-v']).errors, + ['Option --verbose cannot be specified more than once'], + ); + }); + + test('when the flag and its negation are both passed ' + 'then the error is recorded', () { + expect( + parse(['--verbose', '--no-verbose']).errors, + ['Option --verbose cannot be specified more than once'], + ); + }); + + test('when the alias and the long name are both passed ' + 'then the error is recorded', () { + expect( + parse(['--verbose-mode', '--verbose']).errors, + ['Option --verbose cannot be specified more than once'], + ); + }); + + group('when a single dash is followed by the long name', () { + late ArgParseResult result; + + setUp(() { + result = parse(['-verbose']); + }); + + test('then the abbreviation is set', () { + expect(result.flagOptions[verbose], isTrue); + }); + + test('then each other letter is an unknown option', () { + expect(result.errors, [ + 'Unknown option: -e', + 'Unknown option: -r', + 'Unknown option: -b', + 'Unknown option: -o', + 'Unknown option: -s', + 'Unknown option: -e', + ]); + }); + }); + + test('when the abbreviation is used as a long option ' + 'then the error is recorded', () { + expect(parse(['--v']).errors, ['Unknown option: --v']); + }); + + test('when the abbreviation is repeated in one cluster ' + 'then the error is recorded', () { + expect( + parse(['-vv']).errors, + ['Option --verbose cannot be specified more than once'], + ); + }); + }); + + group('Given a non-negatable flag', () { + const color = FlagOption(argName: 'color', negatable: false); + + test('when passed as --color then it is set', () { + final result = scanAndParseArgs(['--color'], options: [color]); + + expect(result.flagOptions[color], isTrue); + }); + + test('when passed as --no-color then the error is recorded', () { + final result = scanAndParseArgs(['--no-color'], options: [color]); + + expect(result.errors, ['Unknown option: --no-color']); + }); + }); + + group('Given a non-negatable flag whose name starts with no-', () { + const noColor = FlagOption(argName: 'no-color', negatable: false); + + ArgParseResult parse(final List args) { + return scanAndParseArgs(args, options: [noColor]); + } + + test('when passed as --no-color then it is set', () { + expect(parse(['--no-color']).flagOptions[noColor], isTrue); + }); + + test('when passed as --no-no-color then the error is recorded', () { + expect( + parse(['--no-no-color']).errors, + ['Unknown option: --no-no-color'], + ); + }); + }); + + group('Given a non-negatable flag with an alias that starts with no-', () { + const color = FlagOption( + argName: 'color', + negatable: false, + argAliases: ['no-color'], + ); + + ArgParseResult parse(final List args) { + return scanAndParseArgs(args, options: [color]); + } + + test('when passed as --color then it is set', () { + expect(parse(['--color']).flagOptions[color], isTrue); + }); + + test('when the alias is passed then the flag is set', () { + expect(parse(['--no-color']).flagOptions[color], isTrue); + }); + }); + + group('Given a negatable flag with an alias that starts with no-', () { + const color = FlagOption( + argName: 'color', + argAliases: ['no-problem'], + ); + + ArgParseResult parse(final List args) { + return scanAndParseArgs(args, options: [color]); + } + + test('when the alias is passed then the flag is set', () { + expect(parse(['--no-problem']).flagOptions[color], isTrue); + }); + + test('when the generated negation is passed then the flag is cleared', () { + expect(parse(['--no-color']).flagOptions[color], isFalse); + }); + }); + + group('Given several short flags', () { + const alpha = FlagOption(argName: 'alpha', argAbbrev: 'a'); + const beta = FlagOption(argName: 'beta', argAbbrev: 'b'); + const gamma = FlagOption(argName: 'gamma', argAbbrev: 'c'); + + group('when they are clustered as -abc', () { + late ArgParseResult result; + + setUp(() { + result = scanAndParseArgs( + ['-abc'], + options: [alpha, beta, gamma], + ); + }); + + test('then alpha is set', () { + expect(result.flagOptions[alpha], isTrue); + }); + + test('then beta is set', () { + expect(result.flagOptions[beta], isTrue); + }); + + test('then gamma is set', () { + expect(result.flagOptions[gamma], isTrue); + }); + }); + + group('when the cluster contains an unknown letter', () { + late ArgParseResult result; + + setUp(() { + result = scanAndParseArgs( + ['-abq'], + options: [alpha, beta], + ); + }); + + test('then the known flags are set', () { + expect(result.flagOptions[alpha], isTrue); + expect(result.flagOptions[beta], isTrue); + }); + + test('then the unknown letter is recorded', () { + expect(result.errors, ['Unknown option: -q']); + }); + }); + }); + + group('Given a string option with a name, abbreviation, and aliases', () { + const name = StringOption( + argName: 'name', + argAbbrev: 'n', + argAliases: ['title', 'label'], + ); + + ArgParseResult parse(final List args) { + return scanAndParseArgs(args, options: [name]); + } + + test( + 'when the value is a separate argument then that argument is used', + () { + expect(parse(['--name', 'ada']).regularOptions[name], 'ada'); + }, + ); + + test('when the value is attached with = then the text after = is used', () { + expect(parse(['--name=ada']).regularOptions[name], 'ada'); + }); + + test('when the attached value contains = then only the first = splits', () { + expect(parse(['--name=a=b']).regularOptions[name], 'a=b'); + }); + + test( + 'when the separate value starts with a dash then it is kept whole', + () { + expect(parse(['--name', '-123']).regularOptions[name], '-123'); + }, + ); + + test('when the attached value starts with a dash then it is kept', () { + expect(parse(['--name=-123']).regularOptions[name], '-123'); + }); + + test( + 'when the short option has a separate value then that value is used', + () { + expect(parse(['-n', 'ada']).regularOptions[name], 'ada'); + }, + ); + + test('when the short option attaches a value with = ' + 'then the value is the text after =', () { + expect(parse(['-n=ada']).regularOptions[name], 'ada'); + }); + + test('when the short option value is a dash cluster ' + 'then the whole argument is the value', () { + expect(parse(['-n', '-abc']).regularOptions[name], '-abc'); + }); + + test('when the separate value is itself an option assignment ' + 'then the whole argument is the value', () { + expect( + parse(['--name', '--file=value']).regularOptions[name], + '--file=value', + ); + }); + + test('when the attached value is empty then the value is empty', () { + expect(parse(['--name=']).regularOptions[name], ''); + }); + + test('when the separate value is empty then the value is empty', () { + expect(parse(['--name', '']).regularOptions[name], ''); + }); + + test('when the value contains spaces then it is kept whole', () { + expect( + parse(['--name', 'ada lovelace']).regularOptions[name], + 'ada lovelace', + ); + }); + + test('when the value follows -- then -- is the value', () { + expect(parse(['--name', '--']).regularOptions[name], '--'); + }); + + test('when the value follows - then - is the value', () { + expect(parse(['--name', '-']).regularOptions[name], '-'); + }); + + test('when passed by the title alias then the value is recorded', () { + expect(parse(['--title', 'ada']).regularOptions[name], 'ada'); + }); + + test('when passed by the label alias then the value is recorded', () { + expect(parse(['--label', 'ada']).regularOptions[name], 'ada'); + }); + + test( + 'when a non-ascii abbreviation is used then the value is recorded', + () { + const labelled = StringOption(argName: 'name', argAbbrev: 'ä'); + + final result = scanAndParseArgs(['-ä', 'ada'], options: [labelled]); + + expect(result.regularOptions[labelled], 'ada'); + }, + ); + + test('when omitted then it is absent', () { + expect(parse([]).regularOptions[name], isNull); + }); + + group('when --name=ada is followed by another word', () { + late ArgParseResult result; + + setUp(() { + result = parse(['--name=ada', 'extra']); + }); + + test('then the attached text is the option value', () { + expect(result.regularOptions[name], 'ada'); + }); + + test('then the following word stays positional', () { + expect(result.positionalWords, ['extra']); + }); + }); + + test('when the value is missing then the error is recorded', () { + expect(parse(['--name']).errors, ['Missing value for option: --name']); + }); + + test('when a short option that takes a value is clustered ' + 'then the error says the value is missing', () { + expect(parse(['-nfile']).errors, ['Missing value for option: -n']); + }); + + test('when it is specified twice then the error is recorded', () { + expect( + parse(['--name', 'ada', '--name', 'grace']).errors, + ['Option --name cannot be specified more than once'], + ); + }); + + test('when it is specified twice then the first value is kept', () { + expect( + parse(['--name', 'ada', '--name', 'grace']).regularOptions[name], + 'ada', + ); + }); + + test('when the name and an alias are both passed ' + 'then the error is recorded', () { + expect( + parse(['--name', 'ada', '--title', 'grace']).errors, + ['Option --name cannot be specified more than once'], + ); + }); + + test('when an alias is missing its value ' + 'then the error uses the alias that was written', () { + expect( + parse(['--title']).errors, + ['Missing value for option: --title'], + ); + }); + + test('when the abbreviation is missing its value ' + 'then the error uses the abbreviation that was written', () { + expect(parse(['-n']).errors, ['Missing value for option: -n']); + }); + }); + + group('Given a string option and another option after a -- value', () { + const name = StringOption(argName: 'name'); + const file = StringOption(argName: 'file'); + + group('when --name takes -- and --file follows', () { + late ArgParseResult result; + + setUp(() { + result = scanAndParseArgs( + ['--name', '--', '--file', 'a.txt'], + options: [name, file], + ); + }); + + test('then -- is the name value', () { + expect(result.regularOptions[name], '--'); + }); + + test('then the later option is still parsed', () { + expect(result.regularOptions[file], 'a.txt'); + }); + }); + }); + + group('Given a multi option with a name, abbreviation, and alias', () { + const files = MultiStringOption( + argName: 'file', + argAbbrev: 'f', + argAliases: ['input'], + ); + + ArgParseResult parse(final List args) { + return scanAndParseArgs(args, options: [files]); + } + + test('when one value contains a comma then it stays one value', () { + expect(parse(['--file', 'a,b']).multiOptions[files], ['a,b']); + }); + + test('when the value starts with a dash then it is kept whole', () { + expect(parse(['--file', '-123']).multiOptions[files], ['-123']); + }); + + test('when omitted then it is absent', () { + expect(parse([]).multiOptions[files], isNull); + }); + + test('when the value is missing then the error is recorded', () { + expect( + parse(['--file']).errors, + ['Missing value for option: --file'], + ); + }); + + group('when values use the name, an alias, and the abbreviation', () { + late ArgParseResult result; + + setUp(() { + result = parse(['--file=a', '--input', 'b', '-f', 'c', '-f=d']); + }); + + test('then the values accumulate in order', () { + expect(result.multiOptions[files], ['a', 'b', 'c', 'd']); + }); + + test('then they are not stored as a single-value option', () { + expect(result.regularOptions[files], isNull); + }); + }); + }); + + group('Given a flag, a string option, and a multi option', () { + const verbose = FlagOption(argName: 'verbose', argAbbrev: 'v'); + const name = StringOption(argName: 'name', argAbbrev: 'n'); + const files = MultiStringOption(argName: 'file', argAbbrev: 'f'); + + group('when options and positional words are interleaved', () { + late ArgParseResult result; + + setUp(() { + result = scanAndParseArgs( + [ + 'src', + '-v', + '--name', + 'ada', + 'mid', + '--file', + 'a', + '-f', + 'b', + 'out', + ], + options: [verbose, name, files], + ); + }); + + test('then positional words exclude option values', () { + expect(result.positionalWords, ['src', 'mid', 'out']); + }); + + test('then the flag is set', () { + expect(result.flagOptions[verbose], isTrue); + }); + + test('then the string option is recorded', () { + expect(result.regularOptions[name], 'ada'); + }); + + test('then the multi option accumulates each value', () { + expect(result.multiOptions[files], ['a', 'b']); + }); + + test('then the result has no command', () { + expect(result.command, isNull); + }); + + test('then there are no unparsed arguments', () { + expect(result.unparsedArgs, isEmpty); + }); + + test('then the flag is not stored as a value', () { + expect(result.regularOptions[verbose], isNull); + }); + + test('then the string option is not stored as a multi option', () { + expect(result.multiOptions.keys, isNot(contains(name))); + }); + + test('then the multi option is not stored as a single value', () { + expect(result.regularOptions[files], isNull); + }); + }); + }); + + group('Given two options with the same name', () { + const first = StringOption(argName: 'name', argAbbrev: 'a'); + const second = StringOption(argName: 'name', argAbbrev: 'b'); + + test('when the options are parsed then parsing fails', () { + expect( + () => scanAndParseArgs( + ['--name', 'ada'], + options: [first, second], + ), + throwsA( + isA().having( + (final e) => e.toString(), + 'toString', + contains('Duplicate argument name: name'), + ), + ), + ); + }); + }); + + group('Given two options with the same abbreviation', () { + const first = StringOption(argName: 'first', argAbbrev: 'x'); + const second = StringOption(argName: 'second', argAbbrev: 'x'); + + test('when the options are parsed then parsing fails', () { + expect( + () => scanAndParseArgs( + ['-x', 'ada'], + options: [first, second], + ), + throwsA( + isA().having( + (final e) => e.toString(), + 'toString', + contains('Duplicate argument abbreviation: x'), + ), + ), + ); + }); + }); + + group('Given a negatable flag and a string option named no-verbose', () { + const verbose = FlagOption(argName: 'verbose'); + const negatedName = StringOption(argName: 'no-verbose'); + + test('when the options are parsed then parsing fails', () { + expect( + () => scanAndParseArgs( + ['--verbose'], + options: [verbose, negatedName], + ), + throwsA( + isA().having( + (final e) => e.toString(), + 'toString', + contains('Duplicate argument name: no-verbose'), + ), + ), + ); + }); + }); + + group('Given a flag that only has an abbreviation', () { + const verbose = FlagOption(argAbbrev: 'v'); + + test('when the options are parsed then parsing fails', () { + expect( + () => scanAndParseArgs(['-v'], options: [verbose]), + throwsA( + isA().having( + (final e) => e.toString(), + 'toString', + contains( + "An argument option can't have an abbreviation but not a full name", + ), + ), + ), + ); + }); + }); + + group('Given pass-through of the rest after --', () { + const verbose = FlagOption(argName: 'verbose', argAbbrev: 'v'); + const name = StringOption(argName: 'name', argAbbrev: 'n'); + const file = StringOption(argName: 'file', argAbbrev: 'f'); + + const passThroughRest = ScanMode( + doubleDashHandling: DoubleDashHandling.passThroughRest, + ); + + ArgParseResult parse(final List args) { + return scanAndParseArgs( + args, + options: [verbose, name, file], + scanMode: passThroughRest, + ); + } + + group('when options and words precede --', () { + late ArgParseResult result; + + setUp(() { + result = parse([ + 'src', + '--name', + 'ada', + '--', + '-v', + '--file=a.txt', + '-abc', + '--', + '', + 'rest', + ]); + }); + + test('then the option before -- is recorded', () { + expect(result.regularOptions[name], 'ada'); + }); + + test('then words before -- stay positional', () { + expect(result.positionalWords, ['src']); + }); + + test('then arguments after -- are unparsed in order', () { + expect( + result.unparsedArgs, + ['-v', '--file=a.txt', '-abc', '--', '', 'rest'], + ); + }); + + test('then the result is the last node', () { + expect(result.child, isNull); + }); + + test('then a flag after -- is not set', () { + expect(result.flagOptions[verbose], isNull); + }); + + test('then an option after -- is not recorded', () { + expect(result.regularOptions[file], isNull); + }); + }); + + group('when -- is the first argument', () { + late ArgParseResult result; + + setUp(() { + result = parse(['--', '-v', 'file']); + }); + + test('then every following argument is unparsed', () { + expect(result.unparsedArgs, ['-v', 'file']); + }); + + test('then no flag is set', () { + expect(result.flagOptions[verbose], isNull); + }); + + test('then there are no positional words', () { + expect(result.positionalWords, isEmpty); + }); + }); + + group('when -- is the last argument', () { + late ArgParseResult result; + + setUp(() { + result = parse(['src', '--']); + }); + + test('then there are no unparsed arguments', () { + expect(result.unparsedArgs, isEmpty); + }); + + test('then the preceding word stays positional', () { + expect(result.positionalWords, ['src']); + }); + }); + + group('when an option value is -- and more arguments follow', () { + late ArgParseResult result; + + setUp(() { + result = parse(['--name', '--', '--file', 'a.txt', 'rest']); + }); + + test('then -- is the option value', () { + expect(result.regularOptions[name], '--'); + }); + + test('then the later option is recorded', () { + expect(result.regularOptions[file], 'a.txt'); + }); + + test('then the later word stays positional', () { + expect(result.positionalWords, ['rest']); + }); + + test('then there are no unparsed arguments', () { + expect(result.unparsedArgs, isEmpty); + }); + }); + + group('when an option value is -- and a later -- follows', () { + late ArgParseResult result; + + setUp(() { + result = parse([ + '--name', + '--', + '--file', + 'a.txt', + 'src', + '--', + '-v', + '--name', + 'other', + 'tail', + ]); + }); + + test('then the first -- is the option value', () { + expect(result.regularOptions[name], '--'); + }); + + test('then the option before the later -- is recorded', () { + expect(result.regularOptions[file], 'a.txt'); + }); + + test('then words before the later -- stay positional', () { + expect(result.positionalWords, ['src']); + }); + + test('then arguments after the later -- are unparsed', () { + expect(result.unparsedArgs, ['-v', '--name', 'other', 'tail']); + }); + + test('then a flag after the later -- is not set', () { + expect(result.flagOptions[verbose], isNull); + }); + }); + + group('when two options take -- and a third -- follows', () { + late ArgParseResult result; + + setUp(() { + result = parse(['--name', '--', '--file', '--', 'src', '--', 'tail']); + }); + + test('then the first -- is the name value', () { + expect(result.regularOptions[name], '--'); + }); + + test('then the second -- is the file value', () { + expect(result.regularOptions[file], '--'); + }); + + test('then the word before the third -- stays positional', () { + expect(result.positionalWords, ['src']); + }); + + test('then arguments after the third -- are unparsed', () { + expect(result.unparsedArgs, ['tail']); + }); + }); + + group('when -- is absent', () { + late ArgParseResult result; + + setUp(() { + result = parse(['-v', 'src']); + }); + + test('then the flag is set', () { + expect(result.flagOptions[verbose], isTrue); + }); + + test('then there are no unparsed arguments', () { + expect(result.unparsedArgs, isEmpty); + }); + }); + + test('when the same arguments use the default scan mode ' + 'then the unexpected -- is recorded', () { + final result = scanAndParseArgs( + ['src', '--', 'rest'], + options: [verbose, name, file], + ); + + expect(result.errors, ['Unexpected value: --']); + }); + + test('when the same arguments use the default scan mode ' + 'then later words stay positional', () { + final result = scanAndParseArgs( + ['src', '--', 'rest'], + options: [verbose, name, file], + ); + + expect(result.positionalWords, ['src', 'rest']); + }); + }); +} 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 new file mode 100644 index 00000000..ef9603f9 --- /dev/null +++ b/packages/config/test/config/arg_parser/scan_and_parse_commands_test.dart @@ -0,0 +1,2259 @@ +import 'package:config/config.dart'; +import 'package:test/test.dart'; + +import 'arg_parser_test_support.dart'; + +void main() { + group('Given a command with no subcommands', () { + const name = StringOption(argName: 'name', argAbbrev: 'n'); + final command = TestCommand( + name: 'tool', + options: [name], + usageDefinition: const CommandUsageDefinition(description: 'tool usage'), + ); + + ArgParseResult parse(final List args) { + return scanAndParseCommands(args, rootCommand: command); + } + + test('when no arguments are parsed then the result is that command', () { + expect(parse([]).command, same(command)); + }); + + test('when no arguments are parsed then there is no child', () { + expect(parse([]).child, isNull); + }); + + test('when no arguments are parsed then toList is that result alone', () { + final result = parse([]); + + expect(result.toList(), [result]); + }); + + test('when words are parsed then they stay positional in order', () { + expect(parse(['a', '', 'c']).positionalWords, ['a', '', 'c']); + }); + + test('when an option is parsed then its value is recorded', () { + expect(parse(['--name', 'ada']).regularOptions[name], 'ada'); + }); + + group('when an option is followed by a positional word', () { + late ArgParseResult result; + + setUp(() { + result = parse(['-n', 'ada', 'file']); + }); + + test('then the option value is not positional', () { + expect(result.regularOptions[name], 'ada'); + }); + + test('then the remaining word is positional', () { + expect(result.positionalWords, ['file']); + }); + }); + + test('when -- is parsed then the error is recorded', () { + expect(parse(['--']).errors, ['Unexpected value: --']); + }); + + test('when - is parsed then it stays positional', () { + expect(parse(['-']).positionalWords, ['-']); + }); + + test('when - is parsed then there is no error', () { + expect(parse(['-']).errors, isEmpty); + }); + + test('when an unknown option is parsed then the error is recorded', () { + expect(parse(['--missing']).errors, ['Unknown option: --missing']); + }); + }); + + group('Given a command tree with persistent and local options', () { + const verbose = FlagOption(argName: 'verbose', argAbbrev: 'v'); + const force = FlagOption(argName: 'force', argAbbrev: 'f'); + const rootOnly = StringOption(argName: 'root-only'); + const midOnly = StringOption(argName: 'mid-only'); + const output = StringOption(argName: 'output', argAbbrev: 'o'); + + final leaf = TestCommand( + name: 'leaf', + aliasesDefinition: const CommandAliasesDefinition( + aliases: ['lf', 'leaf-alias'], + suggestionAliases: ['leave'], + ), + options: [output], + usageDefinition: const CommandUsageDefinition(description: 'leaf usage'), + ); + final mid = TestCommand( + name: 'mid', + aliasesDefinition: const CommandAliasesDefinition(aliases: ['m']), + options: [midOnly], + persistentOptions: [force], + subcommands: [leaf], + canRunAsLeafCommand: true, + usageDefinition: const CommandUsageDefinition(description: 'mid usage'), + ); + final root = TestCommand( + name: 'tool', + options: [rootOnly], + persistentOptions: [verbose], + subcommands: [mid], + usageDefinition: const CommandUsageDefinition(description: 'root usage'), + ); + + ArgParseResult parse(final List args) { + return scanAndParseCommands(args, rootCommand: root); + } + + group('when every level receives options and the leaf has words', () { + late ArgParseResult result; + late ArgParseResult midResult; + late ArgParseResult leafResult; + + setUp(() { + result = parse([ + '--root-only', + 'r', + '-v', + 'mid', + '--mid-only', + 'm', + '--force', + 'leaf', + '--output', + 'o', + 'p1', + 'p2', + ]); + midResult = childResult(result); + leafResult = childResult(midResult); + }); + + test('then toList walks from the root to the leaf', () { + expect( + result.toList().map((final node) => node.command).toList(), + [root, mid, leaf], + ); + }); + + test('then the root has no parent', () { + expect(result.parent, isNull); + }); + + test('then the mid result points at the root', () { + expect(midResult.parent, same(result)); + }); + + test('then the leaf result points at mid', () { + expect(leafResult.parent, same(midResult)); + }); + + test('then the root command recorded its own option', () { + expect(result.regularOptions[rootOnly], 'r'); + }); + + test('then the root command recorded the leading flag', () { + expect(result.flagOptions[verbose], isTrue); + }); + + test('then the root command has no positional words', () { + expect(result.positionalWords, isEmpty); + }); + + test('then the mid command recorded its own option', () { + expect(midResult.regularOptions[midOnly], 'm'); + }); + + test('then the mid command recorded its persistent flag', () { + expect(midResult.flagOptions[force], isTrue); + }); + + test('then the leaf command recorded its option', () { + expect(leafResult.regularOptions[output], 'o'); + }); + + test('then the leaf command keeps the remaining words', () { + expect(leafResult.positionalWords, ['p1', 'p2']); + }); + + test('then the subcommand token is not positional', () { + expect(midResult.positionalWords, isEmpty); + }); + }); + + test('when toList starts at the mid command then the root is omitted', () { + final result = parse(['mid', 'leaf']); + + expect( + childResult(result).toList().map((final node) => node.command).toList(), + [mid, leaf], + ); + }); + + test('when subcommands are selected by alias ' + 'then the same commands run', () { + final result = parse(['m', 'leaf-alias']); + + expect( + result.toList().map((final node) => node.command).toList(), + [root, mid, leaf], + ); + }); + + test('when the second leaf alias is used then the leaf runs', () { + final result = parse(['mid', 'lf']); + + expect(childResult(childResult(result)).command, same(leaf)); + }); + + test('when a suggestion alias is used then the error is recorded', () { + expect( + childResult(parse(['mid', 'leave'])).errors, + ['Unknown subcommand: "leave"'], + ); + }); + + test('when the first word is unknown then the error is on the root', () { + expect(parse(['nope']).errors, ['Unknown subcommand: "nope"']); + }); + + test('when a nested word is unknown then the error is on that command', () { + expect( + childResult(parse(['mid', 'nope'])).errors, + ['Unknown subcommand: "nope"'], + ); + }); + + test('when the root command name is used then the error is recorded', () { + 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 a branch command receives a positional word ' + 'then the error is recorded', () { + expect( + childResult(parse(['mid', 'file'])).errors, + ['Unknown subcommand: "file"'], + ); + }); + + test('when the leaf command is repeated ' + 'then the second word is positional', () { + final result = parse(['mid', 'leaf', 'leaf']); + + expect(childResult(childResult(result)).positionalWords, ['leaf']); + }); + + test('when mid is repeated under itself then the error is recorded', () { + expect( + childResult(parse(['mid', 'mid'])).errors, + ['Unknown subcommand: "mid"'], + ); + }); + + test( + 'when a persistent flag is repeated after a subcommand ' + 'then the error is on that command', + () { + expect( + childResult(parse(['--verbose', 'mid', '--verbose'])).errors, + ['Option --verbose cannot be specified more than once'], + ); + }, + ); + + test('when a persistent flag is repeated on the root ' + 'then the error is recorded and the subcommand is still parsed', () { + final result = parse(['--verbose', '--verbose', 'mid']); + + expect(result.errors, [ + 'Option --verbose cannot be specified more than once', + ]); + expect(childResult(result).command, same(mid)); + }); + + group('when a root persistent flag is passed after mid', () { + late ArgParseResult result; + + setUp(() { + result = parse(['mid', '--verbose']); + }); + + test('then the root records the flag', () { + expect(result.flagOptions[verbose], isTrue); + }); + + test('then the mid command does not record the flag', () { + expect(childResult(result).flagOptions[verbose], isNull); + }); + }); + + group('when a root persistent flag is negated after mid', () { + late ArgParseResult result; + + setUp(() { + result = parse(['mid', '--no-verbose']); + }); + + test('then the root records the flag as false', () { + expect(result.flagOptions[verbose], isFalse); + }); + + test('then the mid command does not record the flag', () { + expect(childResult(result).flagOptions[verbose], isNull); + }); + }); + + group('when a root persistent flag is passed on the leaf', () { + late ArgParseResult result; + + setUp(() { + result = parse(['mid', 'leaf', '-v']); + }); + + test('then the root records the flag', () { + expect(result.flagOptions[verbose], isTrue); + }); + + test('then the mid command does not record the flag', () { + expect(childResult(result).flagOptions[verbose], isNull); + }); + + test('then the leaf command does not record the flag', () { + expect(childResult(childResult(result)).flagOptions[verbose], isNull); + }); + }); + + group('when a mid persistent flag is passed on the leaf', () { + late ArgParseResult result; + + setUp(() { + result = parse(['mid', 'leaf', '--force']); + }); + + test('then the mid command records the flag', () { + expect(childResult(result).flagOptions[force], isTrue); + }); + + test('then the root command does not record the flag', () { + expect(result.flagOptions[force], isNull); + }); + + test('then the leaf command does not record the flag', () { + expect(childResult(childResult(result)).flagOptions[force], isNull); + }); + }); + + test('when force is passed on mid then mid records it', () { + final result = parse(['mid', '-f']); + + expect(childResult(result).flagOptions[force], isTrue); + }); + + test('when force is passed before mid then the error is on the root', () { + final result = parse(['-f', 'mid']); + + expect(result.errors, ['Unknown option: -f']); + expect(childResult(result).command, same(mid)); + }); + + test('when the leaf abbreviation is used on mid ' + 'then that option and the following word are recorded', () { + expect(childResult(parse(['mid', '-o', 'x'])).errors, [ + 'Unknown option: -o', + 'Unknown subcommand: "x"', + ]); + }); + + test('when a root-only option is passed after mid ' + 'then that option and its value word are recorded', () { + expect(childResult(parse(['mid', '--root-only', 'r'])).errors, [ + 'Unknown option: --root-only', + 'Unknown subcommand: "r"', + ]); + }); + + test('when a mid-only option is passed on the leaf ' + 'then the error is on the leaf', () { + expect( + childResult( + childResult(parse(['mid', 'leaf', '--mid-only', 'm'])), + ).errors, + ['Unknown option: --mid-only'], + ); + }); + + test('when a leaf option is passed before mid ' + 'then the option and the following word are recorded', () { + expect(parse(['--output', 'o', 'mid']).errors, [ + 'Unknown option: --output', + 'Unknown subcommand: "o"', + ]); + }); + + test('when the leaf option is repeated then the error is recorded', () { + expect( + childResult( + childResult(parse(['mid', 'leaf', '--output', 'a', '--output', 'b'])), + ).errors, + ['Option --output cannot be specified more than once'], + ); + }); + + test( + 'when the leaf option is missing a value then the error is recorded', + () { + expect( + childResult(childResult(parse(['mid', 'leaf', '--output']))).errors, + ['Missing value for option: --output'], + ); + }, + ); + + test( + 'when the leaf receives an unknown option then the error is recorded', + () { + expect( + childResult(childResult(parse(['mid', 'leaf', '--nope']))).errors, + ['Unknown option: --nope'], + ); + }, + ); + + test('when -- is parsed then both errors are recorded', () { + expect(parse(['--']).errors, [ + 'Unexpected value: --', + 'A subcommand is required under tool', + ]); + }); + + test('when - is parsed then it is an unknown subcommand', () { + expect(parse(['-']).errors, ['Unknown subcommand: "-"']); + }); + + test('when the leaf receives - then it stays positional', () { + expect( + childResult(childResult(parse(['mid', 'leaf', '-']))).positionalWords, + ['-'], + ); + }); + }); + + group('Given a root and subcommand with different option types', () { + final build = _EnumCommand<_BuildOption>( + name: 'build', + options: const [_BuildOption.output], + ); + final root = _EnumCommand<_RootOption>( + name: 'tool', + persistentOptions: const [_RootOption.verbose], + subcommands: [build], + ); + + group('when root and subcommand options are parsed', () { + late ArgParseResult result; + late ArgParseResult buildResult; + + setUp(() { + result = scanAndParseCommands<_RootOption>( + ['--verbose', 'build', '--output', 'out', 'file'], + rootCommand: root, + ); + buildResult = childResult(result); + }); + + test('then the root command is selected', () { + expect(result.command, same(root)); + }); + + test('then the subcommand is selected', () { + expect(buildResult.command, same(build)); + }); + + test('then the root option is recorded', () { + expect(result.flagOptions[_verbose], isTrue); + }); + + test('then the subcommand does not record the root option', () { + expect(buildResult.flagOptions[_verbose], isNull); + }); + + test('then the subcommand option is recorded', () { + expect(buildResult.regularOptions[_output], 'out'); + }); + + test('then the remaining word is positional on the subcommand', () { + expect(buildResult.positionalWords, ['file']); + }); + + test('then the root has no errors', () { + expect(result.errors, isEmpty); + }); + + test('then the subcommand has no errors', () { + expect(buildResult.errors, isEmpty); + }); + }); + }); + + group('Given subcommands that can both answer to the same word', () { + const buildOut = StringOption(argName: 'out'); + const otherOut = StringOption(argName: 'other'); + final build = TestCommand(name: 'build', options: [buildOut]); + final other = TestCommand( + name: 'other', + aliasesDefinition: const CommandAliasesDefinition(aliases: ['build']), + options: [otherOut], + ); + final root = TestCommand(name: 'tool', subcommands: [build, other]); + + ArgParseResult parse(final List args) { + return scanAndParseCommands(args, rootCommand: root); + } + + test('when that word is parsed then the earlier command runs', () { + final result = parse(['build']); + + expect(childResult(result).command, same(build)); + }); + + test('when that word is parsed then the earlier command options apply', () { + final result = parse(['build', '--out', 'a']); + + expect(childResult(result).regularOptions[buildOut], 'a'); + }); + + test( + 'when that word is parsed then the later command options are unknown', + () { + expect( + childResult(parse(['build', '--other', 'a'])).errors, + ['Unknown option: --other'], + ); + }, + ); + + test('when the later command name is parsed then that command runs', () { + final result = parse(['other']); + + expect(childResult(result).command, same(other)); + }); + }); + + group( + 'Given a persistent option and a subcommand option of the same name', + () { + const inherited = FlagOption( + argName: 'verbose', + helpText: 'inherited', + ); + const local = FlagOption(argName: 'verbose', helpText: 'local'); + final leaf = TestCommand(name: 'leaf', options: [local]); + final root = TestCommand( + name: 'tool', + persistentOptions: [inherited], + subcommands: [leaf], + ); + + test('when the command tree is parsed then parsing fails', () { + expect( + () => scanAndParseCommands([], rootCommand: root), + throwsA( + isA().having( + (final e) => e.toString(), + 'toString', + contains('Duplicate argument name: verbose'), + ), + ), + ); + }); + }, + ); + + group( + 'Given a subcommand persistent option that reuses an inherited name', + () { + const inherited = FlagOption( + argName: 'verbose', + helpText: 'inherited', + ); + const local = FlagOption(argName: 'verbose', helpText: 'local'); + final leaf = TestCommand(name: 'leaf', persistentOptions: [local]); + final root = TestCommand( + name: 'tool', + persistentOptions: [inherited], + subcommands: [leaf], + ); + + test('when the command tree is parsed then parsing fails', () { + expect( + () => scanAndParseCommands([], rootCommand: root), + throwsA( + isA().having( + (final e) => e.toString(), + 'toString', + contains('Duplicate argument name: verbose'), + ), + ), + ); + }); + }, + ); + + group( + 'Given a subcommand option that reuses an inherited abbreviation', + () { + const inherited = FlagOption(argName: 'verbose', argAbbrev: 'v'); + const local = FlagOption(argName: 'loud', argAbbrev: 'v'); + final leaf = TestCommand(name: 'leaf', options: [local]); + final root = TestCommand( + name: 'tool', + persistentOptions: [inherited], + subcommands: [leaf], + ); + + test('when the command tree is parsed then parsing fails', () { + expect( + () => scanAndParseCommands([], rootCommand: root), + throwsA( + isA().having( + (final e) => e.toString(), + 'toString', + contains('Duplicate argument abbreviation: v'), + ), + ), + ); + }); + }, + ); + + group('Given a command with two subcommands of the same name', () { + final first = TestCommand(name: 'build'); + final second = TestCommand(name: 'build'); + final root = TestCommand(name: 'tool', subcommands: [first, second]); + + test('when the command tree is parsed then parsing fails', () { + expect( + () => scanAndParseCommands([], rootCommand: root), + throwsA( + isA().having( + (final e) => e.toString(), + 'toString', + 'CommandDefinitionError: Invalid definition for command `build`: ' + 'Duplicate subcommand name: build for command tool', + ), + ), + ); + }); + }); + + group('Given a nested command with two subcommands of the same name', () { + final first = TestCommand(name: 'leaf'); + final second = TestCommand(name: 'leaf'); + final mid = TestCommand(name: 'mid', subcommands: [first, second]); + final root = TestCommand(name: 'tool', subcommands: [mid]); + + test('when the command tree is parsed then parsing fails', () { + expect( + () => scanAndParseCommands([], rootCommand: root), + throwsA( + isA().having( + (final e) => e.toString(), + 'toString', + 'CommandDefinitionError: Invalid definition for command `leaf`: ' + 'Duplicate subcommand name: leaf for command mid', + ), + ), + ); + }); + }); + + group('Given the same command name at different levels', () { + final leaf = TestCommand(name: 'tool'); + final root = TestCommand(name: 'tool', subcommands: [leaf]); + + test('when the leaf command is selected then parsing succeeds', () { + expect( + scanAndParseCommands(['tool'], rootCommand: root).command, + same(root), + ); + }); + }); + + group('Given a command with subcommands and a positional option', () { + const file = StringOption(argName: 'file', argPos: 0); + final leaf = TestCommand(name: 'leaf'); + final root = TestCommand( + name: 'tool', + options: [file], + subcommands: [leaf], + ); + + test('when the command tree is parsed then parsing fails', () { + expect( + () => scanAndParseCommands([], rootCommand: root), + throwsA( + isA().having( + (final e) => e.toString(), + 'toString', + 'CommandDefinitionError: Invalid definition for command `tool`: ' + 'Cannot define positional options on a command with subcommands: option `file`.', + ), + ), + ); + }); + }); + + group( + 'Given a command with subcommands and a persistent positional option', + () { + const file = StringOption(argPos: 0); + final leaf = TestCommand(name: 'leaf'); + final root = TestCommand( + name: 'tool', + persistentOptions: [file], + subcommands: [leaf], + ); + + test('when the command tree is parsed then parsing fails', () { + expect( + () => scanAndParseCommands([], rootCommand: root), + throwsA( + isA().having( + (final e) => e.toString(), + 'toString', + 'CommandDefinitionError: Invalid definition for command `tool`: ' + 'Persistent options must not be positional: ' + 'positional argument 0.', + ), + ), + ); + }); + }, + ); + + group( + 'Given a nested command with subcommands and a positional option', + () { + const file = StringOption(argPos: 0); + final leaf = TestCommand(name: 'leaf'); + final mid = TestCommand( + name: 'mid', + options: [file], + subcommands: [leaf], + ); + final root = TestCommand(name: 'tool', subcommands: [mid]); + + test('when the command tree is parsed then parsing fails', () { + expect( + () => scanAndParseCommands([], rootCommand: root), + throwsA( + isA().having( + (final e) => e.toString(), + 'toString', + 'CommandDefinitionError: Invalid definition for command `mid`: ' + 'Cannot define positional options on a command with subcommands: ' + 'positional argument 0.', + ), + ), + ); + }); + }, + ); + + group('Given a command with a persistent positional option', () { + const file = StringOption(argName: 'file', argPos: 0); + final root = TestCommand(name: 'tool', persistentOptions: [file]); + + test('when the command tree is parsed then parsing fails', () { + expect( + () => scanAndParseCommands([], rootCommand: root), + throwsA( + isA().having( + (final e) => e.toString(), + 'toString', + 'CommandDefinitionError: Invalid definition for command `tool`: ' + 'Persistent options must not be positional: option `file`.', + ), + ), + ); + }); + }); + + group('Given a nested command with a persistent positional option', () { + const file = StringOption(argPos: 0); + final leaf = TestCommand(name: 'run', persistentOptions: [file]); + final root = TestCommand(name: 'tool', subcommands: [leaf]); + + test('when the command tree is parsed then parsing fails', () { + expect( + () => scanAndParseCommands([], rootCommand: root), + throwsA( + isA().having( + (final e) => e.toString(), + 'toString', + 'CommandDefinitionError: Invalid definition for command `run`: ' + 'Persistent options must not be positional: ' + 'positional argument 0.', + ), + ), + ); + }); + }); + + group('Given a leaf command with a positional option', () { + const file = StringOption(argName: 'file', argPos: 0); + final leaf = TestCommand(name: 'run', options: [file]); + final root = TestCommand(name: 'tool', subcommands: [leaf]); + + test('when the command tree is parsed then parsing succeeds', () { + final result = scanAndParseCommands( + ['run', 'main.dart'], + rootCommand: root, + ); + + expect(childResult(result).positionalWords, ['main.dart']); + }); + }); + + group('Given an option that consumes the following word', () { + const config = StringOption(argName: 'config'); + const output = StringOption(argName: 'output'); + final run = TestCommand( + name: 'run', + options: [output], + usageDefinition: const CommandUsageDefinition(description: 'run usage'), + ); + final root = TestCommand( + name: 'tool', + persistentOptions: [config], + subcommands: [run], + canRunAsLeafCommand: true, + usageDefinition: const CommandUsageDefinition(description: 'root usage'), + ); + + ArgParseResult parse(final List args) { + return scanAndParseCommands(args, rootCommand: root); + } + + group('when the following word is a subcommand name', () { + late ArgParseResult result; + + setUp(() { + result = parse(['--config', 'run']); + }); + + test('then that word is the option value', () { + expect(result.regularOptions[config], 'run'); + }); + + test('then no subcommand runs', () { + expect(result.child, isNull); + }); + + test('then the word is not positional', () { + expect(result.positionalWords, isEmpty); + }); + }); + + group('when the value is attached and the subcommand follows', () { + late ArgParseResult result; + + setUp(() { + result = parse(['--config=run', 'run', '--output', 'out', 'file']); + }); + + test('then the attached text is the option value', () { + expect(result.regularOptions[config], 'run'); + }); + + test('then the subcommand runs', () { + expect(childResult(result).command, same(run)); + }); + + test('then the subcommand records its own option', () { + expect(childResult(result).regularOptions[output], 'out'); + }); + + test('then the subcommand keeps the remaining word', () { + expect(childResult(result).positionalWords, ['file']); + }); + }); + + group('when the option follows the subcommand', () { + late ArgParseResult result; + + setUp(() { + result = parse(['run', '--config', 'app', '--output', 'out']); + }); + + test('then the owning command records the value', () { + expect(result.regularOptions[config], 'app'); + }); + + test('then the subcommand does not record the option', () { + expect(childResult(result).regularOptions[config], isNull); + }); + + test('then the subcommand records its own option', () { + expect(childResult(result).regularOptions[output], 'out'); + }); + }); + + test( + 'when the option is repeated after the subcommand ' + 'then the error is on that subcommand', + () { + expect( + childResult(parse(['--config', 'a', 'run', '--config', 'b'])).errors, + ['Option --config cannot be specified more than once'], + ); + }, + ); + }); + + group('Given a persistent option owned by an intermediate command', () { + const profile = StringOption(argName: 'profile'); + const output = StringOption(argName: 'output'); + final leaf = TestCommand(name: 'leaf', options: [output]); + final mid = TestCommand( + name: 'mid', + persistentOptions: [profile], + subcommands: [leaf], + ); + final root = TestCommand(name: 'tool', subcommands: [mid]); + + group('when the option is written after the leaf and a leaf option', () { + late ArgParseResult result; + late ArgParseResult midResult; + late ArgParseResult leafResult; + + setUp(() { + result = scanAndParseCommands( + ['mid', 'leaf', '--output', 'out', '--profile', 'ci'], + rootCommand: root, + ); + midResult = childResult(result); + leafResult = childResult(midResult); + }); + + test('then the owning command records the value', () { + expect(midResult.regularOptions[profile], 'ci'); + }); + + test('then the root does not record the option', () { + expect(result.regularOptions[profile], isNull); + }); + + test('then the leaf does not record the option', () { + expect(leafResult.regularOptions[profile], isNull); + }); + + test('then the leaf records its own option', () { + expect(leafResult.regularOptions[output], 'out'); + }); + }); + }); + + group('Given a command tree and pass-through after --', () { + const verbose = FlagOption(argName: 'verbose', argAbbrev: 'v'); + const config = StringOption(argName: 'config', argAbbrev: 'c'); + const output = StringOption(argName: 'output', argAbbrev: 'o'); + + final leaf = TestCommand( + name: 'leaf', + options: [output], + usageDefinition: const CommandUsageDefinition(description: 'leaf usage'), + ); + final mid = TestCommand( + name: 'mid', + persistentOptions: [verbose], + subcommands: [leaf], + canRunAsLeafCommand: true, + usageDefinition: const CommandUsageDefinition(description: 'mid usage'), + ); + final root = TestCommand( + name: 'tool', + options: [config], + subcommands: [mid], + canRunAsLeafCommand: true, + usageDefinition: const CommandUsageDefinition(description: 'root usage'), + ); + + const passThroughRest = ScanMode( + doubleDashHandling: DoubleDashHandling.passThroughRest, + ); + + ArgParseResult parse(final List args) { + return scanAndParseCommands( + args, + rootCommand: root, + scanMode: passThroughRest, + ); + } + + group('when -- follows the leaf command', () { + late ArgParseResult result; + late ArgParseResult midResult; + late ArgParseResult leafResult; + + setUp(() { + result = parse([ + '--config', + 'app', + 'mid', + '-v', + 'leaf', + '--output', + 'out', + 'file', + '--', + '-v', + 'leaf', + '--output', + 'other', + ]); + midResult = childResult(result); + leafResult = childResult(midResult); + }); + + test('then the root records its option', () { + expect(result.regularOptions[config], 'app'); + }); + + test('then the mid command records its flag', () { + expect(midResult.flagOptions[verbose], isTrue); + }); + + test('then the leaf records its option', () { + expect(leafResult.regularOptions[output], 'out'); + }); + + test('then the leaf keeps words before --', () { + expect(leafResult.positionalWords, ['file']); + }); + + test('then the leaf keeps arguments after --', () { + expect(leafResult.unparsedArgs, ['-v', 'leaf', '--output', 'other']); + }); + + test('then the root has no unparsed arguments', () { + expect(result.unparsedArgs, isEmpty); + }); + + test('then the mid command has no unparsed arguments', () { + expect(midResult.unparsedArgs, isEmpty); + }); + + test('then the leaf is the last node', () { + expect(leafResult.child, isNull); + }); + }); + + group('when -- follows an intermediate command', () { + late ArgParseResult result; + late ArgParseResult midResult; + + setUp(() { + result = parse(['mid', '--', '-v', 'leaf', 'file']); + midResult = childResult(result); + }); + + test('then no further subcommand runs', () { + expect(midResult.child, isNull); + }); + + test('then the intermediate command keeps the remaining arguments', () { + expect(midResult.unparsedArgs, ['-v', 'leaf', 'file']); + }); + + test('then the root has no unparsed arguments', () { + expect(result.unparsedArgs, isEmpty); + }); + + test('then the persistent flag after -- is not recorded', () { + expect(midResult.flagOptions[verbose], isNull); + }); + + test('then the intermediate command has no positional words', () { + expect(midResult.positionalWords, isEmpty); + }); + }); + + group('when -- is before any subcommand', () { + late ArgParseResult result; + + setUp(() { + result = parse(['--', 'mid', '-v', 'leaf']); + }); + + test('then no subcommand runs', () { + expect(result.child, isNull); + }); + + test('then the root keeps the remaining arguments', () { + expect(result.unparsedArgs, ['mid', '-v', 'leaf']); + }); + + test('then the root has no positional words', () { + expect(result.positionalWords, isEmpty); + }); + }); + + group('when a leaf option takes -- as its value', () { + late ArgParseResult result; + late ArgParseResult midResult; + late ArgParseResult leafResult; + + setUp(() { + result = parse([ + 'mid', + 'leaf', + '--output', + '--', + '-v', + 'file', + ]); + midResult = childResult(result); + leafResult = childResult(midResult); + }); + + test('then -- is the option value', () { + expect(leafResult.regularOptions[output], '--'); + }); + + test('then the persistent flag after that -- is recorded', () { + expect(midResult.flagOptions[verbose], isTrue); + }); + + test('then the following word stays positional', () { + expect(leafResult.positionalWords, ['file']); + }); + + test('then the root has no unparsed arguments', () { + expect(result.unparsedArgs, isEmpty); + }); + + test('then the mid command has no unparsed arguments', () { + expect(midResult.unparsedArgs, isEmpty); + }); + + test('then the leaf has no unparsed arguments', () { + expect(leafResult.unparsedArgs, isEmpty); + }); + }); + + group('when a leaf option takes -- and a later -- follows', () { + late ArgParseResult result; + late ArgParseResult midResult; + late ArgParseResult leafResult; + + setUp(() { + result = parse([ + 'mid', + 'leaf', + '--output', + '--', + '-v', + 'file', + '--', + 'extra', + '--output', + 'other', + ]); + midResult = childResult(result); + leafResult = childResult(midResult); + }); + + test('then the first -- is the option value', () { + expect(leafResult.regularOptions[output], '--'); + }); + + test('then the persistent flag before the later -- is recorded', () { + expect(midResult.flagOptions[verbose], isTrue); + }); + + test('then the word before the later -- stays positional', () { + expect(leafResult.positionalWords, ['file']); + }); + + test('then arguments after the later -- are unparsed', () { + expect(leafResult.unparsedArgs, ['extra', '--output', 'other']); + }); + + test('then the root has no unparsed arguments', () { + expect(result.unparsedArgs, isEmpty); + }); + + test('then the mid command has no unparsed arguments', () { + expect(midResult.unparsedArgs, isEmpty); + }); + + test('then the leaf is the last node', () { + expect(leafResult.child, isNull); + }); + }); + + group('when a root option takes -- as its value', () { + late ArgParseResult result; + late ArgParseResult midResult; + late ArgParseResult leafResult; + + setUp(() { + result = parse(['--config', '--', 'mid', 'leaf', 'file']); + midResult = childResult(result); + leafResult = childResult(midResult); + }); + + test('then -- is the option value', () { + expect(result.regularOptions[config], '--'); + }); + + test('then the subcommands run', () { + expect( + result.toList().map((final node) => node.command).toList(), + [root, mid, leaf], + ); + }); + + test('then the leaf keeps the remaining word', () { + expect(leafResult.positionalWords, ['file']); + }); + + test('then the root has no unparsed arguments', () { + expect(result.unparsedArgs, isEmpty); + }); + + test('then the mid command has no unparsed arguments', () { + expect(midResult.unparsedArgs, isEmpty); + }); + + test('then the leaf has no unparsed arguments', () { + expect(leafResult.unparsedArgs, isEmpty); + }); + }); + + group('when a root option takes -- and a later -- follows', () { + late ArgParseResult result; + late ArgParseResult midResult; + + setUp(() { + result = parse(['--config', '--', 'mid', '--', 'leaf', '-v']); + midResult = childResult(result); + }); + + test('then the first -- is the option value', () { + expect(result.regularOptions[config], '--'); + }); + + test('then the later -- stops the next subcommand', () { + expect(midResult.child, isNull); + }); + + test('then the intermediate command keeps the remaining arguments', () { + expect(midResult.unparsedArgs, ['leaf', '-v']); + }); + + test('then the root has no unparsed arguments', () { + expect(result.unparsedArgs, isEmpty); + }); + + test('then the persistent flag after the later -- is not recorded', () { + expect(midResult.flagOptions[verbose], isNull); + }); + }); + + group('when -- ends the leaf command', () { + late ArgParseResult result; + late ArgParseResult midResult; + late ArgParseResult leafResult; + + setUp(() { + result = parse(['mid', 'leaf', 'file', '--']); + midResult = childResult(result); + leafResult = childResult(midResult); + }); + + test('then the root has no unparsed arguments', () { + expect(result.unparsedArgs, isEmpty); + }); + + test('then the mid command has no unparsed arguments', () { + expect(midResult.unparsedArgs, isEmpty); + }); + + test('then the leaf has no unparsed arguments', () { + expect(leafResult.unparsedArgs, isEmpty); + }); + + test('then the word before -- stays positional', () { + expect(leafResult.positionalWords, ['file']); + }); + }); + + group('when -- is absent', () { + late ArgParseResult result; + late ArgParseResult midResult; + late ArgParseResult leafResult; + + setUp(() { + result = parse(['mid', '-v', 'leaf', 'file']); + midResult = childResult(result); + leafResult = childResult(midResult); + }); + + test('then the mid command records its flag', () { + expect(midResult.flagOptions[verbose], isTrue); + }); + + test('then the root has no unparsed arguments', () { + expect(result.unparsedArgs, isEmpty); + }); + + test('then the mid command has no unparsed arguments', () { + expect(midResult.unparsedArgs, isEmpty); + }); + + test('then the leaf has no unparsed arguments', () { + expect(leafResult.unparsedArgs, isEmpty); + }); + }); + + test('when the same arguments use the default scan mode ' + 'then the unexpected -- is recorded on the leaf', () { + final result = scanAndParseCommands( + ['mid', 'leaf', '--', 'rest'], + rootCommand: root, + ); + + expect(childResult(childResult(result)).errors, [ + 'Unexpected value: --', + ]); + }); + + test('when the same arguments use the default scan mode ' + 'then the word after -- stays positional', () { + final result = scanAndParseCommands( + ['mid', 'leaf', '--', 'rest'], + rootCommand: root, + ); + + expect(childResult(childResult(result)).positionalWords, ['rest']); + }); + }); + + group('Given a command that cannot run as a leaf', () { + const verbose = FlagOption(argName: 'verbose'); + final leaf = TestCommand( + name: 'leaf', + usageDefinition: const CommandUsageDefinition(description: 'leaf usage'), + ); + final mid = TestCommand( + name: 'mid', + subcommands: [leaf], + usageDefinition: const CommandUsageDefinition(description: 'mid usage'), + ); + final root = TestCommand( + name: 'tool', + persistentOptions: [verbose], + subcommands: [mid], + usageDefinition: const CommandUsageDefinition(description: 'root usage'), + ); + + test('when no arguments are parsed then a subcommand is required', () { + final result = scanAndParseCommands([], rootCommand: root); + + expect(result.errors, ['A subcommand is required under tool']); + }); + + test('when only an option is parsed then the option is recorded', () { + final result = scanAndParseCommands(['--verbose'], rootCommand: root); + + expect(result.flagOptions[verbose], isTrue); + }); + + test('when only an option is parsed then a subcommand is required', () { + final result = scanAndParseCommands(['--verbose'], rootCommand: root); + + expect(result.errors, ['A subcommand is required under tool']); + }); + + test( + 'when an intermediate command is last then a subcommand is required', + () { + final result = scanAndParseCommands(['mid'], rootCommand: root); + + expect(childResult(result).errors, [ + 'A subcommand is required under mid', + ]); + }, + ); + + test('when the leaf command is selected then parsing succeeds', () { + final result = scanAndParseCommands(['mid', 'leaf'], rootCommand: root); + + expect( + result.toList().map((final node) => node.command).toList(), + [root, mid, leaf], + ); + }); + }); + + group('Given a command that can run as a leaf', () { + const verbose = FlagOption(argName: 'verbose'); + final leaf = TestCommand(name: 'leaf'); + final root = TestCommand( + name: 'tool', + persistentOptions: [verbose], + subcommands: [leaf], + canRunAsLeafCommand: true, + usageDefinition: const CommandUsageDefinition(description: 'root usage'), + ); + + test('when no arguments are parsed then that command is the result', () { + final result = scanAndParseCommands([], rootCommand: root); + + expect(result.command, same(root)); + expect(result.child, isNull); + }); + + test('when only an option is parsed then the option is recorded', () { + final result = scanAndParseCommands(['--verbose'], rootCommand: root); + + expect(result.flagOptions[verbose], isTrue); + expect(result.child, isNull); + }); + + test('when a word is not a subcommand then the error is recorded', () { + final result = scanAndParseCommands(['file'], rootCommand: root); + + expect(result.errors, ['Unknown subcommand: "file"']); + }); + }); + + group( + 'Given pass-through after -- and a command that cannot run as a leaf', + () { + final leaf = TestCommand(name: 'leaf'); + final root = TestCommand( + name: 'tool', + subcommands: [leaf], + usageDefinition: const CommandUsageDefinition( + description: 'root usage', + ), + ); + + test( + 'when -- stops before a subcommand then a subcommand is required', + () { + final result = scanAndParseCommands( + ['--', 'leaf'], + rootCommand: root, + scanMode: const ScanMode( + doubleDashHandling: DoubleDashHandling.passThroughRest, + ), + ); + + expect(result.errors, ['A subcommand is required under tool']); + }, + ); + + test('when -- stops before a subcommand ' + 'then the following word stays unparsed', () { + final result = scanAndParseCommands( + ['--', 'leaf'], + rootCommand: root, + scanMode: const ScanMode( + doubleDashHandling: DoubleDashHandling.passThroughRest, + ), + ); + + expect(result.unparsedArgs, ['leaf']); + }); + }, + ); + + group('Given a subcommand named as a long option', () { + const verbose = FlagOption(argName: 'verbose', argAbbrev: 'v'); + const out = StringOption(argName: 'out'); + final version = TestCommand( + name: '--version', + options: [out], + usageDefinition: const CommandUsageDefinition( + description: 'version usage', + ), + ); + final build = TestCommand(name: 'build'); + final root = TestCommand( + name: 'tool', + persistentOptions: [verbose], + subcommands: [version, build], + usageDefinition: const CommandUsageDefinition(description: 'root usage'), + ); + + ArgParseResult parse(final List args) { + return scanAndParseCommands(args, rootCommand: root); + } + + group('when --version is parsed', () { + late ArgParseResult result; + + setUp(() { + result = parse(['--version']); + }); + + test('then the version command runs', () { + expect(childResult(result).command, same(version)); + }); + + test('then the root has no errors', () { + expect(result.errors, isEmpty); + }); + + test('then the version command is not a positional word', () { + expect(result.positionalWords, isEmpty); + }); + }); + + test( + 'when the word version is parsed then it is an unknown subcommand', + () { + expect(parse(['version']).errors, ['Unknown subcommand: "version"']); + }, + ); + + group('when a root flag precedes --version', () { + late ArgParseResult result; + + setUp(() { + result = parse(['--verbose', '--version']); + }); + + test('then the root records the flag', () { + expect(result.flagOptions[verbose], isTrue); + }); + + test('then the version command runs', () { + expect(childResult(result).command, same(version)); + }); + + test('then the version command does not record the flag', () { + expect(childResult(result).flagOptions[verbose], isNull); + }); + }); + + group('when the version command receives an option and a word', () { + late ArgParseResult result; + late ArgParseResult versionResult; + + setUp(() { + result = parse(['--version', '--out', 'file', 'rest']); + versionResult = childResult(result); + }); + + test('then the option value is recorded on the version command', () { + expect(versionResult.regularOptions[out], 'file'); + }); + + test('then the remaining word is positional on the version command', () { + expect(versionResult.positionalWords, ['rest']); + }); + + test('then the root has no positional words', () { + expect(result.positionalWords, isEmpty); + }); + }); + + test('when a word subcommand of version is parsed then it runs', () { + final show = TestCommand(name: 'show'); + final versionWithShow = TestCommand( + name: '--version', + subcommands: [show], + ); + final command = TestCommand( + name: 'tool', + subcommands: [versionWithShow], + ); + final result = scanAndParseCommands( + ['--version', 'show'], + rootCommand: command, + ); + + expect(childResult(childResult(result)).command, same(show)); + }); + + test('when a word subcommand is parsed then that command runs', () { + expect(childResult(parse(['build'])).command, same(build)); + }); + + test('when an unknown option is parsed then both errors are recorded', () { + expect(parse(['--missing']).errors, [ + 'Unknown option: --missing', + 'A subcommand is required under tool', + ]); + }); + + group('when an unknown option precedes --version', () { + late ArgParseResult result; + + setUp(() { + result = parse(['--missing', '--version']); + }); + + test('then the unknown option is recorded on the root', () { + expect(result.errors, ['Unknown option: --missing']); + }); + + test('then the version command still runs', () { + expect(childResult(result).command, same(version)); + }); + }); + + group('when a value is attached to --version', () { + late ArgParseResult result; + + setUp(() { + result = parse(['--version=1']); + }); + + test('then the version command runs', () { + expect(childResult(result).command, same(version)); + }); + + test('then the attached value is unexpected on the version command', () { + expect(childResult(result).errors, ['Unexpected value: 1']); + }); + }); + + test('when a root option takes --version as its value ' + 'then no subcommand runs', () { + const config = StringOption(argName: 'config'); + final command = TestCommand( + name: 'tool', + options: [config], + subcommands: [version], + ); + final result = scanAndParseCommands( + ['--config', '--version'], + rootCommand: command, + ); + + expect(result.regularOptions[config], '--version'); + expect(result.child, isNull); + }); + }); + + group('Given a subcommand aliased as long and short options', () { + const out = StringOption(argName: 'out'); + final version = TestCommand( + name: 'version', + aliasesDefinition: const CommandAliasesDefinition( + aliases: ['--version', '-V'], + suggestionAliases: ['--ver'], + ), + options: [out], + ); + final root = TestCommand(name: 'tool', subcommands: [version]); + + ArgParseResult parse(final List args) { + return scanAndParseCommands(args, rootCommand: root); + } + + test('when --version is parsed then the version command runs', () { + expect(childResult(parse(['--version'])).command, same(version)); + }); + + test('when -V is parsed then the version command runs', () { + expect(childResult(parse(['-V'])).command, same(version)); + }); + + test('when the word version is parsed then the version command runs', () { + expect(childResult(parse(['version'])).command, same(version)); + }); + + test('when a suggestion alias is parsed then it stays unknown', () { + expect(parse(['--ver']).errors, [ + 'Unknown option: --ver', + 'A subcommand is required under tool', + ]); + }); + + test('when a different short option is parsed then it stays unknown', () { + expect(parse(['-v']).errors, [ + 'Unknown option: -v', + 'A subcommand is required under tool', + ]); + }); + + group('when the version command receives its option', () { + late ArgParseResult result; + + setUp(() { + result = parse(['-V', '--out', 'notes']); + }); + + test('then the option value is recorded on the version command', () { + expect(childResult(result).regularOptions[out], 'notes'); + }); + + test('then the root has no errors', () { + expect(result.errors, isEmpty); + }); + }); + }); + + group('Given a subcommand named as a short option', () { + const alpha = FlagOption(argName: 'alpha', argAbbrev: 'a'); + const help = FlagOption(argName: 'help', argAbbrev: 'h'); + final version = TestCommand( + name: '-v', + options: [help], + ); + final root = TestCommand( + name: 'tool', + options: [alpha], + subcommands: [version], + ); + + ArgParseResult parse(final List args) { + return scanAndParseCommands(args, rootCommand: root); + } + + test('when -v is parsed then the version command runs', () { + expect(childResult(parse(['-v'])).command, same(version)); + }); + + group('when -v is clustered before a version flag', () { + late ArgParseResult result; + + setUp(() { + result = parse(['-vh']); + }); + + test('then the version command runs', () { + expect(childResult(result).command, same(version)); + }); + + test('then the version command records the flag', () { + expect(childResult(result).flagOptions[help], isTrue); + }); + + test('then the root has no errors', () { + expect(result.errors, isEmpty); + }); + }); + + group('when a root flag is clustered before -v', () { + late ArgParseResult result; + + setUp(() { + result = parse(['-av']); + }); + + test('then the root records the flag', () { + expect(result.flagOptions[alpha], isTrue); + }); + + test('then the version command runs', () { + expect(childResult(result).command, same(version)); + }); + }); + + test('when an unknown letter precedes -v in a cluster ' + 'then that letter is recorded and the version command runs', () { + final result = parse(['-qv']); + + expect(result.errors, ['Unknown option: -q']); + expect(childResult(result).command, same(version)); + }); + + test('when a value is attached to -v ' + 'then it is unexpected on the version command', () { + final result = parse(['-v=1']); + + expect(childResult(result).command, same(version)); + expect(childResult(result).errors, ['Unexpected value: 1']); + }); + }); + + group( + 'Given a command option and a subcommand of the same long spelling', + () { + const version = FlagOption(argName: 'version'); + final command = TestCommand(name: '--version'); + final root = TestCommand( + name: 'tool', + options: [version], + subcommands: [command], + ); + + test('when the command tree is parsed then parsing fails', () { + expect( + () => scanAndParseCommands([], rootCommand: root), + throwsA( + isA().having( + (final e) => e.toString(), + 'toString', + 'CommandDefinitionError: Invalid definition for command `--version`: ' + 'Subcommand name `--version` collides with option `version` ' + 'for command tool', + ), + ), + ); + }); + }, + ); + + group( + 'Given a persistent option and a subcommand of the same long spelling', + () { + const version = FlagOption(argName: 'version'); + final command = TestCommand(name: '--version'); + final root = TestCommand( + name: 'tool', + persistentOptions: [version], + subcommands: [command], + ); + + test('when the command tree is parsed then parsing fails', () { + expect( + () => scanAndParseCommands([], rootCommand: root), + throwsA( + isA().having( + (final e) => e.toString(), + 'toString', + 'CommandDefinitionError: Invalid definition for command `--version`: ' + 'Subcommand name `--version` collides with option `version` ' + 'for command tool', + ), + ), + ); + }); + }, + ); + + group( + 'Given an option abbreviation and a subcommand of that short spelling', + () { + const version = FlagOption(argName: 'version', argAbbrev: 'V'); + final command = TestCommand(name: '-V'); + final root = TestCommand( + name: 'tool', + options: [version], + subcommands: [command], + ); + + test('when the command tree is parsed then parsing fails', () { + expect( + () => scanAndParseCommands([], rootCommand: root), + throwsA( + isA().having( + (final e) => e.toString(), + 'toString', + 'CommandDefinitionError: Invalid definition for command `-V`: ' + 'Subcommand name `-V` collides with option `version` ' + 'for command tool', + ), + ), + ); + }); + }, + ); + + group( + 'Given an option abbreviation and a subcommand alias of that spelling', + () { + const version = FlagOption(argName: 'version', argAbbrev: 'V'); + final command = TestCommand( + name: 'show', + aliasesDefinition: const CommandAliasesDefinition(aliases: ['-V']), + ); + final root = TestCommand( + name: 'tool', + persistentOptions: [version], + subcommands: [command], + ); + + test('when the command tree is parsed then parsing fails', () { + expect( + () => scanAndParseCommands([], rootCommand: root), + throwsA( + isA().having( + (final e) => e.toString(), + 'toString', + 'CommandDefinitionError: Invalid definition for command `show`: ' + 'Subcommand alias `-V` collides with option `version` ' + 'for command tool', + ), + ), + ); + }); + }, + ); + + group('Given an option alias and a subcommand of that long spelling', () { + const named = StringOption(argName: 'name', argAliases: ['version']); + final command = TestCommand(name: '--version'); + final root = TestCommand( + name: 'tool', + options: [named], + subcommands: [command], + ); + + test('when the command tree is parsed then parsing fails', () { + expect( + () => scanAndParseCommands([], rootCommand: root), + throwsA( + isA().having( + (final e) => e.toString(), + 'toString', + 'CommandDefinitionError: Invalid definition for command `--version`: ' + 'Subcommand name `--version` collides with option `name` ' + 'for command tool', + ), + ), + ); + }); + }); + + group( + 'Given a negatable flag and a subcommand named as its negation', + () { + const color = FlagOption(argName: 'color'); + final command = TestCommand(name: '--no-color'); + final root = TestCommand( + name: 'tool', + persistentOptions: [color], + subcommands: [command], + ); + + test('when the command tree is parsed then parsing fails', () { + expect( + () => scanAndParseCommands([], rootCommand: root), + throwsA( + isA().having( + (final e) => e.toString(), + 'toString', + 'CommandDefinitionError: Invalid definition for command `--no-color`: ' + 'Subcommand name `--no-color` collides with option `color` ' + 'for command tool', + ), + ), + ); + }); + }, + ); + + group( + 'Given an inherited persistent option and a nested action option', + () { + const verbose = FlagOption(argName: 'verbose'); + final nested = TestCommand(name: '--verbose'); + final mid = TestCommand(name: 'mid', subcommands: [nested]); + final root = TestCommand( + name: 'tool', + persistentOptions: [verbose], + subcommands: [mid], + ); + + test('when the command tree is parsed then parsing fails', () { + expect( + () => scanAndParseCommands([], rootCommand: root), + throwsA( + isA().having( + (final e) => e.toString(), + 'toString', + 'CommandDefinitionError: Invalid definition for command `--verbose`: ' + 'Subcommand name `--verbose` collides with option `verbose` ' + 'for command mid', + ), + ), + ); + }); + }, + ); + + group('Given an action option command that defines the same option', () { + const version = FlagOption(argName: 'version'); + final command = TestCommand(name: '--version', options: [version]); + final root = TestCommand(name: 'tool', subcommands: [command]); + + test('when --version is parsed then the command runs', () { + final result = scanAndParseCommands(['--version'], rootCommand: root); + + expect(childResult(result).command, same(command)); + }); + + test('when the option follows the command then the command records it', () { + final result = scanAndParseCommands( + ['--version', '--version'], + rootCommand: root, + ); + + expect(childResult(result).flagOptions[version], isTrue); + }); + }); + + group('Given a word subcommand and an option of that name', () { + const version = FlagOption(argName: 'version'); + final command = TestCommand(name: 'version'); + final root = TestCommand( + name: 'tool', + options: [version], + subcommands: [command], + canRunAsLeafCommand: true, + ); + + test('when the word is parsed then the subcommand runs', () { + final result = scanAndParseCommands(['version'], rootCommand: root); + + expect(childResult(result).command, same(command)); + }); + }); + + group('Given a suggestion alias with the spelling of an option', () { + const version = FlagOption(argName: 'version'); + final command = TestCommand( + name: 'version', + aliasesDefinition: const CommandAliasesDefinition( + suggestionAliases: ['--version'], + ), + ); + final root = TestCommand( + name: 'tool', + persistentOptions: [version], + subcommands: [command], + canRunAsLeafCommand: true, + ); + + test('when the command tree is parsed then parsing succeeds', () { + final result = scanAndParseCommands([], rootCommand: root); + + expect(result.command, same(root)); + }); + }); + + group( + 'Given a non-negatable flag and a subcommand named as its negation', + () { + const color = FlagOption(argName: 'color', negatable: false); + final command = TestCommand(name: '--no-color'); + final root = TestCommand( + name: 'tool', + options: [color], + subcommands: [command], + canRunAsLeafCommand: true, + ); + + test('when --no-color is parsed then the subcommand runs', () { + final result = scanAndParseCommands(['--no-color'], rootCommand: root); + + expect(childResult(result).command, same(command)); + }); + }, + ); + + group( + 'Given a nested action option and a non-persistent ancestor option', + () { + const version = FlagOption(argName: 'version'); + final nested = TestCommand(name: '--version'); + final mid = TestCommand(name: 'mid', subcommands: [nested]); + final root = TestCommand( + name: 'tool', + options: [version], + subcommands: [mid], + canRunAsLeafCommand: true, + ); + + test('when the nested command is selected then it runs', () { + final result = scanAndParseCommands( + ['mid', '--version'], + rootCommand: root, + ); + + expect(childResult(childResult(result)).command, same(nested)); + }); + }, + ); + + group( + 'Given two subcommands that can both answer to the same action option', + () { + const firstOut = StringOption(argName: 'first'); + const secondOut = StringOption(argName: 'second'); + final first = TestCommand(name: '--version', options: [firstOut]); + final second = TestCommand( + name: 'other', + aliasesDefinition: const CommandAliasesDefinition( + aliases: ['--version'], + ), + options: [secondOut], + ); + final root = TestCommand(name: 'tool', subcommands: [first, second]); + + ArgParseResult parse(final List args) { + return scanAndParseCommands(args, rootCommand: root); + } + + test('when --version is parsed then the earlier command runs', () { + expect(childResult(parse(['--version'])).command, same(first)); + }); + + test( + 'when --version is parsed then the earlier command options apply', + () { + final result = parse(['--version', '--first', 'a']); + + expect(childResult(result).regularOptions[firstOut], 'a'); + }, + ); + + test('when --version is parsed ' + 'then the later command options are unknown', () { + expect( + childResult(parse(['--version', '--second', 'a'])).errors, + ['Unknown option: --second'], + ); + }); + }, + ); + + group('Given a nested subcommand named as a long option', () { + final version = TestCommand(name: '--version'); + final mid = TestCommand(name: 'mid', subcommands: [version]); + final root = TestCommand(name: 'tool', subcommands: [mid]); + + test('when it is parsed under its parent then it runs', () { + final result = scanAndParseCommands( + ['mid', '--version'], + rootCommand: root, + ); + + expect(childResult(childResult(result)).command, same(version)); + }); + + test('when it is parsed on the root then it is an unknown option', () { + final result = scanAndParseCommands(['--version'], rootCommand: root); + + expect(result.errors, [ + 'Unknown option: --version', + 'A subcommand is required under tool', + ]); + }); + }); + + group('Given a short flag and a subcommand named with several letters', () { + const verbose = FlagOption(argName: 'verbose', argAbbrev: 'v'); + final command = TestCommand(name: '-version'); + final root = TestCommand( + name: 'tool', + options: [verbose], + subcommands: [command], + canRunAsLeafCommand: true, + ); + + test('when the command tree is parsed then parsing succeeds', () { + final result = scanAndParseCommands([], rootCommand: root); + + expect(result.command, same(root)); + }); + }); + + group('Given a subcommand whose name is a single-dash word', () { + final version = TestCommand(name: '-version'); + final root = TestCommand(name: 'tool', subcommands: [version]); + + test('when -version is parsed then the command does not run', () { + final result = scanAndParseCommands(['-version'], rootCommand: root); + + expect(result.child, isNull); + }); + + test('when -version is parsed then each letter is an unknown option', () { + final result = scanAndParseCommands(['-version'], rootCommand: root); + + expect(result.errors, [ + 'Unknown option: -v', + 'Unknown option: -e', + 'Unknown option: -r', + 'Unknown option: -s', + 'Unknown option: -i', + 'Unknown option: -o', + 'Unknown option: -n', + 'A subcommand is required under tool', + ]); + }); + }); +} + +const _verbose = FlagOption(argName: 'verbose', argAbbrev: 'v'); +const _output = StringOption(argName: 'output', argAbbrev: 'o'); + +enum _RootOption implements OptionDefinition { + verbose(_verbose); + + const _RootOption(this.option); + + @override + final ConfigOptionBase option; +} + +enum _BuildOption implements OptionDefinition { + output(_output); + + const _BuildOption(this.option); + + @override + final ConfigOptionBase option; +} + +class _EnumCommand implements CommandDefinition { + _EnumCommand({ + required this.name, + final List? persistentOptions, + final List? options, + final List? subcommands, + }) : persistentOptions = persistentOptions ?? const [], + options = options ?? const [], + subcommands = subcommands ?? const []; + + @override + final String name; + + @override + String get usage => name; + + @override + final CommandUsageDefinition usageDefinition = const CommandUsageDefinition( + description: '', + ); + + @override + final CommandAliasesDefinition aliasesDefinition = + const CommandAliasesDefinition(); + + @override + final List persistentOptions; + + @override + List allOptions({final bool onlyPersistent = false}) => [ + ...persistentOptions, + if (!onlyPersistent) ...options, + ]; + + @override + final List options; + + @override + final List subcommands; + + @override + final bool canRunAsLeafCommand = false; +} diff --git a/packages/config/test/config/arg_parser/scanner_test.dart b/packages/config/test/config/arg_parser/scanner_test.dart new file mode 100644 index 00000000..07f5e71f --- /dev/null +++ b/packages/config/test/config/arg_parser/scanner_test.dart @@ -0,0 +1,34 @@ +import 'package:config/src/config/arg_parser/arg_parser.dart'; +import 'package:test/test.dart'; + +void main() { + group('Given a single command line argument', () { + test('when it is a long option then its spelling is awaiting a value', () { + expect(optionAwaitingValue('--target'), '--target'); + }); + + test('when it is a short option then its spelling is awaiting a value', () { + expect(optionAwaitingValue('-t'), '-t'); + }); + + test('when it is a cluster of short options ' + 'then the last one is awaiting a value', () { + expect(optionAwaitingValue('-vft'), '-t'); + }); + + test('when the option has an attached value ' + 'then no option is awaiting a value', () { + expect(optionAwaitingValue('--target=x'), isNull); + expect(optionAwaitingValue('-t=x'), isNull); + expect(optionAwaitingValue('--target='), isNull); + }); + + test('when it is a word or a dash argument ' + 'then no option is awaiting a value', () { + expect(optionAwaitingValue('build'), isNull); + expect(optionAwaitingValue(''), isNull); + expect(optionAwaitingValue('--'), isNull); + expect(optionAwaitingValue('-'), isNull); + }); + }); +} diff --git a/packages/config/test/config/configuration_test.dart b/packages/config/test/config/configuration_test.dart index 2083d4cc..64978e65 100644 --- a/packages/config/test/config/configuration_test.dart +++ b/packages/config/test/config/configuration_test.dart @@ -1,17 +1,15 @@ -import 'package:args/args.dart' show ArgParser, ArgParserException; import 'package:config/config.dart'; import 'package:test/test.dart'; void main() async { - group('Given invalid configuration abbrevation without full name', () { + group('Given an option abbreviation without a full name', () { const projectIdOpt = StringOption( argAbbrev: 'p', ); - final parser = ArgParser(); - test('when preparing for parsing then throws exception', () async { + test('when validating the definition then it throws', () async { expect( - () => [projectIdOpt].prepareForParsing(parser), + () => validateOptions([projectIdOpt]), throwsA( allOf( isA(), @@ -29,11 +27,10 @@ void main() async { mandatory: true, defaultsTo: 'default', ); - final parser = ArgParser(); - test('when preparing for parsing then throws exception', () async { + test('when validating the definition then it throws', () async { expect( - () => [projectIdOpt].prepareForParsing(parser), + () => validateOptions([projectIdOpt]), throwsA( allOf( isA(), @@ -54,11 +51,9 @@ void main() async { fromDefault: _defaultValueFunction, ); - final parser = ArgParser(); - - test('when preparing for parsing then throws exception', () async { + test('when validating the definition then it throws', () async { expect( - () => [projectIdOpt].prepareForParsing(parser), + () => validateOptions([projectIdOpt]), throwsA( allOf( isA(), @@ -73,39 +68,34 @@ void main() async { ); group('Given an option with an invalid argument alias', () { - final parser = ArgParser(); - - test( - "when the alias contains '=' then definition validation throws", - () async { - const option = StringOption( - argName: 'name', - argAliases: ['bad=name'], - ); + test("when the alias contains '=' then definition validation throws", () { + const option = StringOption( + argName: 'name', + argAliases: ['bad=name'], + ); - expect( - () => [option].prepareForParsing(parser), - throwsA( - isA().having( - (final e) => e.message, - 'message', - "An argument option alias can't contain '='", - ), + expect( + () => validateOptions([option]), + throwsA( + isA().having( + (final e) => e.message, + 'message', + "An argument option alias can't contain '='", ), - ); - }, - ); + ), + ); + }); test( "when the alias starts with '-' then definition validation throws", - () async { + () { const option = StringOption( argName: 'name', argAliases: ['-bad'], ); expect( - () => [option].prepareForParsing(parser), + () => validateOptions([option]), throwsA( isA().having( (final e) => e.message, @@ -118,68 +108,6 @@ void main() async { ); }); - group('Given a configuration option definition', () { - const projectIdOpt = StringOption( - argName: 'project', - ); - - group('added to the arg parser', () { - final parser = ArgParser(); - [projectIdOpt].prepareForParsing(parser); - - test('then it is listed as an option there', () async { - expect(parser.options, contains('project')); - }); - - test( - 'when present on the command line, then it is successfully parsed', - () async { - final results = parser.parse(['--project', '123']); - expect(results.option('project'), '123'); - }, - ); - - test( - 'when present on the command line, then it is marked as parsed', - () async { - final results = parser.parse(['--project', '123']); - expect(results.wasParsed('project'), isTrue); - }, - ); - - test( - 'when not present on the command line, then it is marked as not parsed', - () async { - final results = parser.parse(['123']); - expect(results.wasParsed('project'), isFalse); - }, - ); - - test( - 'when misspelled on the command line, then it fails to parse', - () async { - expect( - () => parser.parse(['--projectid', '123']), - throwsA(isA()), - ); - }, - ); - - test( - 'when present twice on the command line, the value is the last one', - () async { - final results = parser.parse([ - '--project', - '123', - '--project', - '456', - ]); - expect(results.option('project'), '456'); - }, - ); - }); - }); - group('Given a configuration option defined for all sources', () { const projectIdOpt = StringOption( argName: 'project', @@ -264,16 +192,26 @@ void main() async { expect(config.value(projectIdOpt), equals('customValueFunction')); }); - test('when provided twice via args then the last value is used', () async { - // Note: This is the behavior of ArgParser. - // It may be considered to make this a usage error instead. - final args = ['--project', '123', '--project', '456']; - final config = Configuration.resolveNoExcept( - options: [projectIdOpt], - args: args, - ); - expect(config.value(projectIdOpt), equals('456')); - }); + test( + 'when provided twice via args ' + 'then it reports that the option cannot be specified more than once', + () async { + final args = ['--project', '123', '--project', '456']; + expect( + () => Configuration.resolve( + options: [projectIdOpt], + args: args, + ), + throwsA( + isA().having( + (final e) => e.message, + 'message', + 'Option --project cannot be specified more than once.', + ), + ), + ); + }, + ); }); group('Given a configuration option with a defaultsTo value', () { @@ -345,7 +283,7 @@ void main() async { configKeys: ['primary:/projectId', 'fallback:/projectId'], ); - test('then lookupConfigKeys lists the keys in order', () async { + test('then allConfigKeys lists the keys in order', () async { expect( projectIdOpt.allConfigKeys, equals(['primary:/projectId', 'fallback:/projectId']), @@ -418,6 +356,14 @@ void main() async { equals('fallbackValue'), ); }); + + test('when finding the option on the option list via a configKeys entry ' + 'then it succeeds', () { + expect( + [projectIdOpt].findOption(configKey: 'fallback:/projectId'), + same(projectIdOpt), + ); + }); }); group('Given a configuration option with both configKey and configKeys', () { @@ -426,7 +372,7 @@ void main() async { configKeys: ['fallback:/projectId'], ); - test('then lookupConfigKeys starts with configKey', () async { + test('then allConfigKeys starts with configKey', () async { expect( projectIdOpt.allConfigKeys, equals(['primary:/projectId', 'fallback:/projectId']), @@ -902,11 +848,22 @@ void main() async { ); test('when provided as argument then parsing fails', () async { - final parser = ArgParser(); - [projectIdOpt].prepareForParsing(parser); expect( - () => parser.parse(['--project', '123']), - throwsA(isA()), + () => Configuration.resolve( + options: [projectIdOpt], + args: ['--project', '123'], + ), + throwsA( + isA().having( + (final e) => e.message, + 'message', + stringContainsInOrder([ + 'Unknown option: --project', + 'Environment variable `PROJECT_ID` is mandatory.', + "Unexpected positional argument(s): '123'", + ]), + ), + ), ); }); @@ -950,6 +907,65 @@ void main() async { }); }); + group('Given a negatable flag whose name starts with no-', () { + const noColor = FlagOption(argName: 'no-color'); + + test('when validating the definition then it throws', () async { + expect( + () => validateOptions([noColor]), + throwsA( + allOf( + isA(), + (final e) => e.toString().contains( + "A flag whose name starts with 'no-' can't be negatable", + ), + ), + ), + ); + }); + }); + + group('Given a non-negatable flag whose name starts with no-', () { + const noColor = FlagOption(argName: 'no-color', negatable: false); + + test('when validating the definition then it is accepted', () { + expect(validateOptions([noColor]), [noColor]); + }); + }); + + group('Given a non-negatable flag with an alias that starts with no-', () { + const color = FlagOption( + argName: 'color', + negatable: false, + argAliases: ['no-color'], + ); + + test('when validating the definition then it is accepted', () { + expect(validateOptions([color]), [color]); + }); + }); + + group('Given a negatable flag whose alias is its negation', () { + const color = FlagOption( + argName: 'color', + argAliases: ['no-color'], + ); + + test('when validating the definition then it throws', () async { + expect( + () => validateOptions([color]), + throwsA( + allOf( + isA(), + (final e) => e.toString().contains( + 'Duplicate argument name: no-color', + ), + ), + ), + ); + }); + }); + group('Given invalid combinations of options', () { const argNameOpt = StringOption( argName: 'arg-name', @@ -970,55 +986,70 @@ void main() async { ); test( - 'when duplicate arg names specified then InvalidOptionConfigurationException is thrown', + 'when duplicate arg names specified then OptionDefinitionError is thrown', () async { - final parser = ArgParser(); expect( - () => [argNameOpt, duplicateOpt].prepareForParsing(parser), + () => validateOptions([argNameOpt, duplicateOpt]), throwsA(isA()), ); }, ); test( - 'when duplicate env names specified then InvalidOptionConfigurationException is thrown', + 'when duplicate abbreviations specified then OptionDefinitionError is thrown', + () async { + const first = StringOption(argName: 'first', argAbbrev: 'x'); + const second = StringOption(argName: 'second', argAbbrev: 'x'); + + expect( + () => validateOptions([first, second]), + throwsA( + allOf( + isA(), + (final e) => e.toString().contains( + 'Duplicate argument abbreviation: x', + ), + ), + ), + ); + }, + ); + + test( + 'when duplicate env names specified then OptionDefinitionError is thrown', () async { - final parser = ArgParser(); expect( - () => [envNameOpt, duplicateOpt].prepareForParsing(parser), + () => validateOptions([envNameOpt, duplicateOpt]), throwsA(isA()), ); }, ); test( - 'when duplicate arg positions specified then InvalidOptionConfigurationException is thrown', + 'when duplicate arg positions specified then OptionDefinitionError is thrown', () async { - final parser = ArgParser(); expect( - () => [argPosOpt, duplicateOpt].prepareForParsing(parser), + () => validateOptions([argPosOpt, duplicateOpt]), throwsA(isA()), ); }, ); test( - 'when non-consecutive arg positions specified then InvalidOptionConfigurationException is thrown', + 'when non-consecutive arg positions specified then OptionDefinitionError is thrown', () async { - final parser = ArgParser(); expect( - () => [argPosOpt, argPos2Opt].prepareForParsing(parser), + () => validateOptions([argPosOpt, argPos2Opt]), throwsA(isA()), ); }, ); test( - 'when first arg position does not start at 0 then InvalidOptionConfigurationException is thrown', + 'when first arg position does not start at 0 then OptionDefinitionError is thrown', () async { - final parser = ArgParser(); expect( - () => [argPos2Opt].prepareForParsing(parser), + () => validateOptions([argPos2Opt]), throwsA(isA()), ); }, @@ -1669,27 +1700,33 @@ void main() async { group('Given argument parsing fails', () { const projectOpt = StringOption(argName: 'project'); - late Configuration config; - - setUp(() { - config = Configuration.resolveNoExcept( - options: [projectOpt], - args: ['--not-an-option'], - ); - }); - - test('then remaining positional arguments are empty', () { - expect(config.remainingPosArgs, isEmpty); - }); - - test('then the parse error is recorded', () { - expect(config.errors, isNotEmpty); - }); + test( + 'then resolveNoExcept registers an error but does not throw a usage exception', + () { + final config = Configuration.resolveNoExcept( + options: [projectOpt], + args: ['--not-an-option'], + ); - test('then a copy has empty remaining positional arguments', () { - final copy = Configuration.from(configuration: config); + expect(config.errors, hasLength(1)); + expect(config.errors.first, 'Unknown option: --not-an-option'); + }, + ); - expect(copy.remainingPosArgs, isEmpty); + test('then resolve throws a usage exception', () { + expect( + () => Configuration.resolve( + options: [projectOpt], + args: ['--not-an-option'], + ), + throwsA( + isA().having( + (final e) => e.message, + 'message', + 'Unknown option: --not-an-option.', + ), + ), + ); }); }); @@ -1747,7 +1784,8 @@ void main() async { ); test( - 'when the first option is provided twice using aliases then the last value is used', + 'when the first option is provided twice using aliases ' + 'then it reports that the option cannot be specified more than once', () async { final args = [ '--alias-first-a', @@ -1759,9 +1797,11 @@ void main() async { options: options, args: args, ); - expect(config.errors, isEmpty); - expect(config.optionalValue(firstOpt), equals('2nd-arg')); - expect(config.optionalValue(secondOpt), isNull); + expect(config.errors, hasLength(1)); + expect( + config.errors.first, + 'Option --first cannot be specified more than once', + ); }, ); @@ -2211,7 +2251,8 @@ void main() async { ); test( - 'when dependee is specified before depender then parsing fails', + 'when dependee is specified before depender ' + 'then resolution throws an out-of-order dependency error', () async { final options = [projectIdOpt, configFileOpt]; @@ -2378,25 +2419,25 @@ void main() async { }); test('when getting an unknown option value via the arg name ' - 'then it succeeds', () async { + 'then it returns null', () async { final value = config.findValueOf(argName: 'unknown'); expect(value, isNull); }); test('when getting an unknown option value via the arg pos ' - 'then it succeeds', () async { + 'then it returns null', () async { final value = config.findValueOf(argPos: 2); expect(value, isNull); }); test('when getting an unknown option value via the env name ' - 'then it succeeds', () async { + 'then it returns null', () async { final value = config.findValueOf(envName: 'UNKNOWN'); expect(value, isNull); }); test('when getting an unknown option value via the config key ' - 'then it succeeds', () async { + 'then it returns null', () async { final value = config.findValueOf(configKey: 'config:/unknown'); expect(value, isNull); }); diff --git a/packages/config/test/config/configuration_type_test.dart b/packages/config/test/config/configuration_type_test.dart index b19adee9..611e62de 100644 --- a/packages/config/test/config/configuration_type_test.dart +++ b/packages/config/test/config/configuration_type_test.dart @@ -181,7 +181,7 @@ void main() async { expect(config.errors, hasLength(1)); expect( config.errors.single, - equals('"99" is not an allowed value for option "--number".'), + contains('`99` is not an allowed value for option `number`'), ); }, ); @@ -873,7 +873,7 @@ void main() async { expect(config.errors, hasLength(1)); expect( config.errors.single, - equals('"wrong" is not an allowed value for option "--many".'), + contains('`wrong` is not an allowed value for option `many`'), ); expect( () => config.optionalValue(typedOpt), @@ -915,7 +915,7 @@ void main() async { expect(config.errors, hasLength(1)); expect( config.errors.single, - equals('"wrong" is not an allowed value for option "--many".'), + contains('`wrong` is not an allowed value for option `many`'), ); expect( () => config.optionalValue(typedOpt),