aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/shirabe-external-packages/src/symfony/console/command
diff options
context:
space:
mode:
authornsfisis <nsfisis@gmail.com>2026-06-12 01:01:35 +0900
committernsfisis <nsfisis@gmail.com>2026-06-12 01:01:43 +0900
commit1e44f5723e4c0e0903d00a61f254901e612fe5e1 (patch)
tree9c2e1eec364bbf6418a4072ee7767b04c3df0297 /crates/shirabe-external-packages/src/symfony/console/command
parentddf0a624145b618c05c2ee47414545b99b685f37 (diff)
downloadphp-shirabe-1e44f5723e4c0e0903d00a61f254901e612fe5e1.tar.gz
php-shirabe-1e44f5723e4c0e0903d00a61f254901e612fe5e1.tar.zst
php-shirabe-1e44f5723e4c0e0903d00a61f254901e612fe5e1.zip
feat(symfony-console): port Symfony Console and make the workspace compile
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Diffstat (limited to 'crates/shirabe-external-packages/src/symfony/console/command')
-rw-r--r--crates/shirabe-external-packages/src/symfony/console/command/command.rs802
-rw-r--r--crates/shirabe-external-packages/src/symfony/console/command/complete_command.rs503
-rw-r--r--crates/shirabe-external-packages/src/symfony/console/command/dump_completion_command.rs337
-rw-r--r--crates/shirabe-external-packages/src/symfony/console/command/help_command.rs269
-rw-r--r--crates/shirabe-external-packages/src/symfony/console/command/lazy_command.rs395
-rw-r--r--crates/shirabe-external-packages/src/symfony/console/command/list_command.rs269
-rw-r--r--crates/shirabe-external-packages/src/symfony/console/command/mod.rs12
-rw-r--r--crates/shirabe-external-packages/src/symfony/console/command/signalable_command_interface.rs8
8 files changed, 2591 insertions, 4 deletions
diff --git a/crates/shirabe-external-packages/src/symfony/console/command/command.rs b/crates/shirabe-external-packages/src/symfony/console/command/command.rs
index 32965cf..1af9c59 100644
--- a/crates/shirabe-external-packages/src/symfony/console/command/command.rs
+++ b/crates/shirabe-external-packages/src/symfony/console/command/command.rs
@@ -1,18 +1,812 @@
-/// Stub for \Symfony\Component\Console\Command\Command.
-pub trait Command {
+use crate::symfony::console::application::Application;
+use crate::symfony::console::completion::completion_input::CompletionInput;
+use crate::symfony::console::completion::completion_suggestions::CompletionSuggestions;
+use crate::symfony::console::exception::invalid_argument_exception::InvalidArgumentException;
+use crate::symfony::console::exception::logic_exception::LogicException;
+use crate::symfony::console::helper::helper_set::HelperSet;
+use crate::symfony::console::input::input_argument::InputArgument;
+use crate::symfony::console::input::input_definition::InputDefinition;
+use crate::symfony::console::input::input_interface::InputInterface;
+use crate::symfony::console::input::input_option::InputOption;
+use crate::symfony::console::output::output_interface::{self, OutputInterface};
+use indexmap::IndexMap;
+use shirabe_php_shim::PhpMixed;
+use std::cell::RefCell;
+use std::rc::Rc;
+
+/// Base class for all commands.
+///
+/// Phase B: the PHP `Command` class is split into the polymorphic `Command` trait
+/// (defined below) and this concrete `BaseCommand` struct holding the base-class
+/// state and behavior. Subclasses embed a `BaseCommand` and implement `Command`.
+pub struct BaseCommand {
+ application: Option<Rc<RefCell<Application>>>,
+ name: Option<String>,
+ process_title: Option<String>,
+ aliases: Vec<String>,
+ definition: Option<InputDefinition>,
+ hidden: bool,
+ help: String,
+ description: String,
+ full_definition: Option<InputDefinition>,
+ ignore_validation_errors: bool,
+ // A callable(InputInterface, OutputInterface) -> i64.
+ code: Option<Box<dyn Fn(&mut dyn InputInterface, &mut dyn OutputInterface) -> PhpMixed>>,
+ synopsis: IndexMap<String, String>,
+ usages: Vec<String>,
+ helper_set: Option<Rc<RefCell<HelperSet>>>,
+}
+
+impl BaseCommand {
+ // see https://tldp.org/LDP/abs/html/exitcodes.html
+ pub const SUCCESS: i64 = 0;
+ pub const FAILURE: i64 = 1;
+ pub const INVALID: i64 = 2;
+
+ /// The default command name.
+ // NOTE: PHP `protected static $defaultName`; static late-binding property.
+ pub const DEFAULT_NAME: Option<&'static str> = None;
+
+ /// The default command description.
+ // NOTE: PHP `protected static $defaultDescription`; static late-binding property.
+ pub const DEFAULT_DESCRIPTION: Option<&'static str> = None;
+
+ pub fn get_default_name() -> Option<String> {
+ // TODO(review): PHP uses ReflectionClass to read the #[AsCommand] attribute
+ // and ReflectionProperty to check that `$defaultName` is declared on the late-static
+ // class itself (not inherited). Reflection-based late static binding cannot be
+ // reproduced in Phase A; human review needed for the porting strategy.
+ todo!()
+ }
+
+ pub fn get_default_description() -> Option<String> {
+ // TODO(review): same Reflection/late-static-binding concern as get_default_name().
+ todo!()
+ }
+
+ /// `$name` is the name of the command; passing None means it must be set in configure().
+ ///
+ /// Throws LogicException when the command name is empty.
+ pub fn __construct(name: Option<String>) -> anyhow::Result<Self> {
+ let mut this = BaseCommand {
+ application: None,
+ name: None,
+ process_title: None,
+ aliases: Vec::new(),
+ definition: Some(InputDefinition::new(Vec::new())?),
+ hidden: false,
+ help: String::new(),
+ description: String::new(),
+ full_definition: None,
+ ignore_validation_errors: false,
+ code: None,
+ synopsis: IndexMap::new(),
+ usages: Vec::new(),
+ helper_set: None,
+ };
+
+ let mut name = name;
+ if name.is_none() {
+ name = Self::get_default_name();
+ if let Some(n) = name.clone() {
+ let mut aliases: Vec<String> = n.split('|').map(|s| s.to_string()).collect();
+
+ let first = if aliases.is_empty() {
+ None
+ } else {
+ Some(aliases.remove(0))
+ };
+ name = first;
+ if name.as_deref() == Some("") {
+ this.set_hidden(true);
+ name = if aliases.is_empty() {
+ None
+ } else {
+ Some(aliases.remove(0))
+ };
+ }
+
+ this.set_aliases(aliases)?;
+ }
+ }
+
+ if let Some(n) = name {
+ this.set_name(&n)?;
+ }
+
+ if this.description.is_empty() {
+ this.set_description(&Self::get_default_description().unwrap_or_default());
+ }
+
+ this.configure();
+
+ Ok(this)
+ }
+
+ /// Ignores validation errors.
+ ///
+ /// This is mainly useful for the help command.
+ pub fn ignore_validation_errors(&mut self) {
+ self.ignore_validation_errors = true;
+ }
+
+ pub fn set_application(&mut self, application: Option<Rc<RefCell<Application>>>) {
+ self.application = application.clone();
+ if let Some(application) = application {
+ self.set_helper_set(application.borrow_mut().get_helper_set());
+ } else {
+ self.helper_set = None;
+ }
+
+ self.full_definition = None;
+ }
+
+ pub fn set_helper_set(&mut self, helper_set: Rc<RefCell<HelperSet>>) {
+ self.helper_set = Some(helper_set);
+ }
+
+ /// Gets the helper set.
+ pub fn get_helper_set(&self) -> Option<Rc<RefCell<HelperSet>>> {
+ self.helper_set.clone()
+ }
+
+ /// Gets the application instance for this command.
+ pub fn get_application(&self) -> Option<Rc<RefCell<Application>>> {
+ self.application.clone()
+ }
+
+ /// Checks whether the command is enabled or not in the current environment.
+ ///
+ /// Override this to check for x or y and return false if the command cannot
+ /// run properly under the current conditions.
+ pub fn is_enabled(&self) -> bool {
+ true
+ }
+
+ /// Configures the current command.
+ pub fn configure(&mut self) {}
+
+ /// Executes the current command.
+ ///
+ /// This method is not abstract because you can use this class
+ /// as a concrete class. In this case, instead of defining the
+ /// execute() method, you set the code to execute by passing
+ /// a Closure to the set_code() method.
+ ///
+ /// Returns 0 if everything went fine, or an exit code.
+ ///
+ /// Throws LogicException when this abstract method is not implemented.
+ pub fn execute(
+ &mut self,
+ _input: &mut dyn InputInterface,
+ _output: &mut dyn OutputInterface,
+ ) -> anyhow::Result<Result<i64, LogicException>> {
+ Ok(Err(LogicException(shirabe_php_shim::LogicException {
+ message: "You must override the execute() method in the concrete command class."
+ .to_string(),
+ code: 0,
+ })))
+ }
+
+ /// Interacts with the user.
+ ///
+ /// This method is executed before the InputDefinition is validated.
+ /// This means that this is the only place where the command can
+ /// interactively ask for values of missing required arguments.
+ pub fn interact(&mut self, _input: &mut dyn InputInterface, _output: &mut dyn OutputInterface) {
+ }
+
+ /// Initializes the command after the input has been bound and before the input
+ /// is validated.
+ ///
+ /// This is mainly useful when a lot of commands extends one main command
+ /// where some things need to be initialized based on the input arguments and options.
+ pub fn initialize(
+ &mut self,
+ _input: &mut dyn InputInterface,
+ _output: &mut dyn OutputInterface,
+ ) {
+ }
+
+ /// Runs the command.
+ ///
+ /// The code to execute is either defined directly with the
+ /// set_code() method or by overriding the execute() method
+ /// in a sub-class.
+ ///
+ /// Returns the command exit code.
+ ///
+ /// Throws ExceptionInterface when input binding fails. Bypass this by calling ignore_validation_errors().
+ pub fn run(
+ &mut self,
+ input: &mut dyn InputInterface,
+ output: &mut dyn OutputInterface,
+ ) -> anyhow::Result<i64> {
+ // add the application arguments and options
+ self.merge_application_definition(true);
+
+ // bind the input against the command specific arguments/options
+ match input.bind(self.get_definition()) {
+ Ok(()) => {}
+ Err(e) => {
+ if !self.ignore_validation_errors {
+ return Err(e);
+ }
+ }
+ }
+
+ self.initialize(input, output);
+
+ if let Some(process_title) = &self.process_title {
+ // TODO: PHP probes for cli_set_process_title / setproctitle availability.
+ if shirabe_php_shim::function_exists("cli_set_process_title") {
+ if !shirabe_php_shim::cli_set_process_title(process_title) {
+ if shirabe_php_shim::PHP_OS == "Darwin" {
+ output.writeln(
+ &["<comment>Running \"cli_set_process_title\" as an unprivileged user is not supported on MacOS.</comment>".to_string()],
+ output_interface::VERBOSITY_VERY_VERBOSE,
+ );
+ } else {
+ shirabe_php_shim::cli_set_process_title(process_title);
+ }
+ }
+ } else if shirabe_php_shim::function_exists("setproctitle") {
+ shirabe_php_shim::setproctitle(process_title);
+ } else if output.get_verbosity() == output_interface::VERBOSITY_VERY_VERBOSE {
+ output.writeln(
+ &["<comment>Install the proctitle PECL to be able to change the process title.</comment>".to_string()],
+ output_interface::OUTPUT_NORMAL,
+ );
+ }
+ }
+
+ if input.is_interactive() {
+ self.interact(input, output);
+ }
+
+ // The command name argument is often omitted when a command is executed directly with its run() method.
+ // It would fail the validation if we didn't make sure the command argument is present,
+ // since it's required by the application.
+ if input.has_argument("command") && matches!(input.get_argument("command")?, PhpMixed::Null)
+ {
+ input.set_argument("command", PhpMixed::from(self.get_name()))?;
+ }
+
+ input.validate()?;
+
+ let status_code: PhpMixed;
+ if let Some(code) = &self.code {
+ status_code = code(input, output);
+ } else {
+ let executed = self.execute(input, output)?;
+ let executed = match executed {
+ Ok(v) => v,
+ Err(e) => return Err(anyhow::Error::new(e)),
+ };
+ status_code = PhpMixed::from(executed);
+ // PHP also raises \TypeError when execute() does not return int; in this
+ // strongly-typed port execute() already returns an int, so the check is moot.
+ }
+
+ // is_numeric($statusCode) ? (int) $statusCode : 0
+ Ok(shirabe_php_shim::is_numeric_to_int(&status_code))
+ }
+
+ /// Adds suggestions to `suggestions` for the current completion input (e.g. option or argument).
+ pub fn complete(&self, _input: &CompletionInput, _suggestions: &mut CompletionSuggestions) {}
+
+ /// Sets the code to execute when running this command.
+ ///
+ /// If this method is used, it overrides the code defined
+ /// in the execute() method.
+ ///
+ /// `$code` is a callable(InputInterface, OutputInterface).
+ ///
+ /// Throws InvalidArgumentException.
+ pub fn set_code(
+ &mut self,
+ code: Box<dyn Fn(&mut dyn InputInterface, &mut dyn OutputInterface) -> PhpMixed>,
+ ) -> &mut Self {
+ // TODO: PHP rebinds an unbound Closure's $this to the command instance via
+ // ReflectionFunction/Closure::bind. Rust closures have no `$this` rebinding;
+ // the closure is stored as-is.
+ self.code = Some(code);
+
+ self
+ }
+
+ /// Merges the application definition with the command definition.
+ ///
+ /// This method is not part of public API and should not be used directly.
+ ///
+ /// `$mergeArgs` is whether to merge or not the Application definition arguments to Command definition arguments.
+ pub fn merge_application_definition(&mut self, merge_args: bool) {
+ let _application = match &self.application {
+ None => return,
+ Some(application) => application.clone(),
+ };
+
+ // TODO: InputDefinition stores options/arguments as `Rc<InputOption>` /
+ // `Rc<InputArgument>` but its setters (`set_options`/`set_arguments`) take owned
+ // `Vec<InputOption>` / `Vec<InputArgument>`. Merging the application and command
+ // definitions therefore requires an agreed-upon ownership model for the
+ // definition entries (Phase C). Left as todo!() pending that design.
+ let _ = merge_args;
+ todo!()
+ }
+
+ /// Sets an array of argument and option instances.
+ ///
+ /// `$definition` is an array of argument and option instances or a definition instance.
+ pub fn set_definition(&mut self, definition: SetDefinitionArg) -> &mut Self {
+ match definition {
+ SetDefinitionArg::Definition(definition) => {
+ self.definition = Some(definition);
+ }
+ SetDefinitionArg::Array(definition) => {
+ let _ = self.definition.as_mut().unwrap().set_definition(definition);
+ }
+ }
+
+ self.full_definition = None;
+
+ self
+ }
+
+ /// Gets the InputDefinition attached to this Command.
+ pub fn get_definition(&self) -> &InputDefinition {
+ match &self.full_definition {
+ Some(full_definition) => full_definition,
+ None => self.get_native_definition(),
+ }
+ }
+
+ /// Gets the InputDefinition to be used to create representations of this Command.
+ ///
+ /// Can be overridden to provide the original command representation when it would otherwise
+ /// be changed by merging with the application InputDefinition.
+ ///
+ /// This method is not part of public API and should not be used directly.
+ pub fn get_native_definition(&self) -> &InputDefinition {
+ match &self.definition {
+ None => {
+ // TODO(review): PHP throws LogicException here, but get_native_definition()
+ // returns InputDefinition (no Result). In this port `definition` is set in
+ // the constructor, so None should not occur; treated as a programming error.
+ panic!(
+ "Command class is not correctly initialized. You probably forgot to call the parent constructor."
+ );
+ }
+ Some(definition) => definition,
+ }
+ }
+
+ /// Adds an argument.
+ ///
+ /// `$mode` is the argument mode: InputArgument::REQUIRED or InputArgument::OPTIONAL.
+ /// `$default` is the default value (for InputArgument::OPTIONAL mode only).
+ ///
+ /// Throws InvalidArgumentException when argument mode is not valid.
+ pub fn add_argument(
+ &mut self,
+ name: &str,
+ mode: Option<i64>,
+ description: &str,
+ default: PhpMixed,
+ ) -> anyhow::Result<&mut Self> {
+ self.definition
+ .as_mut()
+ .unwrap()
+ .add_argument(InputArgument::new(
+ name.to_string(),
+ mode,
+ description.to_string(),
+ default.clone(),
+ )?)?;
+ if self.full_definition.is_some() {
+ self.full_definition
+ .as_mut()
+ .unwrap()
+ .add_argument(InputArgument::new(
+ name.to_string(),
+ mode,
+ description.to_string(),
+ default,
+ )?)?;
+ }
+
+ Ok(self)
+ }
+
+ /// Adds an option.
+ ///
+ /// `$shortcut` is the shortcuts, can be null, a string of shortcuts delimited by | or an array of shortcuts.
+ /// `$mode` is the option mode: One of the InputOption::VALUE_* constants.
+ /// `$default` is the default value (must be null for InputOption::VALUE_NONE).
+ ///
+ /// Throws InvalidArgumentException if option mode is invalid or incompatible.
+ pub fn add_option(
+ &mut self,
+ name: &str,
+ shortcut: PhpMixed,
+ mode: Option<i64>,
+ description: &str,
+ default: PhpMixed,
+ ) -> anyhow::Result<&mut Self> {
+ self.definition
+ .as_mut()
+ .unwrap()
+ .add_option(InputOption::new(
+ name,
+ shortcut.clone(),
+ mode,
+ description.to_string(),
+ default.clone(),
+ )?)?;
+ if self.full_definition.is_some() {
+ self.full_definition
+ .as_mut()
+ .unwrap()
+ .add_option(InputOption::new(
+ name,
+ shortcut,
+ mode,
+ description.to_string(),
+ default,
+ )?)?;
+ }
+
+ Ok(self)
+ }
+
+ /// Sets the name of the command.
+ ///
+ /// This method can set both the namespace and the name if
+ /// you separate them by a colon (:)
+ ///
+ /// command.set_name("foo:bar");
+ ///
+ /// Throws InvalidArgumentException when the name is invalid.
+ pub fn set_name(&mut self, name: &str) -> anyhow::Result<&mut Self> {
+ if let Err(e) = self.validate_name(name)? {
+ return Err(e.into());
+ }
+
+ self.name = Some(name.to_string());
+
+ Ok(self)
+ }
+
+ /// Sets the process title of the command.
+ ///
+ /// This feature should be used only when creating a long process command,
+ /// like a daemon.
+ pub fn set_process_title(&mut self, title: &str) -> &mut Self {
+ self.process_title = Some(title.to_string());
+
+ self
+ }
+
+ /// Returns the command name.
+ pub fn get_name(&self) -> Option<String> {
+ self.name.clone()
+ }
+
+ /// `$hidden` is whether or not the command should be hidden from the list of commands.
+ pub fn set_hidden(&mut self, hidden: bool) -> &mut Self {
+ self.hidden = hidden;
+
+ self
+ }
+
+ /// Returns whether the command should be publicly shown or not.
+ pub fn is_hidden(&self) -> bool {
+ self.hidden
+ }
+
+ /// Sets the description for the command.
+ pub fn set_description(&mut self, description: &str) -> &mut Self {
+ self.description = description.to_string();
+
+ self
+ }
+
+ /// Returns the description for the command.
+ pub fn get_description(&self) -> String {
+ self.description.clone()
+ }
+
+ /// Sets the help for the command.
+ pub fn set_help(&mut self, help: &str) -> &mut Self {
+ self.help = help.to_string();
+
+ self
+ }
+
+ /// Returns the help for the command.
+ pub fn get_help(&self) -> String {
+ self.help.clone()
+ }
+
+ /// Returns the processed help for the command replacing the %command.name% and
+ /// %command.full_name% patterns with the real values dynamically.
+ pub fn get_processed_help(&self) -> String {
+ let name = self.name.clone();
+ let is_single_command = match &self.application {
+ Some(application) => application.borrow().is_single_command(),
+ None => false,
+ };
+
+ let placeholders = [
+ "%command.name%".to_string(),
+ "%command.full_name%".to_string(),
+ ];
+ let php_self = shirabe_php_shim::server("PHP_SELF");
+ let replacements = [
+ name.clone().unwrap_or_default(),
+ if is_single_command {
+ php_self.clone()
+ } else {
+ format!("{} {}", php_self, name.unwrap_or_default())
+ },
+ ];
+
+ let help = self.get_help();
+ let subject = if help.is_empty() {
+ self.get_description()
+ } else {
+ help
+ };
+
+ shirabe_php_shim::str_replace_array(&placeholders, &replacements, &subject)
+ }
+
+ /// Sets the aliases for the command.
+ ///
+ /// `$aliases` is an array of aliases for the command.
+ ///
+ /// Throws InvalidArgumentException when an alias is invalid.
+ pub fn set_aliases(&mut self, aliases: Vec<String>) -> anyhow::Result<&mut Self> {
+ let mut list = Vec::new();
+
+ for alias in &aliases {
+ if let Err(e) = self.validate_name(alias)? {
+ return Err(e.into());
+ }
+ list.push(alias.clone());
+ }
+
+ // PHP: `\is_array($aliases) ? $aliases : $list`. Here `aliases` is always an
+ // array (Vec), so the result is `aliases`; `list` mirrors the validation loop.
+ self.aliases = aliases;
+
+ Ok(self)
+ }
+
+ /// Returns the aliases for the command.
+ pub fn get_aliases(&self) -> Vec<String> {
+ self.aliases.clone()
+ }
+
+ /// Returns the synopsis for the command.
+ ///
+ /// `$short` is whether to show the short version of the synopsis (with options folded) or not.
+ pub fn get_synopsis(&mut self, short: bool) -> String {
+ let key = if short { "short" } else { "long" }.to_string();
+
+ if !self.synopsis.contains_key(&key) {
+ let value = format!(
+ "{} {}",
+ self.name.clone().unwrap_or_default(),
+ self.definition.as_ref().unwrap().get_synopsis(short)
+ )
+ .trim()
+ .to_string();
+ self.synopsis.insert(key.clone(), value);
+ }
+
+ self.synopsis[&key].clone()
+ }
+
+ /// Add a command usage example, it'll be prefixed with the command name.
+ pub fn add_usage(&mut self, usage: &str) -> &mut Self {
+ let mut usage = usage.to_string();
+ let name = self.name.clone().unwrap_or_default();
+ if !usage.starts_with(&name) {
+ usage = format!("{} {}", name, usage);
+ }
+
+ self.usages.push(usage);
+
+ self
+ }
+
+ /// Returns alternative usages of the command.
+ pub fn get_usages(&self) -> Vec<String> {
+ self.usages.clone()
+ }
+
+ /// Gets a helper instance by name.
+ ///
+ /// Throws LogicException if no HelperSet is defined.
+ /// Throws InvalidArgumentException if the helper is not defined.
+ pub fn get_helper(&self, name: &str) -> anyhow::Result<Result<PhpMixed, LogicException>> {
+ let helper_set = match &self.helper_set {
+ None => {
+ return Ok(Err(LogicException(shirabe_php_shim::LogicException {
+ message: format!(
+ "Cannot retrieve helper \"{}\" because there is no HelperSet defined. Did you forget to add your command to the application or to set the application on the command using the setApplication() method? You can also set the HelperSet directly using the setHelperSet() method.",
+ name
+ ),
+ code: 0,
+ })));
+ }
+ Some(helper_set) => helper_set,
+ };
+
+ // TODO(review): HelperSet::get() returns `Rc<RefCell<dyn HelperInterface>>`, but
+ // Command::getHelper() is typed `mixed` (PhpMixed) here and PhpMixed cannot hold a
+ // helper instance. The helper return modelling needs a dedicated type (Phase C).
+ let _ = helper_set;
+ todo!()
+ }
+
+ /// Validates a command name.
+ ///
+ /// It must be non-empty and parts can optionally be separated by ":".
+ ///
+ /// Throws InvalidArgumentException when the name is invalid.
+ fn validate_name(&self, name: &str) -> anyhow::Result<Result<(), InvalidArgumentException>> {
+ let mut matches: Vec<Option<String>> = Vec::new();
+ if shirabe_php_shim::preg_match(r"/^[^\:]++(\:[^\:]++)*$/", name, &mut matches) == 0 {
+ return Ok(Err(InvalidArgumentException(
+ shirabe_php_shim::InvalidArgumentException {
+ message: format!("Command name \"{}\" is invalid.", name),
+ code: 0,
+ },
+ )));
+ }
+
+ Ok(Ok(()))
+ }
+}
+
+/// The argument of Command::set_definition(), which accepts either an array of
+/// argument/option instances or an InputDefinition.
+#[derive(Debug)]
+pub enum SetDefinitionArg {
+ Array(Vec<crate::symfony::console::input::input_definition::DefinitionItem>),
+ Definition(InputDefinition),
+}
+
+/// Polymorphic interface for all commands (PHP's `Command` base class as seen by
+/// callers that hold a command of unknown concrete type).
+///
+/// Phase B: default methods are `todo!()`; the concrete behavior lives on
+/// `BaseCommand`'s inherent methods. Object-safe so `dyn Command` works.
+pub trait Command: std::fmt::Debug + shirabe_php_shim::AsAny {
+ fn clone_box(&self) -> Box<dyn Command> {
+ todo!()
+ }
+
+ fn configure(&mut self) {
+ todo!()
+ }
+
+ fn run(
+ &mut self,
+ _input: &mut dyn InputInterface,
+ _output: &mut dyn OutputInterface,
+ ) -> anyhow::Result<i64> {
+ todo!()
+ }
+
+ fn complete(&self, _input: &CompletionInput, _suggestions: &mut CompletionSuggestions) {
+ todo!()
+ }
+
+ fn is_enabled(&self) -> bool {
+ todo!()
+ }
+
+ fn set_application(&mut self, _application: Option<Rc<RefCell<Application>>>) {
+ todo!()
+ }
+
+ fn get_application(&self) -> Option<Rc<RefCell<Application>>> {
+ todo!()
+ }
+
+ fn set_helper_set(&mut self, _helper_set: Rc<RefCell<HelperSet>>) {
+ todo!()
+ }
+
+ fn get_helper_set(&self) -> Option<Rc<RefCell<HelperSet>>> {
+ todo!()
+ }
+
+ fn merge_application_definition(&mut self, _merge_args: bool) {
+ todo!()
+ }
+
+ fn get_definition(&self) -> &InputDefinition {
+ todo!()
+ }
+
+ fn get_native_definition(&self) -> &InputDefinition {
+ todo!()
+ }
+
+ fn set_name(&mut self, _name: &str) -> anyhow::Result<()> {
+ todo!()
+ }
+
fn get_name(&self) -> Option<String> {
todo!()
}
- fn set_name(&mut self, _name: &str) {
+ fn set_hidden(&mut self, _hidden: bool) {
todo!()
}
- fn get_description(&self) -> String {
+ fn is_hidden(&self) -> bool {
todo!()
}
fn set_description(&mut self, _description: &str) {
todo!()
}
+
+ fn get_description(&self) -> String {
+ todo!()
+ }
+
+ fn set_help(&mut self, _help: &str) {
+ todo!()
+ }
+
+ fn get_help(&self) -> String {
+ todo!()
+ }
+
+ fn get_processed_help(&self) -> String {
+ todo!()
+ }
+
+ fn set_aliases(&mut self, _aliases: Vec<String>) -> anyhow::Result<()> {
+ todo!()
+ }
+
+ fn get_aliases(&self) -> Vec<String> {
+ todo!()
+ }
+
+ fn get_synopsis(&mut self, _short: bool) -> String {
+ todo!()
+ }
+
+ fn get_usages(&self) -> Vec<String> {
+ todo!()
+ }
+
+ fn get_helper(&self, _name: &str) -> anyhow::Result<Result<PhpMixed, LogicException>> {
+ todo!()
+ }
+
+ fn ignore_validation_errors(&mut self) {
+ todo!()
+ }
+}
+
+impl Command for BaseCommand {}
+
+impl std::fmt::Debug for BaseCommand {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("BaseCommand")
+ .field("name", &self.name)
+ .field("aliases", &self.aliases)
+ .field("hidden", &self.hidden)
+ .field("description", &self.description)
+ .finish_non_exhaustive()
+ }
}
diff --git a/crates/shirabe-external-packages/src/symfony/console/command/complete_command.rs b/crates/shirabe-external-packages/src/symfony/console/command/complete_command.rs
new file mode 100644
index 0000000..7a986ec
--- /dev/null
+++ b/crates/shirabe-external-packages/src/symfony/console/command/complete_command.rs
@@ -0,0 +1,503 @@
+use indexmap::IndexMap;
+use shirabe_php_shim::AsAny;
+use shirabe_php_shim::PhpMixed;
+use std::cell::RefCell;
+use std::ops::{Deref, DerefMut};
+use std::rc::Rc;
+
+use crate::symfony::console::command::command::{BaseCommand, Command};
+use crate::symfony::console::command::lazy_command::LazyCommand;
+use crate::symfony::console::completion::completion_input::CompletionInput;
+use crate::symfony::console::completion::completion_suggestions::{
+ CompletionSuggestions, StringOrSuggestion,
+};
+use crate::symfony::console::completion::output::completion_output_interface::CompletionOutputInterface;
+use crate::symfony::console::input::input_interface::InputInterface;
+use crate::symfony::console::input::input_option::InputOption;
+use crate::symfony::console::output::output_interface::{self, OutputInterface};
+
+/// Responsible for providing the values to the shell completion.
+#[derive(Debug)]
+pub struct CompleteCommand {
+ inner: BaseCommand,
+ completion_outputs: IndexMap<String, PhpMixed>,
+ is_debug: bool,
+}
+
+impl Deref for CompleteCommand {
+ type Target = BaseCommand;
+
+ fn deref(&self) -> &Self::Target {
+ &self.inner
+ }
+}
+
+impl DerefMut for CompleteCommand {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ &mut self.inner
+ }
+}
+
+impl CompleteCommand {
+ pub const DEFAULT_NAME: &'static str = "|_complete";
+ pub const DEFAULT_DESCRIPTION: &'static str =
+ "Internal command to provide shell completion suggestions";
+
+ /// @param completion_outputs A list of additional completion outputs, with shell name as
+ /// key and FQCN as value
+ pub fn new(completion_outputs: IndexMap<String, PhpMixed>) -> anyhow::Result<Self> {
+ // must be set before the parent constructor, as the property value is used in configure()
+ let mut completion_outputs = completion_outputs;
+ // $completionOutputs + ['bash' => BashCompletionOutput::class]
+ completion_outputs
+ .entry("bash".to_string())
+ .or_insert_with(|| {
+ PhpMixed::from(
+ "Symfony\\Component\\Console\\Completion\\Output\\BashCompletionOutput"
+ .to_string(),
+ )
+ });
+
+ let this = Self {
+ inner: BaseCommand::__construct(None)?,
+ completion_outputs,
+ is_debug: false,
+ };
+
+ Ok(this)
+ }
+
+ fn configure(&mut self) -> anyhow::Result<()> {
+ let shells = self
+ .completion_outputs
+ .keys()
+ .cloned()
+ .collect::<Vec<_>>()
+ .join("\", \"");
+ self.inner
+ .add_option(
+ "shell",
+ PhpMixed::from("s".to_string()),
+ Some(InputOption::VALUE_REQUIRED),
+ &format!("The shell type (\"{}\")", shells),
+ PhpMixed::Null,
+ )?
+ .add_option(
+ "input",
+ PhpMixed::from("i".to_string()),
+ Some(InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY),
+ "An array of input tokens (e.g. COMP_WORDS or argv)",
+ PhpMixed::Null,
+ )?
+ .add_option(
+ "current",
+ PhpMixed::from("c".to_string()),
+ Some(InputOption::VALUE_REQUIRED),
+ "The index of the \"input\" array that the cursor is in (e.g. COMP_CWORD)",
+ PhpMixed::Null,
+ )?
+ .add_option(
+ "symfony",
+ PhpMixed::from("S".to_string()),
+ Some(InputOption::VALUE_REQUIRED),
+ "The version of the completion script",
+ PhpMixed::Null,
+ )?;
+
+ Ok(())
+ }
+
+ fn initialize(&mut self, _input: &dyn InputInterface, _output: &dyn OutputInterface) {
+ self.is_debug = shirabe_php_shim::filter_var(
+ &shirabe_php_shim::getenv("SYMFONY_COMPLETION_DEBUG").unwrap_or_default(),
+ shirabe_php_shim::FILTER_VALIDATE_BOOLEAN,
+ );
+ }
+
+ fn execute(
+ &mut self,
+ input: &mut dyn InputInterface,
+ output: &mut dyn OutputInterface,
+ ) -> anyhow::Result<i64> {
+ // try { ... } catch (\Throwable $e) { ...; if ($output->isDebug()) { throw $e; } return 2; }
+ let result: anyhow::Result<i64> = (|| {
+ // uncomment when a bugfix or BC break has been introduced in the shell completion scripts
+ // $version = $input->getOption('symfony');
+ // if ($version && version_compare($version, 'x.y', '>=')) {
+ // $message = sprintf('Completion script version is not supported ("%s" given, ">=x.y" required).', $version);
+ // $this->log($message);
+ // $output->writeln($message.' Install the Symfony completion script again by using the "completion" command.');
+ // return 126;
+ // }
+
+ let shell = input.get_option("shell")?;
+ if !shell.to_bool() {
+ anyhow::bail!(shirabe_php_shim::RuntimeException {
+ message: "The \"--shell\" option must be set.".to_string(),
+ code: 0,
+ });
+ }
+
+ let completion_output = self
+ .completion_outputs
+ .get(&shell.to_string())
+ .cloned()
+ .unwrap_or(PhpMixed::Bool(false));
+ if !completion_output.to_bool() {
+ anyhow::bail!(shirabe_php_shim::RuntimeException {
+ message: format!(
+ "Shell completion is not supported for your shell: \"{}\" (supported: \"{}\").",
+ shell,
+ self.completion_outputs
+ .keys()
+ .cloned()
+ .collect::<Vec<_>>()
+ .join("\", \"")
+ ),
+ code: 0,
+ });
+ }
+
+ let mut completion_input = self.create_completion_input(input)?;
+ let mut suggestions = CompletionSuggestions::new();
+
+ self.log_many(vec![
+ String::new(),
+ format!(
+ "<comment>{}</>",
+ shirabe_php_shim::date("Y-m-d H:i:s", None)
+ ),
+ "<info>Input:</> <comment>(\"|\" indicates the cursor position)</>".to_string(),
+ format!(" {}", completion_input.to_string()),
+ "<info>Command:</>".to_string(),
+ format!(" {}", shirabe_php_shim::server_argv().join(" ")),
+ "<info>Messages:</>".to_string(),
+ ]);
+
+ let command = self.find_command(&completion_input, output);
+ match command {
+ None => {
+ self.log(" No command found, completing using the Application class.");
+
+ let application = self.get_application().unwrap();
+ application
+ .borrow_mut()
+ .complete(&completion_input, &mut suggestions)?;
+ }
+ Some(command)
+ if completion_input.must_suggest_argument_values_for("command")
+ && command.borrow().get_name().as_deref()
+ != Some(&completion_input.get_completion_value())
+ && !command
+ .borrow()
+ .get_aliases()
+ .iter()
+ .any(|a| a == &completion_input.get_completion_value()) =>
+ {
+ self.log(" No command found, completing using the Application class.");
+
+ // expand shortcut names ("cache:cl<TAB>") into their full name ("cache:clear")
+ let mut values = vec![command.borrow().get_name()];
+ values.extend(command.borrow().get_aliases().into_iter().map(Some));
+ suggestions.suggest_values(
+ values
+ .into_iter()
+ .flatten()
+ .filter(|v| !v.is_empty())
+ .map(StringOrSuggestion::String)
+ .collect(),
+ );
+ }
+ Some(command) => {
+ command.borrow_mut().merge_application_definition(false);
+ completion_input.bind(command.borrow().get_definition())?;
+
+ if CompletionInput::TYPE_OPTION_NAME == completion_input.get_completion_type() {
+ self.log(&format!(
+ " Completing option names for the <comment>{}</> command.",
+ get_class_of_command(&command)
+ ));
+
+ suggestions.suggest_options(get_definition_options(&command));
+ } else {
+ self.log_many(vec![
+ format!(
+ " Completing using the <comment>{}</> class.",
+ get_class_of_command(&command)
+ ),
+ format!(
+ " Completing <comment>{}</> for <comment>{}</>",
+ completion_input.get_completion_type(),
+ completion_input.get_completion_name().unwrap_or_default()
+ ),
+ ]);
+ let compval = completion_input.get_completion_value();
+ if !compval.is_empty() {
+ self.log(&format!(" Current value: <comment>{}</>", compval));
+ }
+
+ command
+ .borrow()
+ .complete(&completion_input, &mut suggestions);
+ }
+ }
+ }
+
+ // $completionOutput = new $completionOutput();
+ let completion_output: Box<dyn CompletionOutputInterface> =
+ instantiate_completion_output(&completion_output);
+
+ self.log("<info>Suggestions:</>");
+ let option_suggestions = suggestions.get_option_suggestions();
+ if !option_suggestions.is_empty() {
+ self.log(&format!(
+ " --{}",
+ option_suggestions
+ .iter()
+ .map(|o| o.get_name())
+ .collect::<Vec<_>>()
+ .join(" --")
+ ));
+ } else {
+ let value_suggestions: Vec<String> = suggestions
+ .get_value_suggestions()
+ .iter()
+ .map(|s| s.get_value())
+ .collect();
+ if !value_suggestions.is_empty() {
+ self.log(&format!(" {}", value_suggestions.join(" ")));
+ } else {
+ self.log(" <comment>No suggestions were provided</>");
+ }
+ }
+
+ completion_output.write(&suggestions, output);
+
+ Ok(0)
+ })();
+
+ match result {
+ Ok(code) => Ok(code),
+ Err(e) => {
+ self.log_many(vec!["<error>Error!</error>".to_string(), format!("{}", e)]);
+
+ if output.is_debug() {
+ return Err(e);
+ }
+
+ Ok(2)
+ }
+ }
+ }
+
+ fn create_completion_input(
+ &self,
+ input: &dyn InputInterface,
+ ) -> anyhow::Result<CompletionInput> {
+ let current_index = input.get_option("current")?;
+ if !current_index.to_bool() || !shirabe_php_shim::ctype_digit(&current_index.to_string()) {
+ anyhow::bail!(shirabe_php_shim::RuntimeException {
+ message: "The \"--current\" option must be set and it must be an integer."
+ .to_string(),
+ code: 0,
+ });
+ }
+
+ let tokens: Vec<String> = match input.get_option("input")?.as_list() {
+ Some(list) => list.iter().map(|v| v.to_string()).collect(),
+ None => Vec::new(),
+ };
+ let mut completion_input = CompletionInput::from_tokens(
+ tokens,
+ current_index.to_string().parse::<i64>().unwrap_or(0),
+ )?;
+
+ // try { $completionInput->bind(...); } catch (ExceptionInterface $e) {}
+ let application = self.get_application().unwrap();
+ let definition = application.borrow_mut().get_definition();
+ let _ = completion_input.bind(&definition.borrow());
+
+ Ok(completion_input)
+ }
+
+ fn find_command(
+ &self,
+ completion_input: &CompletionInput,
+ _output: &dyn OutputInterface,
+ ) -> Option<Rc<RefCell<dyn Command>>> {
+ // try { ... } catch (CommandNotFoundException $e) {}
+ let input_name = completion_input.get_first_argument()?;
+
+ let application = self.get_application().unwrap();
+ // CommandNotFoundException is caught and swallowed by returning None.
+ application.borrow_mut().find(&input_name).ok()
+ }
+
+ fn log(&self, messages: &str) {
+ self.log_many(vec![messages.to_string()]);
+ }
+
+ fn log_many(&self, messages: Vec<String>) {
+ if !self.is_debug {
+ return;
+ }
+
+ let command_name = shirabe_php_shim::basename(&shirabe_php_shim::server_argv()[0]);
+ shirabe_php_shim::file_put_contents3(
+ &format!(
+ "{}/sf_{}.log",
+ shirabe_php_shim::sys_get_temp_dir(),
+ command_name
+ ),
+ &(messages.join(shirabe_php_shim::PHP_EOL) + shirabe_php_shim::PHP_EOL),
+ shirabe_php_shim::FILE_APPEND,
+ );
+ }
+}
+
+/// \get_class($command instanceof LazyCommand ? $command->getCommand() : $command)
+fn get_class_of_command(command: &Rc<RefCell<dyn Command>>) -> String {
+ let borrowed = command.borrow();
+ let _is_lazy = (*borrowed).as_any().downcast_ref::<LazyCommand>().is_some();
+ // TODO: get_class() takes a PhpMixed but the command is a `dyn Command`; reflecting the
+ // concrete class name of a trait object requires a class-name hook on Command (Phase C).
+ todo!()
+}
+
+/// $command->getDefinition()->getOptions()
+fn get_definition_options(_command: &Rc<RefCell<dyn Command>>) -> Vec<InputOption> {
+ // TODO: InputDefinition::get_options() returns `&IndexMap<String, Rc<InputOption>>` but
+ // CompletionSuggestions::suggest_options() takes `Vec<InputOption>`; the option ownership
+ // model must be reconciled (Phase C).
+ todo!()
+}
+
+/// new $completionOutput();
+fn instantiate_completion_output(_class: &PhpMixed) -> Box<dyn CompletionOutputInterface> {
+ todo!()
+}
+
+impl Command for CompleteCommand {
+ fn configure(&mut self) {
+ let _ = CompleteCommand::configure(self);
+ }
+
+ fn run(
+ &mut self,
+ input: &mut dyn InputInterface,
+ output: &mut dyn OutputInterface,
+ ) -> anyhow::Result<i64> {
+ self.inner.run(input, output)
+ }
+
+ fn is_enabled(&self) -> bool {
+ self.inner.is_enabled()
+ }
+
+ fn set_application(
+ &mut self,
+ application: Option<Rc<RefCell<crate::symfony::console::application::Application>>>,
+ ) {
+ self.inner.set_application(application);
+ }
+
+ fn get_application(
+ &self,
+ ) -> Option<Rc<RefCell<crate::symfony::console::application::Application>>> {
+ self.inner.get_application()
+ }
+
+ fn set_helper_set(
+ &mut self,
+ helper_set: Rc<RefCell<crate::symfony::console::helper::helper_set::HelperSet>>,
+ ) {
+ self.inner.set_helper_set(helper_set);
+ }
+
+ fn get_helper_set(
+ &self,
+ ) -> Option<Rc<RefCell<crate::symfony::console::helper::helper_set::HelperSet>>> {
+ self.inner.get_helper_set()
+ }
+
+ fn merge_application_definition(&mut self, merge_args: bool) {
+ self.inner.merge_application_definition(merge_args);
+ }
+
+ fn get_definition(&self) -> &crate::symfony::console::input::input_definition::InputDefinition {
+ self.inner.get_definition()
+ }
+
+ fn get_native_definition(
+ &self,
+ ) -> &crate::symfony::console::input::input_definition::InputDefinition {
+ self.inner.get_native_definition()
+ }
+
+ fn set_name(&mut self, name: &str) -> anyhow::Result<()> {
+ self.inner.set_name(name)?;
+ Ok(())
+ }
+
+ fn get_name(&self) -> Option<String> {
+ self.inner.get_name()
+ }
+
+ fn set_hidden(&mut self, hidden: bool) {
+ self.inner.set_hidden(hidden);
+ }
+
+ fn is_hidden(&self) -> bool {
+ self.inner.is_hidden()
+ }
+
+ fn set_description(&mut self, description: &str) {
+ self.inner.set_description(description);
+ }
+
+ fn get_description(&self) -> String {
+ self.inner.get_description()
+ }
+
+ fn set_help(&mut self, help: &str) {
+ self.inner.set_help(help);
+ }
+
+ fn get_help(&self) -> String {
+ self.inner.get_help()
+ }
+
+ fn get_processed_help(&self) -> String {
+ self.inner.get_processed_help()
+ }
+
+ fn set_aliases(&mut self, aliases: Vec<String>) -> anyhow::Result<()> {
+ self.inner.set_aliases(aliases)?;
+ Ok(())
+ }
+
+ fn get_aliases(&self) -> Vec<String> {
+ self.inner.get_aliases()
+ }
+
+ fn get_synopsis(&mut self, short: bool) -> String {
+ self.inner.get_synopsis(short)
+ }
+
+ fn get_usages(&self) -> Vec<String> {
+ self.inner.get_usages()
+ }
+
+ fn get_helper(
+ &self,
+ name: &str,
+ ) -> anyhow::Result<
+ Result<PhpMixed, crate::symfony::console::exception::logic_exception::LogicException>,
+ > {
+ self.inner.get_helper(name)
+ }
+
+ fn ignore_validation_errors(&mut self) {
+ self.inner.ignore_validation_errors();
+ }
+}
diff --git a/crates/shirabe-external-packages/src/symfony/console/command/dump_completion_command.rs b/crates/shirabe-external-packages/src/symfony/console/command/dump_completion_command.rs
new file mode 100644
index 0000000..51287c7
--- /dev/null
+++ b/crates/shirabe-external-packages/src/symfony/console/command/dump_completion_command.rs
@@ -0,0 +1,337 @@
+use crate::symfony::console::command::command::{BaseCommand, Command};
+use crate::symfony::console::completion::completion_input::CompletionInput;
+use crate::symfony::console::completion::completion_suggestions::{
+ CompletionSuggestions, StringOrSuggestion,
+};
+use crate::symfony::console::input::input_argument::InputArgument;
+use crate::symfony::console::input::input_interface::InputInterface;
+use crate::symfony::console::input::input_option::InputOption;
+use crate::symfony::console::output::output_interface::{self, OutputInterface};
+use shirabe_php_shim::PhpMixed;
+use std::cell::RefCell;
+use std::ops::{Deref, DerefMut};
+use std::rc::Rc;
+
+/// Dumps the completion script for the current shell.
+#[derive(Debug)]
+pub struct DumpCompletionCommand {
+ inner: BaseCommand,
+}
+
+impl Deref for DumpCompletionCommand {
+ type Target = BaseCommand;
+
+ fn deref(&self) -> &Self::Target {
+ &self.inner
+ }
+}
+
+impl DerefMut for DumpCompletionCommand {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ &mut self.inner
+ }
+}
+
+impl DumpCompletionCommand {
+ pub const DEFAULT_NAME: &'static str = "completion";
+ pub const DEFAULT_DESCRIPTION: &'static str = "Dump the shell completion script";
+
+ pub fn complete_impl(&self, input: &CompletionInput, suggestions: &mut CompletionSuggestions) {
+ if input.must_suggest_argument_values_for("shell") {
+ suggestions.suggest_values(
+ self.get_supported_shells()
+ .into_iter()
+ .map(StringOrSuggestion::String)
+ .collect(),
+ );
+ }
+ }
+
+ fn configure(&mut self) -> anyhow::Result<()> {
+ let full_command = shirabe_php_shim::server_php_self();
+ let command_name = shirabe_php_shim::basename(&full_command);
+ // @realpath($fullCommand) ?: $fullCommand
+ let full_command = match shirabe_php_shim::realpath(&full_command) {
+ Some(p) if !p.is_empty() => p,
+ _ => full_command,
+ };
+
+ self.inner.set_help(&format!(
+ "The <info>%command.name%</> command dumps the shell completion script required\n\
+ to use shell autocompletion (currently only bash completion is supported).\n\
+ \n\
+ <comment>Static installation\n\
+ -------------------</>\n\
+ \n\
+ Dump the script to a global completion file and restart your shell:\n\
+ \n\
+ \x20\x20\x20\x20<info>%command.full_name% bash | sudo tee /etc/bash_completion.d/{command_name}</>\n\
+ \n\
+ Or dump the script to a local file and source it:\n\
+ \n\
+ \x20\x20\x20\x20<info>%command.full_name% bash > completion.sh</>\n\
+ \n\
+ \x20\x20\x20\x20<comment># source the file whenever you use the project</>\n\
+ \x20\x20\x20\x20<info>source completion.sh</>\n\
+ \n\
+ \x20\x20\x20\x20<comment># or add this line at the end of your \"~/.bashrc\" file:</>\n\
+ \x20\x20\x20\x20<info>source /path/to/completion.sh</>\n\
+ \n\
+ <comment>Dynamic installation\n\
+ --------------------</>\n\
+ \n\
+ Add this to the end of your shell configuration file (e.g. <info>\"~/.bashrc\"</>):\n\
+ \n\
+ \x20\x20\x20\x20<info>eval \"$({full_command} completion bash)\"</>",
+ ))
+ .add_argument(
+ "shell",
+ Some(InputArgument::OPTIONAL),
+ "The shell type (e.g. \"bash\"), the value of the \"$SHELL\" env var will be used if this is not given",
+ PhpMixed::Null,
+ )?
+ .add_option(
+ "debug",
+ PhpMixed::Null,
+ Some(InputOption::VALUE_NONE),
+ "Tail the completion debug log",
+ PhpMixed::Null,
+ )?;
+
+ Ok(())
+ }
+
+ fn execute(
+ &mut self,
+ input: &mut dyn InputInterface,
+ output: &mut dyn OutputInterface,
+ ) -> anyhow::Result<i64> {
+ let command_name = shirabe_php_shim::basename(&shirabe_php_shim::server_argv()[0]);
+
+ if input.get_option("debug")?.to_bool() {
+ self.tail_debug_log(&command_name, output);
+
+ return Ok(0);
+ }
+
+ let shell = match input.get_argument("shell")?.as_string() {
+ Some(s) => s.to_string(),
+ None => Self::guess_shell(),
+ };
+ let completion_file = format!(
+ "{}/../Resources/completion.{}",
+ shirabe_php_shim::dir(),
+ shell
+ );
+ if !shirabe_php_shim::file_exists(&completion_file) {
+ let supported_shells = self.get_supported_shells();
+
+ // TODO: PHP does `$output instanceof ConsoleOutputInterface ? $output->getErrorOutput()
+ // : $output`. There is no way to test trait membership through `&dyn OutputInterface`
+ // here; OutputInterface would need a downcast hook (Phase C). Writing to `output`.
+ if !shell.is_empty() {
+ output.writeln(
+ &[format!(
+ "<error>Detected shell \"{}\", which is not supported by Symfony shell completion (supported shells: \"{}\").</>",
+ shell,
+ supported_shells.join("\", \"")
+ )],
+ output_interface::OUTPUT_NORMAL,
+ );
+ } else {
+ output.writeln(
+ &[format!(
+ "<error>Shell not detected, Symfony shell completion only supports \"{}\").</>",
+ supported_shells.join("\", \"")
+ )],
+ output_interface::OUTPUT_NORMAL,
+ );
+ }
+
+ return Ok(2);
+ }
+
+ let application = self.get_application().unwrap();
+ let version = application.borrow().get_version();
+ output.write(
+ &[shirabe_php_shim::str_replace_arrays(
+ &[
+ "{{ COMMAND_NAME }}".to_string(),
+ "{{ VERSION }}".to_string(),
+ ],
+ &[command_name, version],
+ &shirabe_php_shim::file_get_contents(&completion_file).unwrap_or_default(),
+ )],
+ false,
+ output_interface::OUTPUT_NORMAL,
+ );
+
+ Ok(0)
+ }
+
+ fn guess_shell() -> String {
+ shirabe_php_shim::basename(&shirabe_php_shim::server_shell().unwrap_or_default())
+ }
+
+ fn tail_debug_log(&self, command_name: &str, _output: &dyn OutputInterface) {
+ let debug_file = format!(
+ "{}/sf_{}.log",
+ shirabe_php_shim::sys_get_temp_dir(),
+ command_name
+ );
+ if !shirabe_php_shim::file_exists(&debug_file) {
+ shirabe_php_shim::touch(&debug_file);
+ }
+ // TODO: Process::run() expects a `'static` callback, but the PHP closure captures
+ // `$output` by reference and writes each line to it. Bridging the borrowed `output`
+ // into a `'static` callback requires shared ownership of the output (Phase C).
+ todo!()
+ }
+
+ fn get_supported_shells(&self) -> Vec<String> {
+ let mut shells = vec![];
+
+ // foreach (new \DirectoryIterator(__DIR__.'/../Resources/') as $file)
+ for file in shirabe_php_shim::directory_iterator(&format!(
+ "{}/../Resources/",
+ shirabe_php_shim::dir()
+ )) {
+ if shirabe_php_shim::str_starts_with(&file.get_basename(), "completion.")
+ && file.is_file()
+ {
+ shells.push(file.get_extension());
+ }
+ }
+
+ shells
+ }
+}
+
+impl Command for DumpCompletionCommand {
+ fn configure(&mut self) {
+ let _ = DumpCompletionCommand::configure(self);
+ }
+
+ fn run(
+ &mut self,
+ input: &mut dyn InputInterface,
+ output: &mut dyn OutputInterface,
+ ) -> anyhow::Result<i64> {
+ self.inner.run(input, output)
+ }
+
+ fn complete(&self, input: &CompletionInput, suggestions: &mut CompletionSuggestions) {
+ self.complete_impl(input, suggestions);
+ }
+
+ fn is_enabled(&self) -> bool {
+ self.inner.is_enabled()
+ }
+
+ fn set_application(
+ &mut self,
+ application: Option<Rc<RefCell<crate::symfony::console::application::Application>>>,
+ ) {
+ self.inner.set_application(application);
+ }
+
+ fn get_application(
+ &self,
+ ) -> Option<Rc<RefCell<crate::symfony::console::application::Application>>> {
+ self.inner.get_application()
+ }
+
+ fn set_helper_set(
+ &mut self,
+ helper_set: Rc<RefCell<crate::symfony::console::helper::helper_set::HelperSet>>,
+ ) {
+ self.inner.set_helper_set(helper_set);
+ }
+
+ fn get_helper_set(
+ &self,
+ ) -> Option<Rc<RefCell<crate::symfony::console::helper::helper_set::HelperSet>>> {
+ self.inner.get_helper_set()
+ }
+
+ fn merge_application_definition(&mut self, merge_args: bool) {
+ self.inner.merge_application_definition(merge_args);
+ }
+
+ fn get_definition(&self) -> &crate::symfony::console::input::input_definition::InputDefinition {
+ self.inner.get_definition()
+ }
+
+ fn get_native_definition(
+ &self,
+ ) -> &crate::symfony::console::input::input_definition::InputDefinition {
+ self.inner.get_native_definition()
+ }
+
+ fn set_name(&mut self, name: &str) -> anyhow::Result<()> {
+ self.inner.set_name(name)?;
+ Ok(())
+ }
+
+ fn get_name(&self) -> Option<String> {
+ self.inner.get_name()
+ }
+
+ fn set_hidden(&mut self, hidden: bool) {
+ self.inner.set_hidden(hidden);
+ }
+
+ fn is_hidden(&self) -> bool {
+ self.inner.is_hidden()
+ }
+
+ fn set_description(&mut self, description: &str) {
+ self.inner.set_description(description);
+ }
+
+ fn get_description(&self) -> String {
+ self.inner.get_description()
+ }
+
+ fn set_help(&mut self, help: &str) {
+ self.inner.set_help(help);
+ }
+
+ fn get_help(&self) -> String {
+ self.inner.get_help()
+ }
+
+ fn get_processed_help(&self) -> String {
+ self.inner.get_processed_help()
+ }
+
+ fn set_aliases(&mut self, aliases: Vec<String>) -> anyhow::Result<()> {
+ self.inner.set_aliases(aliases)?;
+ Ok(())
+ }
+
+ fn get_aliases(&self) -> Vec<String> {
+ self.inner.get_aliases()
+ }
+
+ fn get_synopsis(&mut self, short: bool) -> String {
+ self.inner.get_synopsis(short)
+ }
+
+ fn get_usages(&self) -> Vec<String> {
+ self.inner.get_usages()
+ }
+
+ fn get_helper(
+ &self,
+ name: &str,
+ ) -> anyhow::Result<
+ Result<PhpMixed, crate::symfony::console::exception::logic_exception::LogicException>,
+ > {
+ self.inner.get_helper(name)
+ }
+
+ fn ignore_validation_errors(&mut self) {
+ self.inner.ignore_validation_errors();
+ }
+}
diff --git a/crates/shirabe-external-packages/src/symfony/console/command/help_command.rs b/crates/shirabe-external-packages/src/symfony/console/command/help_command.rs
new file mode 100644
index 0000000..0a26931
--- /dev/null
+++ b/crates/shirabe-external-packages/src/symfony/console/command/help_command.rs
@@ -0,0 +1,269 @@
+use crate::symfony::console::command::command::{BaseCommand, Command, SetDefinitionArg};
+use crate::symfony::console::completion::completion_input::CompletionInput;
+use crate::symfony::console::completion::completion_suggestions::{
+ CompletionSuggestions, StringOrSuggestion,
+};
+use crate::symfony::console::descriptor::application_description::ApplicationDescription;
+use crate::symfony::console::helper::descriptor_helper::DescriptorHelper;
+use crate::symfony::console::input::input_argument::InputArgument;
+use crate::symfony::console::input::input_definition::DefinitionItem;
+use crate::symfony::console::input::input_interface::InputInterface;
+use crate::symfony::console::input::input_option::InputOption;
+use crate::symfony::console::output::output_interface::OutputInterface;
+use shirabe_php_shim::PhpMixed;
+use std::cell::RefCell;
+use std::ops::{Deref, DerefMut};
+use std::rc::Rc;
+
+/// HelpCommand displays the help for a given command.
+#[derive(Debug)]
+pub struct HelpCommand {
+ inner: BaseCommand,
+ command: Option<Rc<RefCell<dyn Command>>>,
+}
+
+impl Deref for HelpCommand {
+ type Target = BaseCommand;
+
+ fn deref(&self) -> &Self::Target {
+ &self.inner
+ }
+}
+
+impl DerefMut for HelpCommand {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ &mut self.inner
+ }
+}
+
+impl HelpCommand {
+ fn configure(&mut self) -> anyhow::Result<()> {
+ self.inner.ignore_validation_errors();
+
+ self.inner
+ .set_name("help")?
+ .set_definition(SetDefinitionArg::Array(vec![
+ DefinitionItem::InputArgument(InputArgument::new(
+ "command_name".to_string(),
+ Some(InputArgument::OPTIONAL),
+ "The command name".to_string(),
+ PhpMixed::from("help".to_string()),
+ )?),
+ DefinitionItem::InputOption(InputOption::new(
+ "format",
+ PhpMixed::Null,
+ Some(InputOption::VALUE_REQUIRED),
+ "The output format (txt, xml, json, or md)".to_string(),
+ PhpMixed::from("txt".to_string()),
+ )?),
+ DefinitionItem::InputOption(InputOption::new(
+ "raw",
+ PhpMixed::Null,
+ Some(InputOption::VALUE_NONE),
+ "To output raw command help".to_string(),
+ PhpMixed::Null,
+ )?),
+ ]))
+ .set_description("Display help for a command")
+ .set_help(
+ "The <info>%command.name%</info> command displays help for a given command:\n\
+ \n\
+ \x20\x20<info>%command.full_name% list</info>\n\
+ \n\
+ You can also output the help in other formats by using the <comment>--format</comment> option:\n\
+ \n\
+ \x20\x20<info>%command.full_name% --format=xml list</info>\n\
+ \n\
+ To display the list of available commands, please use the <info>list</info> command.",
+ );
+
+ Ok(())
+ }
+
+ pub fn set_command(&mut self, command: Rc<RefCell<dyn Command>>) {
+ self.command = Some(command);
+ }
+
+ fn execute(
+ &mut self,
+ input: &mut dyn InputInterface,
+ output: &mut dyn OutputInterface,
+ ) -> anyhow::Result<i64> {
+ if self.command.is_none() {
+ let application = self.get_application().unwrap();
+ let command_name = input.get_argument("command_name")?.to_string();
+ self.command = Some(application.borrow_mut().find(&command_name)?);
+ }
+
+ let helper = DescriptorHelper::new();
+ // TODO: DescriptorHelper::describe2 takes the described object as Option<PhpMixed>,
+ // but PhpMixed cannot hold a Command. The Command/Application object mixing for
+ // describe needs a dedicated type (Phase C).
+ let object: Option<PhpMixed> = todo!();
+ let mut options = indexmap::IndexMap::new();
+ options.insert("format".to_string(), input.get_option("format")?);
+ options.insert("raw_text".to_string(), input.get_option("raw")?);
+ let _ = helper.describe2(output, object, options);
+
+ self.command = None;
+
+ Ok(0)
+ }
+
+ pub fn complete_impl(&self, input: &CompletionInput, suggestions: &mut CompletionSuggestions) {
+ if input.must_suggest_argument_values_for("command_name") {
+ let application = self.get_application().unwrap();
+ let mut descriptor = ApplicationDescription::new(application, None, false);
+ suggestions.suggest_values(
+ descriptor
+ .get_commands()
+ .keys()
+ .cloned()
+ .map(StringOrSuggestion::String)
+ .collect(),
+ );
+
+ return;
+ }
+
+ if input.must_suggest_option_values_for("format") {
+ let helper = DescriptorHelper::new();
+ suggestions.suggest_values(
+ helper
+ .get_formats()
+ .into_iter()
+ .map(StringOrSuggestion::String)
+ .collect(),
+ );
+ }
+ }
+}
+
+impl Command for HelpCommand {
+ fn configure(&mut self) {
+ let _ = HelpCommand::configure(self);
+ }
+
+ fn run(
+ &mut self,
+ input: &mut dyn InputInterface,
+ output: &mut dyn OutputInterface,
+ ) -> anyhow::Result<i64> {
+ self.inner.run(input, output)
+ }
+
+ fn complete(&self, input: &CompletionInput, suggestions: &mut CompletionSuggestions) {
+ self.complete_impl(input, suggestions);
+ }
+
+ fn is_enabled(&self) -> bool {
+ self.inner.is_enabled()
+ }
+
+ fn set_application(
+ &mut self,
+ application: Option<Rc<RefCell<crate::symfony::console::application::Application>>>,
+ ) {
+ self.inner.set_application(application);
+ }
+
+ fn get_application(
+ &self,
+ ) -> Option<Rc<RefCell<crate::symfony::console::application::Application>>> {
+ self.inner.get_application()
+ }
+
+ fn set_helper_set(
+ &mut self,
+ helper_set: Rc<RefCell<crate::symfony::console::helper::helper_set::HelperSet>>,
+ ) {
+ self.inner.set_helper_set(helper_set);
+ }
+
+ fn get_helper_set(
+ &self,
+ ) -> Option<Rc<RefCell<crate::symfony::console::helper::helper_set::HelperSet>>> {
+ self.inner.get_helper_set()
+ }
+
+ fn merge_application_definition(&mut self, merge_args: bool) {
+ self.inner.merge_application_definition(merge_args);
+ }
+
+ fn get_definition(&self) -> &crate::symfony::console::input::input_definition::InputDefinition {
+ self.inner.get_definition()
+ }
+
+ fn get_native_definition(
+ &self,
+ ) -> &crate::symfony::console::input::input_definition::InputDefinition {
+ self.inner.get_native_definition()
+ }
+
+ fn set_name(&mut self, name: &str) -> anyhow::Result<()> {
+ self.inner.set_name(name)?;
+ Ok(())
+ }
+
+ fn get_name(&self) -> Option<String> {
+ self.inner.get_name()
+ }
+
+ fn set_hidden(&mut self, hidden: bool) {
+ self.inner.set_hidden(hidden);
+ }
+
+ fn is_hidden(&self) -> bool {
+ self.inner.is_hidden()
+ }
+
+ fn set_description(&mut self, description: &str) {
+ self.inner.set_description(description);
+ }
+
+ fn get_description(&self) -> String {
+ self.inner.get_description()
+ }
+
+ fn set_help(&mut self, help: &str) {
+ self.inner.set_help(help);
+ }
+
+ fn get_help(&self) -> String {
+ self.inner.get_help()
+ }
+
+ fn get_processed_help(&self) -> String {
+ self.inner.get_processed_help()
+ }
+
+ fn set_aliases(&mut self, aliases: Vec<String>) -> anyhow::Result<()> {
+ self.inner.set_aliases(aliases)?;
+ Ok(())
+ }
+
+ fn get_aliases(&self) -> Vec<String> {
+ self.inner.get_aliases()
+ }
+
+ fn get_synopsis(&mut self, short: bool) -> String {
+ self.inner.get_synopsis(short)
+ }
+
+ fn get_usages(&self) -> Vec<String> {
+ self.inner.get_usages()
+ }
+
+ fn get_helper(
+ &self,
+ name: &str,
+ ) -> anyhow::Result<
+ Result<PhpMixed, crate::symfony::console::exception::logic_exception::LogicException>,
+ > {
+ self.inner.get_helper(name)
+ }
+
+ fn ignore_validation_errors(&mut self) {
+ self.inner.ignore_validation_errors();
+ }
+}
diff --git a/crates/shirabe-external-packages/src/symfony/console/command/lazy_command.rs b/crates/shirabe-external-packages/src/symfony/console/command/lazy_command.rs
new file mode 100644
index 0000000..47f73bf
--- /dev/null
+++ b/crates/shirabe-external-packages/src/symfony/console/command/lazy_command.rs
@@ -0,0 +1,395 @@
+use shirabe_php_shim::PhpMixed;
+use std::cell::RefCell;
+use std::ops::{Deref, DerefMut};
+use std::rc::Rc;
+
+use crate::symfony::console::application::Application;
+use crate::symfony::console::command::command::{BaseCommand, Command, SetDefinitionArg};
+use crate::symfony::console::completion::completion_input::CompletionInput;
+use crate::symfony::console::completion::completion_suggestions::CompletionSuggestions;
+use crate::symfony::console::helper::helper_set::HelperSet;
+use crate::symfony::console::input::input_definition::InputDefinition;
+use crate::symfony::console::input::input_interface::InputInterface;
+use crate::symfony::console::output::output_interface::OutputInterface;
+
+/// Either an already-built command, or a factory closure that builds one.
+///
+/// PHP: `private $command` holds a `Command` instance or a `\Closure`.
+pub enum LazyCommandInner {
+ Command(Box<dyn Command>),
+ Factory(Box<dyn Fn() -> Box<dyn Command>>),
+}
+
+impl std::fmt::Debug for LazyCommandInner {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ LazyCommandInner::Command(command) => f.debug_tuple("Command").field(command).finish(),
+ LazyCommandInner::Factory(_) => f.debug_tuple("Factory").finish(),
+ }
+ }
+}
+
+#[derive(Debug)]
+pub struct LazyCommand {
+ inner: BaseCommand,
+ command: LazyCommandInner,
+ is_enabled: Option<bool>,
+}
+
+impl Deref for LazyCommand {
+ type Target = BaseCommand;
+
+ fn deref(&self) -> &Self::Target {
+ &self.inner
+ }
+}
+
+impl DerefMut for LazyCommand {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ &mut self.inner
+ }
+}
+
+impl LazyCommand {
+ pub fn new(
+ name: &str,
+ aliases: Vec<String>,
+ description: &str,
+ is_hidden: bool,
+ command_factory: Box<dyn Fn() -> Box<dyn Command>>,
+ is_enabled: Option<bool>,
+ ) -> anyhow::Result<Self> {
+ let mut this = Self {
+ inner: BaseCommand::__construct(None)?,
+ command: LazyCommandInner::Factory(command_factory),
+ is_enabled,
+ };
+
+ this.inner
+ .set_name(name)?
+ .set_aliases(aliases)?
+ .set_hidden(is_hidden)
+ .set_description(description);
+
+ Ok(this)
+ }
+
+ pub fn ignore_validation_errors(&mut self) {
+ self.get_command().ignore_validation_errors();
+ }
+
+ pub fn set_application(&mut self, application: Option<Rc<RefCell<Application>>>) {
+ // if ($this->command instanceof parent)
+ if let LazyCommandInner::Command(command) = &mut self.command {
+ command.set_application(application.clone());
+ }
+
+ // parent::setApplication($application);
+ self.inner.set_application(application);
+ }
+
+ pub fn set_helper_set(&mut self, helper_set: Rc<RefCell<HelperSet>>) {
+ // if ($this->command instanceof parent)
+ if let LazyCommandInner::Command(command) = &mut self.command {
+ command.set_helper_set(helper_set.clone());
+ }
+
+ // parent::setHelperSet($helperSet);
+ self.inner.set_helper_set(helper_set);
+ }
+
+ pub fn is_enabled(&mut self) -> bool {
+ // $this->isEnabled ?? $this->getCommand()->isEnabled()
+ match self.is_enabled {
+ Some(is_enabled) => is_enabled,
+ None => self.get_command().is_enabled(),
+ }
+ }
+
+ pub fn run(
+ &mut self,
+ input: &mut dyn InputInterface,
+ output: &mut dyn OutputInterface,
+ ) -> anyhow::Result<i64> {
+ self.get_command().run(input, output)
+ }
+
+ pub fn complete(&mut self, input: &CompletionInput, suggestions: &mut CompletionSuggestions) {
+ self.get_command().complete(input, suggestions);
+ }
+
+ pub fn set_code(
+ &mut self,
+ code: Box<dyn Fn(&mut dyn InputInterface, &mut dyn OutputInterface) -> PhpMixed>,
+ ) -> &mut Self {
+ // TODO: Command::set_code() lives on BaseCommand's inherent API and is not part of
+ // the polymorphic `Command` trait, so it cannot be forwarded through `get_command()`
+ // (a `&mut Box<dyn Command>`). Resolving this needs `set_code` on the trait (Phase C).
+ let _ = code;
+ todo!()
+ }
+
+ /// @internal
+ pub fn merge_application_definition(&mut self, merge_args: bool) {
+ self.get_command().merge_application_definition(merge_args);
+ }
+
+ pub fn set_definition(&mut self, definition: SetDefinitionArg) -> &mut Self {
+ // TODO: Command::set_definition() is not part of the polymorphic `Command` trait;
+ // it cannot be forwarded through `get_command()` (Phase C).
+ let _ = definition;
+ todo!()
+ }
+
+ pub fn get_definition(&mut self) -> &InputDefinition {
+ self.get_command().get_definition()
+ }
+
+ pub fn get_native_definition(&mut self) -> &InputDefinition {
+ self.get_command().get_native_definition()
+ }
+
+ pub fn add_argument(
+ &mut self,
+ name: &str,
+ mode: Option<i64>,
+ description: &str,
+ default: PhpMixed,
+ ) -> &mut Self {
+ // TODO: Command::add_argument() is not part of the polymorphic `Command` trait;
+ // it cannot be forwarded through `get_command()` (Phase C).
+ let _ = (name, mode, description, default);
+ todo!()
+ }
+
+ pub fn add_option(
+ &mut self,
+ name: &str,
+ shortcut: PhpMixed,
+ mode: Option<i64>,
+ description: &str,
+ default: PhpMixed,
+ ) -> &mut Self {
+ // TODO: Command::add_option() is not part of the polymorphic `Command` trait;
+ // it cannot be forwarded through `get_command()` (Phase C).
+ let _ = (name, shortcut, mode, description, default);
+ todo!()
+ }
+
+ pub fn set_process_title(&mut self, title: &str) -> &mut Self {
+ // TODO: Command::set_process_title() is not part of the polymorphic `Command` trait;
+ // it cannot be forwarded through `get_command()` (Phase C).
+ let _ = title;
+ todo!()
+ }
+
+ pub fn set_help(&mut self, help: &str) -> &mut Self {
+ self.get_command().set_help(help);
+
+ self
+ }
+
+ pub fn get_help(&mut self) -> String {
+ self.get_command().get_help()
+ }
+
+ pub fn get_processed_help(&mut self) -> String {
+ self.get_command().get_processed_help()
+ }
+
+ pub fn get_synopsis(&mut self, short: bool) -> String {
+ self.get_command().get_synopsis(short)
+ }
+
+ pub fn add_usage(&mut self, usage: &str) -> &mut Self {
+ // TODO: Command::add_usage() is not part of the polymorphic `Command` trait;
+ // it cannot be forwarded through `get_command()` (Phase C).
+ let _ = usage;
+ todo!()
+ }
+
+ pub fn get_usages(&mut self) -> Vec<String> {
+ self.get_command().get_usages()
+ }
+
+ pub fn get_helper(
+ &mut self,
+ name: &str,
+ ) -> anyhow::Result<
+ Result<PhpMixed, crate::symfony::console::exception::logic_exception::LogicException>,
+ > {
+ self.get_command().get_helper(name)
+ }
+
+ pub fn get_command(&mut self) -> &mut Box<dyn Command> {
+ // if (!$this->command instanceof \Closure) { return $this->command; }
+ if let LazyCommandInner::Command(_) = &self.command {
+ if let LazyCommandInner::Command(command) = &mut self.command {
+ return command;
+ }
+ unreachable!()
+ }
+
+ // $command = $this->command = ($this->command)();
+ let mut command = match &self.command {
+ LazyCommandInner::Factory(factory) => factory(),
+ LazyCommandInner::Command(_) => unreachable!(),
+ };
+ command.set_application(self.inner.get_application());
+
+ // if (null !== $this->getHelperSet())
+ if let Some(helper_set) = self.inner.get_helper_set() {
+ command.set_helper_set(helper_set);
+ }
+
+ let name = self.inner.get_name().unwrap_or_default();
+ let aliases = self.inner.get_aliases();
+ let hidden = self.inner.is_hidden();
+ let description = self.inner.get_description();
+ let _ = command.set_name(&name);
+ let _ = command.set_aliases(aliases);
+ command.set_hidden(hidden);
+ command.set_description(&description);
+
+ // Will throw if the command is not correctly initialized.
+ command.get_definition();
+
+ self.command = LazyCommandInner::Command(command);
+ match &mut self.command {
+ LazyCommandInner::Command(command) => command,
+ LazyCommandInner::Factory(_) => unreachable!(),
+ }
+ }
+}
+
+impl Command for LazyCommand {
+ fn configure(&mut self) {
+ // LazyCommand has no configure() of its own; nothing to do.
+ }
+
+ fn run(
+ &mut self,
+ input: &mut dyn InputInterface,
+ output: &mut dyn OutputInterface,
+ ) -> anyhow::Result<i64> {
+ LazyCommand::run(self, input, output)
+ }
+
+ fn complete(&self, _input: &CompletionInput, _suggestions: &mut CompletionSuggestions) {
+ // TODO: LazyCommand::complete() lazily materializes the wrapped command and so needs
+ // `&mut self`, which conflicts with the `Command::complete(&self, ...)` signature
+ // (Phase C).
+ todo!()
+ }
+
+ fn is_enabled(&self) -> bool {
+ // TODO: LazyCommand::is_enabled() lazily materializes the wrapped command and so needs
+ // `&mut self`, which conflicts with the trait signature (Phase C).
+ todo!()
+ }
+
+ fn set_application(&mut self, application: Option<Rc<RefCell<Application>>>) {
+ LazyCommand::set_application(self, application);
+ }
+
+ fn get_application(&self) -> Option<Rc<RefCell<Application>>> {
+ self.inner.get_application()
+ }
+
+ fn set_helper_set(&mut self, helper_set: Rc<RefCell<HelperSet>>) {
+ LazyCommand::set_helper_set(self, helper_set);
+ }
+
+ fn get_helper_set(&self) -> Option<Rc<RefCell<HelperSet>>> {
+ self.inner.get_helper_set()
+ }
+
+ fn merge_application_definition(&mut self, merge_args: bool) {
+ LazyCommand::merge_application_definition(self, merge_args);
+ }
+
+ fn get_definition(&self) -> &InputDefinition {
+ // TODO: LazyCommand::get_definition() lazily materializes the wrapped command and so
+ // needs `&mut self`, which conflicts with the trait signature (Phase C).
+ todo!()
+ }
+
+ fn get_native_definition(&self) -> &InputDefinition {
+ // TODO: same lazy-materialization / `&self` conflict as get_definition() (Phase C).
+ todo!()
+ }
+
+ fn set_name(&mut self, name: &str) -> anyhow::Result<()> {
+ self.inner.set_name(name)?;
+ Ok(())
+ }
+
+ fn get_name(&self) -> Option<String> {
+ self.inner.get_name()
+ }
+
+ fn set_hidden(&mut self, hidden: bool) {
+ self.inner.set_hidden(hidden);
+ }
+
+ fn is_hidden(&self) -> bool {
+ self.inner.is_hidden()
+ }
+
+ fn set_description(&mut self, description: &str) {
+ self.inner.set_description(description);
+ }
+
+ fn get_description(&self) -> String {
+ self.inner.get_description()
+ }
+
+ fn set_help(&mut self, help: &str) {
+ LazyCommand::set_help(self, help);
+ }
+
+ fn get_help(&self) -> String {
+ // TODO: LazyCommand::get_help() lazily materializes the wrapped command and so needs
+ // `&mut self`, which conflicts with the trait signature (Phase C).
+ todo!()
+ }
+
+ fn get_processed_help(&self) -> String {
+ // TODO: same lazy-materialization / `&self` conflict (Phase C).
+ todo!()
+ }
+
+ fn set_aliases(&mut self, aliases: Vec<String>) -> anyhow::Result<()> {
+ self.inner.set_aliases(aliases)?;
+ Ok(())
+ }
+
+ fn get_aliases(&self) -> Vec<String> {
+ self.inner.get_aliases()
+ }
+
+ fn get_synopsis(&mut self, short: bool) -> String {
+ LazyCommand::get_synopsis(self, short)
+ }
+
+ fn get_usages(&self) -> Vec<String> {
+ // TODO: LazyCommand::get_usages() lazily materializes the wrapped command and so needs
+ // `&mut self`, which conflicts with the trait signature (Phase C).
+ todo!()
+ }
+
+ fn get_helper(
+ &self,
+ _name: &str,
+ ) -> anyhow::Result<
+ Result<PhpMixed, crate::symfony::console::exception::logic_exception::LogicException>,
+ > {
+ // TODO: LazyCommand::get_helper() lazily materializes the wrapped command and so needs
+ // `&mut self`, which conflicts with the trait signature (Phase C).
+ todo!()
+ }
+
+ fn ignore_validation_errors(&mut self) {
+ LazyCommand::ignore_validation_errors(self);
+ }
+}
diff --git a/crates/shirabe-external-packages/src/symfony/console/command/list_command.rs b/crates/shirabe-external-packages/src/symfony/console/command/list_command.rs
new file mode 100644
index 0000000..7581c90
--- /dev/null
+++ b/crates/shirabe-external-packages/src/symfony/console/command/list_command.rs
@@ -0,0 +1,269 @@
+use crate::symfony::console::command::command::{BaseCommand, Command, SetDefinitionArg};
+use crate::symfony::console::completion::completion_input::CompletionInput;
+use crate::symfony::console::completion::completion_suggestions::{
+ CompletionSuggestions, StringOrSuggestion,
+};
+use crate::symfony::console::descriptor::application_description::ApplicationDescription;
+use crate::symfony::console::helper::descriptor_helper::DescriptorHelper;
+use crate::symfony::console::input::input_argument::InputArgument;
+use crate::symfony::console::input::input_definition::DefinitionItem;
+use crate::symfony::console::input::input_interface::InputInterface;
+use crate::symfony::console::input::input_option::InputOption;
+use crate::symfony::console::output::output_interface::OutputInterface;
+use shirabe_php_shim::PhpMixed;
+use std::cell::RefCell;
+use std::ops::{Deref, DerefMut};
+use std::rc::Rc;
+
+/// ListCommand displays the list of all available commands for the application.
+#[derive(Debug)]
+pub struct ListCommand {
+ inner: BaseCommand,
+}
+
+impl Deref for ListCommand {
+ type Target = BaseCommand;
+
+ fn deref(&self) -> &Self::Target {
+ &self.inner
+ }
+}
+
+impl DerefMut for ListCommand {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ &mut self.inner
+ }
+}
+
+impl ListCommand {
+ fn configure(&mut self) -> anyhow::Result<()> {
+ self.inner
+ .set_name("list")?
+ .set_definition(SetDefinitionArg::Array(vec![
+ DefinitionItem::InputArgument(InputArgument::new(
+ "namespace".to_string(),
+ Some(InputArgument::OPTIONAL),
+ "The namespace name".to_string(),
+ PhpMixed::Null,
+ )?),
+ DefinitionItem::InputOption(InputOption::new(
+ "raw",
+ PhpMixed::Null,
+ Some(InputOption::VALUE_NONE),
+ "To output raw command list".to_string(),
+ PhpMixed::Null,
+ )?),
+ DefinitionItem::InputOption(InputOption::new(
+ "format",
+ PhpMixed::Null,
+ Some(InputOption::VALUE_REQUIRED),
+ "The output format (txt, xml, json, or md)".to_string(),
+ PhpMixed::from("txt".to_string()),
+ )?),
+ DefinitionItem::InputOption(InputOption::new(
+ "short",
+ PhpMixed::Null,
+ Some(InputOption::VALUE_NONE),
+ "To skip describing commands' arguments".to_string(),
+ PhpMixed::Null,
+ )?),
+ ]))
+ .set_description("List commands")
+ .set_help(
+ "The <info>%command.name%</info> command lists all commands:\n\
+ \n\
+ \x20\x20<info>%command.full_name%</info>\n\
+ \n\
+ You can also display the commands for a specific namespace:\n\
+ \n\
+ \x20\x20<info>%command.full_name% test</info>\n\
+ \n\
+ You can also output the information in other formats by using the <comment>--format</comment> option:\n\
+ \n\
+ \x20\x20<info>%command.full_name% --format=xml</info>\n\
+ \n\
+ It's also possible to get raw list of commands (useful for embedding command runner):\n\
+ \n\
+ \x20\x20<info>%command.full_name% --raw</info>",
+ );
+
+ Ok(())
+ }
+
+ fn execute(
+ &mut self,
+ input: &mut dyn InputInterface,
+ output: &mut dyn OutputInterface,
+ ) -> anyhow::Result<i64> {
+ let helper = DescriptorHelper::new();
+ // TODO: DescriptorHelper::describe2 takes the described object as Option<PhpMixed>,
+ // but PhpMixed cannot hold an Application. The Command/Application object mixing for
+ // describe needs a dedicated type (Phase C).
+ let object: Option<PhpMixed> = todo!();
+ let mut options = indexmap::IndexMap::new();
+ options.insert("format".to_string(), input.get_option("format")?);
+ options.insert("raw_text".to_string(), input.get_option("raw")?);
+ options.insert("namespace".to_string(), input.get_argument("namespace")?);
+ options.insert("short".to_string(), input.get_option("short")?);
+ let _ = helper.describe2(output, object, options);
+
+ Ok(0)
+ }
+
+ pub fn complete_impl(&self, input: &CompletionInput, suggestions: &mut CompletionSuggestions) {
+ if input.must_suggest_argument_values_for("namespace") {
+ let application = self.get_application().unwrap();
+ let mut descriptor = ApplicationDescription::new(application, None, false);
+ suggestions.suggest_values(
+ descriptor
+ .get_namespaces()
+ .keys()
+ .cloned()
+ .map(StringOrSuggestion::String)
+ .collect(),
+ );
+
+ return;
+ }
+
+ if input.must_suggest_option_values_for("format") {
+ let helper = DescriptorHelper::new();
+ suggestions.suggest_values(
+ helper
+ .get_formats()
+ .into_iter()
+ .map(StringOrSuggestion::String)
+ .collect(),
+ );
+ }
+ }
+}
+
+impl Command for ListCommand {
+ fn configure(&mut self) {
+ let _ = ListCommand::configure(self);
+ }
+
+ fn run(
+ &mut self,
+ input: &mut dyn InputInterface,
+ output: &mut dyn OutputInterface,
+ ) -> anyhow::Result<i64> {
+ self.inner.run(input, output)
+ }
+
+ fn complete(&self, input: &CompletionInput, suggestions: &mut CompletionSuggestions) {
+ self.complete_impl(input, suggestions);
+ }
+
+ fn is_enabled(&self) -> bool {
+ self.inner.is_enabled()
+ }
+
+ fn set_application(
+ &mut self,
+ application: Option<Rc<RefCell<crate::symfony::console::application::Application>>>,
+ ) {
+ self.inner.set_application(application);
+ }
+
+ fn get_application(
+ &self,
+ ) -> Option<Rc<RefCell<crate::symfony::console::application::Application>>> {
+ self.inner.get_application()
+ }
+
+ fn set_helper_set(
+ &mut self,
+ helper_set: Rc<RefCell<crate::symfony::console::helper::helper_set::HelperSet>>,
+ ) {
+ self.inner.set_helper_set(helper_set);
+ }
+
+ fn get_helper_set(
+ &self,
+ ) -> Option<Rc<RefCell<crate::symfony::console::helper::helper_set::HelperSet>>> {
+ self.inner.get_helper_set()
+ }
+
+ fn merge_application_definition(&mut self, merge_args: bool) {
+ self.inner.merge_application_definition(merge_args);
+ }
+
+ fn get_definition(&self) -> &crate::symfony::console::input::input_definition::InputDefinition {
+ self.inner.get_definition()
+ }
+
+ fn get_native_definition(
+ &self,
+ ) -> &crate::symfony::console::input::input_definition::InputDefinition {
+ self.inner.get_native_definition()
+ }
+
+ fn set_name(&mut self, name: &str) -> anyhow::Result<()> {
+ self.inner.set_name(name)?;
+ Ok(())
+ }
+
+ fn get_name(&self) -> Option<String> {
+ self.inner.get_name()
+ }
+
+ fn set_hidden(&mut self, hidden: bool) {
+ self.inner.set_hidden(hidden);
+ }
+
+ fn is_hidden(&self) -> bool {
+ self.inner.is_hidden()
+ }
+
+ fn set_description(&mut self, description: &str) {
+ self.inner.set_description(description);
+ }
+
+ fn get_description(&self) -> String {
+ self.inner.get_description()
+ }
+
+ fn set_help(&mut self, help: &str) {
+ self.inner.set_help(help);
+ }
+
+ fn get_help(&self) -> String {
+ self.inner.get_help()
+ }
+
+ fn get_processed_help(&self) -> String {
+ self.inner.get_processed_help()
+ }
+
+ fn set_aliases(&mut self, aliases: Vec<String>) -> anyhow::Result<()> {
+ self.inner.set_aliases(aliases)?;
+ Ok(())
+ }
+
+ fn get_aliases(&self) -> Vec<String> {
+ self.inner.get_aliases()
+ }
+
+ fn get_synopsis(&mut self, short: bool) -> String {
+ self.inner.get_synopsis(short)
+ }
+
+ fn get_usages(&self) -> Vec<String> {
+ self.inner.get_usages()
+ }
+
+ fn get_helper(
+ &self,
+ name: &str,
+ ) -> anyhow::Result<
+ Result<PhpMixed, crate::symfony::console::exception::logic_exception::LogicException>,
+ > {
+ self.inner.get_helper(name)
+ }
+
+ fn ignore_validation_errors(&mut self) {
+ self.inner.ignore_validation_errors();
+ }
+}
diff --git a/crates/shirabe-external-packages/src/symfony/console/command/mod.rs b/crates/shirabe-external-packages/src/symfony/console/command/mod.rs
index 375170c..ee2dd4f 100644
--- a/crates/shirabe-external-packages/src/symfony/console/command/mod.rs
+++ b/crates/shirabe-external-packages/src/symfony/console/command/mod.rs
@@ -1,3 +1,15 @@
pub mod command;
+pub mod complete_command;
+pub mod dump_completion_command;
+pub mod help_command;
+pub mod lazy_command;
+pub mod list_command;
+pub mod signalable_command_interface;
pub use command::*;
+pub use complete_command::*;
+pub use dump_completion_command::*;
+pub use help_command::*;
+pub use lazy_command::*;
+pub use list_command::*;
+pub use signalable_command_interface::*;
diff --git a/crates/shirabe-external-packages/src/symfony/console/command/signalable_command_interface.rs b/crates/shirabe-external-packages/src/symfony/console/command/signalable_command_interface.rs
new file mode 100644
index 0000000..1af4a96
--- /dev/null
+++ b/crates/shirabe-external-packages/src/symfony/console/command/signalable_command_interface.rs
@@ -0,0 +1,8 @@
+/// Interface for command reacting to signal.
+pub trait SignalableCommandInterface {
+ /// Returns the list of signals to subscribe.
+ fn get_subscribed_signals(&self) -> Vec<i64>;
+
+ /// The method will be called when the application is signaled.
+ fn handle_signal(&mut self, signal: i64);
+}