From 9ba99a7bebc2ed0ccf572a1ae331b549f68eee88 Mon Sep 17 00:00:00 2001 From: Young-Flash Date: Thu, 28 Nov 2024 15:38:25 +0800 Subject: [PATCH] internal: use safe get_package --- crates/moon/src/cli/build.rs | 12 ++++++++++-- crates/mooncake/src/pkg/install.rs | 25 +++++++++++++++---------- crates/moonutil/src/module.rs | 8 ++++++-- 3 files changed, 31 insertions(+), 14 deletions(-) diff --git a/crates/moon/src/cli/build.rs b/crates/moon/src/cli/build.rs index 576a5571..9d52aedf 100644 --- a/crates/moon/src/cli/build.rs +++ b/crates/moon/src/cli/build.rs @@ -170,8 +170,16 @@ fn run_build_internal( )?; if let Some(bin_alias) = cmd.bin_alias.clone() { - let pkg = module.get_package_by_name_mut(cmd.package.as_ref().unwrap()); - pkg.bin_name = Some(bin_alias); + let pkg = module.get_package_by_name_mut_safe(cmd.package.as_ref().unwrap()); + match pkg { + Some(pkg) => { + pkg.bin_name = Some(bin_alias); + } + _ => anyhow::bail!(format!( + "package `{}` not found", + cmd.package.as_ref().unwrap() + )), + } } moonutil::common::set_native_backend_link_flags( diff --git a/crates/mooncake/src/pkg/install.rs b/crates/mooncake/src/pkg/install.rs index ab033db9..67757561 100644 --- a/crates/mooncake/src/pkg/install.rs +++ b/crates/mooncake/src/pkg/install.rs @@ -96,16 +96,21 @@ pub(crate) fn install_impl( let full_pkg_name = format!("{bin_mod_to_install}/{pkg_name}"); - let pkg = module_db.get_package_by_name(&full_pkg_name); - build_and_install_bin_package( - &moon_path, - &bin_mod_path, - &full_pkg_name, - &install_path, - pkg.bin_target.to_backend_ext(), - bin_alias, - verbose, - )?; + let pkg = module_db.get_package_by_name_safe(&full_pkg_name); + match pkg { + Some(pkg) => { + build_and_install_bin_package( + &moon_path, + &bin_mod_path, + &full_pkg_name, + &install_path, + pkg.bin_target.to_backend_ext(), + bin_alias, + verbose, + )?; + } + _ => anyhow::bail!(format!("package `{}` not found", full_pkg_name)), + } } } else { for (full_pkg_name, pkg) in module_db diff --git a/crates/moonutil/src/module.rs b/crates/moonutil/src/module.rs index 5132e8fa..b986c8e1 100644 --- a/crates/moonutil/src/module.rs +++ b/crates/moonutil/src/module.rs @@ -83,8 +83,12 @@ impl ModuleDB { self.packages.get(name).unwrap() } - pub fn get_package_by_name_mut(&mut self, name: &str) -> &mut Package { - self.packages.get_mut(name).unwrap() + pub fn get_package_by_name_safe(&self, name: &str) -> Option<&Package> { + self.packages.get(name) + } + + pub fn get_package_by_name_mut_safe(&mut self, name: &str) -> Option<&mut Package> { + self.packages.get_mut(name) } pub fn get_package_by_path(&self, path: &Path) -> Option<&Package> {