diff options
Diffstat (limited to 'crates/shirabe/src/command')
23 files changed, 466 insertions, 648 deletions
diff --git a/crates/shirabe/src/command/archive_command.rs b/crates/shirabe/src/command/archive_command.rs index e749d13f..1c428c58 100644 --- a/crates/shirabe/src/command/archive_command.rs +++ b/crates/shirabe/src/command/archive_command.rs @@ -303,13 +303,10 @@ impl ArchiveCommand { }; let Some(complete) = package.as_complete() else { - return Err(LogicException { - message: format!( - "Expected a CompletePackageInterface instance but found {}", - get_debug_type(&shirabe_php_shim::PhpMixed::Null) - ), - code: 0, - } + return Err(LogicException::new(format!( + "Expected a CompletePackageInterface instance but found {}", + get_debug_type(&shirabe_php_shim::PhpMixed::Null) + )) .into()); }; diff --git a/crates/shirabe/src/command/audit_command.rs b/crates/shirabe/src/command/audit_command.rs index 0eee0036..268984d6 100644 --- a/crates/shirabe/src/command/audit_command.rs +++ b/crates/shirabe/src/command/audit_command.rs @@ -60,10 +60,7 @@ impl AuditCommand { let locker = composer.get_locker().clone(); let mut locker = locker.borrow_mut(); if !locker.is_locked() { - return Err(UnexpectedValueException { - message: "Valid composer.json and composer.lock files are required to run this command with --locked".to_string(), - code: 0, - }.into()); + return Err(UnexpectedValueException::new("Valid composer.json and composer.lock files are required to run this command with --locked".to_string()).into()); } let locked_repo = locker.get_locked_repository( !input @@ -228,19 +225,16 @@ impl Command for AuditCommand { .collect::<Vec<_>>(), ) { - return Err(InvalidArgumentException { - message: format!( - "--abandoned must be one of {}.", - implode( - ", ", - &Auditor::ABANDONEDS - .iter() - .map(|s| s.to_string()) - .collect::<Vec<_>>() - ) - ), - code: 0, - } + return Err(InvalidArgumentException::new(format!( + "--abandoned must be one of {}.", + implode( + ", ", + &Auditor::ABANDONEDS + .iter() + .map(|s| s.to_string()) + .collect::<Vec<_>>() + ) + )) .into()); } diff --git a/crates/shirabe/src/command/base_command.rs b/crates/shirabe/src/command/base_command.rs index 7a66862e..a1de9783 100644 --- a/crates/shirabe/src/command/base_command.rs +++ b/crates/shirabe/src/command/base_command.rs @@ -294,10 +294,7 @@ impl BaseCommand for BaseCommandData { if self.composer.borrow().is_none() { let application = self.get_application(); let Some(application) = application else { - return Err(RuntimeException { - message: "Could not create a Composer\\Composer instance, you must inject one if this command is not used with a Composer\\Console\\Application instance".to_string(), - code: 0, - } + return Err(RuntimeException::new("Could not create a Composer\\Composer instance, you must inject one if this command is not used with a Composer\\Console\\Application instance".to_string()) .into()); }; let composer = { @@ -455,11 +452,9 @@ impl BaseCommand for BaseCommandData { .as_bool() .unwrap_or(false) { - return Err(InvalidArgumentException { - message: "--prefer-source can not be used together with --prefer-install" - .to_string(), - code: 0, - } + return Err(InvalidArgumentException::new( + "--prefer-source can not be used together with --prefer-install".to_string(), + ) .into()); } if input @@ -468,11 +463,9 @@ impl BaseCommand for BaseCommandData { .as_bool() .unwrap_or(false) { - return Err(InvalidArgumentException { - message: "--prefer-dist can not be used together with --prefer-install" - .to_string(), - code: 0, - } + return Err(InvalidArgumentException::new( + "--prefer-dist can not be used together with --prefer-install".to_string(), + ) .into()); } let prefer_install = input.borrow().get_option("prefer-install")?; @@ -492,13 +485,10 @@ impl BaseCommand for BaseCommandData { prefer_source = false; } other => { - return Err(UnexpectedValueException { - message: format!( - "--prefer-install accepts one of \"dist\", \"source\" or \"auto\", got {}", - other - ), - code: 0, - } + return Err(UnexpectedValueException::new(format!( + "--prefer-install accepts one of \"dist\", \"source\" or \"auto\", got {}", + other + )) .into()); } } @@ -551,12 +541,8 @@ impl BaseCommand for BaseCommandData { if !input.borrow().has_option("ignore-platform-reqs") || !input.borrow().has_option("ignore-platform-req") { - return Err(LogicException { - message: - "Calling getPlatformRequirementFilter from a command which does not define the --ignore-platform-req[s] flags is not permitted." - .to_string(), - code: 0, - } + return Err(LogicException::new("Calling getPlatformRequirementFilter from a command which does not define the --ignore-platform-req[s] flags is not permitted." + .to_string()) .into()); } @@ -585,14 +571,11 @@ impl BaseCommand for BaseCommandData { let requirements = self.normalize_requirements(requirements)?; for requirement in requirements { if !requirement.contains_key("version") { - return Err(UnexpectedValueException { - message: format!( - "Option {} is missing a version constraint, use e.g. {}:^1.0", - requirement.get("name").map(|s| s.as_str()).unwrap_or(""), - requirement.get("name").map(|s| s.as_str()).unwrap_or(""), - ), - code: 0, - } + return Err(UnexpectedValueException::new(format!( + "Option {} is missing a version constraint, use e.g. {}:^1.0", + requirement.get("name").map(|s| s.as_str()).unwrap_or(""), + requirement.get("name").map(|s| s.as_str()).unwrap_or(""), + )) .into()); } requires.insert( @@ -648,13 +631,10 @@ impl BaseCommand for BaseCommandData { opt_name: &str, ) -> anyhow::Result<String> { if !input.borrow().has_option(opt_name) { - return Err(LogicException { - message: format!( - "This should not be called on a Command which has no {} option defined.", - opt_name - ), - code: 0, - } + return Err(LogicException::new(format!( + "This should not be called on a Command which has no {} option defined.", + opt_name + )) .into()); } @@ -664,14 +644,11 @@ impl BaseCommand for BaseCommandData { .map(|s| PhpMixed::String(s.to_string())) .collect(); if !in_array_strict(val.clone(), &formats) { - return Err(InvalidArgumentException { - message: format!( - "--{} must be one of {}.", - opt_name, - Auditor::FORMATS.join(", ") - ), - code: 0, - } + return Err(InvalidArgumentException::new(format!( + "--{} must be one of {}.", + opt_name, + Auditor::FORMATS.join(", ") + )) .into()); } diff --git a/crates/shirabe/src/command/base_dependency_command.rs b/crates/shirabe/src/command/base_dependency_command.rs index 46cc654f..e46cac8c 100644 --- a/crates/shirabe/src/command/base_dependency_command.rs +++ b/crates/shirabe/src/command/base_dependency_command.rs @@ -63,12 +63,11 @@ pub trait BaseDependencyCommand: BaseCommand { let mut locker = locker.borrow_mut(); if !locker.is_locked() { - return Err(anyhow::anyhow!(UnexpectedValueException { - message: - "A valid composer.lock file is required to run this command with --locked" - .to_string(), - code: 0, - })); + return Err(UnexpectedValueException::new( + "A valid composer.lock file is required to run this command with --locked" + .to_string(), + ) + .into()); } repos.push(locker.get_locked_repository(true)?.into()); @@ -134,10 +133,11 @@ pub trait BaseDependencyCommand: BaseCommand { let packages = installed_repo.find_packages_with_replacers_and_providers(&needle, None)?; if packages.is_empty() { - return Err(anyhow::anyhow!(InvalidArgumentException { - message: format!("Could not find package \"{}\" in your project", needle), - code: 0, - })); + return Err(InvalidArgumentException::new(format!( + "Could not find package \"{}\" in your project", + needle + )) + .into()); } let matched_package = installed_repo.find_package( diff --git a/crates/shirabe/src/command/bump_command.rs b/crates/shirabe/src/command/bump_command.rs index a4518b0b..51a779ef 100644 --- a/crates/shirabe/src/command/bump_command.rs +++ b/crates/shirabe/src/command/bump_command.rs @@ -305,10 +305,10 @@ impl BumpCommand { let contents = match file_get_contents(json.get_path()) { Some(c) => c, None => { - return Err(shirabe_php_shim::RuntimeException { - message: format!("Unable to read {} contents.", json.get_path()), - code: 0, - } + return Err(shirabe_php_shim::RuntimeException::new(format!( + "Unable to read {} contents.", + json.get_path() + )) .into()); } }; @@ -325,10 +325,10 @@ impl BumpCommand { match file_put_contents(json.get_path(), manipulator.get_contents().as_bytes()) { Some(_) => Ok(true), - None => Err(shirabe_php_shim::RuntimeException { - message: format!("Unable to write new {} contents.", json.get_path()), - code: 0, - } + None => Err(shirabe_php_shim::RuntimeException::new(format!( + "Unable to write new {} contents.", + json.get_path() + )) .into()), } } diff --git a/crates/shirabe/src/command/config_command.rs b/crates/shirabe/src/command/config_command.rs index 2727f36b..3b976ba2 100644 --- a/crates/shirabe/src/command/config_command.rs +++ b/crates/shirabe/src/command/config_command.rs @@ -86,11 +86,10 @@ impl ConfigCommand { ) -> anyhow::Result<()> { let (validator, normalizer) = callbacks; if 1 != values.len() { - return Err(RuntimeException { - message: "You can only pass one value. Example: shirabe config process-timeout 300" + return Err(RuntimeException::new( + "You can only pass one value. Example: shirabe config process-timeout 300" .to_string(), - code: 0, - } + ) .into()); } @@ -101,10 +100,11 @@ impl ConfigCommand { } else { String::new() }; - return Err(RuntimeException { - message: format!("\"{}\" is an invalid value{}", values[0].clone(), suffix), - code: 0, - } + return Err(RuntimeException::new(format!( + "\"{}\" is an invalid value{}", + values[0].clone(), + suffix + )) .into()); } @@ -160,14 +160,11 @@ impl ConfigCommand { } else { String::new() }; - return Err(RuntimeException { - message: format!( - "{} is an invalid value{}", - PhpMixed::from(json_encode(&values_mixed).ok()), - suffix - ), - code: 0, - } + return Err(RuntimeException::new(format!( + "{} is an invalid value{}", + PhpMixed::from(json_encode(&values_mixed).ok()), + suffix + )) .into()); } @@ -679,10 +676,9 @@ impl Command for ConfigCommand { .unwrap_or_default(); if !setting_values.is_empty() && input.borrow().get_option("unset")?.as_bool() == Some(true) { - return Err(RuntimeException { - message: "You can not combine a setting value with --unset".to_string(), - code: 0, - } + return Err(RuntimeException::new( + "You can not combine a setting value with --unset".to_string(), + ) .into()); } @@ -731,10 +727,10 @@ impl Command for ConfigCommand { { Some(v) => v.clone(), None => { - return Err(InvalidArgumentException { - message: format!("There is no {} repository defined", repo_key), - code: 0, - } + return Err(InvalidArgumentException::new(format!( + "There is no {} repository defined", + repo_key + )) .into()); } }; @@ -766,11 +762,9 @@ impl Command for ConfigCommand { } if !r#match { - return Err(RuntimeException { - message: format!("{} is not defined.", setting_key), - code: 0, - } - .into()); + return Err( + RuntimeException::new(format!("{} is not defined.", setting_key)).into(), + ); } value = cursor; @@ -847,11 +841,9 @@ impl Command for ConfigCommand { value = v.clone(); source = "defaults".to_string(); } else { - return Err(RuntimeException { - message: format!("{} is not defined", setting_key), - code: 0, - } - .into()); + return Err( + RuntimeException::new(format!("{} is not defined", setting_key)).into(), + ); } let value_str = if is_array(&value) || is_object(&value) || is_bool(&value) { @@ -961,13 +953,10 @@ impl Command for ConfigCommand { .as_bool() .unwrap_or(false) { - return Err(RuntimeException { - message: format!( - "Invalid value for {}. Should be one of: auto, source, or dist", - setting_key - ), - code: 0, - } + return Err(RuntimeException::new(format!( + "Invalid value for {}. Should be one of: auto, source, or dist", + setting_key + )) .into()); } @@ -998,10 +987,10 @@ impl Command for ConfigCommand { } if !boolean_validator(&PhpMixed::String(values[0].clone())) { - return Err(RuntimeException { - message: format!("\"{}\" is an invalid value", values[0].clone()), - code: 0, - } + return Err(RuntimeException::new(format!( + "\"{}\" is an invalid value", + values[0].clone() + )) .into()); } @@ -1025,10 +1014,7 @@ impl Command for ConfigCommand { || multi_props.contains_key(&setting_key) || strpos(&setting_key, "extra.") == Some(0)) { - return Err(InvalidArgumentException { - message: format!("The {} property can not be set in the global config.json file. Use `composer global config` to apply changes to the global composer.json", setting_key), - code: 0, - } + return Err(InvalidArgumentException::new(format!("The {} property can not be set in the global config.json file. Use `composer global config` to apply changes to the global composer.json", setting_key)) .into()); } if input.borrow().get_option("unset")?.as_bool() == Some(true) @@ -1122,10 +1108,7 @@ impl Command for ConfigCommand { } } - return Err(RuntimeException { - message: "You must pass the type and a url. Example: shirabe config repositories.foo vcs https://bar.com".to_string(), - code: 0, - } + return Err(RuntimeException::new("You must pass the type and a url. Example: shirabe config repositories.foo vcs https://bar.com".to_string()) .into()); } @@ -1308,10 +1291,10 @@ impl Command for ConfigCommand { if input.borrow().get_option("json")?.as_bool() == Some(true) { value = JsonFile::parse_json(Some(&values[0]), Some("composer.json"))?; if !is_array(&value) { - return Err(RuntimeException { - message: format!("Expected an array or object for {}", setting_key), - code: 0, - } + return Err(RuntimeException::new(format!( + "Expected an array or object for {}", + setting_key + )) .into()); } } @@ -1349,10 +1332,10 @@ impl Command for ConfigCommand { } value = PhpMixed::Array(merged); } else { - return Err(RuntimeException { - message: format!("Cannot merge array and object for {}", setting_key), - code: 0, - } + return Err(RuntimeException::new(format!( + "Cannot merge array and object for {}", + setting_key + )) .into()); } } @@ -1394,13 +1377,10 @@ impl Command for ConfigCommand { let key = format!("{}.{}", matches[1], matches[2]); if matches[1] == "bitbucket-oauth" { if 2 != values.len() { - return Err(RuntimeException { - message: format!( - "Expected two arguments (consumer-key, consumer-secret), got {}", - values.len() - ), - code: 0, - } + return Err(RuntimeException::new(format!( + "Expected two arguments (consumer-key, consumer-secret), got {}", + values.len() + )) .into()); } self.config_source @@ -1441,10 +1421,9 @@ impl Command for ConfigCommand { "github-oauth" | "gitlab-oauth" | "gitlab-token" | "bearer" ) { if 1 != values.len() { - return Err(RuntimeException { - message: "Too many arguments, expected only one token".to_string(), - code: 0, - } + return Err(RuntimeException::new( + "Too many arguments, expected only one token".to_string(), + ) .into()); } self.config_source @@ -1459,13 +1438,10 @@ impl Command for ConfigCommand { .add_config_setting(&key, PhpMixed::String(values[0].clone())); } else if matches[1] == "http-basic" { if 2 != values.len() { - return Err(RuntimeException { - message: format!( - "Expected two arguments (username, password), got {}", - values.len() - ), - code: 0, - } + return Err(RuntimeException::new(format!( + "Expected two arguments (username, password), got {}", + values.len() + )) .into()); } self.config_source @@ -1483,10 +1459,9 @@ impl Command for ConfigCommand { .add_config_setting(&key, PhpMixed::Array(obj)); } else if matches[1] == "custom-headers" { if values.is_empty() { - return Err(RuntimeException { - message: "Expected at least one argument (header), got none".to_string(), - code: 0, - } + return Err(RuntimeException::new( + "Expected at least one argument (header), got none".to_string(), + ) .into()); } @@ -1494,12 +1469,10 @@ impl Command for ConfigCommand { let mut formatted_headers: Vec<PhpMixed> = vec![]; for header in &values { if !is_string(&PhpMixed::String(header.clone())) { - return Err(RuntimeException { - message: - "Headers must be strings in \"Header-Name: Header-Value\" format" - .to_string(), - code: 0, - } + return Err(RuntimeException::new( + "Headers must be strings in \"Header-Name: Header-Value\" format" + .to_string(), + ) .into()); } @@ -1510,13 +1483,10 @@ impl Command for ConfigCommand { header, Some(&mut header_parts), ) { - return Err(RuntimeException { - message: format!( - "Header \"{}\" is not in \"Header-Name: Header-Value\" format", - header - ), - code: 0, - } + return Err(RuntimeException::new(format!( + "Header \"{}\" is not in \"Header-Name: Header-Value\" format", + header + )) .into()); } @@ -1535,13 +1505,10 @@ impl Command for ConfigCommand { .add_config_setting(&key, PhpMixed::List(formatted_headers)); } else if matches[1] == "forgejo-token" { if 2 != values.len() { - return Err(RuntimeException { - message: format!( - "Expected two arguments (username, access token), got {}", - values.len() - ), - code: 0, - } + return Err(RuntimeException::new(format!( + "Expected two arguments (username, access token), got {}", + values.len() + )) .into()); } self.config_source @@ -1604,13 +1571,10 @@ impl Command for ConfigCommand { return Ok(0); } - Err(InvalidArgumentException { - message: format!( - "Setting {} does not exist or is not supported by this command", - setting_key - ), - code: 0, - } + Err(InvalidArgumentException::new(format!( + "Setting {} does not exist or is not supported by this command", + setting_key + )) .into()) } diff --git a/crates/shirabe/src/command/create_project_command.rs b/crates/shirabe/src/command/create_project_command.rs index aa1b79a8..267c866e 100644 --- a/crates/shirabe/src/command/create_project_command.rs +++ b/crates/shirabe/src/command/create_project_command.rs @@ -42,6 +42,7 @@ use shirabe_external_packages::symfony::console::command::command::Command; use shirabe_external_packages::symfony::console::input::InputInterface; use shirabe_external_packages::symfony::console::output::OutputInterface; use shirabe_external_packages::symfony::finder::Finder; +use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ DIRECTORY_SEPARATOR, InvalidArgumentException, PhpMixed, RuntimeException, UnexpectedValueException, array_pop, chdir, explode_with_limit, file_exists, getcwd, @@ -311,7 +312,7 @@ impl CreateProjectCommand { } } Err(e) => { - if e.downcast_ref::<PluginBlockedException>().is_some() { + if e.is_instanceof::<PluginBlockedException>() { io.write_error("<error>Hint: To allow running the config command recommended below before dependencies are installed, run create-project with --no-install.</error>"); io.write_error(&format!( "<error>You can then cd into {}, configure allow-plugins, and finally run a composer install to complete the process.</error>", @@ -365,11 +366,7 @@ impl CreateProjectCommand { for dir in &dirs { if !fs.remove_directory(dir)? { had_error = Some( - RuntimeException { - message: format!("Could not remove {}", dir.display()), - code: 0, - } - .into(), + RuntimeException::new(format!("Could not remove {}", dir.display())).into(), ); break; } @@ -485,10 +482,9 @@ impl CreateProjectCommand { ); } if directory.is_empty() { - return Err(UnexpectedValueException { - message: "Got an empty target directory, something went wrong".to_string(), - code: 0, - } + return Err(UnexpectedValueException::new( + "Got an empty target directory, something went wrong".to_string(), + ) .into()); } @@ -513,20 +509,17 @@ impl CreateProjectCommand { if file_exists(&directory) { if !is_dir(&directory) { - return Err(InvalidArgumentException { - message: format!( - "Cannot create project directory at \"{}\", it exists as a file.", - directory - ), - code: 0, - } + return Err(InvalidArgumentException::new(format!( + "Cannot create project directory at \"{}\", it exists as a file.", + directory + )) .into()); } if !fs.borrow().is_dir_empty(&directory) { - return Err(InvalidArgumentException { - message: format!("Project directory \"{}\" is not empty.", directory), - code: 0, - } + return Err(InvalidArgumentException::new(format!( + "Project directory \"{}\" is not empty.", + directory + )) .into()); } } @@ -575,20 +568,17 @@ impl CreateProjectCommand { .unwrap_or_default(); if !STABILITIES.contains_key(stability.as_str()) { - return Err(InvalidArgumentException { - message: format!( - "Invalid stability provided ({}), must be one of: {}", - stability, - implode( - ", ", - &STABILITIES - .keys() - .map(|k| k.to_string()) - .collect::<Vec<_>>() - ) - ), - code: 0, - } + return Err(InvalidArgumentException::new(format!( + "Invalid stability provided ({}), must be one of: {}", + stability, + implode( + ", ", + &STABILITIES + .keys() + .map(|k| k.to_string()) + .collect::<Vec<_>>() + ) + )) .into()); } @@ -730,21 +720,14 @@ impl CreateProjectCommand { )? .is_some() { - return Err(InvalidArgumentException { - message: format!( - "{} in a version installable using your PHP version, PHP extensions and Composer version.", - error_message - ), - code: 0, - } + return Err(InvalidArgumentException::new(format!( + "{} in a version installable using your PHP version, PHP extensions and Composer version.", + error_message + )) .into()); } - return Err(InvalidArgumentException { - message: format!("{}.", error_message), - code: 0, - } - .into()); + return Err(InvalidArgumentException::new(format!("{}.", error_message)).into()); } let mut package = package.unwrap(); @@ -936,10 +919,9 @@ impl Command for CreateProjectCommand { { let package = input.borrow().get_argument("package")?; if package.is_null() { - return Err(RuntimeException { - message: "Not enough arguments (missing: \"package\").".to_string(), - code: 0, - } + return Err(RuntimeException::new( + "Not enough arguments (missing: \"package\").".to_string(), + ) .into()); } let mut parts = diff --git a/crates/shirabe/src/command/diagnose_command.rs b/crates/shirabe/src/command/diagnose_command.rs index 72b58dea..857e517d 100644 --- a/crates/shirabe/src/command/diagnose_command.rs +++ b/crates/shirabe/src/command/diagnose_command.rs @@ -38,11 +38,12 @@ use shirabe_external_packages::symfony::console::command::command::Command; use shirabe_external_packages::symfony::console::input::InputInterface; use shirabe_external_packages::symfony::console::output::OutputInterface; use shirabe_external_packages::symfony::process::ExecutableFinder; +use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ - CmpOp, InvalidArgumentException, PHP_EOL, PhpMixed, disk_free_space, file_exists, - filter_var_boolean, get_class_err, hash, impl_php_class, implode, is_array, is_string, - php_regex, rtrim, str_contains, str_replace, str_starts_with, strpos, strstr, strstr3, - strtolower, trim, version_compare, + AnyThrowable, CmpOp, InvalidArgumentException, PHP_EOL, PhpClass as _, PhpMixed, + disk_free_space, file_exists, filter_var_boolean, hash, impl_php_class, implode, is_array, + is_string, php_regex, rtrim, str_contains, str_replace, str_starts_with, strpos, strstr, + strstr3, strtolower, trim, version_compare, }; #[derive(Debug)] @@ -106,7 +107,7 @@ impl DiagnoseCommand { match json.validate_schema(JsonFile::LOCK_SCHEMA, None) { Ok(_) => {} Err(e) => { - if let Some(jve) = e.downcast_ref::<JsonValidationException>() { + if let Some(jve) = e.catch::<JsonValidationException>() { let mut output = String::new(); for error in jve.get_errors() { output.push_str(&format!("<error>{}</error>{}", error, PHP_EOL)); @@ -191,7 +192,7 @@ impl DiagnoseCommand { ) { Ok(_) => {} Err(e) => { - if let Some(te) = e.downcast_ref::<TransportException>() { + if let Some(te) = e.catch::<TransportException>() { let hints = HttpDownloader::get_exception_hints(&e).unwrap_or_default(); if !hints.is_empty() { for hint in hints { @@ -202,7 +203,7 @@ impl DiagnoseCommand { result_list.push(PhpMixed::String(format!( "<error>[{}] {}</error>", std::any::type_name_of_val(te), - te.message + te.get_message() ))); } else { return Err(e); @@ -249,7 +250,7 @@ impl DiagnoseCommand { { Ok(_) => {} Err(e) => { - if let Some(te) = e.downcast_ref::<TransportException>() { + if let Some(te) = e.catch::<TransportException>() { let hints = HttpDownloader::get_exception_hints(&e).unwrap_or_default(); if !hints.is_empty() { for hint in hints { @@ -260,7 +261,7 @@ impl DiagnoseCommand { result_list.push(PhpMixed::String(format!( "<error>[{}] {}</error>", std::any::type_name_of_val(te), - te.message + te.get_message() ))); } else { return Err(e); @@ -394,7 +395,7 @@ impl DiagnoseCommand { ))) } Err(e) => { - if let Some(te) = e.downcast_ref::<TransportException>() + if let Some(te) = e.catch::<TransportException>() && te.get_code() == 401 { return Ok(PhpMixed::String(format!( @@ -404,7 +405,9 @@ impl DiagnoseCommand { } Ok(PhpMixed::String(format!( "<error>[{}] {}</error>", - get_class_err(&e), + AnyThrowable::of(e.as_ref()) + .expect("PHP reaches this only with a caught \\Throwable") + .php_class_name(), e ))) } @@ -540,13 +543,16 @@ impl DiagnoseCommand { Ok(Err(e)) => { return Ok(PhpMixed::String(format!( "<error>[{}] {}</error>", - "UnexpectedValueException", e.message + "UnexpectedValueException", + e.get_message() ))); } Err(e) => { return Ok(PhpMixed::String(format!( "<error>[{}] {}</error>", - get_class_err(&e), + AnyThrowable::of(e.as_ref()) + .expect("PHP reaches this only with a caught \\Throwable") + .php_class_name(), e ))); } @@ -960,13 +966,10 @@ impl DiagnoseCommand { PHP_EOL, PHP_EOL ), other => { - return Err(InvalidArgumentException { - message: format!( - "DiagnoseCommand: Unknown error type \"{}\". Please report at https://github.com/composer/composer/issues/new.", - other, - ), - code: 0, - } + return Err(InvalidArgumentException::new(format!( + "DiagnoseCommand: Unknown error type \"{}\". Please report at https://github.com/composer/composer/issues/new.", + other, + )) .into()); } }; @@ -1042,13 +1045,10 @@ impl DiagnoseCommand { PHP_EOL ), other => { - return Err(InvalidArgumentException { - message: format!( - "DiagnoseCommand: Unknown warning type \"{}\". Please report at https://github.com/composer/composer/issues/new.", - other, - ), - code: 0, - } + return Err(InvalidArgumentException::new(format!( + "DiagnoseCommand: Unknown warning type \"{}\". Please report at https://github.com/composer/composer/issues/new.", + other, + )) .into()); } }; @@ -1409,13 +1409,19 @@ impl Command for DiagnoseCommand { Ok(()) })(); if let Err(e) = proxy_check_result { - if let Some(_te) = e.downcast_ref::<TransportException>() { + if let Some(_te) = e.catch::<TransportException>() { io.write_no_newline("Checking HTTP proxy: "); let status = self.check_connectivity_and_composer_network_http_enablement(); self.output_result(if is_string(&status) { status } else { - PhpMixed::String(format!("<error>[{}] {}</error>", get_class_err(&e), e)) + PhpMixed::String(format!( + "<error>[{}] {}</error>", + AnyThrowable::of(e.as_ref()) + .expect("PHP reaches this only with a caught \\Throwable") + .php_class_name(), + e + )) }); } else { return Err(e); @@ -1455,20 +1461,24 @@ impl Command for DiagnoseCommand { } } Err(e) => { - if let Some(te) = e.downcast_ref::<TransportException>() { + if let Some(te) = e.catch::<TransportException>() { if te.get_code() == 401 { self.output_result(PhpMixed::String("<comment>The oauth token for github.com seems invalid, run \"composer config --global --unset github-oauth.github.com\" to remove it</comment>".to_string())); } else { self.output_result(PhpMixed::String(format!( "<error>[{}] {}</error>", - get_class_err(&e), + AnyThrowable::of(e.as_ref()) + .expect("PHP reaches this only with a caught \\Throwable") + .php_class_name(), e ))); } } else { self.output_result(PhpMixed::String(format!( "<error>[{}] {}</error>", - get_class_err(&e), + AnyThrowable::of(e.as_ref()) + .expect("PHP reaches this only with a caught \\Throwable") + .php_class_name(), e ))); } diff --git a/crates/shirabe/src/command/dump_autoload_command.rs b/crates/shirabe/src/command/dump_autoload_command.rs index 8aad0705..f9be4cff 100644 --- a/crates/shirabe/src/command/dump_autoload_command.rs +++ b/crates/shirabe/src/command/dump_autoload_command.rs @@ -149,10 +149,7 @@ impl Command for DumpAutoloadCommand { && !optimize && !authoritative { - return Err(InvalidArgumentException { - message: "--strict-psr mode only works with optimized autoloader, use --optimize or --classmap-authoritative if you want a strict return value.".to_string(), - code: 0, - } + return Err(InvalidArgumentException::new("--strict-psr mode only works with optimized autoloader, use --optimize or --classmap-authoritative if you want a strict return value.".to_string()) .into()); } if input @@ -163,10 +160,7 @@ impl Command for DumpAutoloadCommand { && !optimize && !authoritative { - return Err(InvalidArgumentException { - message: "--strict-ambiguous mode only works with optimized autoloader, use --optimize or --classmap-authoritative if you want a strict return value.".to_string(), - code: 0, - } + return Err(InvalidArgumentException::new("--strict-ambiguous mode only works with optimized autoloader, use --optimize or --classmap-authoritative if you want a strict return value.".to_string()) .into()); } @@ -208,12 +202,10 @@ impl Command for DumpAutoloadCommand { .as_bool() .unwrap_or(false) { - return Err(InvalidArgumentException { - message: - "You can not use both --no-dev and --dev as they conflict with each other." - .to_string(), - code: 0, - } + return Err(InvalidArgumentException::new( + "You can not use both --no-dev and --dev as they conflict with each other." + .to_string(), + ) .into()); } composer diff --git a/crates/shirabe/src/command/exec_command.rs b/crates/shirabe/src/command/exec_command.rs index d05b6c58..a67c234e 100644 --- a/crates/shirabe/src/command/exec_command.rs +++ b/crates/shirabe/src/command/exec_command.rs @@ -174,13 +174,10 @@ impl Command for ExecCommand { .as_string() .unwrap_or("") .to_string(); - return Err(RuntimeException { - message: format!( - "No binaries found in composer.json or in bin-dir ({})", - bin_dir - ), - code: 0, - } + return Err(RuntimeException::new(format!( + "No binaries found in composer.json or in bin-dir ({})", + bin_dir + )) .into()); } @@ -222,9 +219,11 @@ impl Command for ExecCommand { if let Some(ref iwd) = initial_working_directory && getcwd().as_deref() != Some(iwd.as_str()) { - chdir(iwd).map_err(|e| RuntimeException { - message: format!("Could not switch back to working directory \"{}\"", iwd), - code: 0, + chdir(iwd).map_err(|e| { + RuntimeException::new(format!( + "Could not switch back to working directory \"{}\"", + iwd + )) })?; } diff --git a/crates/shirabe/src/command/global_command.rs b/crates/shirabe/src/command/global_command.rs index 79037e55..78b6f3e6 100644 --- a/crates/shirabe/src/command/global_command.rs +++ b/crates/shirabe/src/command/global_command.rs @@ -61,11 +61,10 @@ impl GlobalCommand { } else if let Some(completion_input) = input_any.downcast_ref::<CompletionInput>() { Ok(completion_input.to_string()) } else { - Err(LogicException { - message: "Expected an Input instance that is stringable".to_string(), - code: 0, - } - .into()) + Err( + LogicException::new("Expected an Input instance that is stringable".to_string()) + .into(), + ) } } @@ -85,17 +84,14 @@ impl GlobalCommand { let mut fs = Filesystem::new(None); fs.ensure_directory_exists(&home)?; if !Path::new(&home).is_dir() { - return Err(RuntimeException { - message: "Could not create home directory".to_string(), - code: 0, - } - .into()); + return Err( + RuntimeException::new("Could not create home directory".to_string()).into(), + ); } } - chdir(&home).map_err(|_e| RuntimeException { - message: format!("Could not switch to home directory \"{}\"", home), - code: 0, + chdir(&home).map_err(|_e| { + RuntimeException::new(format!("Could not switch to home directory \"{}\"", home)) })?; if !quiet { diff --git a/crates/shirabe/src/command/init_command.rs b/crates/shirabe/src/command/init_command.rs index 5168b2ba..7b4012ce 100644 --- a/crates/shirabe/src/command/init_command.rs +++ b/crates/shirabe/src/command/init_command.rs @@ -25,6 +25,7 @@ use shirabe_external_packages::symfony::console::helper::FormatBlockMessages; use shirabe_external_packages::symfony::console::input::ArrayInput; use shirabe_external_packages::symfony::console::input::InputInterface; use shirabe_external_packages::symfony::console::output::OutputInterface; +use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ FILE_IGNORE_NEW_LINES, InvalidArgumentException, PHP_EOL, PHP_SERVER, PhpMixed, array_flip_strings, array_intersect_key, array_map, basename, empty, explode, file, @@ -99,11 +100,9 @@ impl InitCommand { if let Some(ref email) = email && !self.is_valid_email(email) { - return Err(InvalidArgumentException { - message: format!("Invalid email \"{}\"", email), - code: 0, - } - .into()); + return Err( + InvalidArgumentException::new(format!("Invalid email \"{}\"", email)).into(), + ); } let mut result: IndexMap<String, Option<String>> = IndexMap::new(); @@ -121,11 +120,8 @@ impl InitCommand { return Ok(result); } - Err(InvalidArgumentException { - message: "Invalid author string. Must be in the formats: Jane Doe or John Smith <john@example.com>" - .to_string(), - code: 0, - } + Err(InvalidArgumentException::new("Invalid author string. Must be in the formats: Jane Doe or John Smith <john@example.com>" + .to_string()) .into()) } @@ -517,13 +513,10 @@ impl Command for InitCommand { .unwrap_or(""), ) { - return Err(InvalidArgumentException { - message: format!( - "The package name {} is invalid, it should be lowercase and have a vendor name, a forward slash, and a package name, matching: [a-z0-9_.-]+/[a-z0-9_.-]+", - options.get("name").and_then(|v| v.as_string()).unwrap_or("") - ), - code: 0, - } + return Err(InvalidArgumentException::new(format!( + "The package name {} is invalid, it should be lowercase and have a vendor name, a forward slash, and a package name, matching: [a-z0-9_.-]+/[a-z0-9_.-]+", + options.get("name").and_then(|v| v.as_string()).unwrap_or("") + )) .into()); } @@ -678,7 +671,7 @@ impl Command for InitCommand { let validate_result = file_obj.validate_schema(JsonFile::LAX_SCHEMA, None); if let Err(e) = validate_result { // try to downcast to JsonValidationException - if let Some(json_err) = e.downcast_ref::<JsonValidationException>() { + if let Some(json_err) = e.catch::<JsonValidationException>() { io.write_error3( "<error>Schema validation error, aborting</error>", true, @@ -926,13 +919,10 @@ impl Command for InitCommand { php_regex!(r"{^[a-z0-9]([_.-]?[a-z0-9]+)*\/[a-z0-9](([_.]|-{1,2})?[a-z0-9]+)*$}D"), value.as_string().unwrap_or(""), ) { - return Err(InvalidArgumentException { - message: format!( - "The package name {} is invalid, it should be lowercase and have a vendor name, a forward slash, and a package name, matching: [a-z0-9_.-]+/[a-z0-9_.-]+", - value.as_string().unwrap_or("") - ), - code: 0, - } + return Err(InvalidArgumentException::new(format!( + "The package name {} is invalid, it should be lowercase and have a vendor name, a forward slash, and a package name, matching: [a-z0-9_.-]+/[a-z0-9_.-]+", + value.as_string().unwrap_or("") + )) .into()); } @@ -1031,20 +1021,17 @@ impl Command for InitCommand { } if !base_package::STABILITIES.contains_key(value.as_string().unwrap_or("")) { - return Err(InvalidArgumentException { - message: format!( - "Invalid minimum stability \"{}\". Must be empty or one of: {}", - value.as_string().unwrap_or(""), - implode( - ", ", - &base_package::STABILITIES - .keys() - .map(|k| k.to_string()) - .collect::<Vec<_>>() - ) - ), - code: 0, - } + return Err(InvalidArgumentException::new(format!( + "Invalid minimum stability \"{}\". Must be empty or one of: {}", + value.as_string().unwrap_or(""), + implode( + ", ", + &base_package::STABILITIES + .keys() + .map(|k| k.to_string()) + .collect::<Vec<_>>() + ) + )) .into()); } @@ -1107,13 +1094,10 @@ impl Command for InitCommand { && !spdx.validate(license.as_string().unwrap_or("")) && license.as_string() != Some("proprietary") { - return Err(InvalidArgumentException { - message: format!( + return Err(InvalidArgumentException::new(format!( "Invalid license provided: {}. Only SPDX license identifiers (https://spdx.org/licenses/) or \"proprietary\" are accepted.", license.as_string().unwrap_or("") - ), - code: 0, - } + )) .into()); } input.borrow_mut().set_option("license", license); @@ -1246,13 +1230,10 @@ impl Command for InitCommand { if !Preg::is_match(php_regex!(r"{^[^/][A-Za-z0-9\-_/]+/$}"), &value_or_default) { - return Err(InvalidArgumentException { - message: format!( - "The src folder name \"{}\" is invalid. Please add a relative path with tailing forward slash. [A-Za-z0-9_-/]+/", - value_or_default, - ), - code: 0, - } + return Err(InvalidArgumentException::new(format!( + "The src folder name \"{}\" is invalid. Please add a relative path with tailing forward slash. [A-Za-z0-9_-/]+/", + value_or_default, + )) .into()); } diff --git a/crates/shirabe/src/command/licenses_command.rs b/crates/shirabe/src/command/licenses_command.rs index 41e9ba90..1b2ec6b6 100644 --- a/crates/shirabe/src/command/licenses_command.rs +++ b/crates/shirabe/src/command/licenses_command.rs @@ -128,10 +128,7 @@ impl Command for LicensesCommand { let locker = composer.get_locker().clone(); let mut locker = locker.borrow_mut(); if !locker.is_locked() { - return Err(UnexpectedValueException { - message: "Valid composer.json and composer.lock files are required to run this command with --locked".to_string(), - code: 0, - }.into()); + return Err(UnexpectedValueException::new("Valid composer.json and composer.lock files are required to run this command with --locked".to_string()).into()); } let no_dev = input .borrow() @@ -314,13 +311,10 @@ impl Command for LicensesCommand { ); } _ => { - return Err(RuntimeException { - message: format!( - "Unsupported format \"{}\". See help for supported formats.", - format - ), - code: 0, - } + return Err(RuntimeException::new(format!( + "Unsupported format \"{}\". See help for supported formats.", + format + )) .into()); } } diff --git a/crates/shirabe/src/command/package_discovery_trait.rs b/crates/shirabe/src/command/package_discovery_trait.rs index db7db488..17332083 100644 --- a/crates/shirabe/src/command/package_discovery_trait.rs +++ b/crates/shirabe/src/command/package_discovery_trait.rs @@ -22,6 +22,7 @@ use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; use shirabe_external_packages::symfony::console::input::InputInterface; use shirabe_external_packages::symfony::console::output::OutputInterface; +use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ Exception, InvalidArgumentException, LogicException, PHP_EOL, PhpMixed, array_keys, array_slice, asort, explode, file_get_contents, implode, in_array_strict, is_array, is_file, @@ -359,11 +360,7 @@ pub trait PackageDiscoveryTrait: BaseCommand { )); } - Err(Exception { - message: "Not a valid selection".to_string(), - code: 0, - } - .into()) + Err(Exception::new("Not a valid selection".to_string()).into()) }, ); @@ -541,17 +538,14 @@ pub trait PackageDiscoveryTrait: BaseCommand { ShowWarnings::Always, )?; if let Some(candidate) = candidate { - return Err(InvalidArgumentException { - message: format!( - "Package {} has requirements incompatible with your PHP version, PHP extensions and Composer version{}", - name, - self.get_platform_exception_details( - candidate, - platform_repo, - )?, - ), - code: 0, - } + return Err(InvalidArgumentException::new(format!( + "Package {} has requirements incompatible with your PHP version, PHP extensions and Composer version{}", + name, + self.get_platform_exception_details( + candidate, + platform_repo, + )?, + )) .into()); } } @@ -577,34 +571,28 @@ pub trait PackageDiscoveryTrait: BaseCommand { ShowWarnings::Always, )?; if let Some(all_repos_package) = all_repos_package { - return Err(InvalidArgumentException { - message: format!( - "Package {} exists in {} and {} which has a higher repository priority. The packages from the higher priority repository do not match your minimum-stability and are therefore not installable. That repository is canonical so the lower priority repo's packages are not installable. See https://getcomposer.org/repoprio for details and assistance.", - name, - all_repos_package - .get_repository() - .map(|r| r.get_repo_name()) - .transpose()? - .unwrap_or_default(), - package - .get_repository() - .map(|r| r.get_repo_name()) - .transpose()? - .unwrap_or_default(), - ), - code: 0, - } + return Err(InvalidArgumentException::new(format!( + "Package {} exists in {} and {} which has a higher repository priority. The packages from the higher priority repository do not match your minimum-stability and are therefore not installable. That repository is canonical so the lower priority repo's packages are not installable. See https://getcomposer.org/repoprio for details and assistance.", + name, + all_repos_package + .get_repository() + .map(|r| r.get_repo_name()) + .transpose()? + .unwrap_or_default(), + package + .get_repository() + .map(|r| r.get_repo_name()) + .transpose()? + .unwrap_or_default(), + )) .into()); } - return Err(InvalidArgumentException { - message: format!( - "Could not find a version of package {} matching your minimum-stability ({}). Require it with an explicit version constraint allowing its desired stability.", - name, - effective_minimum_stability, - ), - code: 0, - } + return Err(InvalidArgumentException::new(format!( + "Could not find a version of package {} matching your minimum-stability ({}). Require it with an explicit version constraint allowing its desired stability.", + name, + effective_minimum_stability, + )) .into()); } // Check whether the PHP version was the problem for all versions @@ -639,18 +627,15 @@ pub trait PackageDiscoveryTrait: BaseCommand { ); } - return Err(InvalidArgumentException { - message: format!( - "Could not find package {} in any version matching your PHP version, PHP extensions and Composer version{}{}", - name, - self.get_platform_exception_details( - candidate, - platform_repo, - )?, - additional, - ), - code: 0, - } + return Err(InvalidArgumentException::new(format!( + "Could not find package {} in any version matching your PHP version, PHP extensions and Composer version{}{}", + name, + self.get_platform_exception_details( + candidate, + platform_repo, + )?, + additional, + )) .into()); } } @@ -665,13 +650,10 @@ pub trait PackageDiscoveryTrait: BaseCommand { .map(|s| PhpMixed::String(s.clone())) .collect::<Vec<_>>(), ) { - return Err(InvalidArgumentException { - message: format!( - "Could not find package {}. It was however found via repository search, which indicates a consistency issue with the repository.", - name, - ), - code: 0, - } + return Err(InvalidArgumentException::new(format!( + "Could not find package {}. It was however found via repository search, which indicates a consistency issue with the repository.", + name, + )) .into()); } @@ -704,30 +686,24 @@ pub trait PackageDiscoveryTrait: BaseCommand { } } - return Err(InvalidArgumentException { - message: format!( - "Could not find package {}.\n\nDid you mean {}?\n {}", - name, - if similar.len() > 1 { - "one of these" - } else { - "this" - }, - implode("\n ", &similar), - ), - code: 0, - } + return Err(InvalidArgumentException::new(format!( + "Could not find package {}.\n\nDid you mean {}?\n {}", + name, + if similar.len() > 1 { + "one of these" + } else { + "this" + }, + implode("\n ", &similar), + )) .into()); } - return Err(InvalidArgumentException { - message: format!( - "Could not find a matching version of package {}. Check the package spelling, your version constraint and that the package is available in a stability which matches your minimum-stability ({}).", - name, - effective_minimum_stability, - ), - code: 0, - } + return Err(InvalidArgumentException::new(format!( + "Could not find a matching version of package {}. Check the package spelling, your version constraint and that the package is available in a stability which matches your minimum-stability ({}).", + name, + effective_minimum_stability, + )) .into()); } @@ -745,11 +721,9 @@ pub trait PackageDiscoveryTrait: BaseCommand { fn find_similar(&self, package: &str) -> anyhow::Result<Vec<String>> { let results: Vec<SearchResult> = match (|| -> anyhow::Result<Vec<SearchResult>> { if self.get_repos_mut().is_none() { - return Err(LogicException { - message: "findSimilar was called before $this->repos was initialized" - .to_string(), - code: 0, - } + return Err(LogicException::new( + "findSimilar was called before $this->repos was initialized".to_string(), + ) .into()); } self.get_repos_mut() @@ -760,7 +734,7 @@ pub trait PackageDiscoveryTrait: BaseCommand { Ok(r) => r, Err(e) => { // PHP: if ($e instanceof \LogicException) throw $e; - if e.downcast_ref::<LogicException>().is_some() { + if e.is_instanceof::<LogicException>() { return Err(e); } diff --git a/crates/shirabe/src/command/reinstall_command.rs b/crates/shirabe/src/command/reinstall_command.rs index b16b6c92..f9753f2a 100644 --- a/crates/shirabe/src/command/reinstall_command.rs +++ b/crates/shirabe/src/command/reinstall_command.rs @@ -98,12 +98,10 @@ impl Command for ReinstallCommand { if type_count > 0 { if packages_count > 0 { - return Err(InvalidArgumentException { - message: - "You cannot specify package names and filter by type at the same time." - .to_string(), - code: 0, - } + return Err(InvalidArgumentException::new( + "You cannot specify package names and filter by type at the same time." + .to_string(), + ) .into()); } let filter_types: Vec<String> = type_option @@ -122,11 +120,9 @@ impl Command for ReinstallCommand { } } else { if packages_count == 0 { - return Err(InvalidArgumentException { - message: "You must pass one or more package names to be reinstalled." - .to_string(), - code: 0, - } + return Err(InvalidArgumentException::new( + "You must pass one or more package names to be reinstalled.".to_string(), + ) .into()); } let patterns: Vec<String> = packages_arg diff --git a/crates/shirabe/src/command/remove_command.rs b/crates/shirabe/src/command/remove_command.rs index 77deaf14..e89e9535 100644 --- a/crates/shirabe/src/command/remove_command.rs +++ b/crates/shirabe/src/command/remove_command.rs @@ -193,12 +193,10 @@ impl Command for RemoveCommand { .as_bool() .unwrap_or(false) { - return Err(anyhow::anyhow!(InvalidArgumentException( - shirabe_php_shim::InvalidArgumentException { - message: "Not enough arguments (missing: \"packages\").".to_string(), - code: 0, - } - ))); + return Err(InvalidArgumentException::new( + "Not enough arguments (missing: \"packages\").".to_string(), + ) + .into()); } let mut packages: Vec<String> = input @@ -224,12 +222,11 @@ impl Command for RemoveCommand { let locker = composer.get_locker().clone(); let mut locker = locker.borrow_mut(); if !locker.is_locked() { - return Err(anyhow::anyhow!(UnexpectedValueException { - message: - "A valid composer.lock file is required to run this command with --unused" - .to_string(), - code: 0, - })); + return Err(UnexpectedValueException::new( + "A valid composer.lock file is required to run this command with --unused" + .to_string(), + ) + .into()); } } diff --git a/crates/shirabe/src/command/repository_command.rs b/crates/shirabe/src/command/repository_command.rs index ab2cf2d4..47fd2d28 100644 --- a/crates/shirabe/src/command/repository_command.rs +++ b/crates/shirabe/src/command/repository_command.rs @@ -362,26 +362,20 @@ impl Command for RepositoryCommand { } "add" => { if name.is_none() { - return Err(anyhow::anyhow!(RuntimeException { - message: "You must pass a repository name. Example: composer repo add foo vcs https://example.org".to_string(), - code: 0, - })); + return Err(RuntimeException::new("You must pass a repository name. Example: composer repo add foo vcs https://example.org".to_string()).into()); } if arg1.is_none() { - return Err(anyhow::anyhow!(RuntimeException { - message: "You must pass the type and a url, or a JSON string.".to_string(), - code: 0, - })); + return Err(RuntimeException::new( + "You must pass the type and a url, or a JSON string.".to_string(), + ) + .into()); } let arg1_str = arg1.as_deref().unwrap(); let repo_config: PhpMixed = if Preg::is_match(php_regex!(r"{^\s*\{}"), arg1_str) { JsonFile::parse_json(Some(arg1_str), None)? } else { if arg2.is_none() { - return Err(anyhow::anyhow!(RuntimeException { - message: "You must pass the type and a url. Example: composer repo add foo vcs https://example.org".to_string(), - code: 0, - })); + return Err(RuntimeException::new("You must pass the type and a url. Example: composer repo add foo vcs https://example.org".to_string()).into()); } let mut m = IndexMap::new(); m.insert("type".to_string(), PhpMixed::String(arg1_str.to_string())); @@ -400,19 +394,19 @@ impl Command for RepositoryCommand { .as_string() .map(|s| s.to_string()); if before.is_some() && after.is_some() { - return Err(anyhow::anyhow!(RuntimeException { - message: "You can not combine --before and --after".to_string(), - code: 0, - })); + return Err(RuntimeException::new( + "You can not combine --before and --after".to_string(), + ) + .into()); } if before.is_some() || after.is_some() { if matches!(repo_config, PhpMixed::Bool(false)) { - return Err(anyhow::anyhow!(RuntimeException { - message: "Cannot use --before/--after with boolean repository values" + return Err(RuntimeException::new( + "Cannot use --before/--after with boolean repository values" .to_string(), - code: 0, - })); + ) + .into()); } let reference_name = before.as_deref().or(after.as_deref()).unwrap(); let offset: i64 = if after.is_some() { 1 } else { 0 }; @@ -443,10 +437,10 @@ impl Command for RepositoryCommand { } "remove" | "rm" | "delete" => { if name.is_none() { - return Err(anyhow::anyhow!(RuntimeException { - message: "You must pass the repository name to remove.".to_string(), - code: 0, - })); + return Err(RuntimeException::new( + "You must pass the repository name to remove.".to_string(), + ) + .into()); } let name_str = name.as_deref().unwrap(); self.config_source @@ -465,10 +459,10 @@ impl Command for RepositoryCommand { } "set-url" | "seturl" => { if name.is_none() || arg1.is_none() { - return Err(anyhow::anyhow!(RuntimeException { - message: "Usage: composer repo set-url <name> <new-url>".to_string(), - code: 0, - })); + return Err(RuntimeException::new( + "Usage: composer repo set-url <name> <new-url>".to_string(), + ) + .into()); } self.config_source .borrow_mut() @@ -479,10 +473,10 @@ impl Command for RepositoryCommand { } "get-url" | "geturl" => { if name.is_none() { - return Err(anyhow::anyhow!(RuntimeException { - message: "Usage: composer repo get-url <name>".to_string(), - code: 0, - })); + return Err(RuntimeException::new( + "Usage: composer repo get-url <name>".to_string(), + ) + .into()); } let name_str = name.as_deref().unwrap(); if let Some(repo) = repos.get(name_str) @@ -493,10 +487,11 @@ impl Command for RepositoryCommand { self.get_io().write(url); return Ok(0); } - return Err(anyhow::anyhow!(InvalidArgumentException { - message: format!("The {} repository does not have a URL", name_str), - code: 0, - })); + return Err(InvalidArgumentException::new(format!( + "The {} repository does not have a URL", + name_str + )) + .into()); } for (_key, val) in &repos { if let PhpMixed::Array(ref repo_map) = *val @@ -508,23 +503,25 @@ impl Command for RepositoryCommand { self.get_io().write(url); return Ok(0); } - return Err(anyhow::anyhow!(InvalidArgumentException { - message: format!("The {} repository does not have a URL", name_str), - code: 0, - })); + return Err(InvalidArgumentException::new(format!( + "The {} repository does not have a URL", + name_str + )) + .into()); } } - Err(anyhow::anyhow!(InvalidArgumentException { - message: format!("There is no {} repository defined", name_str), - code: 0, - })) + Err(InvalidArgumentException::new(format!( + "There is no {} repository defined", + name_str + )) + .into()) } "disable" => { if name.is_none() { - return Err(anyhow::anyhow!(RuntimeException { - message: "Usage: composer repo disable packagist.org".to_string(), - code: 0, - })); + return Err(RuntimeException::new( + "Usage: composer repo disable packagist.org".to_string(), + ) + .into()); } let name_str = name.as_deref().unwrap(); if ["packagist", "packagist.org"].contains(&name_str) { @@ -540,17 +537,14 @@ impl Command for RepositoryCommand { .add_repository("packagist.org", PhpMixed::Bool(false), append); return Ok(0); } - Err(anyhow::anyhow!(RuntimeException { - message: "Only packagist.org can be enabled/disabled using this command. Use add/remove for other repositories.".to_string(), - code: 0, - })) + Err(RuntimeException::new("Only packagist.org can be enabled/disabled using this command. Use add/remove for other repositories.".to_string()).into()) } "enable" => { if name.is_none() { - return Err(anyhow::anyhow!(RuntimeException { - message: "Usage: composer repo enable packagist.org".to_string(), - code: 0, - })); + return Err(RuntimeException::new( + "Usage: composer repo enable packagist.org".to_string(), + ) + .into()); } let name_str = name.as_deref().unwrap(); if ["packagist", "packagist.org"].contains(&name_str) { @@ -561,19 +555,16 @@ impl Command for RepositoryCommand { .remove_repository("packagist.org"); return Ok(0); } - Err(anyhow::anyhow!(RuntimeException { - message: "Only packagist.org can be enabled/disabled using this command." - .to_string(), - code: 0, - })) + Err(RuntimeException::new( + "Only packagist.org can be enabled/disabled using this command.".to_string(), + ) + .into()) } - _ => Err(anyhow::anyhow!(InvalidArgumentException { - message: format!( - "Unknown action \"{}\". Use list, add, remove, set-url, get-url, enable, disable", - action - ), - code: 0, - })), + _ => Err(InvalidArgumentException::new(format!( + "Unknown action \"{}\". Use list, add, remove, set-url, get-url, enable, disable", + action + )) + .into()), } } diff --git a/crates/shirabe/src/command/require_command.rs b/crates/shirabe/src/command/require_command.rs index 85e53a37..84b4a6e4 100644 --- a/crates/shirabe/src/command/require_command.rs +++ b/crates/shirabe/src/command/require_command.rs @@ -977,13 +977,10 @@ impl Command for RequireCommand { if self.newly_created.get() { self.revert_composer_file(); - return Err(RuntimeException { - message: format!( - "No composer.json present in the current directory ({}), this may be the cause of the following exception.", - self.file.borrow() - ), - code: 0, - } + return Err(RuntimeException::new(format!( + "No composer.json present in the current directory ({}), this may be the cause of the following exception.", + self.file.borrow() + )) .into()); } diff --git a/crates/shirabe/src/command/run_script_command.rs b/crates/shirabe/src/command/run_script_command.rs index fe020de3..be50c4be 100644 --- a/crates/shirabe/src/command/run_script_command.rs +++ b/crates/shirabe/src/command/run_script_command.rs @@ -16,6 +16,7 @@ use shirabe_external_packages::symfony::console::exception::CommandNotFoundExcep use shirabe_external_packages::symfony::console::exception::namespace_not_found_exception::NamespaceNotFoundException; use shirabe_external_packages::symfony::console::input::InputInterface; use shirabe_external_packages::symfony::console::output::OutputInterface; +use shirabe_php_shim::Catch as _; use shirabe_php_shim::{InvalidArgumentException, RuntimeException}; use shirabe_php_shim::{PhpMixed, impl_php_class}; @@ -102,8 +103,8 @@ impl RunScriptCommand { match application.borrow_mut().find(&name) { Ok(cmd) => description = cmd.borrow().get_description(), Err(e) - if e.downcast_ref::<CommandNotFoundException>().is_some() - || e.downcast_ref::<NamespaceNotFoundException>().is_some() => {} + if e.is_instanceof::<CommandNotFoundException>() + || e.is_instanceof::<NamespaceNotFoundException>() => {} Err(e) => return Err(e), } } @@ -255,10 +256,9 @@ impl Command for RunScriptCommand { let script = match input.borrow().get_argument("script")?.as_string() { None => { - return Err(RuntimeException { - message: "Missing required argument \"script\"".to_string(), - code: 0, - } + return Err(RuntimeException::new( + "Missing required argument \"script\"".to_string(), + ) .into()); } Some(s) => s.to_string(), @@ -267,10 +267,10 @@ impl Command for RunScriptCommand { if !self.script_events.contains(&script.as_str()) { let const_name = script.to_uppercase().replace('-', "_"); if ScriptEvents::is_defined(&const_name) { - return Err(InvalidArgumentException { - message: format!("Script \"{}\" cannot be run with this command", script), - code: 0, - } + return Err(InvalidArgumentException::new(format!( + "Script \"{}\" cannot be run with this command", + script + )) .into()); } } @@ -299,10 +299,10 @@ impl Command for RunScriptCommand { ); let has_listeners = dispatcher.borrow_mut().has_event_listeners(&event); if !has_listeners { - return Err(InvalidArgumentException { - message: format!("Script \"{}\" is not defined in this package", script), - code: 0, - } + return Err(InvalidArgumentException::new(format!( + "Script \"{}\" is not defined in this package", + script + )) .into()); } @@ -320,12 +320,10 @@ impl Command for RunScriptCommand { if let Some(timeout_val) = input.borrow().get_option("timeout")?.as_string() { let timeout_str = timeout_val.to_string(); if !timeout_str.chars().all(|c| c.is_ascii_digit()) { - return Err(RuntimeException { - message: - "Timeout value must be numeric and positive if defined, or 0 for forever" - .to_string(), - code: 0, - } + return Err(RuntimeException::new( + "Timeout value must be numeric and positive if defined, or 0 for forever" + .to_string(), + ) .into()); } let timeout: i64 = timeout_str.parse().unwrap_or(0); diff --git a/crates/shirabe/src/command/script_alias_command.rs b/crates/shirabe/src/command/script_alias_command.rs index e6a13545..e3faf3a6 100644 --- a/crates/shirabe/src/command/script_alias_command.rs +++ b/crates/shirabe/src/command/script_alias_command.rs @@ -36,12 +36,10 @@ impl ScriptAliasCommand { for alias in &aliases { if !is_string(&PhpMixed::String(alias.clone())) { - return Err(InvalidArgumentException { - message: - r#""scripts-aliases" element array values should contain only strings"# - .to_string(), - code: 0, - } + return Err(InvalidArgumentException::new( + r#""scripts-aliases" element array values should contain only strings"# + .to_string(), + ) .into()); } } @@ -123,10 +121,9 @@ impl Command for ScriptAliasCommand { // TODO(phase-c): InputInterface has_to_string/get_class_name not modeled in Rust // TODO remove for Symfony 6+ as it is then in the interface if false { - return Err(LogicException { - message: "Expected an Input instance that is stringable".to_string(), - code: 0, - } + return Err(LogicException::new( + "Expected an Input instance that is stringable".to_string(), + ) .into()); } diff --git a/crates/shirabe/src/command/search_command.rs b/crates/shirabe/src/command/search_command.rs index 4bf75c8b..51432ed9 100644 --- a/crates/shirabe/src/command/search_command.rs +++ b/crates/shirabe/src/command/search_command.rs @@ -181,10 +181,9 @@ impl Command for SearchCommand { .as_bool() .unwrap_or(false) { - return Err(InvalidArgumentException { - message: "--only-name and --only-vendor cannot be used together".to_string(), - code: 0, - } + return Err(InvalidArgumentException::new( + "--only-name and --only-vendor cannot be used together".to_string(), + ) .into()); } mode = repository_interface::SEARCH_NAME; diff --git a/crates/shirabe/src/command/show_command.rs b/crates/shirabe/src/command/show_command.rs index aa63d8e7..6c693e62 100644 --- a/crates/shirabe/src/command/show_command.rs +++ b/crates/shirabe/src/command/show_command.rs @@ -359,14 +359,11 @@ impl ShowCommand { if let Some(ref mp) = matched_package && mp.as_complete().is_none() { - return Err(LogicException { - message: format!( - "ShowCommand::getPackage can only work with CompletePackageInterface, but got {}", - shirabe_php_shim::get_class(&PhpMixed::Null) - ), - code: 0, - } - .into()); + return Err(LogicException::new(format!( + "ShowCommand::getPackage can only work with CompletePackageInterface, but got {}", + shirabe_php_shim::get_class(&PhpMixed::Null) + )) + .into()); } let matched_package = matched_package.and_then(|mp| mp.as_complete()); @@ -1817,10 +1814,9 @@ impl Command for ShowCommand { .as_string() .is_some() { - return Err(InvalidArgumentException { - message: "You cannot use --self together with a package name".to_string(), - code: 0, - } + return Err(InvalidArgumentException::new( + "You cannot use --self together with a package name".to_string(), + ) .into()); } installed_repo = RepositoryInterfaceHandle::new(InstalledRepository::new(vec