Delete from registry. # Returns Nothing on success. # Errors `RegistryError` - The error that occurred.
(&self)
| 259 | /// |
| 260 | /// * `RegistryError` - The error that occurred. |
| 261 | pub fn remove(&self) -> Result<Option<Registry>, RegistryError> { |
| 262 | // For deleting a value, we need SetValue permission (KEY_SET_VALUE). |
| 263 | // Try to open with the minimal required permission. |
| 264 | // If that fails due to permission, try with AllAccess as a fallback. |
| 265 | let (reg_key, _subkey) = match self.open(Security::SetValue) { |
| 266 | Ok(reg_key) => reg_key, |
| 267 | // handle NotFound error |
| 268 | Err(RegistryError::RegistryKeyNotFound(_)) => { |
| 269 | eprintln!("{}", t!("registry_helper.removeErrorKeyNotExist")); |
| 270 | return Ok(None); |
| 271 | }, |
| 272 | Err(RegistryError::RegistryKey(key::Error::PermissionDenied(_, _))) => { |
| 273 | match self.open(Security::AllAccess) { |
| 274 | Ok(reg_key) => reg_key, |
| 275 | Err(e) => return self.handle_error_or_what_if(e), |
| 276 | } |
| 277 | }, |
| 278 | Err(e) => return self.handle_error_or_what_if(e), |
| 279 | }; |
| 280 | |
| 281 | // Accumulate what-if metadata like set() |
| 282 | let mut what_if_metadata: Vec<String> = Vec::new(); |
| 283 | |
| 284 | if let Some(value_name) = &self.config.value_name { |
| 285 | if self.what_if { |
| 286 | what_if_metadata.push(t!("registry_helper.whatIfDeleteValue", value_name = value_name).to_string()); |
| 287 | return Ok(Some(Registry { |
| 288 | key_path: self.config.key_path.clone(), |
| 289 | value_name: Some(value_name.clone()), |
| 290 | metadata: Some(Metadata { what_if: Some(what_if_metadata) }), |
| 291 | ..Default::default() |
| 292 | })); |
| 293 | } |
| 294 | match reg_key.delete_value(value_name) { |
| 295 | Ok(()) | Err(value::Error::NotFound(_, _)) => { |
| 296 | // if the value doesn't exist, we don't need to do anything |
| 297 | }, |
| 298 | Err(e) => return self.handle_error_or_what_if(RegistryError::RegistryValue(e)), |
| 299 | } |
| 300 | } else { |
| 301 | // to delete the key, we need to open the parent key with CreateSubKey permission |
| 302 | // which includes the ability to delete subkeys |
| 303 | let parent_path = get_parent_key_path(&self.config.key_path); |
| 304 | let (hive, parent_subkey) = get_hive_from_path(parent_path)?; |
| 305 | let parent_reg_key = match hive.open(parent_subkey, Security::CreateSubKey) { |
| 306 | Ok(k) => k, |
| 307 | Err(e) => return self.handle_error_or_what_if(RegistryError::RegistryKey(e)), |
| 308 | }; |
| 309 | |
| 310 | // get the subkey name |
| 311 | let subkey_name = &self.config.key_path[parent_path.len() + 1..]; |
| 312 | |
| 313 | if self.what_if { |
| 314 | what_if_metadata.push(t!("registry_helper.whatIfDeleteSubkey", subkey_name = subkey_name).to_string()); |
| 315 | return Ok(Some(Registry { |
| 316 | key_path: self.config.key_path.clone(), |
| 317 | metadata: Some(Metadata { what_if: Some(what_if_metadata) }), |
| 318 | ..Default::default() |