aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/shirabe/src/command
diff options
context:
space:
mode:
Diffstat (limited to 'crates/shirabe/src/command')
-rw-r--r--crates/shirabe/src/command/about_command.rs6
-rw-r--r--crates/shirabe/src/command/archive_command.rs21
-rw-r--r--crates/shirabe/src/command/audit_command.rs8
-rw-r--r--crates/shirabe/src/command/base_command.rs94
-rw-r--r--crates/shirabe/src/command/base_config_command.rs2
-rw-r--r--crates/shirabe/src/command/base_dependency_command.rs9
-rw-r--r--crates/shirabe/src/command/bump_command.rs14
-rw-r--r--crates/shirabe/src/command/check_platform_reqs_command.rs10
-rw-r--r--crates/shirabe/src/command/clear_cache_command.rs6
-rw-r--r--crates/shirabe/src/command/config_command.rs57
-rw-r--r--crates/shirabe/src/command/create_project_command.rs181
-rw-r--r--crates/shirabe/src/command/depends_command.rs6
-rw-r--r--crates/shirabe/src/command/diagnose_command.rs83
-rw-r--r--crates/shirabe/src/command/dump_autoload_command.rs8
-rw-r--r--crates/shirabe/src/command/exec_command.rs32
-rw-r--r--crates/shirabe/src/command/fund_command.rs52
-rw-r--r--crates/shirabe/src/command/global_command.rs8
-rw-r--r--crates/shirabe/src/command/home_command.rs20
-rw-r--r--crates/shirabe/src/command/init_command.rs31
-rw-r--r--crates/shirabe/src/command/install_command.rs10
-rw-r--r--crates/shirabe/src/command/licenses_command.rs9
-rw-r--r--crates/shirabe/src/command/outdated_command.rs6
-rw-r--r--crates/shirabe/src/command/package_discovery_trait.rs58
-rw-r--r--crates/shirabe/src/command/prohibits_command.rs6
-rw-r--r--crates/shirabe/src/command/reinstall_command.rs19
-rw-r--r--crates/shirabe/src/command/remove_command.rs54
-rw-r--r--crates/shirabe/src/command/repository_command.rs66
-rw-r--r--crates/shirabe/src/command/require_command.rs15
-rw-r--r--crates/shirabe/src/command/run_script_command.rs10
-rw-r--r--crates/shirabe/src/command/script_alias_command.rs4
-rw-r--r--crates/shirabe/src/command/search_command.rs8
-rw-r--r--crates/shirabe/src/command/self_update_command.rs6
-rw-r--r--crates/shirabe/src/command/show_command.rs508
-rw-r--r--crates/shirabe/src/command/status_command.rs83
-rw-r--r--crates/shirabe/src/command/suggests_command.rs6
-rw-r--r--crates/shirabe/src/command/update_command.rs60
-rw-r--r--crates/shirabe/src/command/validate_command.rs13
37 files changed, 855 insertions, 734 deletions
diff --git a/crates/shirabe/src/command/about_command.rs b/crates/shirabe/src/command/about_command.rs
index e476bb6..8ca44db 100644
--- a/crates/shirabe/src/command/about_command.rs
+++ b/crates/shirabe/src/command/about_command.rs
@@ -25,6 +25,12 @@ pub struct AboutCommand {
base_command_data: BaseCommandData,
}
+impl Default for AboutCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl AboutCommand {
pub fn new() -> Self {
let mut command = AboutCommand {
diff --git a/crates/shirabe/src/command/archive_command.rs b/crates/shirabe/src/command/archive_command.rs
index cd5fa04..1a043af 100644
--- a/crates/shirabe/src/command/archive_command.rs
+++ b/crates/shirabe/src/command/archive_command.rs
@@ -40,6 +40,12 @@ pub struct ArchiveCommand {
base_command_data: BaseCommandData,
}
+impl Default for ArchiveCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl ArchiveCommand {
const FORMATS: &'static [&'static str] = &["tar", "tar.gz", "tar.bz2", "zip"];
@@ -201,6 +207,7 @@ impl BaseCommand for ArchiveCommand {
}
impl ArchiveCommand {
+ #[allow(clippy::too_many_arguments, reason = "to keep PHP signature")]
pub fn archive(
&mut self,
io: std::rc::Rc<std::cell::RefCell<dyn IOInterface>>,
@@ -239,7 +246,7 @@ impl ArchiveCommand {
Some(process),
)));
owned_archive_manager =
- factory.create_archive_manager(&*config.borrow(), &download_manager, &loop_)?;
+ factory.create_archive_manager(&config.borrow(), &download_manager, &loop_)?;
&mut owned_archive_manager
};
@@ -299,12 +306,7 @@ impl ArchiveCommand {
let repository_manager = repository_manager.borrow();
let local_repo = repository_manager.get_local_repository();
let mut repos: Vec<crate::repository::RepositoryInterfaceHandle> = vec![local_repo];
- repos.extend(
- repository_manager
- .get_repositories()
- .iter()
- .map(|r| r.clone()),
- );
+ repos.extend(repository_manager.get_repositories().iter().cloned());
repo = CompositeRepository::new(repos);
min_stability = composer.get_package().get_minimum_stability().to_string();
} else {
@@ -368,7 +370,7 @@ impl ArchiveCommand {
None,
shirabe_php_shim::PhpMixed::Bool(true),
)?;
- let p = best.unwrap_or_else(|| packages.into_iter().next().unwrap().into());
+ let p = best.unwrap_or_else(|| packages.into_iter().next().unwrap());
io.write_error(&format!(
"<info>Found multiple matches, selected {}.</info>",
@@ -378,8 +380,7 @@ impl ArchiveCommand {
io.write_error("<comment>Please use a more specific constraint to pick a different package.</comment>");
p
} else if packages.len() == 1 {
- let p: crate::package::PackageInterfaceHandle =
- packages.into_iter().next().unwrap().into();
+ let p: crate::package::PackageInterfaceHandle = packages.into_iter().next().unwrap();
io.write_error(&format!(
"<info>Found an exact match {}.</info>",
p.get_pretty_string()
diff --git a/crates/shirabe/src/command/audit_command.rs b/crates/shirabe/src/command/audit_command.rs
index 4677b40..3014736 100644
--- a/crates/shirabe/src/command/audit_command.rs
+++ b/crates/shirabe/src/command/audit_command.rs
@@ -34,6 +34,12 @@ pub struct AuditCommand {
base_command_data: BaseCommandData,
}
+impl Default for AuditCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl AuditCommand {
pub fn new() -> Self {
let mut command = AuditCommand {
@@ -147,7 +153,7 @@ impl Command for AuditCommand {
}
let audit_config = AuditConfig::from_config(
- &mut *composer.get_config().borrow_mut(),
+ &mut composer.get_config().borrow_mut(),
true,
Auditor::FORMAT_SUMMARY,
)?;
diff --git a/crates/shirabe/src/command/base_command.rs b/crates/shirabe/src/command/base_command.rs
index 24c1bbf..c6b5550 100644
--- a/crates/shirabe/src/command/base_command.rs
+++ b/crates/shirabe/src/command/base_command.rs
@@ -287,20 +287,20 @@ impl BaseCommand for BaseCommandData {
disable_plugins: Option<bool>,
disable_scripts: Option<bool>,
) -> Option<PartialComposerHandle> {
- if self.composer.is_none() {
- if let Some(application) = self.get_application() {
- let result = {
- let mut app_ref = application.borrow_mut();
- let app_dyn: &mut dyn shirabe_external_packages::symfony::console::application::Application = &mut *app_ref;
- let app = app_dyn
- .as_any_mut()
- .downcast_mut::<Application>()
- .expect("a Composer command's application is a shirabe Application");
- app.get_composer(false, disable_plugins, disable_scripts)
- };
- if let Ok(composer) = result {
- self.composer = composer;
- }
+ if self.composer.is_none()
+ && let Some(application) = self.get_application()
+ {
+ let result = {
+ let mut app_ref = application.borrow_mut();
+ let app_dyn: &mut dyn shirabe_external_packages::symfony::console::application::Application = &mut *app_ref;
+ let app = app_dyn
+ .as_any_mut()
+ .downcast_mut::<Application>()
+ .expect("a Composer command's application is a shirabe Application");
+ app.get_composer(false, disable_plugins, disable_scripts)
+ };
+ if let Ok(composer) = result {
+ self.composer = composer;
}
}
@@ -399,7 +399,7 @@ impl BaseCommand for BaseCommandData {
"dist" => {
prefer_dist = true;
}
- "auto" | _ => {
+ _ => {
// noop
}
}
@@ -523,21 +523,18 @@ impl BaseCommand for BaseCommandData {
.into());
}
- if true
- == input
- .borrow()
- .get_option("ignore-platform-reqs")?
- .as_bool()
- .unwrap_or(false)
+ if input
+ .borrow()
+ .get_option("ignore-platform-reqs")?
+ .as_bool()
+ .unwrap_or(false)
{
return Ok(PlatformRequirementFilterFactory::ignore_all());
}
let ignores = input.borrow().get_option("ignore-platform-req")?;
if count(&ignores) > 0 {
- return Ok(PlatformRequirementFilterFactory::from_bool_or_list(
- ignores,
- )?);
+ return PlatformRequirementFilterFactory::from_bool_or_list(ignores);
}
Ok(PlatformRequirementFilterFactory::ignore_nothing())
@@ -664,7 +661,7 @@ impl BaseCommand for BaseCommandData {
let audit_config = AuditConfig::from_config(config, audit, &audit_format)?;
if Platform::get_env("COMPOSER_NO_SECURITY_BLOCKING")
- .map_or(false, |s| !s.is_empty() && s != "0")
+ .is_some_and(|s| !s.is_empty() && s != "0")
|| (input.borrow().has_option("no-security-blocking")
&& input
.borrow()
@@ -777,41 +774,38 @@ pub fn base_command_initialize(
.collect();
for (env_name, option_names) in &env_options {
for option_name in option_names {
- if true == input.borrow().has_option(option_name) {
- if false
- == input
- .borrow()
- .get_option(option_name)?
- .as_bool()
- .unwrap_or(false)
- && Platform::get_env(env_name).map_or(false, |s| !s.is_empty() && s != "0")
- {
- input
- .borrow_mut()
- .set_option(option_name, PhpMixed::Bool(true));
- }
+ if input.borrow().has_option(option_name)
+ && !input
+ .borrow()
+ .get_option(option_name)?
+ .as_bool()
+ .unwrap_or(false)
+ && Platform::get_env(env_name).is_some_and(|s| !s.is_empty() && s != "0")
+ {
+ input
+ .borrow_mut()
+ .set_option(option_name, PhpMixed::Bool(true));
}
}
}
- if true == input.borrow().has_option("ignore-platform-reqs") {
- if !input
+ if input.borrow().has_option("ignore-platform-reqs")
+ && !input
.borrow()
.get_option("ignore-platform-reqs")?
.as_bool()
.unwrap_or(false)
- && Platform::get_env("COMPOSER_IGNORE_PLATFORM_REQS")
- .map_or(false, |s| !s.is_empty() && s != "0")
- {
- input
- .borrow_mut()
- .set_option("ignore-platform-reqs", PhpMixed::Bool(true));
+ && Platform::get_env("COMPOSER_IGNORE_PLATFORM_REQS")
+ .is_some_and(|s| !s.is_empty() && s != "0")
+ {
+ input
+ .borrow_mut()
+ .set_option("ignore-platform-reqs", PhpMixed::Bool(true));
- io.write_error("<warning>COMPOSER_IGNORE_PLATFORM_REQS is set. You may experience unexpected errors.</warning>");
- }
+ io.write_error("<warning>COMPOSER_IGNORE_PLATFORM_REQS is set. You may experience unexpected errors.</warning>");
}
- if true == input.borrow().has_option("ignore-platform-req")
+ if input.borrow().has_option("ignore-platform-req")
&& (!input.borrow().has_option("ignore-platform-reqs")
|| !input
.borrow()
@@ -823,7 +817,7 @@ pub fn base_command_initialize(
let ignore_str = ignore_platform_req_env.clone().unwrap_or_default();
if 0 == count(&input.borrow().get_option("ignore-platform-req")?)
&& ignore_platform_req_env.is_some()
- && "" != ignore_str
+ && !ignore_str.is_empty()
{
input.borrow_mut().set_option(
"ignore-platform-req",
diff --git a/crates/shirabe/src/command/base_config_command.rs b/crates/shirabe/src/command/base_config_command.rs
index 5e77715..00098f2 100644
--- a/crates/shirabe/src/command/base_config_command.rs
+++ b/crates/shirabe/src/command/base_config_command.rs
@@ -56,7 +56,7 @@ pub trait BaseConfigCommand: BaseCommand {
config_rc.borrow_mut().set_base_dir(Some(home));
}
- let config_file = self.get_composer_config_file(input.clone(), &*config_rc.borrow())?;
+ let config_file = self.get_composer_config_file(input.clone(), &config_rc.borrow())?;
// Create global composer.json if invoked using `composer global [config-cmd]`
if (config_file == "composer.json" || config_file == "./composer.json")
diff --git a/crates/shirabe/src/command/base_dependency_command.rs b/crates/shirabe/src/command/base_dependency_command.rs
index 5424dd1..98a2622 100644
--- a/crates/shirabe/src/command/base_dependency_command.rs
+++ b/crates/shirabe/src/command/base_dependency_command.rs
@@ -90,8 +90,8 @@ pub trait BaseDependencyCommand: BaseCommand {
let local_repo = repository_manager.get_local_repository();
let root_pkg = composer.get_package();
- if local_repo.get_packages()?.len() == 0
- && (root_pkg.get_requires().len() > 0 || root_pkg.get_dev_requires().len() > 0)
+ if local_repo.get_packages()?.is_empty()
+ && (!root_pkg.get_requires().is_empty() || !root_pkg.get_dev_requires().is_empty())
{
output.borrow().writeln(
&["<warning>No dependencies installed. Try running composer install or update, or use --locked.</warning>".to_string()],
@@ -451,7 +451,7 @@ pub trait BaseDependencyCommand: BaseCommand {
""
};
self.write_tree_line(
- &format!(
+ format!(
"{}{}{} ({}) {}",
prefix,
if is_last { "└──" } else { "├──" },
@@ -459,8 +459,7 @@ pub trait BaseDependencyCommand: BaseCommand {
link_text,
circular_warn
)
- .trim_end()
- .to_string(),
+ .trim_end(),
);
if let Some(children_vec) = children {
self.print_tree(
diff --git a/crates/shirabe/src/command/bump_command.rs b/crates/shirabe/src/command/bump_command.rs
index faa1ea7..1d5a81d 100644
--- a/crates/shirabe/src/command/bump_command.rs
+++ b/crates/shirabe/src/command/bump_command.rs
@@ -37,6 +37,12 @@ pub struct BumpCommand {
base_command_data: BaseCommandData,
}
+impl Default for BumpCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl BumpCommand {
const ERROR_GENERIC: i64 = 1;
const ERROR_LOCK_OUTDATED: i64 = 2;
@@ -72,7 +78,7 @@ impl BumpCommand {
}
let mut composer_json = JsonFile::new(composer_json_path.clone(), None, None)?;
- let contents = match file_get_contents(&composer_json.get_path()) {
+ let contents = match file_get_contents(composer_json.get_path()) {
Some(c) => c,
None => {
io.write_error3(
@@ -146,7 +152,7 @@ impl BumpCommand {
let contents_data = composer_json.read()?;
if !contents_data
.as_array()
- .map_or(false, |m| m.contains_key("type"))
+ .is_some_and(|m| m.contains_key("type"))
{
io.write_error3(
"If your package is not a library, you can explicitly specify the \"type\" by using \"composer config type project\".",
@@ -301,7 +307,7 @@ impl BumpCommand {
json: &JsonFile,
updates: &indexmap::IndexMap<&str, indexmap::IndexMap<String, String>>,
) -> Result<bool> {
- let contents = match file_get_contents(&json.get_path()) {
+ let contents = match file_get_contents(json.get_path()) {
Some(c) => c,
None => {
return Err(shirabe_php_shim::RuntimeException {
@@ -322,7 +328,7 @@ impl BumpCommand {
}
}
- match file_put_contents(&json.get_path(), manipulator.get_contents().as_bytes()) {
+ 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()),
diff --git a/crates/shirabe/src/command/check_platform_reqs_command.rs b/crates/shirabe/src/command/check_platform_reqs_command.rs
index 23d2240..bfd8b99 100644
--- a/crates/shirabe/src/command/check_platform_reqs_command.rs
+++ b/crates/shirabe/src/command/check_platform_reqs_command.rs
@@ -40,6 +40,12 @@ pub struct CheckPlatformReqsCommand {
base_command_data: BaseCommandData,
}
+impl Default for CheckPlatformReqsCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl CheckPlatformReqsCommand {
pub fn new() -> Self {
let mut command = CheckPlatformReqsCommand {
@@ -253,7 +259,7 @@ impl Command for CheckPlatformReqsCommand {
for (require, link) in composer.get_package().get_dev_requires() {
requires
.entry(require.to_string())
- .or_insert_with(Vec::new)
+ .or_default()
.push(link.clone());
}
}
@@ -273,7 +279,7 @@ impl Command for CheckPlatformReqsCommand {
for (require, link) in package.get_requires() {
requires
.entry(require.to_string())
- .or_insert_with(Vec::new)
+ .or_default()
.push(link.clone());
}
}
diff --git a/crates/shirabe/src/command/clear_cache_command.rs b/crates/shirabe/src/command/clear_cache_command.rs
index 31ba953..a414c11 100644
--- a/crates/shirabe/src/command/clear_cache_command.rs
+++ b/crates/shirabe/src/command/clear_cache_command.rs
@@ -26,6 +26,12 @@ pub struct ClearCacheCommand {
base_command_data: BaseCommandData,
}
+impl Default for ClearCacheCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl ClearCacheCommand {
pub fn new() -> Self {
let mut command = ClearCacheCommand {
diff --git a/crates/shirabe/src/command/config_command.rs b/crates/shirabe/src/command/config_command.rs
index 0752052..556dbdd 100644
--- a/crates/shirabe/src/command/config_command.rs
+++ b/crates/shirabe/src/command/config_command.rs
@@ -70,6 +70,12 @@ impl ConfigCommand {
];
}
+impl Default for ConfigCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl ConfigCommand {
pub fn new() -> Self {
let mut command = ConfigCommand {
@@ -157,7 +163,7 @@ impl Command for ConfigCommand {
)?;
let auth_config_file =
- self.get_auth_config_file(input.clone(), &*self.config.as_ref().unwrap().borrow())?;
+ self.get_auth_config_file(input.clone(), &self.config.as_ref().unwrap().borrow())?;
let auth_config_file_jf = std::rc::Rc::new(std::cell::RefCell::new(JsonFile::new(
auth_config_file,
@@ -299,7 +305,7 @@ impl Command for ConfigCommand {
let config_rc = self.config.as_ref().unwrap().clone();
self.get_io()
.borrow_mut()
- .load_configuration(&mut *config_rc.borrow_mut())?;
+ .load_configuration(&mut config_rc.borrow_mut())?;
}
// List the configuration of the file settings
@@ -407,12 +413,7 @@ impl Command for ConfigCommand {
let bits = explode(".", &setting_key);
// PHP: $data here is the mixed dot-segment cursor; the rest of the loop walks it.
let mut cursor: PhpMixed = if bits[0] == "extra" || bits[0] == "suggest" {
- PhpMixed::Array(
- raw_data
- .as_array()
- .map(|a| a.clone())
- .unwrap_or_else(IndexMap::new),
- )
+ PhpMixed::Array(raw_data.as_array().cloned().unwrap_or_else(IndexMap::new))
} else {
data.get("config").cloned().unwrap_or(PhpMixed::Null)
};
@@ -425,12 +426,12 @@ impl Command for ConfigCommand {
};
key_acc = Some(new_key.clone());
r#match = false;
- if let Some(arr) = cursor.as_array() {
- if let Some(v) = arr.get(&new_key) {
- r#match = true;
- cursor = (**v).clone();
- key_acc = None;
- }
+ if let Some(arr) = cursor.as_array()
+ && let Some(v) = arr.get(&new_key)
+ {
+ r#match = true;
+ cursor = (**v).clone();
+ key_acc = None;
}
}
@@ -564,7 +565,7 @@ impl Command for ConfigCommand {
};
let boolean_normalizer = |val: &PhpMixed| -> PhpMixed {
let s = val.as_string().unwrap_or("");
- PhpMixed::Bool(s != "false" && s != "" && s != "0")
+ PhpMixed::Bool(s != "false" && !s.is_empty() && s != "0")
};
// handle config values
@@ -1133,7 +1134,7 @@ impl Command for ConfigCommand {
.unwrap()
.add_config_setting(&key, PhpMixed::Array(obj));
} else if matches[1] == "custom-headers" {
- if values.len() == 0 {
+ if values.is_empty() {
return Err(RuntimeException {
message: "Expected at least one argument (header), got none".to_string(),
code: 0,
@@ -1279,7 +1280,7 @@ impl ConfigCommand {
&mut self,
key: &str,
callbacks: &(ValidatorFn, NormalizerFn),
- values: &Vec<String>,
+ values: &[String],
method: &str,
) -> anyhow::Result<()> {
let (validator, normalizer) = callbacks;
@@ -1349,7 +1350,7 @@ impl ConfigCommand {
&mut self,
key: &str,
callbacks: &(ValidatorFn, NormalizerFn),
- values: &Vec<String>,
+ values: &[String],
method: &str,
) -> anyhow::Result<()> {
let (validator, normalizer) = callbacks;
@@ -1551,7 +1552,7 @@ fn boolean_validator(val: &PhpMixed) -> PhpMixed {
fn boolean_normalizer(val: &PhpMixed) -> PhpMixed {
let s = val.as_string().unwrap_or("");
- PhpMixed::Bool(s != "false" && s != "" && s != "0")
+ PhpMixed::Bool(s != "false" && !s.is_empty() && s != "0")
}
fn build_unique_config_values() -> IndexMap<String, (ValidatorFn, NormalizerFn)> {
@@ -1624,7 +1625,7 @@ fn build_unique_config_values() -> IndexMap<String, (ValidatorFn, NormalizerFn)>
if s == "prompt" {
PhpMixed::String("prompt".to_string())
} else {
- PhpMixed::Bool(s != "false" && s != "" && s != "0")
+ PhpMixed::Bool(s != "false" && !s.is_empty() && s != "0")
}
}),
),
@@ -1772,7 +1773,7 @@ fn build_unique_config_values() -> IndexMap<String, (ValidatorFn, NormalizerFn)>
if s == "stash" {
PhpMixed::String("stash".to_string())
} else {
- PhpMixed::Bool(s != "false" && s != "" && s != "0")
+ PhpMixed::Bool(s != "false" && !s.is_empty() && s != "0")
}
}),
),
@@ -1845,7 +1846,7 @@ fn build_unique_config_values() -> IndexMap<String, (ValidatorFn, NormalizerFn)>
if s == "dev" || s == "no-dev" {
val.clone()
} else {
- PhpMixed::Bool(s != "false" && s != "" && s != "0")
+ PhpMixed::Bool(s != "false" && !s.is_empty() && s != "0")
}
}),
),
@@ -1924,7 +1925,7 @@ fn build_unique_config_values() -> IndexMap<String, (ValidatorFn, NormalizerFn)>
if s == "php-only" {
PhpMixed::String("php-only".to_string())
} else {
- PhpMixed::Bool(s != "false" && s != "" && s != "0")
+ PhpMixed::Bool(s != "false" && !s.is_empty() && s != "0")
}
}),
),
@@ -1949,7 +1950,7 @@ fn build_unique_config_values() -> IndexMap<String, (ValidatorFn, NormalizerFn)>
if s == "prompt" {
PhpMixed::String("prompt".to_string())
} else {
- PhpMixed::Bool(s != "false" && s != "" && s != "0")
+ PhpMixed::Bool(s != "false" && !s.is_empty() && s != "0")
}
}),
),
@@ -2197,10 +2198,10 @@ fn key_first_key(value: &PhpMixed) -> Option<String> {
if let Some(arr) = value.as_array() {
return arr.keys().next().cloned();
}
- if let Some(list) = value.as_list() {
- if !list.is_empty() {
- return Some("0".to_string());
- }
+ if let Some(list) = value.as_list()
+ && !list.is_empty()
+ {
+ return Some("0".to_string());
}
None
}
diff --git a/crates/shirabe/src/command/create_project_command.rs b/crates/shirabe/src/command/create_project_command.rs
index 99f73e9..3322008 100644
--- a/crates/shirabe/src/command/create_project_command.rs
+++ b/crates/shirabe/src/command/create_project_command.rs
@@ -61,6 +61,12 @@ pub struct CreateProjectCommand {
Option<std::rc::Rc<std::cell::RefCell<SuggestedPackagesReporter>>>,
}
+impl Default for CreateProjectCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl CreateProjectCommand {
pub fn new() -> Self {
let mut command = CreateProjectCommand {
@@ -178,7 +184,7 @@ impl Command for CreateProjectCommand {
let repository_url_opt = input.borrow().get_option("repository-url")?;
let repositories = if repository_opt
.as_list()
- .map(|l| l.len() > 0)
+ .map(|l| !l.is_empty())
.unwrap_or(false)
{
Some(repository_opt)
@@ -321,7 +327,7 @@ impl CreateProjectCommand {
// we need to manually load the configuration to pass the auth credentials to the io interface!
io.borrow_mut()
- .load_configuration(&mut *config.borrow_mut())?;
+ .load_configuration(&mut config.borrow_mut())?;
self.suggested_packages_reporter = Some(std::rc::Rc::new(std::cell::RefCell::new(
SuggestedPackagesReporter::new(io.clone()),
@@ -363,61 +369,61 @@ impl CreateProjectCommand {
)?;
// add the repository to the composer.json and use it for the install run later
- if let Some(repos) = repositories.as_ref() {
- if add_repository {
- for (index, repo) in repos.iter().enumerate() {
- let config = crate::command::composer_full(&composer_handle).get_config();
- let repo_config =
- RepositoryFactory::config_from_string(io.clone(), &config, repo, true)?;
- let composer_json_repositories_config =
- crate::command::composer_full(&composer_handle)
- .get_config()
- .borrow()
- .get_repositories();
- let name = RepositoryFactory::generate_repository_name(
- &PhpMixed::Int(index as i64),
- &repo_config,
- &composer_json_repositories_config,
- );
- let mut config_source = JsonConfigSource::new(
- std::rc::Rc::new(std::cell::RefCell::new(JsonFile::new(
- "composer.json".to_string(),
- None,
- None,
- )?)),
- false,
- );
-
- let is_packagist_disabled = (repo_config.contains_key("packagist")
- && repo_config.len() == 1
- && repo_config.get("packagist").and_then(|v| v.as_bool()) == Some(false))
- || (repo_config.contains_key("packagist.org")
- && repo_config.len() == 1
- && repo_config.get("packagist.org").and_then(|v| v.as_bool())
- == Some(false));
- if is_packagist_disabled {
- config_source.add_repository("packagist.org", PhpMixed::Bool(false), false);
- } else {
- config_source.add_repository(
- &name,
- PhpMixed::Array(
- repo_config
- .iter()
- .map(|(k, v)| (k.clone(), Box::new(v.clone())))
- .collect(),
- ),
- false,
- );
- }
-
- composer_handle = self.create_composer_instance(
- input.clone(),
- io.clone(),
+ if let Some(repos) = repositories.as_ref()
+ && add_repository
+ {
+ for (index, repo) in repos.iter().enumerate() {
+ let config = crate::command::composer_full(&composer_handle).get_config();
+ let repo_config =
+ RepositoryFactory::config_from_string(io.clone(), &config, repo, true)?;
+ let composer_json_repositories_config =
+ crate::command::composer_full(&composer_handle)
+ .get_config()
+ .borrow()
+ .get_repositories();
+ let name = RepositoryFactory::generate_repository_name(
+ &PhpMixed::Int(index as i64),
+ &repo_config,
+ &composer_json_repositories_config,
+ );
+ let mut config_source = JsonConfigSource::new(
+ std::rc::Rc::new(std::cell::RefCell::new(JsonFile::new(
+ "composer.json".to_string(),
None,
- disable_plugins,
None,
- )?;
+ )?)),
+ false,
+ );
+
+ let is_packagist_disabled = (repo_config.contains_key("packagist")
+ && repo_config.len() == 1
+ && repo_config.get("packagist").and_then(|v| v.as_bool()) == Some(false))
+ || (repo_config.contains_key("packagist.org")
+ && repo_config.len() == 1
+ && repo_config.get("packagist.org").and_then(|v| v.as_bool())
+ == Some(false));
+ if is_packagist_disabled {
+ config_source.add_repository("packagist.org", PhpMixed::Bool(false), false);
+ } else {
+ config_source.add_repository(
+ &name,
+ PhpMixed::Array(
+ repo_config
+ .iter()
+ .map(|(k, v)| (k.clone(), Box::new(v.clone())))
+ .collect(),
+ ),
+ false,
+ );
}
+
+ composer_handle = self.create_composer_instance(
+ input.clone(),
+ io.clone(),
+ None,
+ disable_plugins,
+ None,
+ )?;
}
}
@@ -444,12 +450,12 @@ impl CreateProjectCommand {
// use the new config including the newly installed project
let config = composer.get_config();
let (ps, pd) =
- self.get_preferred_install_options(&*config.borrow(), input.clone(), false)?;
+ self.get_preferred_install_options(&config.borrow(), input.clone(), false)?;
prefer_source = ps;
prefer_dist = pd;
// install dependencies of the created project
- if no_install == false {
+ if !no_install {
composer
.get_installation_manager()
.borrow_mut()
@@ -487,7 +493,7 @@ impl CreateProjectCommand {
None,
)
.set_audit_config(
- self.create_audit_config(&mut *config.borrow_mut(), input.clone())?,
+ self.create_audit_config(&mut config.borrow_mut(), input.clone())?,
);
if !composer.get_locker().borrow_mut().is_locked() {
@@ -654,16 +660,17 @@ impl CreateProjectCommand {
}
// if no directory was specified, use the 2nd part of the package name
- let mut directory = if directory.is_none() {
- let mut parts = explode_with_limit("/", &name, 2);
- format!(
- "{}{}{}",
- Platform::get_cwd(false)?,
- DIRECTORY_SEPARATOR,
- array_pop(&mut parts).unwrap_or_default()
- )
- } else {
- directory.unwrap()
+ let mut directory = match directory {
+ None => {
+ let mut parts = explode_with_limit("/", &name, 2);
+ format!(
+ "{}{}{}",
+ Platform::get_cwd(false)?,
+ DIRECTORY_SEPARATOR,
+ array_pop(&mut parts).unwrap_or_default()
+ )
+ }
+ Some(directory) => directory,
};
directory = rtrim(&directory, Some("/\\"));
@@ -679,7 +686,7 @@ impl CreateProjectCommand {
directory
);
}
- if "" == directory {
+ if directory.is_empty() {
return Err(UnexpectedValueException {
message: "Got an empty target directory, something went wrong".to_string(),
code: 0,
@@ -806,21 +813,8 @@ impl CreateProjectCommand {
indexmap::IndexMap::new(),
indexmap::IndexMap::new(),
);
- if repositories.is_none() {
- repository_set.add_repository(crate::repository::RepositoryInterfaceHandle::new(
- CompositeRepository::new(
- RepositoryFactory::default_repos(
- Some(io.clone()),
- Some(config.clone()),
- Some(&mut rm.borrow_mut()),
- )?
- .into_iter()
- .map(|(_, v)| v)
- .collect(),
- ),
- ))?;
- } else {
- for repo in repositories.unwrap() {
+ if let Some(repositories) = repositories {
+ for repo in repositories {
let mut repo_config =
RepositoryFactory::config_from_string(io.clone(), &config, repo, true)?;
let is_packagist_disabled = (repo_config.contains_key("packagist")
@@ -860,6 +854,19 @@ impl CreateProjectCommand {
None,
)?);
}
+ } else {
+ repository_set.add_repository(crate::repository::RepositoryInterfaceHandle::new(
+ CompositeRepository::new(
+ RepositoryFactory::default_repos(
+ Some(io.clone()),
+ Some(config.clone()),
+ Some(&mut rm.borrow_mut()),
+ )?
+ .into_iter()
+ .map(|(_, v)| v)
+ .collect(),
+ ),
+ ))?;
}
let platform_overrides = config.borrow_mut().get("platform");
@@ -965,10 +972,10 @@ impl CreateProjectCommand {
}
// avoid displaying 9999999-dev as version if default-branch was selected
- if let Some(alias) = package.as_alias() {
- if package.get_pretty_version() == VersionParser::DEFAULT_BRANCH_ALIAS {
- package = alias.get_alias_of().into();
- }
+ if let Some(alias) = package.as_alias()
+ && package.get_pretty_version() == VersionParser::DEFAULT_BRANCH_ALIAS
+ {
+ package = alias.get_alias_of().into();
}
io.write_error(&format!(
diff --git a/crates/shirabe/src/command/depends_command.rs b/crates/shirabe/src/command/depends_command.rs
index bc9dd27..133f8b2 100644
--- a/crates/shirabe/src/command/depends_command.rs
+++ b/crates/shirabe/src/command/depends_command.rs
@@ -28,6 +28,12 @@ pub struct DependsCommand {
colors: Vec<String>,
}
+impl Default for DependsCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl DependsCommand {
pub fn new() -> Self {
let mut command = DependsCommand {
diff --git a/crates/shirabe/src/command/diagnose_command.rs b/crates/shirabe/src/command/diagnose_command.rs
index 252208d..7f1aec5 100644
--- a/crates/shirabe/src/command/diagnose_command.rs
+++ b/crates/shirabe/src/command/diagnose_command.rs
@@ -69,6 +69,12 @@ pub struct DiagnoseCommand {
pub(crate) exit_code: i64,
}
+impl Default for DiagnoseCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl DiagnoseCommand {
pub fn new() -> Self {
let mut command = DiagnoseCommand {
@@ -158,7 +164,7 @@ impl Command for DiagnoseCommand {
if strpos(file!(), "phar:") == Some(0) {
io.write_no_newline("Checking pubkeys: ");
- let r = self.check_pub_keys(&*config.borrow())?;
+ let r = self.check_pub_keys(&config.borrow())?;
self.output_result(r);
io.write_no_newline("Checking Composer version: ");
@@ -172,7 +178,7 @@ impl Command for DiagnoseCommand {
));
io.write_no_newline("Checking Composer and its dependencies for vulnerabilities: ");
- let r = self.check_composer_audit(&*config.borrow())?;
+ let r = self.check_composer_audit(&config.borrow())?;
self.output_result(r);
let platform_overrides = config
@@ -194,14 +200,14 @@ impl Command for DiagnoseCommand {
)?
.unwrap();
let mut php_version = php_pkg.get_pretty_version().to_string();
- if let Some(cp) = php_pkg.as_complete() {
- if str_contains(&cp.get_description().unwrap_or_default(), "overridden") {
- php_version = format!(
- "{} - {}",
- php_version,
- cp.get_description().unwrap_or_default()
- );
- }
+ if let Some(cp) = php_pkg.as_complete()
+ && str_contains(&cp.get_description().unwrap_or_default(), "overridden")
+ {
+ php_version = format!(
+ "{} - {}",
+ php_version,
+ cp.get_description().unwrap_or_default()
+ );
}
io.write(&format!("PHP version: <comment>{}</comment>", php_version));
@@ -298,11 +304,11 @@ impl Command for DiagnoseCommand {
self.output_result(PhpMixed::String(r));
io.write_no_newline("Checking http connectivity to packagist: ");
- let r = self.check_http("http", &*config.borrow())?;
+ let r = self.check_http("http", &config.borrow())?;
self.output_result(r);
io.write_no_newline("Checking https connectivity to packagist: ");
- let r = self.check_http("https", &*config.borrow())?;
+ let r = self.check_http("https", &config.borrow())?;
self.output_result(r);
for repo in config.borrow().get_repositories() {
@@ -317,7 +323,7 @@ impl Command for DiagnoseCommand {
let composer_repo = ComposerRepository::new(
repo_arr_unboxed,
self.get_io().clone(),
- &*config.borrow(),
+ &config.borrow(),
self.http_downloader.clone().unwrap(),
None,
)
@@ -339,7 +345,7 @@ impl Command for DiagnoseCommand {
.and_then(|v| v.as_string())
.unwrap_or("")
));
- let r = self.check_composer_repo(&url, &*config.borrow())?;
+ let r = self.check_composer_repo(&url, &config.borrow())?;
self.output_result(r);
}
}
@@ -375,11 +381,7 @@ impl Command for DiagnoseCommand {
self.output_result(if is_string(&status) {
status
} else {
- PhpMixed::String(format!(
- "<error>[{}] {}</error>",
- get_class_err(&e),
- e.to_string()
- ))
+ PhpMixed::String(format!("<error>[{}] {}</error>", get_class_err(&e), e))
});
} else {
return Err(e);
@@ -426,14 +428,14 @@ impl Command for DiagnoseCommand {
self.output_result(PhpMixed::String(format!(
"<error>[{}] {}</error>",
get_class_err(&e),
- e.to_string()
+ e
)));
}
} else {
self.output_result(PhpMixed::String(format!(
"<error>[{}] {}</error>",
get_class_err(&e),
- e.to_string()
+ e
)));
}
}
@@ -441,7 +443,7 @@ impl Command for DiagnoseCommand {
}
io.write_no_newline("Checking disk free space: ");
- let r = self.check_disk_space(&*config.borrow());
+ let r = self.check_disk_space(&config.borrow());
self.output_result(r);
Ok(self.exit_code)
@@ -519,7 +521,7 @@ impl DiagnoseCommand {
let mut output = String::new();
let _ = self.process.as_mut().unwrap().borrow_mut().execute(
- &vec![
+ vec![
"git".to_string(),
"config".to_string(),
"color.ui".to_string(),
@@ -588,7 +590,7 @@ impl DiagnoseCommand {
result_list.push(Box::new(PhpMixed::String(w)));
}
- if result_list.len() > 0 {
+ if !result_list.is_empty() {
return Ok(PhpMixed::List(result_list));
}
@@ -639,7 +641,7 @@ impl DiagnoseCommand {
result_list.push(Box::new(PhpMixed::String(w)));
}
- if result_list.len() > 0 {
+ if !result_list.is_empty() {
return Ok(PhpMixed::List(result_list));
}
@@ -759,18 +761,18 @@ impl DiagnoseCommand {
)))
}
Err(e) => {
- if let Some(te) = e.downcast_ref::<TransportException>() {
- if te.get_code() == 401 {
- return Ok(PhpMixed::String(format!(
- "<comment>The oauth token for {} seems invalid, run \"composer config --global --unset github-oauth.{}\" to remove it</comment>",
- domain, domain
- )));
- }
+ if let Some(te) = e.downcast_ref::<TransportException>()
+ && te.get_code() == 401
+ {
+ return Ok(PhpMixed::String(format!(
+ "<comment>The oauth token for {} seems invalid, run \"composer config --global --unset github-oauth.{}\" to remove it</comment>",
+ domain, domain
+ )));
}
Ok(PhpMixed::String(format!(
"<error>[{}] {}</error>",
get_class_err(&e),
- e.to_string()
+ e
)))
}
}
@@ -913,7 +915,7 @@ impl DiagnoseCommand {
return Ok(PhpMixed::String(format!(
"<error>[{}] {}</error>",
get_class_err(&e),
- e.to_string()
+ e
)));
}
};
@@ -1006,7 +1008,7 @@ impl DiagnoseCommand {
Err(e) => {
return Ok(PhpMixed::String(format!(
"<highlight>Failed performing audit: {}</>",
- e.to_string()
+ e
)));
}
};
@@ -1102,8 +1104,7 @@ impl DiagnoseCommand {
let mut had_warning = false;
let mut result = result;
// PHP: $result instanceof \Exception → already converted to string at call sites here
- if !result.as_bool().unwrap_or(true) && !result.as_string().is_some() && !is_array(&result)
- {
+ if !result.as_bool().unwrap_or(true) && result.as_string().is_none() && !is_array(&result) {
// falsey results should be considered as an error, even if there is nothing to output
had_error = true;
} else {
@@ -1334,7 +1335,7 @@ impl DiagnoseCommand {
return Err(InvalidArgumentException {
message: format!(
"DiagnoseCommand: Unknown error type \"{}\". Please report at https://github.com/composer/composer/issues/new.",
- other.to_string(),
+ other,
),
code: 0,
}
@@ -1413,7 +1414,7 @@ impl DiagnoseCommand {
return Err(InvalidArgumentException {
message: format!(
"DiagnoseCommand: Unknown warning type \"{}\". Please report at https://github.com/composer/composer/issues/new.",
- other.to_string(),
+ other,
),
code: 0,
}
@@ -1429,7 +1430,7 @@ impl DiagnoseCommand {
}
let composer_ipresolve = Platform::get_env("COMPOSER_IPRESOLVE").unwrap_or_default();
- if vec!["4".to_string(), "6".to_string()].contains(&composer_ipresolve) {
+ if ["4".to_string(), "6".to_string()].contains(&composer_ipresolve) {
warnings.insert("ipresolve".to_string(), PhpMixed::Bool(true));
out_fn(
&format!(
@@ -1441,7 +1442,7 @@ impl DiagnoseCommand {
);
}
- Ok(if warnings.len() == 0 && errors.len() == 0 {
+ Ok(if warnings.is_empty() && errors.is_empty() {
PhpMixed::Bool(true)
} else {
PhpMixed::String(output)
diff --git a/crates/shirabe/src/command/dump_autoload_command.rs b/crates/shirabe/src/command/dump_autoload_command.rs
index a1e50f5..9369267 100644
--- a/crates/shirabe/src/command/dump_autoload_command.rs
+++ b/crates/shirabe/src/command/dump_autoload_command.rs
@@ -27,6 +27,12 @@ pub struct DumpAutoloadCommand {
base_command_data: BaseCommandData,
}
+impl Default for DumpAutoloadCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl DumpAutoloadCommand {
pub fn new() -> Self {
let mut command = DumpAutoloadCommand {
@@ -269,7 +275,7 @@ impl Command for DumpAutoloadCommand {
&config_ref,
local_repo,
package,
- &mut *installation_manager_ref,
+ &mut installation_manager_ref,
"composer",
optimize,
None,
diff --git a/crates/shirabe/src/command/exec_command.rs b/crates/shirabe/src/command/exec_command.rs
index aef22a3..c4a1e94 100644
--- a/crates/shirabe/src/command/exec_command.rs
+++ b/crates/shirabe/src/command/exec_command.rs
@@ -26,6 +26,12 @@ pub struct ExecCommand {
base_command_data: BaseCommandData,
}
+impl Default for ExecCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl ExecCommand {
pub fn new() -> Self {
let mut command = ExecCommand {
@@ -61,10 +67,10 @@ impl ExecCommand {
let mut binaries: Vec<String> = Vec::new();
let mut previous_bin: Option<String> = None;
for bin in bins.iter().chain(local_bins.iter()) {
- if let Some(prev) = &previous_bin {
- if bin == &format!("{}.bat", prev) {
- continue;
- }
+ if let Some(prev) = &previous_bin
+ && bin == &format!("{}.bat", prev)
+ {
+ continue;
}
previous_bin = Some(bin.clone());
binaries.push(basename(bin));
@@ -201,13 +207,13 @@ impl Command for ExecCommand {
// Application handle (deferred with the Application shared-ownership work). Until then the
// working-directory restore is skipped.
let initial_working_directory: Option<String> = None;
- if let Some(ref iwd) = initial_working_directory {
- if 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,
- })?;
- }
+ 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,
+ })?;
}
let args = input
@@ -221,12 +227,12 @@ impl Command for ExecCommand {
})
.unwrap_or_default();
- Ok(dispatcher.borrow_mut().dispatch_script(
+ dispatcher.borrow_mut().dispatch_script(
"__exec_command",
true,
args,
indexmap::IndexMap::new(),
- )?)
+ )
}
fn initialize(
diff --git a/crates/shirabe/src/command/fund_command.rs b/crates/shirabe/src/command/fund_command.rs
index 1e26fc0..4b58a7a 100644
--- a/crates/shirabe/src/command/fund_command.rs
+++ b/crates/shirabe/src/command/fund_command.rs
@@ -38,6 +38,12 @@ pub struct FundCommand {
base_command_data: BaseCommandData,
}
+impl Default for FundCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl FundCommand {
pub fn new() -> Self {
let mut command = FundCommand {
@@ -60,7 +66,7 @@ impl FundCommand {
for funding_option in package.get_funding() {
let url_val = funding_option.get("url").and_then(|v| v.as_string());
- if url_val.map_or(true, |s| s.is_empty()) {
+ if url_val.is_none_or(|s| s.is_empty()) {
continue;
}
let mut url = url_val.unwrap().to_string();
@@ -68,14 +74,12 @@ impl FundCommand {
.get("type")
.and_then(|v| v.as_string())
.unwrap_or("");
- if r#type == "github" {
- if let Some(matches) =
+ if r#type == "github"
+ && let Some(matches) =
Preg::is_match_with_indexed_captures(r"^https://github.com/([^/]+)$", &url)
- {
- if let Some(sponsor) = matches.into_iter().nth(1) {
- url = format!("https://github.com/sponsors/{}", sponsor);
- }
- }
+ && let Some(sponsor) = matches.into_iter().nth(1)
+ {
+ url = format!("https://github.com/sponsors/{}", sponsor);
}
fundings
.entry(vendor.to_string())
@@ -115,13 +119,8 @@ impl Command for FundCommand {
let repository_manager = composer.get_repository_manager().clone();
let repository_manager = repository_manager.borrow();
let repo = repository_manager.get_local_repository();
- let mut remote_repos = CompositeRepository::new(
- repository_manager
- .get_repositories()
- .iter()
- .map(|r| r.clone())
- .collect(),
- );
+ let mut remote_repos =
+ CompositeRepository::new(repository_manager.get_repositories().to_vec());
let mut fundings: IndexMap<String, IndexMap<String, Vec<String>>> = IndexMap::new();
let mut packages_to_load: IndexMap<String, Option<AnyConstraint>> = IndexMap::new();
@@ -149,14 +148,13 @@ impl Command for FundCommand {
for (_, package) in &result.packages {
if package.as_alias().is_none() {
// TODO: check for CompleteAliasPackage as well
- if let Some(complete_pkg) = package.as_complete() {
- if complete_pkg.is_default_branch()
- && !complete_pkg.get_funding().is_empty()
- && packages_to_load_names.contains(&complete_pkg.get_name())
- {
- Self::insert_funding_data(&mut fundings, &complete_pkg)?;
- packages_to_load_names.shift_remove(&complete_pkg.get_name());
- }
+ if let Some(complete_pkg) = package.as_complete()
+ && complete_pkg.is_default_branch()
+ && !complete_pkg.get_funding().is_empty()
+ && packages_to_load_names.contains(&complete_pkg.get_name())
+ {
+ Self::insert_funding_data(&mut fundings, &complete_pkg)?;
+ packages_to_load_names.shift_remove(&complete_pkg.get_name());
}
}
}
@@ -168,10 +166,10 @@ impl Command for FundCommand {
continue;
}
// TODO: check for CompleteAliasPackage as well
- if let Some(complete_pkg) = package.as_complete() {
- if !complete_pkg.get_funding().is_empty() {
- Self::insert_funding_data(&mut fundings, &complete_pkg)?;
- }
+ if let Some(complete_pkg) = package.as_complete()
+ && !complete_pkg.get_funding().is_empty()
+ {
+ Self::insert_funding_data(&mut fundings, &complete_pkg)?;
}
}
diff --git a/crates/shirabe/src/command/global_command.rs b/crates/shirabe/src/command/global_command.rs
index 69cf48a..941315b 100644
--- a/crates/shirabe/src/command/global_command.rs
+++ b/crates/shirabe/src/command/global_command.rs
@@ -35,6 +35,12 @@ pub struct GlobalCommand {
base_command_data: BaseCommandData,
}
+impl Default for GlobalCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl GlobalCommand {
pub fn new() -> Self {
let mut command = GlobalCommand {
@@ -116,7 +122,7 @@ impl GlobalCommand {
// TODO(phase-c): getApplication()->resetComposer() needs the shared shirabe Application
// handle (deferred with the Application shared-ownership work).
- Ok(StringInput::new(&new_input_str)?)
+ StringInput::new(&new_input_str)
}
}
diff --git a/crates/shirabe/src/command/home_command.rs b/crates/shirabe/src/command/home_command.rs
index 0ac7483..1620205 100644
--- a/crates/shirabe/src/command/home_command.rs
+++ b/crates/shirabe/src/command/home_command.rs
@@ -35,6 +35,12 @@ pub struct HomeCommand {
base_command_data: BaseCommandData,
}
+impl Default for HomeCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl HomeCommand {
pub fn new() -> Self {
let mut command = HomeCommand {
@@ -57,7 +63,7 @@ impl HomeCommand {
.get("source")
.cloned()
.or_else(|| package.get_source_url().map(|s| s.to_string()));
- if url.as_deref().map_or(true, |s| s.is_empty()) || show_homepage {
+ if url.as_deref().is_none_or(|s| s.is_empty()) || show_homepage {
url = package.get_homepage().map(|s| s.to_string());
}
@@ -224,13 +230,13 @@ impl Command for HomeCommand {
let mut package_exists = false;
'repos: for repo in &repos {
- for package in repo.find_packages(&package_name, None)? {
+ for package in repo.find_packages(package_name, None)? {
package_exists = true;
- if let Some(complete_pkg) = package.as_complete() {
- if self.handle_package(complete_pkg, show_homepage, show_only) {
- handled = true;
- break 'repos;
- }
+ if let Some(complete_pkg) = package.as_complete()
+ && self.handle_package(complete_pkg, show_homepage, show_only)
+ {
+ handled = true;
+ break 'repos;
}
}
}
diff --git a/crates/shirabe/src/command/init_command.rs b/crates/shirabe/src/command/init_command.rs
index 3806da5..afb4e9d 100644
--- a/crates/shirabe/src/command/init_command.rs
+++ b/crates/shirabe/src/command/init_command.rs
@@ -93,6 +93,12 @@ impl PackageDiscoveryTrait for InitCommand {
}
}
+impl Default for InitCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl InitCommand {
pub fn new() -> Self {
let mut command = InitCommand {
@@ -357,7 +363,7 @@ impl Command for InitCommand {
);
let errors = format!(
" - {}",
- implode(&format!("{} - ", PHP_EOL), &json_err.get_errors())
+ implode(&format!("{} - ", PHP_EOL), json_err.get_errors())
);
io.write_error3(
&format!("{}:{}{}", json_err.get_message(), PHP_EOL, errors),
@@ -496,7 +502,7 @@ impl Command for InitCommand {
None,
)?));
io.borrow_mut()
- .load_configuration(&mut *config.borrow_mut())?;
+ .load_configuration(&mut config.borrow_mut())?;
let mut repo_manager =
RepositoryFactory::manager(io.clone(), &config, None, None, None)?;
@@ -970,14 +976,14 @@ impl InitCommand {
Some(&mut m),
) {
let email = m.get(&CaptureKey::ByName("email".to_string())).cloned();
- if let Some(ref email) = email {
- if !self.is_valid_email(email) {
- return Err(InvalidArgumentException {
- message: format!("Invalid email \"{}\"", email),
- code: 0,
- }
- .into());
+ if let Some(ref email) = email
+ && !self.is_valid_email(email)
+ {
+ return Err(InvalidArgumentException {
+ message: format!("Invalid email \"{}\"", email),
+ code: 0,
}
+ .into());
}
let mut result: IndexMap<String, Option<String>> = IndexMap::new();
@@ -1029,7 +1035,7 @@ impl InitCommand {
let namespace: Vec<String> = array_map(
|part: &String| {
- let part = Preg::replace(r"/[^a-z0-9]/i", " ", &part);
+ let part = Preg::replace(r"/[^a-z0-9]/i", " ", part);
let part = ucwords(&part);
str_replace(" ", "", &part)
},
@@ -1049,7 +1055,7 @@ impl InitCommand {
let mut output = String::new();
if process.execute_args(
- &vec!["git".to_string(), "config".to_string(), "-l".to_string()],
+ &["git".to_string(), "config".to_string(), "-l".to_string()],
&mut output,
(),
) == 0
@@ -1175,9 +1181,8 @@ impl InitCommand {
);
let name = strtolower(&name);
let name = Preg::replace(r"{^[_.-]+|[_.-]+$|[^a-z0-9_.-]}u", "", &name);
- let name = Preg::replace(r"{([_.-]){2,}}u", "$1", &name);
- name
+ Preg::replace(r"{([_.-]){2,}}u", "$1", &name)
}
fn get_default_package_name(&mut self) -> String {
diff --git a/crates/shirabe/src/command/install_command.rs b/crates/shirabe/src/command/install_command.rs
index 3fa8ed2..1605015 100644
--- a/crates/shirabe/src/command/install_command.rs
+++ b/crates/shirabe/src/command/install_command.rs
@@ -31,6 +31,12 @@ pub struct InstallCommand {
base_command_data: BaseCommandData,
}
+impl Default for InstallCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl InstallCommand {
pub fn new() -> Self {
let mut command = InstallCommand {
@@ -150,7 +156,7 @@ impl Command for InstallCommand {
let config = composer.get_config();
let (prefer_source, prefer_dist) =
- self.get_preferred_install_options(&*config.borrow(), input.clone(), false)?;
+ self.get_preferred_install_options(&config.borrow(), input.clone(), false)?;
let optimize = input
.borrow()
@@ -243,7 +249,7 @@ impl Command for InstallCommand {
.set_apcu_autoloader(apcu, apcu_prefix.clone())
.set_platform_requirement_filter(self.get_platform_requirement_filter(input.clone())?)
.set_audit_config(
- self.create_audit_config(&mut *composer.get_config().borrow_mut(), input.clone())?,
+ self.create_audit_config(&mut composer.get_config().borrow_mut(), input.clone())?,
)
.set_error_on_audit(
input
diff --git a/crates/shirabe/src/command/licenses_command.rs b/crates/shirabe/src/command/licenses_command.rs
index 56aa042..1f054d1 100644
--- a/crates/shirabe/src/command/licenses_command.rs
+++ b/crates/shirabe/src/command/licenses_command.rs
@@ -41,6 +41,12 @@ pub struct LicensesCommand {
base_command_data: BaseCommandData,
}
+impl Default for LicensesCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl LicensesCommand {
pub fn new() -> Self {
let mut command = LicensesCommand {
@@ -161,8 +167,7 @@ impl Command for LicensesCommand {
}
};
- let packages: Vec<crate::package::PackageInterfaceHandle> =
- packages.into_iter().map(|p| p.into()).collect();
+ let packages: Vec<crate::package::PackageInterfaceHandle> = packages.into_iter().collect();
let packages = PackageSorter::sort_packages_alphabetically(packages);
let io = self.get_io();
diff --git a/crates/shirabe/src/command/outdated_command.rs b/crates/shirabe/src/command/outdated_command.rs
index 0627901..22dd120 100644
--- a/crates/shirabe/src/command/outdated_command.rs
+++ b/crates/shirabe/src/command/outdated_command.rs
@@ -26,6 +26,12 @@ pub struct OutdatedCommand {
base_command_data: BaseCommandData,
}
+impl Default for OutdatedCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl OutdatedCommand {
pub fn new() -> Self {
let mut command = OutdatedCommand {
diff --git a/crates/shirabe/src/command/package_discovery_trait.rs b/crates/shirabe/src/command/package_discovery_trait.rs
index 3263444..e2ffa7c 100644
--- a/crates/shirabe/src/command/package_discovery_trait.rs
+++ b/crates/shirabe/src/command/package_discovery_trait.rs
@@ -136,24 +136,19 @@ pub trait PackageDiscoveryTrait {
if is_file(&file) && Filesystem::is_readable(&file) {
let contents = file_get_contents(&file).unwrap_or_default();
let composer = json_decode(&contents, true).unwrap_or(PhpMixed::Null);
- if is_array(&composer) {
- if let Some(arr) = composer.as_array() {
- if let Some(ms) = arr.get("minimum-stability") {
- if let Some(s) = ms.as_string() {
- return VersionParser::normalize_stability(s).unwrap_or_default();
- }
- }
- }
+ if is_array(&composer)
+ && let Some(arr) = composer.as_array()
+ && let Some(ms) = arr.get("minimum-stability")
+ && let Some(s) = ms.as_string()
+ {
+ return VersionParser::normalize_stability(s).unwrap_or_default();
}
}
"stable".to_string()
}
- /// @param array<string> $requires
- ///
- /// @return array<string>
- /// @throws \Exception
+ #[allow(clippy::too_many_arguments, reason = "to keep PHP signature")]
fn determine_requirements(
&mut self,
input: std::rc::Rc<std::cell::RefCell<dyn InputInterface>>,
@@ -164,7 +159,7 @@ pub trait PackageDiscoveryTrait {
use_best_version_constraint: bool,
fixed: bool,
) -> Result<Vec<String>> {
- if requires.len() > 0 {
+ if !requires.is_empty() {
let requires_norm = self.normalize_requirements(requires.clone());
let mut result: Vec<String> = vec![];
let io = self.get_io();
@@ -268,7 +263,7 @@ pub trait PackageDiscoveryTrait {
None,
)?;
- if matches.len() > 0 {
+ if !matches.is_empty() {
// Remove existing packages from search results.
matches.retain(|found_package| {
!in_array(
@@ -295,7 +290,7 @@ pub trait PackageDiscoveryTrait {
if !exact_match {
let providers: IndexMap<String, crate::repository::ProviderInfo> =
self.get_repos().get_providers(package.clone())?;
- if providers.len() > 0 {
+ if !providers.is_empty() {
// PHP: array_unshift($matches, ['name' => $package, 'description' => '']);
matches.insert(
0,
@@ -356,7 +351,7 @@ pub trait PackageDiscoveryTrait {
let validator: Box<dyn Fn(PhpMixed) -> anyhow::Result<PhpMixed>> = Box::new(
move |selection_mixed: PhpMixed| -> anyhow::Result<PhpMixed> {
let selection = selection_mixed.as_string().unwrap_or("").to_string();
- if "" == selection {
+ if selection.is_empty() {
return Ok(PhpMixed::Bool(false));
}
@@ -530,7 +525,7 @@ pub trait PackageDiscoveryTrait {
// Check if it is a virtual package provided by others
let providers = repo_set.borrow().get_providers(name)?;
- if providers.len() > 0 {
+ if !providers.is_empty() {
let mut constraint = "*".to_string();
if input.borrow().is_interactive() {
let providers_count = providers.len();
@@ -693,7 +688,7 @@ pub trait PackageDiscoveryTrait {
// Check for similar names/typos
let similar = self.find_similar(name)?;
- if similar.len() > 0 {
+ if !similar.is_empty() {
if in_array(
PhpMixed::String(name.to_string()),
&PhpMixed::List(
@@ -720,25 +715,24 @@ pub trait PackageDiscoveryTrait {
"<error>Could not find package {}.</error>\nPick one of these or leave empty to abort:",
name,
),
- similar.iter().map(|s| s.clone()).collect(),
+ similar.to_vec(),
PhpMixed::Bool(false),
PhpMixed::Int(1),
"No package named \"%s\" is installed.".to_string(),
false,
);
- if let Some(idx_str) = result_mixed.as_string() {
- if let Ok(idx) = idx_str.parse::<usize>() {
- if let Some(selected) = similar.get(idx) {
- return self.find_best_version_and_name_for_package(
- io.clone(),
- input,
- selected,
- platform_repo,
- preferred_stability,
- fixed,
- );
- }
- }
+ if let Some(idx_str) = result_mixed.as_string()
+ && let Ok(idx) = idx_str.parse::<usize>()
+ && let Some(selected) = similar.get(idx)
+ {
+ return self.find_best_version_and_name_for_package(
+ io.clone(),
+ input,
+ selected,
+ platform_repo,
+ preferred_stability,
+ fixed,
+ );
}
}
diff --git a/crates/shirabe/src/command/prohibits_command.rs b/crates/shirabe/src/command/prohibits_command.rs
index 5e66c33..ddbf02a 100644
--- a/crates/shirabe/src/command/prohibits_command.rs
+++ b/crates/shirabe/src/command/prohibits_command.rs
@@ -27,6 +27,12 @@ pub struct ProhibitsCommand {
colors: Vec<String>,
}
+impl Default for ProhibitsCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl ProhibitsCommand {
pub fn new() -> Self {
let mut command = ProhibitsCommand {
diff --git a/crates/shirabe/src/command/reinstall_command.rs b/crates/shirabe/src/command/reinstall_command.rs
index c7b6cc0..8f48243 100644
--- a/crates/shirabe/src/command/reinstall_command.rs
+++ b/crates/shirabe/src/command/reinstall_command.rs
@@ -39,6 +39,12 @@ pub struct ReinstallCommand {
base_command_data: BaseCommandData,
}
+impl Default for ReinstallCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl ReinstallCommand {
pub fn new() -> Self {
let mut command = ReinstallCommand {
@@ -171,11 +177,10 @@ impl Command for ReinstallCommand {
let present_packages = local_repo.get_packages()?;
let result_packages: Vec<crate::package::PackageInterfaceHandle> =
- present_packages.iter().map(|p| p.clone().into()).collect();
+ present_packages.to_vec();
let present_packages: Vec<crate::package::PackageInterfaceHandle> = present_packages
.into_iter()
.filter(|package| !package_names_to_reinstall.contains(&package.get_name()))
- .map(|p| p.into())
.collect();
let transaction = Transaction::new(present_packages, result_packages);
@@ -183,10 +188,10 @@ impl Command for ReinstallCommand {
let mut install_order = indexmap::IndexMap::new();
for (index, op) in install_operations.iter().enumerate() {
- if let Some(install_op) = op.as_any().downcast_ref::<InstallOperation>() {
- if install_op.get_package().as_alias().is_none() {
- install_order.insert(install_op.get_package().get_name(), index);
- }
+ if let Some(install_op) = op.as_any().downcast_ref::<InstallOperation>()
+ && install_op.get_package().as_alias().is_none()
+ {
+ install_order.insert(install_op.get_package().get_name(), index);
}
}
@@ -212,7 +217,7 @@ impl Command for ReinstallCommand {
let config = composer.get_config();
let (prefer_source, prefer_dist) =
- self.get_preferred_install_options(&*config.borrow(), input.clone(), false)?;
+ self.get_preferred_install_options(&config.borrow(), input.clone(), false)?;
let installation_manager = composer.get_installation_manager().clone();
let download_manager = composer.get_download_manager();
diff --git a/crates/shirabe/src/command/remove_command.rs b/crates/shirabe/src/command/remove_command.rs
index 4e4f5dc..c1ba536 100644
--- a/crates/shirabe/src/command/remove_command.rs
+++ b/crates/shirabe/src/command/remove_command.rs
@@ -39,6 +39,12 @@ pub struct RemoveCommand {
base_command_data: BaseCommandData,
}
+impl Default for RemoveCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl RemoveCommand {
pub fn new() -> Self {
let mut command = RemoveCommand {
@@ -208,7 +214,7 @@ impl Command for RemoveCommand {
.as_list()
.map(|l| {
l.iter()
- .filter_map(|v| v.as_string().map(|s| strtolower(s)))
+ .filter_map(|v| v.as_string().map(strtolower))
.collect()
})
.unwrap_or_default();
@@ -375,22 +381,22 @@ impl Command for RemoveCommand {
"<warning>{} could not be found in {} but it is present in {}</warning>",
canonical_name, r#type, alt_type
));
- if io.is_interactive() {
- if io.ask_confirmation(
+ if io.is_interactive()
+ && io.ask_confirmation(
format!(
"Do you want to remove it from {} [<comment>yes</comment>]? ",
alt_type
),
true,
- ) {
- if dry_run {
- to_remove
- .entry(alt_type.to_string())
- .or_default()
- .push(canonical_name.clone());
- } else {
- json.remove_link(alt_type, &canonical_name);
- }
+ )
+ {
+ if dry_run {
+ to_remove
+ .entry(alt_type.to_string())
+ .or_default()
+ .push(canonical_name.clone());
+ } else {
+ json.remove_link(alt_type, &canonical_name);
}
}
} else {
@@ -436,22 +442,22 @@ impl Command for RemoveCommand {
"<warning>{} could not be found in {} but it is present in {}</warning>",
matched_package, r#type, alt_type
));
- if io.is_interactive() {
- if io.ask_confirmation(
+ if io.is_interactive()
+ && io.ask_confirmation(
format!(
"Do you want to remove it from {} [<comment>yes</comment>]? ",
alt_type
),
true,
- ) {
- if dry_run {
- to_remove
- .entry(alt_type.to_string())
- .or_default()
- .push(matched_package.clone());
- } else {
- json.remove_link(alt_type, matched_package);
- }
+ )
+ {
+ if dry_run {
+ to_remove
+ .entry(alt_type.to_string())
+ .or_default()
+ .push(matched_package.clone());
+ } else {
+ json.remove_link(alt_type, matched_package);
}
}
}
@@ -675,7 +681,7 @@ impl Command for RemoveCommand {
.set_platform_requirement_filter(self.get_platform_requirement_filter(input.clone())?);
install.set_dry_run(dry_run);
install.set_audit_config(
- self.create_audit_config(&mut *composer.get_config().borrow_mut(), input)?,
+ self.create_audit_config(&mut composer.get_config().borrow_mut(), input)?,
);
install.set_minimal_update(minimal_changes);
diff --git a/crates/shirabe/src/command/repository_command.rs b/crates/shirabe/src/command/repository_command.rs
index 284b523..6ea26d2 100644
--- a/crates/shirabe/src/command/repository_command.rs
+++ b/crates/shirabe/src/command/repository_command.rs
@@ -36,6 +36,12 @@ pub struct RepositoryCommand {
config_source: Option<JsonConfigSource>,
}
+impl Default for RepositoryCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl RepositoryCommand {
pub fn new() -> Self {
let mut command = RepositoryCommand {
@@ -94,14 +100,13 @@ impl RepositoryCommand {
}
if let PhpMixed::Array(ref repo_map) = *repo {
- if repo_map.len() == 1 {
- if let Some(first_val) = repo_map.values().next() {
- if matches!(**first_val, PhpMixed::Bool(false)) {
- let first_key = repo_map.keys().next().unwrap();
- io.write(&format!("[{}] <info>disabled</info>", first_key));
- continue;
- }
- }
+ if repo_map.len() == 1
+ && let Some(first_val) = repo_map.values().next()
+ && matches!(**first_val, PhpMixed::Bool(false))
+ {
+ let first_key = repo_map.keys().next().unwrap();
+ io.write(&format!("[{}] <info>disabled</info>", first_key));
+ continue;
}
let name = repo_map
@@ -237,12 +242,11 @@ impl Command for RepositoryCommand {
_output: std::rc::Rc<std::cell::RefCell<dyn OutputInterface>>,
) -> anyhow::Result<i64> {
let action = strtolower(
- &input
+ input
.borrow()
.get_argument("action")?
.as_string()
- .unwrap_or("")
- .to_string(),
+ .unwrap_or(""),
);
let name = input
.borrow()
@@ -406,8 +410,24 @@ impl Command for RepositoryCommand {
}));
}
let name_str = name.as_deref().unwrap();
- if let Some(repo) = repos.get(name_str) {
- if let PhpMixed::Array(ref repo_map) = *repo {
+ if let Some(repo) = repos.get(name_str)
+ && let PhpMixed::Array(ref repo_map) = *repo
+ {
+ let url = repo_map.get("url").and_then(|v| v.as_string());
+ if let Some(url) = url {
+ 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,
+ }));
+ }
+ for (_key, val) in &repos {
+ if let PhpMixed::Array(ref repo_map) = *val
+ && let Some(n) = repo_map.get("name").and_then(|v| v.as_string())
+ && n == name_str
+ {
let url = repo_map.get("url").and_then(|v| v.as_string());
if let Some(url) = url {
self.get_io().write(url);
@@ -419,26 +439,6 @@ impl Command for RepositoryCommand {
}));
}
}
- for (_key, val) in &repos {
- if let PhpMixed::Array(ref repo_map) = *val {
- if let Some(n) = repo_map.get("name").and_then(|v| v.as_string()) {
- if n == name_str {
- let url = repo_map.get("url").and_then(|v| v.as_string());
- if let Some(url) = url {
- 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,
- }));
- }
- }
- }
- }
Err(anyhow::anyhow!(InvalidArgumentException {
message: format!("There is no {} repository defined", name_str),
code: 0,
diff --git a/crates/shirabe/src/command/require_command.rs b/crates/shirabe/src/command/require_command.rs
index a82f858..31d345a 100644
--- a/crates/shirabe/src/command/require_command.rs
+++ b/crates/shirabe/src/command/require_command.rs
@@ -67,6 +67,12 @@ pub struct RequireCommand {
dependency_resolution_completed: bool,
}
+impl Default for RequireCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl RequireCommand {
pub fn new() -> Self {
let mut command = RequireCommand {
@@ -394,7 +400,6 @@ impl Command for RequireCommand {
.get_repos()
.find_packages(name, None)?
.into_iter()
- .map(|p| p.into())
.collect();
let pkg: Option<crate::package::PackageInterfaceHandle> =
PackageSorter::get_most_current_version(found_packages);
@@ -537,9 +542,7 @@ impl Command for RequireCommand {
}
input.borrow_mut().set_option("dev", PhpMixed::Bool(true))?;
- let swap = require_key;
- require_key = remove_key;
- remove_key = swap;
+ std::mem::swap(&mut require_key, &mut remove_key);
}
}
}
@@ -980,7 +983,7 @@ impl RequireCommand {
let mut install = Installer::create(io.clone(), &composer_handle);
let (prefer_source, prefer_dist) = self.get_preferred_install_options(
- &*composer.get_config().borrow(),
+ &composer.get_config().borrow(),
input.clone(),
false,
)?;
@@ -1034,7 +1037,7 @@ impl RequireCommand {
.unwrap_or(false),
)
.set_audit_config(
- self.create_audit_config(&mut *composer.get_config().borrow_mut(), input.clone())?,
+ self.create_audit_config(&mut composer.get_config().borrow_mut(), input.clone())?,
)
.set_minimal_update(minimal_changes);
diff --git a/crates/shirabe/src/command/run_script_command.rs b/crates/shirabe/src/command/run_script_command.rs
index 92f9ccf..141b458 100644
--- a/crates/shirabe/src/command/run_script_command.rs
+++ b/crates/shirabe/src/command/run_script_command.rs
@@ -33,6 +33,12 @@ pub struct RunScriptCommand {
script_events: Vec<&'static str>,
}
+impl Default for RunScriptCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl RunScriptCommand {
pub fn new() -> Self {
let mut command = RunScriptCommand {
@@ -314,9 +320,9 @@ impl Command for RunScriptCommand {
Platform::put_env("COMPOSER_DEV_MODE", if dev_mode { "1" } else { "0" });
- Ok(dispatcher
+ dispatcher
.borrow_mut()
- .dispatch_script(&script, dev_mode, args, IndexMap::new())?)
+ .dispatch_script(&script, dev_mode, args, IndexMap::new())
}
fn initialize(
diff --git a/crates/shirabe/src/command/script_alias_command.rs b/crates/shirabe/src/command/script_alias_command.rs
index 02a25b2..1d94f09 100644
--- a/crates/shirabe/src/command/script_alias_command.rs
+++ b/crates/shirabe/src/command/script_alias_command.rs
@@ -161,9 +161,9 @@ impl Command for ScriptAliasCommand {
})
.unwrap_or_default();
- Ok(dispatcher
+ dispatcher
.borrow_mut()
- .dispatch_script(&self.script, dev_mode, args_value, flags)?)
+ .dispatch_script(&self.script, dev_mode, args_value, flags)
}
fn initialize(
diff --git a/crates/shirabe/src/command/search_command.rs b/crates/shirabe/src/command/search_command.rs
index a3254e4..19a215f 100644
--- a/crates/shirabe/src/command/search_command.rs
+++ b/crates/shirabe/src/command/search_command.rs
@@ -33,6 +33,12 @@ pub struct SearchCommand {
base_command_data: BaseCommandData,
}
+impl Default for SearchCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl SearchCommand {
pub fn new() -> Self {
let mut command = SearchCommand {
@@ -217,7 +223,7 @@ impl Command for SearchCommand {
let results = repos.search(query, mode, r#type)?;
- if results.len() > 0 && format == "text" {
+ if !results.is_empty() && format == "text" {
let width = self.get_terminal_width();
let mut name_length: i64 = 0;
for result in &results {
diff --git a/crates/shirabe/src/command/self_update_command.rs b/crates/shirabe/src/command/self_update_command.rs
index 510b097..2f319ff 100644
--- a/crates/shirabe/src/command/self_update_command.rs
+++ b/crates/shirabe/src/command/self_update_command.rs
@@ -27,6 +27,12 @@ pub struct SelfUpdateCommand {
base_command_data: BaseCommandData,
}
+impl Default for SelfUpdateCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl SelfUpdateCommand {
pub fn new() -> Self {
let mut command = SelfUpdateCommand {
diff --git a/crates/shirabe/src/command/show_command.rs b/crates/shirabe/src/command/show_command.rs
index 520e716..f7319ed 100644
--- a/crates/shirabe/src/command/show_command.rs
+++ b/crates/shirabe/src/command/show_command.rs
@@ -69,6 +69,12 @@ pub struct ShowCommand {
repository_set: Option<std::rc::Rc<std::cell::RefCell<RepositorySet>>>,
}
+impl Default for ShowCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl ShowCommand {
pub fn new() -> Self {
let mut command = ShowCommand {
@@ -283,9 +289,7 @@ impl Command for ShowCommand {
.get_repository_manager()
.borrow()
.get_repositories()
- .iter()
- .map(|r| r.clone())
- .collect(),
+ .to_vec(),
));
ir.add_repository(
composer
@@ -512,28 +516,30 @@ impl Command for ShowCommand {
// show single package or single version
if let Some(ref pkg) = single_package {
versions_map.insert(pkg.get_pretty_version(), pkg.get_version());
- } else if let Some(ref pf) = package_filter {
- if !pf.contains('*') {
- let (matched_package, vers) = self.get_package(
- &*installed_repo.borrow(),
- &repos,
- pf,
- input.borrow().get_argument("version")?,
- )?;
+ } else if let Some(ref pf) = package_filter
+ && !pf.contains('*')
+ {
+ let (matched_package, vers) = self.get_package(
+ &*installed_repo.borrow(),
+ &repos,
+ pf,
+ input.borrow().get_argument("version")?,
+ )?;
- if let Some(ref pkg) = matched_package {
- if input.borrow().get_option("direct")?.as_bool() == Some(true) {
- if !in_array(
- PhpMixed::String(pkg.get_name()),
- &PhpMixed::List(
- self.get_root_requires()
- .into_iter()
- .map(|s| Box::new(PhpMixed::String(s)))
- .collect(),
- ),
- true,
- ) {
- return Err(InvalidArgumentException {
+ if let Some(ref pkg) = matched_package
+ && input.borrow().get_option("direct")?.as_bool() == Some(true)
+ && !in_array(
+ PhpMixed::String(pkg.get_name()),
+ &PhpMixed::List(
+ self.get_root_requires()
+ .into_iter()
+ .map(|s| Box::new(PhpMixed::String(s)))
+ .collect(),
+ ),
+ true,
+ )
+ {
+ return Err(InvalidArgumentException {
message: format!(
"Package \"{}\" is installed but not a direct dependent of the root package.",
pkg.get_name()
@@ -541,47 +547,42 @@ impl Command for ShowCommand {
code: 0,
}
.into());
- }
- }
- }
+ }
- if matched_package.is_none() {
- let options = input.borrow().get_options();
- let mut hint = String::new();
- if input.borrow().get_option("locked")?.as_bool() == Some(true) {
- hint.push_str(" in lock file");
- }
- if options.contains_key("working-dir") {
- hint.push_str(&format!(
- " in {}/composer.json",
- options
- .get("working-dir")
- .and_then(|v| v.as_string())
- .unwrap_or("")
- ));
- }
- if PlatformRepository::is_platform_package(pf)
- && input.borrow().get_option("platform")?.as_bool() != Some(true)
- {
- hint.push_str(", try using --platform (-p) to show platform packages");
- }
- if input.borrow().get_option("all")?.as_bool() != Some(true)
- && input.borrow().get_option("available")?.as_bool() != Some(true)
- {
- hint.push_str(
- ", try using --available (-a) to show all available packages",
- );
- }
+ if matched_package.is_none() {
+ let options = input.borrow().get_options();
+ let mut hint = String::new();
+ if input.borrow().get_option("locked")?.as_bool() == Some(true) {
+ hint.push_str(" in lock file");
+ }
+ if options.contains_key("working-dir") {
+ hint.push_str(&format!(
+ " in {}/composer.json",
+ options
+ .get("working-dir")
+ .and_then(|v| v.as_string())
+ .unwrap_or("")
+ ));
+ }
+ if PlatformRepository::is_platform_package(pf)
+ && input.borrow().get_option("platform")?.as_bool() != Some(true)
+ {
+ hint.push_str(", try using --platform (-p) to show platform packages");
+ }
+ if input.borrow().get_option("all")?.as_bool() != Some(true)
+ && input.borrow().get_option("available")?.as_bool() != Some(true)
+ {
+ hint.push_str(", try using --available (-a) to show all available packages");
+ }
- return Err(InvalidArgumentException {
- message: format!("Package \"{}\" not found{}.", pf, hint),
- code: 0,
- }
- .into());
+ return Err(InvalidArgumentException {
+ message: format!("Package \"{}\" not found{}.", pf, hint),
+ code: 0,
}
- single_package = matched_package;
- versions_map = vers;
+ .into());
}
+ single_package = matched_package;
+ versions_map = vers;
}
if let Some(ref package) = single_package {
@@ -653,7 +654,7 @@ impl Command for ShowCommand {
.as_ref()
.unwrap()
.as_complete()
- .map_or(true, |c| !c.is_abandoned()))
+ .is_none_or(|c| !c.is_abandoned()))
{
exit_code = 1;
}
@@ -669,7 +670,7 @@ impl Command for ShowCommand {
};
if let Some(path) = path {
let real = realpath(&path).unwrap_or_default();
- let trimmed = real.split(|c| c == '\r' || c == '\n').next().unwrap_or("");
+ let trimmed = real.split(['\r', '\n']).next().unwrap_or("");
self.get_io().write(&format!(" {}", trimmed));
} else {
self.get_io().write(" null");
@@ -776,7 +777,7 @@ impl Command for ShowCommand {
"platform"
} else if locked_repo
.as_ref()
- .map_or(false, |lr| Self::same_repository(&repo, lr))
+ .is_some_and(|lr| Self::same_repository(&repo, lr))
{
"locked"
} else if Self::same_repository(&repo, &installed_repo)
@@ -784,9 +785,7 @@ impl Command for ShowCommand {
.borrow()
.as_any()
.downcast_ref::<InstalledRepository>()
- .map_or(false, |ir| {
- ir.get_repositories().iter().any(|r| r.ptr_eq(&repo))
- })
+ .is_some_and(|ir| ir.get_repositories().iter().any(|r| r.ptr_eq(&repo)))
{
"installed"
} else {
@@ -800,7 +799,7 @@ impl Command for ShowCommand {
for name in names {
packages
.entry(type_owned.clone())
- .or_insert_with(IndexMap::new)
+ .or_default()
.insert(name.clone(), PackageOrName::Name(name));
}
} else {
@@ -816,7 +815,7 @@ impl Command for ShowCommand {
}
};
if need_replace {
- let mut p: crate::package::PackageInterfaceHandle = package.clone().into();
+ let mut p: crate::package::PackageInterfaceHandle = package.clone();
while let Some(alias) = p.as_alias() {
p = alias.get_alias_of().into();
}
@@ -840,7 +839,7 @@ impl Command for ShowCommand {
if matches_list {
packages
.entry(type_owned.clone())
- .or_insert_with(IndexMap::new)
+ .or_default()
.insert(p.get_name(), PackageOrName::Pkg(p));
}
}
@@ -850,7 +849,7 @@ impl Command for ShowCommand {
for (name, p) in platform_repo.borrow().get_disabled_packages() {
packages
.entry(type_owned.clone())
- .or_insert_with(IndexMap::new)
+ .or_default()
.insert(name.clone(), PackageOrName::Pkg(p.clone().into()));
}
}
@@ -869,7 +868,7 @@ impl Command for ShowCommand {
.as_list()
.map(|l| {
l.iter()
- .filter_map(|v| v.as_string().map(|s| strtolower(s)))
+ .filter_map(|v| v.as_string().map(strtolower))
.collect::<Vec<_>>()
})
.unwrap_or_default(),
@@ -902,24 +901,23 @@ impl Command for ShowCommand {
if show_latest && *show_version {
for package_or_name in type_packages.values() {
- if let PackageOrName::Pkg(package) = package_or_name {
- if !Preg::is_match(&ignored_packages_regex, &package.get_pretty_name())
- {
- let latest = self.find_latest_package(
- package.clone(),
- composer.as_ref().unwrap(),
- &platform_repo,
- show_major_only,
- show_minor_only,
- show_patch_only,
- platform_req_filter.clone(),
- )?;
- if latest.is_none() {
- continue;
- }
-
- latest_packages.insert(package.get_pretty_name(), latest.unwrap());
+ if let PackageOrName::Pkg(package) = package_or_name
+ && !Preg::is_match(&ignored_packages_regex, &package.get_pretty_name())
+ {
+ let latest = self.find_latest_package(
+ package.clone(),
+ composer.as_ref().unwrap(),
+ &platform_repo,
+ show_major_only,
+ show_minor_only,
+ show_patch_only,
+ platform_req_filter.clone(),
+ )?;
+ if latest.is_none() {
+ continue;
}
+
+ latest_packages.insert(package.get_pretty_name(), latest.unwrap());
}
}
}
@@ -967,7 +965,7 @@ impl Command for ShowCommand {
) == package.get_full_pretty_version(
true,
crate::package::DisplayMode::SourceRefIfDev,
- ) && latest.as_complete().map_or(true, |c| !c.is_abandoned())
+ ) && latest.as_complete().is_none_or(|c| !c.is_abandoned())
} else {
false
};
@@ -1065,8 +1063,7 @@ impl Command for ShowCommand {
);
}
}
- if write_latest && latest_package.is_some() {
- let latest = latest_package.unwrap();
+ if write_latest && let Some(latest) = latest_package {
let mut latest_version_str = latest.get_full_pretty_version(
true,
crate::package::DisplayMode::SourceRefIfDev,
@@ -1107,13 +1104,11 @@ impl Command for ShowCommand {
);
latest_length = latest_length.max("[none matched]".len());
}
- if write_description {
- if let Some(c) = package.as_complete() {
- package_view_data.insert(
- "description".to_string(),
- PhpMixed::String(c.get_description().unwrap_or_default()),
- );
- }
+ if write_description && let Some(c) = package.as_complete() {
+ package_view_data.insert(
+ "description".to_string(),
+ PhpMixed::String(c.get_description().unwrap_or_default()),
+ );
}
if write_path {
let installation_manager = composer
@@ -1126,8 +1121,7 @@ impl Command for ShowCommand {
.get_install_path(package.clone());
if let Some(p) = path {
let r = realpath(&p).unwrap_or_default();
- let trimmed =
- r.split(|c| c == '\r' || c == '\n').next().unwrap_or("");
+ let trimmed = r.split(['\r', '\n']).next().unwrap_or("");
package_view_data.insert(
"path".to_string(),
PhpMixed::String(trimmed.to_string()),
@@ -1138,31 +1132,27 @@ impl Command for ShowCommand {
}
let mut package_is_abandoned: PhpMixed = PhpMixed::Bool(false);
- if let Some(latest) = latest_package {
- if let Some(c) = latest.as_complete() {
- if c.is_abandoned() {
- let replacement_package_name = c.get_replacement_package();
- let replacement = if let Some(ref rp) = replacement_package_name
- {
- format!("Use {} instead", rp)
- } else {
- "No replacement was suggested".to_string()
- };
- let package_warning = format!(
- "Package {} is abandoned, you should avoid using it. {}.",
- package.get_pretty_name(),
- replacement
- );
- package_view_data.insert(
- "warning".to_string(),
- PhpMixed::String(package_warning),
- );
- package_is_abandoned = match replacement_package_name {
- Some(rp) => PhpMixed::String(rp),
- None => PhpMixed::Bool(true),
- };
- }
- }
+ if let Some(latest) = latest_package
+ && let Some(c) = latest.as_complete()
+ && c.is_abandoned()
+ {
+ let replacement_package_name = c.get_replacement_package();
+ let replacement = if let Some(ref rp) = replacement_package_name {
+ format!("Use {} instead", rp)
+ } else {
+ "No replacement was suggested".to_string()
+ };
+ let package_warning = format!(
+ "Package {} is abandoned, you should avoid using it. {}.",
+ package.get_pretty_name(),
+ replacement
+ );
+ package_view_data
+ .insert("warning".to_string(), PhpMixed::String(package_warning));
+ package_is_abandoned = match replacement_package_name {
+ Some(rp) => PhpMixed::String(rp),
+ None => PhpMixed::Bool(true),
+ };
}
package_view_data.insert("abandoned".to_string(), package_is_abandoned);
@@ -1390,6 +1380,7 @@ impl BaseCommand for ShowCommand {
impl ShowCommand {
// TODO(cli-completion): pub fn suggest_package_based_on_mode(&self) -> Box<dyn Fn(&CompletionInput) -> Vec<String>>
+ #[allow(clippy::too_many_arguments, reason = "to keep PHP signature")]
fn print_packages(
&mut self,
packages: &[IndexMap<String, PhpMixed>],
@@ -1445,91 +1436,90 @@ impl ShowCommand {
let width_pad = if pad_name { name_length } else { 0 };
io.write_no_newline(&format!("{}{:<width$}", indent, name, width = width_pad));
}
- if let Some(version) = package.get("version").and_then(|v| v.as_string()) {
- if write_version {
- let width_pad = if pad_version { version_length } else { 0 };
- io.write_no_newline(&format!(" {:<width$}", version, width = width_pad));
- }
+ if let Some(version) = package.get("version").and_then(|v| v.as_string())
+ && write_version
+ {
+ let width_pad = if pad_version { version_length } else { 0 };
+ io.write_no_newline(&format!(" {:<width$}", version, width = width_pad));
}
if let (Some(latest_version), Some(update_status)) = (
package.get("latest").and_then(|v| v.as_string()),
package.get("latest-status").and_then(|v| v.as_string()),
- ) {
- if write_latest {
- let mut latest_version = latest_version.to_string();
- let style = Self::update_status_to_version_style(update_status);
- if !io.is_decorated() {
- let marker = update_status
- .replace("up-to-date", "=")
- .replace("semver-safe-update", "!")
- .replace("update-possible", "~");
- latest_version = format!("{} {}", marker, latest_version);
- }
- let width_pad = if pad_latest { latest_length } else { 0 };
- io.write_no_newline(&format!(
- " <{}>{:<width$}</{}>",
- style,
- latest_version,
- style,
- width = width_pad
- ));
- if write_release_date {
- if let Some(age) = package.get("release-age").and_then(|v| v.as_string()) {
- let width_pad = if pad_release_date {
- release_date_length
- } else {
- 0
- };
- io.write_no_newline(&format!(" {:<width$}", age, width = width_pad));
- }
- }
+ ) && write_latest
+ {
+ let mut latest_version = latest_version.to_string();
+ let style = Self::update_status_to_version_style(update_status);
+ if !io.is_decorated() {
+ let marker = update_status
+ .replace("up-to-date", "=")
+ .replace("semver-safe-update", "!")
+ .replace("update-possible", "~");
+ latest_version = format!("{} {}", marker, latest_version);
+ }
+ let width_pad = if pad_latest { latest_length } else { 0 };
+ io.write_no_newline(&format!(
+ " <{}>{:<width$}</{}>",
+ style,
+ latest_version,
+ style,
+ width = width_pad
+ ));
+ if write_release_date
+ && let Some(age) = package.get("release-age").and_then(|v| v.as_string())
+ {
+ let width_pad = if pad_release_date {
+ release_date_length
+ } else {
+ 0
+ };
+ io.write_no_newline(&format!(" {:<width$}", age, width = width_pad));
}
}
- if let Some(description) = package.get("description").and_then(|v| v.as_string()) {
- if write_description {
- let mut description = description
- .split(|c| c == '\r' || c == '\n')
- .next()
- .unwrap_or("")
- .to_string();
+ if let Some(description) = package.get("description").and_then(|v| v.as_string())
+ && write_description
+ {
+ let mut description = description
+ .split(['\r', '\n'])
+ .next()
+ .unwrap_or("")
+ .to_string();
- // Compute remaining width available for the description.
- let mut remaining = (width as i64)
- - (name_length as i64)
- - (version_length as i64)
- - (release_date_length as i64)
- - 4;
- if write_latest {
- remaining -= latest_length as i64;
- }
+ // Compute remaining width available for the description.
+ let mut remaining = (width as i64)
+ - (name_length as i64)
+ - (version_length as i64)
+ - (release_date_length as i64)
+ - 4;
+ if write_latest {
+ remaining -= latest_length as i64;
+ }
- // If nothing fits, clear the description.
- if remaining <= 0 {
- description = String::new();
- } else if extension_loaded("mbstring") {
- // Use mb_strwidth/mb_strimwidth to measure and trim by display width
- // (CJK characters count as width 2). mb_strimwidth counts the trim
- // marker ('...') in the width parameter, so pass $remaining directly.
- if description.chars().count() > remaining as usize {
- description = format!(
- "{}...",
- description
- .chars()
- .take((remaining as usize).saturating_sub(3))
- .collect::<String>()
- );
- }
- } else {
- // Fallback when mbstring is not available: do a conservative byte-based cut.
- // Ensure cut length is non-negative and leave room for the ellipsis.
- let cut = (remaining as i64 - 3).max(0) as usize;
- if description.len() > cut {
- description = format!("{}...", &description[..cut]);
- }
+ // If nothing fits, clear the description.
+ if remaining <= 0 {
+ description = String::new();
+ } else if extension_loaded("mbstring") {
+ // Use mb_strwidth/mb_strimwidth to measure and trim by display width
+ // (CJK characters count as width 2). mb_strimwidth counts the trim
+ // marker ('...') in the width parameter, so pass $remaining directly.
+ if description.chars().count() > remaining as usize {
+ description = format!(
+ "{}...",
+ description
+ .chars()
+ .take((remaining as usize).saturating_sub(3))
+ .collect::<String>()
+ );
+ }
+ } else {
+ // Fallback when mbstring is not available: do a conservative byte-based cut.
+ // Ensure cut length is non-negative and leave room for the ellipsis.
+ let cut = (remaining - 3).max(0) as usize;
+ if description.len() > cut {
+ description = format!("{}...", &description[..cut]);
}
-
- io.write_no_newline(&format!(" {}", description));
}
+
+ io.write_no_newline(&format!(" {}", description));
}
if package.contains_key("path") {
let path_str = match package.get("path") {
@@ -1616,11 +1606,11 @@ impl ShowCommand {
let mut literals: Vec<i64> = Vec::new();
for package in matches.iter() {
// avoid showing the 9999999-dev alias if the default branch has no branch-alias set
- let mut p: crate::package::PackageInterfaceHandle = package.clone().into();
- if let Some(alias) = p.as_alias() {
- if p.get_version() == VersionParser::DEFAULT_BRANCH_ALIAS {
- p = alias.get_alias_of().into();
- }
+ let mut p: crate::package::PackageInterfaceHandle = package.clone();
+ if let Some(alias) = p.as_alias()
+ && p.get_version() == VersionParser::DEFAULT_BRANCH_ALIAS
+ {
+ p = alias.get_alias_of().into();
}
// select an exact match if it is in the installed repo and no specific version was required
@@ -1635,12 +1625,13 @@ impl ShowCommand {
// select preferred package according to policy rules
if matched_package.is_none() && !literals.is_empty() {
let preferred = policy.select_preferred_packages(&pool, literals.clone(), None);
- matched_package = Some(pool.literal_to_package(preferred[0]).into());
+ matched_package = Some(pool.literal_to_package(preferred[0]));
}
- if let Some(ref mp) = matched_package {
- if mp.as_complete().is_none() {
- return Err(LogicException {
+ 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)
@@ -1648,7 +1639,6 @@ impl ShowCommand {
code: 0,
}
.into());
- }
}
let matched_package = matched_package.and_then(|mp| mp.as_complete());
@@ -1708,15 +1698,13 @@ impl ShowCommand {
self.get_io()
.write(&format!("<info>keywords</info> : {}", keywords.join(", ")));
self.print_versions(package.clone(), versions, installed_repo)?;
- if is_installed_package {
- if let Some(rd) = package.get_release_date() {
- let rel = self.get_relative_time(&rd);
- self.get_io().write(&format!(
- "<info>released</info> : {}, {}",
- rd.format(date_format_to_strftime("Y-m-d")),
- rel
- ));
- }
+ if is_installed_package && let Some(rd) = package.get_release_date() {
+ let rel = self.get_relative_time(&rd);
+ self.get_io().write(&format!(
+ "<info>released</info> : {}, {}",
+ rd.format(date_format_to_strftime("Y-m-d")),
+ rel
+ ));
}
let latest: PackageInterfaceHandle = if let Some(latest) = latest_package {
let style = self.get_version_style(latest.clone(), package.clone().into());
@@ -1764,10 +1752,10 @@ impl ShowCommand {
if is_installed_package {
let path: Option<String> = self.require_composer(None, None).ok().and_then(|c| {
let installation_manager = c.borrow_partial().get_installation_manager();
- let p = installation_manager
+
+ installation_manager
.borrow_mut()
- .get_install_path(package.clone().into());
- p
+ .get_install_path(package.clone().into())
});
if let Some(p) = path {
self.get_io().write(&format!(
@@ -1783,18 +1771,18 @@ impl ShowCommand {
package.get_names(true).join(", ")
));
- if let Some(c) = latest.as_complete() {
- if c.is_abandoned() {
- let replacement = match c.get_replacement_package() {
- Some(rp) => format!(" The author suggests using the {} package instead.", rp),
- None => String::new(),
- };
+ if let Some(c) = latest.as_complete()
+ && c.is_abandoned()
+ {
+ let replacement = match c.get_replacement_package() {
+ Some(rp) => format!(" The author suggests using the {} package instead.", rp),
+ None => String::new(),
+ };
- self.get_io().write_error(&format!(
+ self.get_io().write_error(&format!(
"<warning>Attention: This package is abandoned and no longer maintained.{}</warning>",
replacement
));
- }
}
let support = package.get_support();
@@ -1830,14 +1818,14 @@ impl ShowCommand {
.write(&format!("{} => {}", name_disp, path_str));
}
}
- } else if r#type == "classmap" {
- if let PhpMixed::List(l) = autoloads {
- let joined: Vec<String> = l
- .iter()
- .filter_map(|v| v.as_string().map(|s| s.to_string()))
- .collect();
- self.get_io().write(&joined.join(", "));
- }
+ } else if r#type == "classmap"
+ && let PhpMixed::List(l) = autoloads
+ {
+ let joined: Vec<String> = l
+ .iter()
+ .filter_map(|v| v.as_string().map(|s| s.to_string()))
+ .collect();
+ self.get_io().write(&joined.join(", "));
}
}
let include_paths = package.get_include_paths();
@@ -1869,10 +1857,10 @@ impl ShowCommand {
.iter()
.map(|v| (v.clone(), v.clone()))
.collect();
- if let Some(found) = array_search(&installed_version, &key_map) {
- if let Some(idx) = versions_keys.iter().position(|v| v == &found) {
- versions_keys[idx] = format!("<info>* {}</info>", installed_version);
- }
+ if let Some(found) = array_search(&installed_version, &key_map)
+ && let Some(idx) = versions_keys.iter().position(|v| v == &found)
+ {
+ versions_keys[idx] = format!("<info>* {}</info>", installed_version);
}
}
}
@@ -1924,7 +1912,7 @@ impl ShowCommand {
// SpdxLicenses::getLicenseByIdentifier returns [0 => fullname, 1 => osiApproved, 2 => url].
let list = license.as_list();
let fullname = list
- .and_then(|l| l.get(0))
+ .and_then(|l| l.first())
.and_then(|v| v.as_string())
.unwrap_or("")
.to_string();
@@ -2075,16 +2063,16 @@ impl ShowCommand {
}
}
- if let Some(c) = latest.as_complete() {
- if c.is_abandoned() {
- json.insert(
- "replacement".to_string(),
- match c.get_replacement_package() {
- Some(rp) => PhpMixed::String(rp.to_string()),
- None => PhpMixed::Null,
- },
- );
- }
+ if let Some(c) = latest.as_complete()
+ && c.is_abandoned()
+ {
+ json.insert(
+ "replacement".to_string(),
+ match c.get_replacement_package() {
+ Some(rp) => PhpMixed::String(rp.to_string()),
+ None => PhpMixed::Null,
+ },
+ );
}
if !package.get_suggests().is_empty() {
@@ -2182,7 +2170,7 @@ impl ShowCommand {
// Note 'osi' is the license id string, not the OSI-approved flag.
let list = l.as_list();
let name = list
- .and_then(|x| x.get(0))
+ .and_then(|x| x.first())
.and_then(|v| v.as_string())
.unwrap_or("")
.to_string();
@@ -2340,10 +2328,7 @@ impl ShowCommand {
.to_string();
self.get_io().write_no_newline(&format!(" {}", version));
if let Some(description) = package.get("description").and_then(|v| v.as_string()) {
- let trimmed = description
- .split(|c| c == '\r' || c == '\n')
- .next()
- .unwrap_or("");
+ let trimmed = description.split(['\r', '\n']).next().unwrap_or("");
self.get_io().write(&format!(" {}", trimmed));
} else {
// output newline
@@ -2680,6 +2665,7 @@ impl ShowCommand {
}
/// Given a package, this finds the latest package matching it
+ #[allow(clippy::too_many_arguments, reason = "to keep PHP signature")]
fn find_latest_package(
&mut self,
package: PackageInterfaceHandle,
@@ -2829,9 +2815,7 @@ impl ShowCommand {
.get_repository_manager()
.borrow()
.get_repositories()
- .iter()
- .map(|r| r.clone())
- .collect(),
+ .to_vec(),
)))?;
self.repository_set = Some(std::rc::Rc::new(std::cell::RefCell::new(rs)));
}
diff --git a/crates/shirabe/src/command/status_command.rs b/crates/shirabe/src/command/status_command.rs
index 9115caf..06f19e0 100644
--- a/crates/shirabe/src/command/status_command.rs
+++ b/crates/shirabe/src/command/status_command.rs
@@ -32,6 +32,12 @@ pub struct StatusCommand {
base_command_data: BaseCommandData,
}
+impl Default for StatusCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl StatusCommand {
const EXIT_CODE_ERRORS: i64 = 1;
const EXIT_CODE_UNPUSHED_CHANGES: i64 = 2;
@@ -115,57 +121,54 @@ impl StatusCommand {
}
}
- if let Some(vcs_downloader) = downloader.as_vcs_capable_downloader_interface() {
- if vcs_downloader
+ if let Some(vcs_downloader) = downloader.as_vcs_capable_downloader_interface()
+ && vcs_downloader
.get_vcs_reference(package.clone(), target_dir.clone())
.is_some()
- {
- let previous_ref = match package.get_installation_source().as_deref() {
- Some("source") => package.get_source_reference().map(|s| s.to_string()),
- Some("dist") => package.get_dist_reference().map(|s| s.to_string()),
- _ => None,
- };
+ {
+ let previous_ref = match package.get_installation_source().as_deref() {
+ Some("source") => package.get_source_reference().map(|s| s.to_string()),
+ Some("dist") => package.get_dist_reference().map(|s| s.to_string()),
+ _ => None,
+ };
- let current_version =
- guesser.guess_version(&dumper.dump(package.clone()), &target_dir)?;
+ let current_version =
+ guesser.guess_version(&dumper.dump(package.clone()), &target_dir)?;
- if let (Some(prev_ref), Some(cur_version)) = (&previous_ref, &current_version) {
- if cur_version.commit.as_deref() != Some(prev_ref.as_str())
- && cur_version.pretty_version.as_deref() != Some(prev_ref.as_str())
- {
- let mut previous = IndexMap::new();
- previous.insert(
- "version".to_string(),
- package.get_pretty_version().to_string(),
- );
- previous.insert("ref".to_string(), prev_ref.clone());
+ if let (Some(prev_ref), Some(cur_version)) = (&previous_ref, &current_version)
+ && cur_version.commit.as_deref() != Some(prev_ref.as_str())
+ && cur_version.pretty_version.as_deref() != Some(prev_ref.as_str())
+ {
+ let mut previous = IndexMap::new();
+ previous.insert(
+ "version".to_string(),
+ package.get_pretty_version().to_string(),
+ );
+ previous.insert("ref".to_string(), prev_ref.clone());
- let mut current = IndexMap::new();
- current.insert(
- "version".to_string(),
- cur_version.pretty_version.clone().unwrap_or_default(),
- );
- current.insert(
- "ref".to_string(),
- cur_version.commit.clone().unwrap_or_default(),
- );
+ let mut current = IndexMap::new();
+ current.insert(
+ "version".to_string(),
+ cur_version.pretty_version.clone().unwrap_or_default(),
+ );
+ current.insert(
+ "ref".to_string(),
+ cur_version.commit.clone().unwrap_or_default(),
+ );
- let mut change = IndexMap::new();
- change.insert("previous".to_string(), previous);
- change.insert("current".to_string(), current);
+ let mut change = IndexMap::new();
+ change.insert("previous".to_string(), previous);
+ change.insert("current".to_string(), current);
- vcs_version_changes.insert(target_dir.clone(), change);
- }
- }
+ vcs_version_changes.insert(target_dir.clone(), change);
}
}
- if let Some(dvcs_downloader) = downloader.as_dvcs_downloader_interface() {
- if let Some(unpushed) =
+ if let Some(dvcs_downloader) = downloader.as_dvcs_downloader_interface()
+ && let Some(unpushed) =
dvcs_downloader.get_unpushed_changes(package.clone(), target_dir.clone())?
- {
- unpushed_changes.insert(target_dir, unpushed);
- }
+ {
+ unpushed_changes.insert(target_dir, unpushed);
}
}
diff --git a/crates/shirabe/src/command/suggests_command.rs b/crates/shirabe/src/command/suggests_command.rs
index 344887e..8766196 100644
--- a/crates/shirabe/src/command/suggests_command.rs
+++ b/crates/shirabe/src/command/suggests_command.rs
@@ -29,6 +29,12 @@ pub struct SuggestsCommand {
base_command_data: BaseCommandData,
}
+impl Default for SuggestsCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl SuggestsCommand {
pub fn new() -> Self {
let mut command = SuggestsCommand {
diff --git a/crates/shirabe/src/command/update_command.rs b/crates/shirabe/src/command/update_command.rs
index 33a13a8..4581ce1 100644
--- a/crates/shirabe/src/command/update_command.rs
+++ b/crates/shirabe/src/command/update_command.rs
@@ -49,6 +49,12 @@ pub struct UpdateCommand {
base_command_data: BaseCommandData,
}
+impl Default for UpdateCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl UpdateCommand {
pub fn new() -> Self {
let mut command = UpdateCommand {
@@ -152,7 +158,7 @@ impl Command for UpdateCommand {
)?;
// extract --with shorthands from the allowlist
- if packages.len() > 0 {
+ if !packages.is_empty() {
let allowlist_packages_with_requirements: Vec<String> =
array_filter(&packages, |pkg: &String| -> bool {
Preg::is_match(r"{\S+[ =:]\S+}", pkg)
@@ -191,9 +197,10 @@ impl Command for UpdateCommand {
let package = strtolower(package);
let parsed_constraint = parser.parse_constraints(constraint)?;
temporary_constraints.insert(package.clone(), parsed_constraint.clone());
- if let Some(root_req) = root_requirements.get(&package) {
- if !Intervals::have_intersections(&parsed_constraint, root_req.get_constraint())? {
- io.write_error3(
+ if let Some(root_req) = root_requirements.get(&package)
+ && !Intervals::have_intersections(&parsed_constraint, root_req.get_constraint())?
+ {
+ io.write_error3(
&format!(
"<error>The temporary constraint \"{}\" for \"{}\" must be a subset of the constraint in your composer.json ({})</error>",
constraint,
@@ -203,13 +210,12 @@ impl Command for UpdateCommand {
true,
io_interface::NORMAL,
);
- io.write(&format!(
+ io.write(&format!(
"<info>Run `composer require {}` or `composer require {}:{}` instead to replace the constraint</info>",
package, package, constraint,
));
- return Ok(crate::command::FAILURE);
- }
+ return Ok(crate::command::FAILURE);
}
}
@@ -346,7 +352,7 @@ impl Command for UpdateCommand {
let config = composer.get_config();
let (prefer_source, prefer_dist) =
- self.get_preferred_install_options(&*config.borrow(), input.clone(), false)?;
+ self.get_preferred_install_options(&config.borrow(), input.clone(), false)?;
let optimize = input
.borrow()
@@ -476,7 +482,7 @@ impl Command for UpdateCommand {
)
.set_temporary_constraints(temporary_constraints)
.set_audit_config(
- self.create_audit_config(&mut *composer.get_config().borrow_mut(), input.clone())?,
+ self.create_audit_config(&mut composer.get_config().borrow_mut(), input.clone())?,
)
.set_minimal_update(minimal_changes);
@@ -587,7 +593,7 @@ impl UpdateCommand {
composer_ref.get_package().get_dev_requires(),
);
- let filter: Option<String> = if packages.len() > 0 {
+ let filter: Option<String> = if !packages.is_empty() {
Some(base_package::package_names_to_regexp(&packages, "%s"))
} else {
None
@@ -615,10 +621,10 @@ impl UpdateCommand {
};
let mut version_selector = self.create_version_selector(composer)?;
for package in &installed_packages {
- if let Some(filter) = &filter {
- if !Preg::is_match(filter, &package.get_name()) {
- continue;
- }
+ if let Some(filter) = &filter
+ && !Preg::is_match(filter, &package.get_name())
+ {
+ continue;
}
let current_version = package.get_pretty_version();
let constraint = requires
@@ -642,20 +648,20 @@ impl UpdateCommand {
PhpMixed::Bool(true),
)?;
let _ = &platform_req_filter;
- if let Some(latest) = latest_version {
- if package.get_version() != latest.get_version() || latest.is_dev() {
- autocompleter_values.insert(
- package.get_name(),
- format!(
- "<comment>{}</comment> => <comment>{}</comment>",
- current_version,
- latest.get_pretty_version(),
- ),
- );
- }
+ if let Some(latest) = latest_version
+ && (package.get_version() != latest.get_version() || latest.is_dev())
+ {
+ autocompleter_values.insert(
+ package.get_name(),
+ format!(
+ "<comment>{}</comment> => <comment>{}</comment>",
+ current_version,
+ latest.get_pretty_version(),
+ ),
+ );
}
}
- if 0 == installed_packages.len() {
+ if installed_packages.is_empty() {
for (req, _constraint) in &requires {
if PlatformRepository::is_platform_package(req) {
continue;
@@ -664,7 +670,7 @@ impl UpdateCommand {
}
}
- if 0 == autocompleter_values.len() {
+ if autocompleter_values.is_empty() {
return Err(RuntimeException {
message: "Could not find any package with new versions available".to_string(),
code: 0,
diff --git a/crates/shirabe/src/command/validate_command.rs b/crates/shirabe/src/command/validate_command.rs
index 5fc8f3d..a32a10c 100644
--- a/crates/shirabe/src/command/validate_command.rs
+++ b/crates/shirabe/src/command/validate_command.rs
@@ -32,6 +32,12 @@ pub struct ValidateCommand {
base_command_data: BaseCommandData,
}
+impl Default for ValidateCommand {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl ValidateCommand {
pub fn new() -> Self {
let mut command = ValidateCommand {
@@ -325,6 +331,7 @@ impl BaseCommand for ValidateCommand {
}
impl ValidateCommand {
+ #[allow(clippy::too_many_arguments, reason = "to keep PHP signature")]
fn output_result(
&self,
io: std::rc::Rc<std::cell::RefCell<dyn IOInterface>>,
@@ -387,16 +394,16 @@ impl ValidateCommand {
if !publish_errors.is_empty() && check_publish {
*publish_errors = publish_errors.iter().map(|e| format!("- {}", e)).collect();
publish_errors.insert(0, "# Publish errors".to_string());
- errors.extend(publish_errors.drain(..));
+ errors.append(publish_errors);
}
if !lock_errors.is_empty() {
if check_lock {
lock_errors.insert(0, "# Lock file errors".to_string());
- errors.extend(lock_errors.drain(..));
+ errors.append(lock_errors);
} else {
lock_errors.insert(0, "# Lock file warnings".to_string());
- extra_warnings.extend(lock_errors.drain(..));
+ extra_warnings.append(lock_errors);
}
}