From 3a052a141cfebf6696fad8d77a90735cfdad2b3b Mon Sep 17 00:00:00 2001 From: Christer Date: Thu, 19 Nov 2026 13:29:44 +0100 Subject: [PATCH 1/3] feat(command): Subcommands now shadow parents' options, rather than causing name conflict --- packages/config/README_command.md | 31 +- packages/config/lib/src/command/command.dart | 4 +- .../lib/src/command/command_runner.dart | 3 +- .../command/completion/completion_engine.dart | 77 ++- .../lib/src/config/arg_parser/parser.dart | 33 +- .../command/command_run_context_test.dart | 65 +++ .../completion/completion_engine_test.dart | 99 ++++ .../scan_and_parse_commands_test.dart | 503 +++++++++++++++++- 8 files changed, 751 insertions(+), 64 deletions(-) diff --git a/packages/config/README_command.md b/packages/config/README_command.md index e7500f05..69ef7c32 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 39f0fac9..d73e2612 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 3471ef9e..fb2ebc29 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 6b9b3599..debd5aff 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,8 +466,11 @@ 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. + /// + /// A nearer option may take one spelling of an ancestor option and leave + /// the others. [spellings] records which option each spelling refers to. Iterable get visibleOptions sync* { final seen = {}; for (final command in commands) { @@ -440,6 +483,8 @@ class _CommandLine { } } + late final _VisibleSpellings spellings = _VisibleSpellings(visibleOptions); + 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 3d9e460c..1ef9c8ee 100644 --- a/packages/config/lib/src/config/arg_parser/parser.dart +++ b/packages/config/lib/src/config/arg_parser/parser.dart @@ -211,6 +211,11 @@ ArgParseResult _parseArgs( final result = ArgParseResult(command: command, parent: parent); var rejectedSubcommand = false; + final ownOptions = [ + ...?command?.allOptions(), + ...?options, + ]; + final persistentOwners = >{ ...?inheritedPersistentOwners, if (command != null) ...{ @@ -219,10 +224,9 @@ ArgParseResult _parseArgs( }, }; - final allOptions = [ - ...?command?.options, - ...?options, - ...persistentOwners.keys, + final allOptions = [ + ...?inheritedPersistentOwners?.keys, + for (final option in ownOptions) option.option, ]; final possibleOptionNames = {}; @@ -426,14 +430,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 +483,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 6165a248..84b4f318 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 392a1d55..2492b49d 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,104 @@ 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 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 e32f7121..39a639a5 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,83 @@ 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 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 +1092,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)), + ); + }, + ); }, ); From af7e197f8882e6d901dcb618d6fb9f82858b4f25 Mon Sep 17 00:00:00 2001 From: Christer Date: Thu, 19 Nov 2026 13:52:30 +0100 Subject: [PATCH 2/3] fix(command): Record a reused option on the command that declares it again The same option object on a later command was still owned by the earlier registration, so a command in between could take its spelling. Co-authored-by: Cursor --- .../command/completion/completion_engine.dart | 31 ++++-- .../lib/src/config/arg_parser/parser.dart | 48 ++++++++-- .../completion/completion_engine_test.dart | 50 ++++++++++ .../scan_and_parse_commands_test.dart | 96 +++++++++++++++++++ 4 files changed, 210 insertions(+), 15 deletions(-) diff --git a/packages/config/lib/src/command/completion/completion_engine.dart b/packages/config/lib/src/command/completion/completion_engine.dart index debd5aff..472c9ded 100644 --- a/packages/config/lib/src/command/completion/completion_engine.dart +++ b/packages/config/lib/src/command/completion/completion_engine.dart @@ -469,21 +469,34 @@ class _CommandLine { /// The options in scope at the leaf command: its own options and the /// persistent options, built-in or not, of it and its ancestors. /// - /// A nearer option may take one spelling of an ancestor option and leave - /// the others. [spellings] records which option each spelling refers to. + /// 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(visibleOptions); + late final _VisibleSpellings spellings = _VisibleSpellings( + _optionsInPrecedenceOrder(), + ); bool wasParsed(final ConfigOptionBase option) { return chain.any( diff --git a/packages/config/lib/src/config/arg_parser/parser.dart b/packages/config/lib/src/config/arg_parser/parser.dart index 1ef9c8ee..cf72fac6 100644 --- a/packages/config/lib/src/config/arg_parser/parser.dart +++ b/packages/config/lib/src/config/arg_parser/parser.dart @@ -216,18 +216,30 @@ ArgParseResult _parseArgs( ...?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 = [ ...?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 = {}; @@ -260,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, @@ -285,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, @@ -358,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, diff --git a/packages/config/test/command/completion/completion_engine_test.dart b/packages/config/test/command/completion/completion_engine_test.dart index 2492b49d..a331bc93 100644 --- a/packages/config/test/command/completion/completion_engine_test.dart +++ b/packages/config/test/command/completion/completion_engine_test.dart @@ -1028,6 +1028,56 @@ void main() { ); }); + 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 { + final shared = StringOption( + argName: 'opt', + allowedValues: const ['a'], + ); + final middleOpt = StringOption( + argName: 'opt', + allowedValues: const ['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 39a639a5..55e370ca 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 @@ -1032,6 +1032,102 @@ void main() { }, ); + group( + 'Given one option object that is persistent on the root and the leaf', + () { + final shared = StringOption(argName: 'opt', helpText: 'shared'); + final 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', + () { + final 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', () { From a9f2739292913824efe7983c638206ac443287ed Mon Sep 17 00:00:00 2001 From: Christer Date: Thu, 19 Nov 2026 13:53:47 +0100 Subject: [PATCH 3/3] fix(command): Use const option definitions in the reuse tests The analyzer treats a non-const constructor as an info, and CI runs with fatal infos. Co-authored-by: Cursor --- .../test/command/completion/completion_engine_test.dart | 8 ++++---- .../config/arg_parser/scan_and_parse_commands_test.dart | 6 +++--- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/config/test/command/completion/completion_engine_test.dart b/packages/config/test/command/completion/completion_engine_test.dart index a331bc93..47797928 100644 --- a/packages/config/test/command/completion/completion_engine_test.dart +++ b/packages/config/test/command/completion/completion_engine_test.dart @@ -1036,13 +1036,13 @@ void main() { 'when the leaf option value is completed ' 'then the leaf occurrence supplies the values', () async { - final shared = StringOption( + const shared = StringOption( argName: 'opt', - allowedValues: const ['a'], + allowedValues: ['a'], ); - final middleOpt = StringOption( + const middleOpt = StringOption( argName: 'opt', - allowedValues: const ['b'], + allowedValues: ['b'], ); final engine = CompletionEngine( TestCommand( 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 55e370ca..28bac23d 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 @@ -1035,8 +1035,8 @@ void main() { group( 'Given one option object that is persistent on the root and the leaf', () { - final shared = StringOption(argName: 'opt', helpText: 'shared'); - final middleOpt = StringOption(argName: 'opt', helpText: 'middle'); + const shared = StringOption(argName: 'opt', helpText: 'shared'); + const middleOpt = StringOption(argName: 'opt', helpText: 'middle'); final nested = TestCommand(name: 'nested'); final leaf = TestCommand( name: 'leaf', @@ -1092,7 +1092,7 @@ void main() { 'Given one option object that is persistent on the root ' 'and non-persistent on the leaf', () { - final shared = StringOption(argName: 'opt', helpText: 'shared'); + const shared = StringOption(argName: 'opt', helpText: 'shared'); final leaf = TestCommand(name: 'leaf', options: [shared]); final root = TestCommand( name: 'tool',