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
4 changes: 3 additions & 1 deletion packages/config/lib/src/config/arg_parser/arg_parser.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,7 @@ export 'parser.dart'
ArgParseResult,
scanAndParseArgs,
scanAndParseCommands,
subcommandRequiredErrorPrefix,
unknownSubcommandErrorPrefix;
export 'scanner.dart' show DoubleDashHandling, ScanMode, optionAwaitingValue;
export 'parser_settings.dart';
export 'scanner.dart' show optionAwaitingValue;
30 changes: 16 additions & 14 deletions packages/config/lib/src/config/arg_parser/command_definition.dart
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,6 @@ abstract interface class CommandDefinition<O extends OptionDefinition> {
}

class CommandUsageDefinition {
// TODO: Support overriding `summary` and `invocation` of the formatted usage
// like the old Command did.

/// A description of this command, included in usage.
final String description;

Expand All @@ -46,7 +43,7 @@ class CommandUsageDefinition {

/// The command's category.
///
/// Displayed in [parent]'s [CommandRunner.usage]. Commands with categories
/// Displayed in [parent]'s usage. Commands with categories
/// will be grouped together, and displayed after commands without a category.
final String? category;

Expand All @@ -56,11 +53,25 @@ class CommandUsageDefinition {
/// as long as any of their leaf commands are visible.
final bool hidden;

/// A short description of this command, included in [parent]'s usage.
/// If null, the default is used which is typically the first line of [description].
final String? summary;

/// A custom template for this command's own invocation, replacing its name
/// and argument synopsis.
///
/// Parent command names are prepended. If the default synopsis would be
/// `executable branch leaf <args>`, this string replaces `leaf <args>`
/// (for example `"leaf <package>"`). If null, the synopsis is generated.
final String? invocation;

const CommandUsageDefinition({
final String? description,
this.usageFooter,
this.category,
final bool? hidden,
this.summary,
this.invocation,
}) : description = description ?? '',
hidden = hidden ?? false;
}
Expand All @@ -78,18 +89,9 @@ class CommandAliasesDefinition {
/// A name does not have to be repeated both here and in [aliases].
final List<String> suggestionAliases;

/// The maximum edit distance allowed when suggesting possible intended
/// commands.
///
/// Set to `0` in order to disable suggestions, defaults to `2`.
// TODO: Make this global on the CommandRunner instead?
final int suggestionDistanceLimit;

const CommandAliasesDefinition({
final List<String>? aliases,
final List<String>? suggestionAliases,
final int? suggestionDistanceLimit,
}) : aliases = aliases ?? const <String>[],
suggestionAliases = suggestionAliases ?? const <String>[],
suggestionDistanceLimit = suggestionDistanceLimit ?? 2;
suggestionAliases = suggestionAliases ?? const <String>[];
}
51 changes: 37 additions & 14 deletions packages/config/lib/src/config/arg_parser/parser.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,18 @@ import '../config.dart'
CommandDefinitionError,
validateOptions;
import 'command_definition.dart';
import 'parser_settings.dart';
import 'scanner.dart';
import 'suggestions.dart';

/// The start of the [ArgParseResult.errors] message recorded when a word
/// is not a known subcommand of a command that has subcommands.
const String unknownSubcommandErrorPrefix = 'Unknown subcommand: ';

/// The start of the [ArgParseResult.errors] message recorded when a command
/// that cannot run on its own is invoked without a subcommand.
const String subcommandRequiredErrorPrefix = 'A subcommand is required under ';

/// Scans the arguments and parses them into an [ArgParseResult]
/// corresponding to a single set of options.
///
Expand All @@ -22,7 +28,7 @@ const String unknownSubcommandErrorPrefix = 'Unknown subcommand: ';
ArgParseResult<O> scanAndParseArgs<O extends OptionDefinition>(
final Iterable<String> args, {
required final Iterable<O> options,
final ScanMode scanMode = const ScanMode(),
final ParserSettings settings = const ParserSettings(),
}) {
validateOptions(options);

Expand All @@ -31,7 +37,7 @@ ArgParseResult<O> scanAndParseArgs<O extends OptionDefinition>(
return _parseArgs(
_ArgCursor(scannedArgs),
options: options,
scanMode: scanMode,
settings: settings,
);
}

Expand All @@ -48,7 +54,7 @@ ArgParseResult<O> scanAndParseArgs<O extends OptionDefinition>(
ArgParseResult<O> scanAndParseCommands<O extends OptionDefinition>(
final Iterable<String> args, {
required final CommandDefinition<O> rootCommand,
final ScanMode scanMode = const ScanMode(),
final ParserSettings settings = const ParserSettings(),
}) {
_validateCommandsAndOptions(rootCommand);

Expand All @@ -57,7 +63,7 @@ ArgParseResult<O> scanAndParseCommands<O extends OptionDefinition>(
return _parseArgs(
_ArgCursor(scannedArgs),
command: rootCommand,
scanMode: scanMode,
settings: settings,
);
}

Expand Down Expand Up @@ -200,7 +206,7 @@ ArgParseResult<O> _parseArgs<O extends OptionDefinition>(
final Iterable<O>? options,
final ArgParseResult? parent,
final Map<ConfigOptionBase, ArgParseResult<O>>? inheritedPersistentOwners,
required final ScanMode scanMode,
required final ParserSettings settings,
}) {
final result = ArgParseResult<O>(command: command, parent: parent);
var rejectedSubcommand = false;
Expand Down Expand Up @@ -263,7 +269,7 @@ ArgParseResult<O> _parseArgs<O extends OptionDefinition>(
scannedArgs: scannedArgs,
command: command,
persistentOwners: persistentOwners,
scanMode: scanMode,
settings: settings,
name: '--${arg.string}',
)) {
return result;
Expand All @@ -288,15 +294,15 @@ ArgParseResult<O> _parseArgs<O extends OptionDefinition>(
scannedArgs: scannedArgs,
command: command,
persistentOwners: persistentOwners,
scanMode: scanMode,
settings: settings,
name: '-${arg.string}',
)) {
return result;
}
result.errors.add('Unknown option: -${arg.string}');

case DoubleDashToken():
if (scanMode.doubleDashHandling != DoubleDashHandling.passThroughRest) {
if (settings.doubleDashHandling != DoubleDashHandling.passThroughRest) {
result.errors.add('Unexpected value: ${arg.string}');
break;
}
Expand All @@ -305,7 +311,9 @@ ArgParseResult<O> _parseArgs<O extends OptionDefinition>(
case SingleDashToken():
if (command != null && command.subcommands.isNotEmpty) {
rejectedSubcommand = true;
result.errors.add('$unknownSubcommandErrorPrefix"${arg.string}"');
result.errors.add(
_unknownSubcommandError(arg.string, command, settings),
);
} else {
result.positionalWords.add(arg.string);
}
Expand All @@ -319,14 +327,16 @@ ArgParseResult<O> _parseArgs<O extends OptionDefinition>(
scannedArgs: scannedArgs,
command: command,
persistentOwners: persistentOwners,
scanMode: scanMode,
settings: settings,
name: arg.string,
)) {
return result;
}
if (command != null && command.subcommands.isNotEmpty) {
rejectedSubcommand = true;
result.errors.add('$unknownSubcommandErrorPrefix"${arg.string}"');
result.errors.add(
_unknownSubcommandError(arg.string, command, settings),
);
} else {
result.positionalWords.add(arg.string);
}
Expand All @@ -338,12 +348,25 @@ ArgParseResult<O> _parseArgs<O extends OptionDefinition>(
!command.canRunAsLeafCommand &&
result.child == null &&
!rejectedSubcommand) {
result.errors.add('A subcommand is required under ${command.name}');
result.errors.add('$subcommandRequiredErrorPrefix${command.name}');
}

return result;
}

String _unknownSubcommandError<O extends OptionDefinition>(
final String name,
final CommandDefinition<O> command,
final ParserSettings settings,
) {
final suggestions = similarCommandSuggestions(
name,
command.subcommands,
settings.suggestionDistanceLimit,
);
return '$unknownSubcommandErrorPrefix"$name"$suggestions';
}

void _assignOption<O extends OptionDefinition>({
required final ArgParseResult<O> result,
required final ArgParseResult<O> target,
Expand Down Expand Up @@ -577,7 +600,7 @@ bool _enterMatchedSubcommand<O extends OptionDefinition>({
required final _ArgCursor scannedArgs,
required final CommandDefinition<O>? command,
required final Map<ConfigOptionBase, ArgParseResult<O>> persistentOwners,
required final ScanMode scanMode,
required final ParserSettings settings,
required final String name,
}) {
final subcommands = command?.subcommands;
Expand All @@ -589,7 +612,7 @@ bool _enterMatchedSubcommand<O extends OptionDefinition>({
command: subcommand,
parent: result,
inheritedPersistentOwners: persistentOwners,
scanMode: scanMode,
settings: settings,
);
return true;
}
Expand Down
25 changes: 25 additions & 0 deletions packages/config/lib/src/config/arg_parser/parser_settings.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
enum DoubleDashHandling {
/// No special handling means it is treated as any other word.
noSpecialHandling,

/// When `--` is not taken as an option value, leave the following
/// arguments unparsed. A `--` used as a value does not start this,
/// so a later `--` still can.
passThroughRest,
}

class ParserSettings {
/// How to handle a standalone `--`.
final DoubleDashHandling doubleDashHandling;

/// The maximum edit distance allowed when suggesting possible intended
/// commands.
///
/// Set to `0` in order to disable suggestions, defaults to `2`.
final int suggestionDistanceLimit;

const ParserSettings({
this.doubleDashHandling = DoubleDashHandling.noSpecialHandling,
this.suggestionDistanceLimit = 2,
});
}
18 changes: 0 additions & 18 deletions packages/config/lib/src/config/arg_parser/scanner.dart
Original file line number Diff line number Diff line change
Expand Up @@ -50,24 +50,6 @@ final class ScannedArg {
const ScannedArg(this.raw, this.tokens);
}

enum DoubleDashHandling {
/// No special handling means it is treated as any other word.
noSpecialHandling,

/// When `--` is not taken as an option value, leave the following
/// arguments unparsed. A `--` used as a value does not start this,
/// so a later `--` still can.
passThroughRest,
}

class ScanMode {
final DoubleDashHandling doubleDashHandling;

const ScanMode({
this.doubleDashHandling = DoubleDashHandling.noSpecialHandling,
});
}

/// Scans command-line arguments into one [ScannedArg] per argument.
///
/// Does not validate and does not throw [Exception]s.
Expand Down
88 changes: 88 additions & 0 deletions packages/config/lib/src/config/arg_parser/suggestions.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// Returns help text for commands similar to `name`, in sorted order.
import 'dart:collection' show SplayTreeSet;
import 'dart:math' as math;

import 'command_definition.dart';

String similarCommandSuggestions(
final String name,
final Iterable<CommandDefinition> commands,
final int suggestionDistanceLimit,
) {
final candidates = similarCommands(name, commands, suggestionDistanceLimit);
if (candidates.isEmpty) return '';
return ' (Did you mean ${candidates.map((final command) => command.name).join(', ')}?)';
}

List<CommandDefinition> similarCommands(
final String name,
final Iterable<CommandDefinition> commands,
final int suggestionDistanceLimit,
) {
if (suggestionDistanceLimit <= 0) return [];
final distances = <CommandDefinition, int>{};
final candidates = SplayTreeSet<CommandDefinition>((final a, final b) {
final byDistance = distances[a]! - distances[b]!;
if (byDistance != 0) return byDistance;
return a.name.compareTo(b.name);
});
for (final command in commands) {
if (command.usageDefinition.hidden) continue;
int? bestDistance;
for (final alias in [
command.name,
...command.aliasesDefinition.aliases,
...command.aliasesDefinition.suggestionAliases,
]) {
final distance = _editDistance(name, alias);
if (distance <= suggestionDistanceLimit) {
bestDistance = math.min(bestDistance ?? distance, distance);
}
}
if (bestDistance == null) continue;
distances[command] = bestDistance;
candidates.add(command);
}
return candidates.toList();
}

/// Returns the edit distance between `from` and `to`.
//
/// Allows for edits, deletes, substitutions, and swaps all as single cost.
///
/// See https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance#Optimal_string_alignment_distance
int _editDistance(String from, String to) {
// Add a space in front to mimic indexing by 1 instead of 0.
from = ' $from';
to = ' $to';
final distances = [
for (var i = 0; i < from.length; i++)
[
for (var j = 0; j < to.length; j++)
if (i == 0) j else if (j == 0) i else 0,
],
];

for (var i = 1; i < from.length; i++) {
for (var j = 1; j < to.length; j++) {
// Removals from `from`.
var min = distances[i - 1][j] + 1;
// Additions to `from`.
min = math.min(min, distances[i][j - 1] + 1);
// Substitutions (and equality).
min = math.min(
min,
distances[i - 1][j - 1] +
// Cost is zero if substitution was not actually necessary.
(from[i] == to[j] ? 0 : 1),
);
// Allows for basic swaps, but no additional edits of swapped regions.
if (i > 1 && j > 1 && from[i] == to[j - 1] && from[i - 1] == to[j]) {
min = math.min(min, distances[i - 2][j - 2] + 1);
}
distances[i][j] = min;
}
}

return distances.last.last;
}
Loading
Loading