import '../../config.dart' show OptionDefinition, Configuration, ValueSourceType; import 'abstract_command.dart'; import 'action_option.dart'; import 'builtin_global_option.dart'; import 'context_provider.dart'; /// Whether a command context is being used to run or to complete the command line. enum CommandRunMode { /// The command line is being executed. execution, /// The command line is being completed. completion, } /// The configuration context for the individual command being run. /// /// The contexts for the commands on the command line form a linked list /// via the prev and next fields. class CommandContext { final AbstractCommand command; /// Whether this context is part of executing or completing the command line. final CommandRunMode runMode; /// The configuration of the command's own (application-defined) options. final Configuration config; /// The configuration of the command's built-in options. /// Empty for commands without built-in options. final Configuration builtinConfig; /// The context of the preceding command on the command line. /// Null if this is the root command. final CommandContext? prev; /// The context of the succeeding command on the command line. /// Null if this is the leaf command. late final CommandContext? next; /// User-defined objects / state provider. final ContextProvider provider; CommandContext({ required this.command, required this.config, required this.prev, required this.provider, required this.runMode, final Configuration? builtinConfig, }) : builtinConfig = builtinConfig ?? Configuration.fromValues(values: const {}); CommandContext copyWith({ final AbstractCommand? command, final Configuration? config, final Configuration? builtinConfig, final CommandContext? prev, final CommandContext? next, final ContextProvider? provider, final CommandRunMode? runMode, }) { return CommandContext( command: command ?? this.command, config: config ?? this.config, builtinConfig: builtinConfig ?? this.builtinConfig, prev: prev ?? this.prev, provider: provider ?? this.provider, runMode: runMode ?? this.runMode, )..next = next ?? this.next; } /// Returns the root command's context. CommandContext root() { final prevContext = prev; return prevContext == null ? this : prevContext.root(); } /// Returns the leaf command's context. CommandContext leaf() { final nextContext = next; return nextContext == null ? this : nextContext.leaf(); } /// Returns the action options of the command that were specified on the /// command line, if any. /// /// If non-empty, the first one is run instead of the command. List specifiedActionOptions() { final allArgOptions = [ ...config.optionsWhereSource( (final ValueSourceType s) => s == ValueSourceType.arg, ), ...builtinConfig.optionsWhereSource( (final ValueSourceType s) => s == ValueSourceType.arg, ), ]; return allArgOptions .map((final o) => o is ActionOptionMixin ? o : o.option) .whereType() .toList(); } }