diff --git a/packages/config/README_command.md b/packages/config/README_command.md index e7500f0..69ef7c3 100644 --- a/packages/config/README_command.md +++ b/packages/config/README_command.md @@ -27,12 +27,35 @@ code reentrant, which also makes it easier to write tests. ## Persistent options A persistent option belongs to the command that defines it and may be written -anywhere after that command on the command line, including after its subcommands. -The value is recorded on the defining command's context where it can be read by -that command as well as its successor commands. +anywhere after that command on the command line, including after its subcommands, +unless a later command shadows that spelling. The value is recorded on the +defining command's context where it can be read by that command as well as its +successor commands. + +Shadowing is per spelling. A subcommand's `--opt` hides an ancestor's `--opt` +and leaves the ancestor's abbreviation, unless the subcommand defines that +abbreviation too. An alias or a `--no-` form hides the same string on the +ancestor and no other spelling. + +```sh +executable --opt=3 subcommand --opt=foo +executable subcommand --opt=foo +executable subcommand -o 3 +``` + +The first sets the ancestor's `--opt` to `3` and the subcommand's `--opt` to +`foo`. The second sets only the subcommand's option. When the ancestor's +`--opt` also has `-o` and the subcommand does not, the third sets the ancestor's +option. Options of one command still cannot share a spelling. + +A non-persistent option hides those spellings only on the command that defines +it, so a further nested command sees the ancestor spellings again. A persistent +option hides them for that command and every command below it, until another +option shadows them. Environment variable names are not part of this: each +command resolves its own configuration. Global options are the root command's persistent options, so they are valid -anywhere on the command line: +anywhere on the command line, except where a later command shadows them: ```sh executable --verbose subcommand diff --git a/packages/config/lib/src/command/command.dart b/packages/config/lib/src/command/command.dart index 39f0fac..d73e261 100644 --- a/packages/config/lib/src/command/command.dart +++ b/packages/config/lib/src/command/command.dart @@ -21,7 +21,9 @@ import 'usage_generator.dart' /// /// All commands can have options. For a branch command, the options are /// "persistent", i.e. they are available anywhere to the right on the command -/// line (across any subcommands). Leaf command options can be positional, +/// line (across any subcommands). A later command shadows an identical +/// spelling, so its `--opt` hides an ancestor's `--opt`. +/// Leaf command options can be positional, /// i.e. directly as values without being prefixed by an option name. /// (Branch commands can't have positional options as they would conflict with /// subcommand names.) diff --git a/packages/config/lib/src/command/command_runner.dart b/packages/config/lib/src/command/command_runner.dart index 3471ef9..fb2ebc2 100644 --- a/packages/config/lib/src/command/command_runner.dart +++ b/packages/config/lib/src/command/command_runner.dart @@ -145,7 +145,8 @@ class CommandRunner /// /// [globalOptions] is the list of global options. /// Global options are "persistent" which means they are valid anywhere on the - /// command line. + /// command line. A subcommand shadows an identical spelling of a global + /// option, and leaves the global option's other spellings in place. /// /// The built-in global option `--help` / `-h` is available in addition, /// as is `--completion ` for a runner without subcommands, diff --git a/packages/config/lib/src/command/completion/completion_engine.dart b/packages/config/lib/src/command/completion/completion_engine.dart index 6b9b359..472c9de 100644 --- a/packages/config/lib/src/command/completion/completion_engine.dart +++ b/packages/config/lib/src/command/completion/completion_engine.dart @@ -180,21 +180,17 @@ class CompletionEngine { /// Finds the option visible on the leaf command that is spelled /// `--name`, `--alias`, or `-x`. + /// + /// A nearer option wins when it repeats that spelling. ConfigOptionBase? _findOptionBySpelling( final _CommandLine line, final String spelling, ) { - for (final option in line.visibleOptions) { - if (spelling.startsWith('--')) { - final name = spelling.substring(2); - if (option.argName == name) return option; - if (option.argAliases?.contains(name) == true) return option; - if (option is FlagOption && name == 'no-${option.argName}') { - return option; - } - } else if (spelling.length == 2 && spelling.startsWith('-')) { - if (option.argAbbrev == spelling[1]) return option; - } + if (spelling.startsWith('--')) { + return line.spellings.names[spelling.substring(2)]; + } + if (spelling.length == 2 && spelling.startsWith('-')) { + return line.spellings.abbrevs[spelling[1]]; } return null; } @@ -256,6 +252,7 @@ class CompletionEngine { ) { final includeShort = !current.startsWith('--'); final candidates = []; + final spellings = line.spellings; for (final option in line.visibleOptions) { final name = option.argName; @@ -264,16 +261,23 @@ class CompletionEngine { if (line.isExcluded(option)) continue; final description = _firstLine(option.helpText); - candidates.add(CompletionCandidate('--$name', description: description)); + if (spellings.ownsName(option, name)) { + candidates.add( + CompletionCandidate('--$name', description: description), + ); + } if (option is FlagOption && option.negatable && - !option.hideNegatedUsage) { + !option.hideNegatedUsage && + spellings.ownsName(option, 'no-$name')) { candidates.add( CompletionCandidate('--no-$name', description: description), ); } final abbrev = option.argAbbrev; - if (includeShort && abbrev != null) { + if (includeShort && + abbrev != null && + spellings.ownsAbbrev(option, abbrev)) { candidates.add( CompletionCandidate('-$abbrev', description: description), ); @@ -406,6 +410,42 @@ final _fileRedirection = RegExp( r'(.*)$', ); +/// Which option each command-line spelling refers to. +/// +/// Options are registered from the root toward the leaf. A later option +/// replaces only the spellings it defines: argument name, aliases, the +/// `--no-` form of a negatable flag, and abbreviation. +class _VisibleSpellings { + final Map names = {}; + final Map abbrevs = {}; + + _VisibleSpellings(final Iterable options) { + for (final option in options) { + final name = option.argName; + if (name != null) { + names[name] = option; + if (option is FlagOption && option.negatable) { + names['no-$name'] = option; + } + } + final aliases = option.argAliases; + if (aliases != null) { + for (final alias in aliases) { + names[alias] = option; + } + } + final abbrev = option.argAbbrev; + if (abbrev != null) abbrevs[abbrev] = option; + } + } + + bool ownsName(final ConfigOptionBase option, final String name) => + identical(names[name], option); + + bool ownsAbbrev(final ConfigOptionBase option, final String abbrev) => + identical(abbrevs[abbrev], option); +} + /// The parsed state of the command line preceding the word being completed. class _CommandLine { final List chain; @@ -426,20 +466,38 @@ class _CommandLine { for (final result in chain) _commandOf(result), ]; - /// The options that can be given at the leaf command: its own options - /// and the persistent options, built-in or not, of it and its ancestors. + /// The options in scope at the leaf command: its own options and the + /// persistent options, built-in or not, of it and its ancestors. + /// + /// Each option object is listed once, for offering candidates. [spellings] + /// is built from every occurrence, so a later command that reuses an option + /// object still owns the spellings it defines. Iterable get visibleOptions sync* { final seen = {}; - for (final command in commands) { - for (final option in command.allOptions(onlyPersistent: true)) { - if (seen.add(option.option)) yield option.option; - } + for (final option in _optionsInPrecedenceOrder()) { + if (seen.add(option)) yield option; } - for (final option in leafCommand.options) { - if (seen.add(option.option)) yield option.option; + } + + /// Persistent options from the root toward the leaf, then the leaf's own + /// options. Repeated option objects are kept, in the order they are declared. + Iterable _optionsInPrecedenceOrder() sync* { + final chain = commands; + for (var i = 0; i < chain.length; i++) { + final isLeaf = i == chain.length - 1; + final definitions = isLeaf + ? chain[i].allOptions() + : chain[i].allOptions(onlyPersistent: true); + for (final definition in definitions) { + yield definition.option; + } } } + late final _VisibleSpellings spellings = _VisibleSpellings( + _optionsInPrecedenceOrder(), + ); + bool wasParsed(final ConfigOptionBase option) { return chain.any( (final result) => diff --git a/packages/config/lib/src/config/arg_parser/parser.dart b/packages/config/lib/src/config/arg_parser/parser.dart index 3d9e460..cf72fac 100644 --- a/packages/config/lib/src/config/arg_parser/parser.dart +++ b/packages/config/lib/src/config/arg_parser/parser.dart @@ -211,19 +211,35 @@ ArgParseResult _parseArgs( final result = ArgParseResult(command: command, parent: parent); var rejectedSubcommand = false; + final ownOptions = [ + ...?command?.allOptions(), + ...?options, + ]; + + // Spread keeps ancestor registration order. Re-inserting an option this + // command also defines moves that key to the end, so a later command sees + // it as the latest registration. Updating the value in place would leave + // an earlier key ahead of options registered in between. final persistentOwners = >{ ...?inheritedPersistentOwners, - if (command != null) ...{ - for (final option in command.allOptions(onlyPersistent: true)) - option.option: result, - }, }; + if (command != null) { + for (final option in command.allOptions(onlyPersistent: true)) { + persistentOwners.remove(option.option); + persistentOwners[option.option] = result; + } + } - final allOptions = [ - ...?command?.options, - ...?options, - ...persistentOwners.keys, + final allOptions = [ + ...?inheritedPersistentOwners?.keys, + for (final option in ownOptions) option.option, ]; + // The same option object can be persistent on an ancestor and declared + // again here. The declaration on this command owns values written here, + // including when this declaration is not itself persistent. + final ownOptionBases = { + for (final option in ownOptions) option.option, + }; final possibleOptionNames = {}; final possibleOptionAbbrevs = {}; @@ -256,7 +272,12 @@ ArgParseResult _parseArgs( if (option != null) { _assignOption( result: result, - target: persistentOwners[option] ?? result, + target: _optionTarget( + option, + ownOptionBases: ownOptionBases, + persistentOwners: persistentOwners, + result: result, + ), option: option, scannedArgs: scannedArgs, name: arg.string, @@ -281,7 +302,12 @@ ArgParseResult _parseArgs( if (option != null) { _assignOption( result: result, - target: persistentOwners[option] ?? result, + target: _optionTarget( + option, + ownOptionBases: ownOptionBases, + persistentOwners: persistentOwners, + result: result, + ), option: option, scannedArgs: scannedArgs, name: arg.string, @@ -354,6 +380,20 @@ ArgParseResult _parseArgs( return result; } +/// Where a parsed option's value is recorded. +/// +/// An option declared on [result]'s command is recorded there. An inherited +/// persistent option is recorded on the command that registered it. +ArgParseResult _optionTarget( + final ConfigOptionBase option, { + required final Set ownOptionBases, + required final Map> persistentOwners, + required final ArgParseResult result, +}) { + if (ownOptionBases.contains(option)) return result; + return persistentOwners[option] ?? result; +} + String _unknownSubcommandError( final String name, final CommandDefinition command, @@ -426,14 +466,17 @@ void _validateCommandsAndOptions( final CommandDefinition command, { final List inheritedPersistentOptions = const [], }) { - final visibleOptions = [ - ...inheritedPersistentOptions, - ...command.allOptions(), - ]; - validateOptions(visibleOptions); + final ownOptions = command.allOptions(); + validateOptions(ownOptions); _rejectPositionalPersistentOptions(command); + // Ancestors first, so a spelling defined on this command replaces the same + // spelling of an inherited persistent option. + final visibleOptions = [ + ...inheritedPersistentOptions, + ...ownOptions, + ]; final subcommands = command.subcommands; if (subcommands.isNotEmpty) { _rejectDuplicateSubcommandNames(command.name, subcommands); @@ -476,10 +519,10 @@ void _rejectDuplicateSubcommandNames( /// 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. +/// Visible spellings are the command's own option spellings and every +/// persistent spelling inherited from its ancestors that this command does not +/// repeat. 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, diff --git a/packages/config/test/command/command_run_context_test.dart b/packages/config/test/command/command_run_context_test.dart index 6165a24..84b4f31 100644 --- a/packages/config/test/command/command_run_context_test.dart +++ b/packages/config/test/command/command_run_context_test.dart @@ -933,6 +933,71 @@ void main() { }, ); }); + + group( + 'Given a global option and a subcommand option of the same name', + () { + const globalOpt = StringOption(argName: 'opt', helpText: 'global'); + const localOpt = StringOption(argName: 'opt', helpText: 'local'); + + late CommandContext rootContext; + late CommandContext leafContext; + + Future run(final List args) async { + final command = CommandImpl.leafWithRunFunction( + name: 'build', + description: 'Build the app', + options: [localOpt], + run: (final runContext) { + leafContext = runContext; + rootContext = runContext.root(); + }, + ); + final runner = CommandRunner( + 'tool', + 'Tools', + globalOptions: [globalOpt], + subcommands: [command], + ); + await runner.run(args); + } + + group('when both options are set', () { + setUp(() async { + await run(['--opt', '3', 'build', '--opt', 'foo']); + }); + + test('then the root configuration has the global value', () { + expect(rootContext.config.optionalValue(globalOpt), '3'); + }); + + test('then the subcommand configuration has its own value', () { + expect(leafContext.config.optionalValue(localOpt), 'foo'); + }); + + test('then the subcommand does not own the global option', () { + expect( + () => leafContext.config.optionalValue(globalOpt), + throwsArgumentError, + ); + }); + }); + + group('when only the subcommand option is set', () { + setUp(() async { + await run(['build', '--opt', 'foo']); + }); + + test('then the global option is unset', () { + expect(rootContext.config.optionalValue(globalOpt), isNull); + }); + + test('then the subcommand configuration has its value', () { + expect(leafContext.config.optionalValue(localOpt), 'foo'); + }); + }); + }, + ); } /// Middleware class whose type arguments are inferred from the runner. diff --git a/packages/config/test/command/completion/completion_engine_test.dart b/packages/config/test/command/completion/completion_engine_test.dart index 392a1d5..4779792 100644 --- a/packages/config/test/command/completion/completion_engine_test.dart +++ b/packages/config/test/command/completion/completion_engine_test.dart @@ -2,6 +2,7 @@ import 'package:config/command.dart'; import 'package:config/config.dart'; import 'package:test/test.dart'; +import '../../config/arg_parser/arg_parser_test_support.dart'; import 'fixtures/completion_cli.dart'; /// The parsed response of a `__complete` request. @@ -929,6 +930,154 @@ void main() { }); }); + group('Given a subcommand option that shadows a global option', () { + const globalOpt = StringOption( + argName: 'opt', + argAbbrev: 'o', + helpText: 'global', + ); + const localOpt = StringOption(argName: 'opt', helpText: 'local'); + const branchOpt = StringOption(argName: 'opt', helpText: 'branch'); + const midOpt = StringOption(argName: 'opt', helpText: 'middle'); + + late CompletionEngine engine; + + setUp(() { + final shadowed = TestCommand(name: 'build', options: [localOpt]); + final branch = TestCommand( + name: 'group', + persistentOptions: [branchOpt], + subcommands: [TestCommand(name: 'leaf')], + ); + final open = TestCommand( + name: 'open', + options: [midOpt], + subcommands: [TestCommand(name: 'leaf')], + ); + engine = CompletionEngine( + TestCommand( + name: 'tool', + persistentOptions: [globalOpt], + subcommands: [shadowed, branch, open], + ), + ); + }); + + test( + 'when completing after the subcommand ' + 'then the subcommand name is offered and the global abbreviation remains', + () async { + final response = await engine.complete(['build', '-']); + + expect( + response.candidates + .where((final c) => c.value == '--opt') + .single + .description, + 'local', + ); + expect( + response.candidates + .where((final c) => c.value == '-o') + .single + .description, + 'global', + ); + }, + ); + + test( + 'when completing after a nested command ' + 'then the nearest name is offered and the global abbreviation remains', + () async { + final response = await engine.complete(['group', 'leaf', '-']); + + expect( + response.candidates + .where((final c) => c.value == '--opt') + .single + .description, + 'branch', + ); + expect( + response.candidates + .where((final c) => c.value == '-o') + .single + .description, + 'global', + ); + }, + ); + + test( + 'when a non-persistent option shadows only the middle command ' + 'then the global option is offered on the nested command', + () async { + final response = await engine.complete(['open', 'leaf', '-']); + final values = [for (final c in response.candidates) c.value]; + + expect(values, containsAll(['--opt', '-o'])); + expect( + response.candidates + .where((final c) => c.value == '--opt') + .single + .description, + 'global', + ); + }, + ); + }); + + group( + 'Given the same option object on the root and the leaf, ' + 'with another option of that name between them', + () { + test( + 'when the leaf option value is completed ' + 'then the leaf occurrence supplies the values', + () async { + const shared = StringOption( + argName: 'opt', + allowedValues: ['a'], + ); + const middleOpt = StringOption( + argName: 'opt', + allowedValues: ['b'], + ); + final engine = CompletionEngine( + TestCommand( + name: 'tool', + persistentOptions: [shared], + subcommands: [ + TestCommand( + name: 'middle', + persistentOptions: [middleOpt], + subcommands: [ + TestCommand( + name: 'leaf', + persistentOptions: [shared], + ), + ], + ), + ], + ), + ); + + final response = await engine.complete([ + 'middle', + 'leaf', + '--opt=', + ]); + + expect( + [for (final candidate in response.candidates) candidate.value], + ['a'], + ); + }, + ); + }, + ); + group('Given a CompletionResponse', () { test('when formatted then tabs and newlines in candidates ' 'are replaced', () { diff --git a/packages/config/test/config/arg_parser/scan_and_parse_commands_test.dart b/packages/config/test/config/arg_parser/scan_and_parse_commands_test.dart index e32f712..28bac23 100644 --- a/packages/config/test/config/arg_parser/scan_and_parse_commands_test.dart +++ b/packages/config/test/config/arg_parser/scan_and_parse_commands_test.dart @@ -685,11 +685,12 @@ void main() { group( 'Given a persistent option and a subcommand option of the same name', () { - const inherited = FlagOption( - argName: 'verbose', + const inherited = StringOption( + argName: 'opt', + argAbbrev: 'o', helpText: 'inherited', ); - const local = FlagOption(argName: 'verbose', helpText: 'local'); + const local = StringOption(argName: 'opt', helpText: 'local'); final leaf = TestCommand(name: 'leaf', options: [local]); final root = TestCommand( name: 'tool', @@ -697,6 +698,295 @@ void main() { subcommands: [leaf], ); + ArgParseResult parse(final List args) { + return scanAndParseCommands(args, rootCommand: root); + } + + test('when the command tree is parsed then parsing succeeds', () { + expect(parse([]).command, same(root)); + }); + + test( + 'when both options are set ' + 'then each value is recorded on its own command', + () { + final result = parse(['--opt', '3', 'leaf', '--opt', 'foo']); + + expect(result.regularOptions[inherited], '3'); + expect(childResult(result).regularOptions[local], 'foo'); + }, + ); + + test( + 'when only the subcommand option is set ' + 'then the persistent option is unset', + () { + final result = parse(['leaf', '--opt', 'foo']); + + expect(result.regularOptions, isNot(contains(inherited))); + expect(childResult(result).regularOptions[local], 'foo'); + }, + ); + + test( + 'when the persistent abbreviation is used before the subcommand ' + 'then the persistent option is set', + () { + final result = parse(['-o', '3', 'leaf']); + + expect(result.regularOptions[inherited], '3'); + }, + ); + + test( + 'when the persistent abbreviation is used after the subcommand ' + 'then the persistent option is set', + () { + final result = parse(['leaf', '-o', '3']); + + expect(result.regularOptions[inherited], '3'); + expect( + childResult(result).regularOptions, + isNot(contains(local)), + ); + }, + ); + }, + ); + + group( + 'Given a subcommand persistent option that reuses an inherited name', + () { + const inherited = StringOption(argName: 'opt', helpText: 'inherited'); + const local = StringOption(argName: 'opt', helpText: 'local'); + final nested = TestCommand(name: 'nested'); + final leaf = TestCommand( + name: 'leaf', + persistentOptions: [local], + subcommands: [nested], + ); + final root = TestCommand( + name: 'tool', + persistentOptions: [inherited], + subcommands: [leaf], + ); + + ArgParseResult parse(final List args) { + return scanAndParseCommands(args, rootCommand: root); + } + + test('when the command tree is parsed then parsing succeeds', () { + expect(parse([]).command, same(root)); + }); + + test( + 'when the option is set on the root and on the subcommand ' + 'then each command keeps its own value', + () { + final result = parse(['--opt', '3', 'leaf', '--opt', 'foo']); + + expect(result.regularOptions[inherited], '3'); + expect(childResult(result).regularOptions[local], 'foo'); + }, + ); + + test( + 'when the option is set after a nested command ' + 'then the subcommand persistent option receives it', + () { + final result = parse(['leaf', 'nested', '--opt', 'foo']); + + expect(result.regularOptions, isNot(contains(inherited))); + expect(childResult(result).regularOptions[local], 'foo'); + expect(childResult(result).child!.errors, isEmpty); + }, + ); + }, + ); + + group( + 'Given a non-persistent option that shadows an ancestor on one command', + () { + const inherited = StringOption(argName: 'opt', helpText: 'inherited'); + const local = StringOption(argName: 'opt', helpText: 'local'); + final nested = TestCommand(name: 'nested'); + final leaf = TestCommand( + name: 'leaf', + options: [local], + subcommands: [nested], + ); + final root = TestCommand( + name: 'tool', + persistentOptions: [inherited], + subcommands: [leaf], + ); + + ArgParseResult parse(final List args) { + return scanAndParseCommands(args, rootCommand: root); + } + + test( + 'when the option is set on the shadowing command ' + 'then that command receives it', + () { + final result = parse(['leaf', '--opt', 'foo', 'nested']); + + expect(result.regularOptions, isNot(contains(inherited))); + expect(childResult(result).regularOptions[local], 'foo'); + }, + ); + + test( + 'when the option is set on a further nested command ' + 'then the ancestor persistent option receives it', + () { + final result = parse(['leaf', 'nested', '--opt', '3']); + + expect(result.regularOptions[inherited], '3'); + expect( + childResult(result).regularOptions, + isNot(contains(local)), + ); + }, + ); + }, + ); + + group( + 'Given a subcommand option that reuses a shadowed abbreviation', + () { + const inherited = StringOption( + argName: 'opt', + argAbbrev: 'o', + helpText: 'inherited', + ); + const local = StringOption( + argName: 'opt', + argAbbrev: 'o', + helpText: 'local', + ); + final leaf = TestCommand(name: 'leaf', options: [local]); + final root = TestCommand( + name: 'tool', + persistentOptions: [inherited], + subcommands: [leaf], + ); + + test( + 'when the abbreviation is used after the subcommand ' + 'then the subcommand option is set', + () { + final result = scanAndParseCommands( + ['leaf', '-o', 'foo'], + rootCommand: root, + ); + + expect(childResult(result).regularOptions[local], 'foo'); + expect(result.regularOptions, isNot(contains(inherited))); + }, + ); + }, + ); + + group( + 'Given a subcommand option that reuses an inherited alias', + () { + const inherited = StringOption( + argName: 'color', + argAliases: ['colour'], + ); + const local = StringOption(argName: 'colour'); + final leaf = TestCommand(name: 'leaf', options: [local]); + final root = TestCommand( + name: 'tool', + persistentOptions: [inherited], + subcommands: [leaf], + ); + + ArgParseResult parse(final List args) { + return scanAndParseCommands(args, rootCommand: root); + } + + test('when the command tree is parsed then parsing succeeds', () { + expect(parse([]).command, same(root)); + }); + + test( + 'when the alias is used after the subcommand ' + 'then the subcommand option is set', + () { + final result = parse(['leaf', '--colour', 'red']); + + expect(childResult(result).regularOptions[local], 'red'); + expect(result.regularOptions, isNot(contains(inherited))); + }, + ); + + test( + 'when the persistent name is used after the subcommand ' + 'then the persistent option is set', + () { + final result = parse(['leaf', '--color', 'blue']); + + expect(result.regularOptions[inherited], 'blue'); + expect( + childResult(result).regularOptions, + isNot(contains(local)), + ); + }, + ); + }, + ); + + group( + 'Given a subcommand alias that reuses an inherited name', + () { + const inherited = StringOption(argName: 'opt', argAbbrev: 'o'); + const local = StringOption(argName: 'mode', argAliases: ['opt']); + final leaf = TestCommand(name: 'leaf', options: [local]); + final root = TestCommand( + name: 'tool', + persistentOptions: [inherited], + subcommands: [leaf], + ); + + ArgParseResult parse(final List args) { + return scanAndParseCommands(args, rootCommand: root); + } + + test( + 'when the shared name is used after the subcommand ' + 'then the subcommand option is set', + () { + final result = parse(['leaf', '--opt', 'foo']); + + expect(childResult(result).regularOptions[local], 'foo'); + expect(result.regularOptions, isNot(contains(inherited))); + }, + ); + + test( + 'when the persistent abbreviation is used after the subcommand ' + 'then the persistent option is set', + () { + final result = parse(['leaf', '-o', '3']); + + expect(result.regularOptions[inherited], '3'); + }, + ); + }, + ); + + group( + 'Given a command with a persistent option and a regular option ' + 'of the same name', + () { + final root = TestCommand( + name: 'tool', + persistentOptions: const [StringOption(argName: 'opt')], + options: const [StringOption(argName: 'opt')], + ); + test('when the command tree is parsed then parsing fails', () { expect( () => scanAndParseCommands([], rootCommand: root), @@ -704,7 +994,7 @@ void main() { isA().having( (final e) => e.toString(), 'toString', - contains('Duplicate argument name: verbose'), + contains('Duplicate argument name: opt'), ), ), ); @@ -713,35 +1003,179 @@ void main() { ); group( - 'Given a subcommand persistent option that reuses an inherited name', + 'Given a persistent option and a subcommand option ' + 'that share an environment name', () { - const inherited = FlagOption( - argName: 'verbose', + const inherited = StringOption( + argName: 'opt', + envName: 'OPT', helpText: 'inherited', ); - const local = FlagOption(argName: 'verbose', helpText: 'local'); - final leaf = TestCommand(name: 'leaf', persistentOptions: [local]); + const local = StringOption( + argName: 'opt', + envName: 'OPT', + 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', () { + test('when the command tree is parsed then parsing succeeds', () { expect( - () => scanAndParseCommands([], rootCommand: root), - throwsA( - isA().having( - (final e) => e.toString(), - 'toString', - contains('Duplicate argument name: verbose'), - ), - ), + scanAndParseCommands([], rootCommand: root).command, + same(root), ); }); }, ); + group( + 'Given one option object that is persistent on the root and the leaf', + () { + const shared = StringOption(argName: 'opt', helpText: 'shared'); + const middleOpt = StringOption(argName: 'opt', helpText: 'middle'); + final nested = TestCommand(name: 'nested'); + final leaf = TestCommand( + name: 'leaf', + persistentOptions: [shared], + subcommands: [nested], + ); + final middle = TestCommand( + name: 'middle', + persistentOptions: [middleOpt], + subcommands: [leaf], + ); + final root = TestCommand( + name: 'tool', + persistentOptions: [shared], + subcommands: [middle], + ); + + ArgParseResult parse(final List args) { + return scanAndParseCommands(args, rootCommand: root); + } + + test( + 'when the option is set under a command below the leaf ' + 'then the leaf receives it', + () { + final result = parse(['middle', 'leaf', 'nested', '--opt', 'leaf']); + final middleResult = childResult(result); + final leafResult = childResult(middleResult); + + expect(leafResult.regularOptions[shared], 'leaf'); + expect(middleResult.regularOptions, isNot(contains(middleOpt))); + expect(result.regularOptions, isNot(contains(shared))); + }, + ); + + test( + 'when the option is set on the middle command ' + 'then the middle option receives it', + () { + final result = parse(['middle', '--opt', 'mid', 'leaf', 'nested']); + + expect(childResult(result).regularOptions[middleOpt], 'mid'); + expect( + childResult(childResult(result)).regularOptions, + isNot(contains(shared)), + ); + }, + ); + }, + ); + + group( + 'Given one option object that is persistent on the root ' + 'and non-persistent on the leaf', + () { + const shared = StringOption(argName: 'opt', helpText: 'shared'); + final leaf = TestCommand(name: 'leaf', options: [shared]); + final root = TestCommand( + name: 'tool', + persistentOptions: [shared], + subcommands: [leaf], + ); + + ArgParseResult parse(final List args) { + return scanAndParseCommands(args, rootCommand: root); + } + + test( + 'when the option is set on the root and on the leaf ' + 'then each command keeps its own value', + () { + final result = parse(['--opt', 'root', 'leaf', '--opt', 'local']); + + expect(result.regularOptions[shared], 'root'); + expect(childResult(result).regularOptions[shared], 'local'); + }, + ); + + test( + 'when the option is set only on the leaf ' + 'then the root does not receive it', + () { + final result = parse(['leaf', '--opt', 'local']); + + expect(result.regularOptions, isNot(contains(shared))); + expect(childResult(result).regularOptions[shared], 'local'); + }, + ); + }, + ); + + group( + 'Given a negatable persistent flag shadowed by a subcommand flag', + () { + const inherited = FlagOption( + argName: 'verbose', + negatable: true, + helpText: 'inherited', + ); + const local = FlagOption( + argName: 'verbose', + negatable: true, + helpText: 'local', + ); + final leaf = TestCommand(name: 'leaf', options: [local]); + final root = TestCommand( + name: 'tool', + persistentOptions: [inherited], + subcommands: [leaf], + ); + + ArgParseResult parse(final List args) { + return scanAndParseCommands(args, rootCommand: root); + } + + test( + 'when the root flag is negated and the subcommand flag is set ' + 'then each flag has its own value', + () { + final result = parse(['--no-verbose', 'leaf', '--verbose']); + + expect(result.flagOptions[inherited], isFalse); + expect(childResult(result).flagOptions[local], isTrue); + }, + ); + + test( + 'when the negation is written after the subcommand ' + 'then the subcommand flag is negated', + () { + final result = parse(['leaf', '--no-verbose']); + + expect(result.flagOptions, isNot(contains(inherited))); + expect(childResult(result).flagOptions[local], isFalse); + }, + ); + }, + ); + group( 'Given a subcommand option that reuses an inherited abbreviation', () { @@ -754,18 +1188,125 @@ void main() { 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'), - ), - ), - ); + ArgParseResult parse(final List args) { + return scanAndParseCommands(args, rootCommand: root); + } + + test('when the command tree is parsed then parsing succeeds', () { + expect(parse([]).command, same(root)); }); + + test( + 'when the abbreviation is used after the subcommand ' + 'then the subcommand option is set', + () { + final result = parse(['leaf', '-v']); + + expect(childResult(result).flagOptions[local], isTrue); + expect(result.flagOptions, isNot(contains(inherited))); + }, + ); + + test( + 'when the persistent name is used after the subcommand ' + 'then the persistent option is set', + () { + final result = parse(['leaf', '--verbose']); + + expect(result.flagOptions[inherited], isTrue); + expect( + childResult(result).flagOptions, + isNot(contains(local)), + ); + }, + ); + }, + ); + + group( + 'Given a negatable persistent flag and a subcommand option ' + 'that reuses only its name', + () { + const inherited = FlagOption(argName: 'verbose', negatable: true); + const local = FlagOption(argName: 'verbose', negatable: false); + final leaf = TestCommand(name: 'leaf', options: [local]); + final root = TestCommand( + name: 'tool', + persistentOptions: [inherited], + subcommands: [leaf], + ); + + ArgParseResult parse(final List args) { + return scanAndParseCommands(args, rootCommand: root); + } + + test( + 'when --verbose is written after the subcommand ' + 'then the subcommand flag is set', + () { + final result = parse(['leaf', '--verbose']); + + expect(childResult(result).flagOptions[local], isTrue); + expect(result.flagOptions, isNot(contains(inherited))); + }, + ); + + test( + 'when --no-verbose is written after the subcommand ' + 'then the persistent flag is negated', + () { + final result = parse(['leaf', '--no-verbose']); + + expect(result.flagOptions[inherited], isFalse); + expect( + childResult(result).flagOptions, + isNot(contains(local)), + ); + }, + ); + }, + ); + + group( + "Given a subcommand option named like a persistent flag's no- form", + () { + const inherited = FlagOption(argName: 'verbose', negatable: true); + const local = StringOption(argName: 'no-verbose'); + final leaf = TestCommand(name: 'leaf', options: [local]); + final root = TestCommand( + name: 'tool', + persistentOptions: [inherited], + subcommands: [leaf], + ); + + ArgParseResult parse(final List args) { + return scanAndParseCommands(args, rootCommand: root); + } + + test( + 'when --no-verbose is written after the subcommand ' + 'then the subcommand option is set', + () { + final result = parse(['leaf', '--no-verbose', 'off']); + + expect(childResult(result).regularOptions[local], 'off'); + expect(result.flagOptions, isNot(contains(inherited))); + }, + ); + + test( + 'when --verbose is written after the subcommand ' + 'then the persistent flag is set', + () { + final result = parse(['leaf', '--verbose']); + + expect(result.flagOptions[inherited], isTrue); + expect( + childResult(result).regularOptions, + isNot(contains(local)), + ); + }, + ); }, );