Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 27 additions & 4 deletions packages/config/README_command.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion packages/config/lib/src/command/command.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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.)
Expand Down
3 changes: 2 additions & 1 deletion packages/config/lib/src/command/command_runner.dart
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,8 @@ class CommandRunner<O extends OptionDefinition, T>
///
/// [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 <shell>` for a runner without subcommands,
Expand Down
102 changes: 80 additions & 22 deletions packages/config/lib/src/command/completion/completion_engine.dart
Original file line number Diff line number Diff line change
Expand Up @@ -180,21 +180,17 @@ class CompletionEngine<O extends OptionDefinition, T> {

/// 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;
}
Expand Down Expand Up @@ -256,6 +252,7 @@ class CompletionEngine<O extends OptionDefinition, T> {
) {
final includeShort = !current.startsWith('--');
final candidates = <CompletionCandidate>[];
final spellings = line.spellings;

for (final option in line.visibleOptions) {
final name = option.argName;
Expand All @@ -264,16 +261,23 @@ class CompletionEngine<O extends OptionDefinition, T> {
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),
);
Expand Down Expand Up @@ -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<String, ConfigOptionBase> names = {};
final Map<String, ConfigOptionBase> abbrevs = {};

_VisibleSpellings(final Iterable<ConfigOptionBase> 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<ArgParseResult> chain;
Expand All @@ -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<ConfigOptionBase> get visibleOptions sync* {
final seen = <ConfigOptionBase>{};
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<ConfigOptionBase> _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) =>
Expand Down
81 changes: 62 additions & 19 deletions packages/config/lib/src/config/arg_parser/parser.dart
Original file line number Diff line number Diff line change
Expand Up @@ -211,19 +211,35 @@ ArgParseResult<O> _parseArgs<O extends OptionDefinition>(
final result = ArgParseResult<O>(command: command, parent: parent);
var rejectedSubcommand = false;

final ownOptions = <OptionDefinition>[
...?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 = <ConfigOptionBase, ArgParseResult<O>>{
...?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 = <ConfigOptionBase>[
...?inheritedPersistentOwners?.keys,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
for (final option in ownOptions) option.option,
Comment thread
christerswahn marked this conversation as resolved.
Resolved
];
// 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 = <ConfigOptionBase>{
for (final option in ownOptions) option.option,
};

final possibleOptionNames = <String, ConfigOptionBase>{};
final possibleOptionAbbrevs = <String, ConfigOptionBase>{};
Expand Down Expand Up @@ -256,7 +272,12 @@ ArgParseResult<O> _parseArgs<O extends OptionDefinition>(
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,
Expand All @@ -281,7 +302,12 @@ ArgParseResult<O> _parseArgs<O extends OptionDefinition>(
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,
Expand Down Expand Up @@ -354,6 +380,20 @@ ArgParseResult<O> _parseArgs<O extends OptionDefinition>(
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<O> _optionTarget<O extends OptionDefinition>(
final ConfigOptionBase option, {
required final Set<ConfigOptionBase> ownOptionBases,
required final Map<ConfigOptionBase, ArgParseResult<O>> persistentOwners,
required final ArgParseResult<O> result,
}) {
if (ownOptionBases.contains(option)) return result;
return persistentOwners[option] ?? result;
}

String _unknownSubcommandError<O extends OptionDefinition>(
final String name,
final CommandDefinition<O> command,
Expand Down Expand Up @@ -426,14 +466,17 @@ void _validateCommandsAndOptions<O extends OptionDefinition>(
final CommandDefinition<O> command, {
final List<OptionDefinition> inheritedPersistentOptions = const [],
}) {
final visibleOptions = <OptionDefinition>[
...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 = <OptionDefinition>[
...inheritedPersistentOptions,
...ownOptions,
];
final subcommands = command.subcommands;
if (subcommands.isNotEmpty) {
_rejectDuplicateSubcommandNames(command.name, subcommands);
Expand Down Expand Up @@ -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<O extends OptionDefinition>(
final String commandName,
final List<O> options,
Expand Down
Loading
Loading