Skip to content

Commit a7c9268

Browse files
committed
refactor: further cleanup code
1 parent c601007 commit a7c9268

12 files changed

Lines changed: 457 additions & 521 deletions

File tree

src/cleanup_modules/device_cleanup.rs

Lines changed: 28 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,20 @@
11
use async_trait::async_trait;
22
use error_stack::{IntoReport, Result, ResultExt};
3+
use regex::Regex;
34
use serde::Deserialize;
45
use uuid::Uuid;
5-
use windows::{
6-
core::HSTRING,
7-
Win32::{Devices::DeviceAndDriverInstallation::*, Foundation::BOOL},
8-
};
9-
10-
use super::{
11-
get_path_to_dump, Dumper, IntoModuleReport, IntoUninstallReport, ModuleError, ModuleMetadata,
12-
ModuleRunInfo, ModuleStrategy, ToUninstall, UninstallError,
13-
};
14-
use crate::{
15-
cleanup_modules::create_dump_file,
16-
services::{
17-
self, identifiers, regex_cache,
18-
windows::{enumerate_devices, inf_regex, Device},
19-
},
20-
State,
21-
};
6+
use windows::core::HSTRING;
7+
use windows::Win32::Devices::DeviceAndDriverInstallation::*;
8+
use windows::Win32::Foundation::BOOL;
9+
10+
use super::*;
11+
12+
use crate::cleanup_modules::create_dump_file;
13+
use crate::services;
14+
use crate::services::identifiers;
15+
use crate::services::regex_cache;
16+
use crate::services::windows::{enumerate_devices, Device};
17+
use crate::State;
2218

2319
const DEVICE_MODULE_NAME: &str = "Device Cleanup";
2420
const DEVICE_MODULE_CLI: &str = "device-cleanup";
@@ -152,7 +148,7 @@ struct DeviceDumper {}
152148
#[async_trait]
153149
impl Dumper for DeviceDumper {
154150
async fn dump(&self, state: &State) -> Result<(), ModuleError> {
155-
let inf_regex = inf_regex();
151+
let inf_regex = Regex::new(r"^oem[0-9]+\.inf$").unwrap();
156152
let devices: Vec<Device> = enumerate_devices()
157153
.into_module_report(DEVICE_MODULE_NAME)?
158154
.into_iter()
@@ -184,20 +180,6 @@ impl Dumper for DeviceDumper {
184180
}
185181
}
186182

187-
fn is_of_interest(device: &Device) -> bool {
188-
use crate::services::interest::is_of_interest_iter as candidate_iter;
189-
let strings = [
190-
device.description(),
191-
device.manufacturer(),
192-
device.inf_original_name(),
193-
]
194-
.into_iter()
195-
.flatten()
196-
.chain(device.hardware_ids().iter().map(|s| s.as_str()));
197-
198-
candidate_iter(strings)
199-
}
200-
201183
#[derive(Deserialize, Debug)]
202184
#[serde(deny_unknown_fields)]
203185
pub struct DeviceToUninstall {
@@ -228,3 +210,17 @@ impl std::fmt::Display for DeviceToUninstall {
228210
write!(f, "{}", self.friendly_name)
229211
}
230212
}
213+
214+
fn is_of_interest(device: &Device) -> bool {
215+
use crate::services::interest::is_of_interest_iter as candidate_iter;
216+
let strings = [
217+
device.description(),
218+
device.manufacturer(),
219+
device.inf_original_name(),
220+
]
221+
.into_iter()
222+
.flatten()
223+
.chain(device.hardware_ids().iter().map(|s| s.as_str()));
224+
225+
candidate_iter(strings)
226+
}

src/cleanup_modules/driver_cleanup.rs

Lines changed: 19 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -4,23 +4,18 @@ use async_trait::async_trait;
44
use error_stack::{IntoReport, Result, ResultExt};
55
use serde::Deserialize;
66
use uuid::Uuid;
7-
use windows::{
8-
core::HSTRING,
9-
Win32::{Devices::DeviceAndDriverInstallation::DiUninstallDriverW, Foundation::BOOL},
10-
};
11-
12-
use super::{
13-
Dumper, IntoModuleReport, IntoUninstallReport, ModuleError, ModuleMetadata, ModuleRunInfo,
14-
ModuleStrategy, ToUninstall, UninstallError,
15-
};
16-
use crate::{
17-
cleanup_modules::{create_dump_file, get_path_to_dump},
18-
services::{
19-
self, identifiers, regex_cache,
20-
windows::{enumerate_drivers, Driver},
21-
},
22-
State,
23-
};
7+
use windows::core::HSTRING;
8+
use windows::Win32::Devices::DeviceAndDriverInstallation::DiUninstallDriverW;
9+
use windows::Win32::Foundation::BOOL;
10+
11+
use super::*;
12+
13+
use crate::cleanup_modules::{create_dump_file, get_path_to_dump};
14+
use crate::services;
15+
use crate::services::identifiers;
16+
use crate::services::regex_cache;
17+
use crate::services::windows::{enumerate_drivers, Driver};
18+
use crate::State;
2419

2520
const DRIVER_MODULE_NAME: &str = "Driver Cleanup";
2621
const DRIVER_MODULE_CLI: &str = "driver-cleanup";
@@ -159,13 +154,6 @@ impl Dumper for DriverDumper {
159154
}
160155
}
161156

162-
fn is_of_interest(driver: &Driver) -> bool {
163-
use crate::services::interest::is_of_interest_iter as candidate_iter;
164-
let strings = [driver.inf_original_name(), driver.provider()];
165-
166-
candidate_iter(strings.into_iter().flatten())
167-
}
168-
169157
#[derive(Deserialize, Debug)]
170158
#[serde(deny_unknown_fields)]
171159
pub struct DriverToUninstall {
@@ -191,3 +179,10 @@ impl std::fmt::Display for DriverToUninstall {
191179
write!(f, "{}", self.friendly_name)
192180
}
193181
}
182+
183+
fn is_of_interest(driver: &Driver) -> bool {
184+
use crate::services::interest::is_of_interest_iter as candidate_iter;
185+
186+
let strings = [driver.inf_original_name(), driver.provider()];
187+
candidate_iter(strings.into_iter().flatten())
188+
}

src/cleanup_modules/driver_package_cleanup.rs

Lines changed: 76 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,39 @@
11
use core::result::Result as CResult;
2-
use std::{
3-
future::Future,
4-
io::{ErrorKind, Write},
5-
path::Path,
6-
process::{Child, ExitStatus},
7-
};
2+
use std::future::Future;
3+
use std::io::{ErrorKind, Write};
4+
use std::path::Path;
5+
use std::process::{Child, ExitStatus};
86

97
use async_trait::async_trait;
108
use error_stack::{bail, IntoReport, Result, ResultExt};
119
use lazy_static::lazy_static;
1210
use regex::Regex;
1311
use serde::Deserialize;
1412
use tokio_util::sync::CancellationToken;
15-
use winreg::{enums::HKEY_LOCAL_MACHINE, RegKey};
13+
use winreg::enums::HKEY_LOCAL_MACHINE;
14+
use winreg::RegKey;
1615
use wmi::{COMLibrary, WMIConnection, WMIError};
1716

18-
use super::{
19-
create_dump_file, Dumper, IntoModuleReport, IntoUninstallReport, ModuleError, ModuleMetadata,
20-
ModuleRunInfo, ModuleStrategy, ToUninstall, UninstallError,
21-
};
22-
use crate::{
23-
cleanup_modules::get_path_to_dump,
24-
services::{
25-
self, identifiers, regex_cache, terminal,
26-
windows::{enumerate_driver_packages, DriverPackage},
27-
},
28-
State,
29-
};
17+
use super::*;
18+
19+
use crate::services;
20+
use crate::services::identifiers;
21+
use crate::services::regex_cache;
22+
use crate::services::terminal;
23+
use crate::services::windows::{enumerate_driver_packages, DriverPackage};
24+
use crate::State;
3025

3126
const MODULE_NAME: &str = "Driver Package Cleanup";
3227
const MODULE_CLI: &str = "driver-package-cleanup";
3328
const IDENTIFIER: &str = "driver_package_identifiers.json";
3429

30+
#[derive(Deserialize, Debug)]
31+
enum UninstallMethod {
32+
Normal,
33+
Deferred,
34+
RegistryOnly,
35+
}
36+
3537
#[derive(Default)]
3638
pub struct DriverPackageCleanupModule {
3739
objects_to_uninstall: Vec<DriverPackageToUninstall>,
@@ -68,7 +70,6 @@ impl ModuleStrategy for DriverPackageCleanupModule {
6870
type ToUninstall = DriverPackageToUninstall;
6971

7072
async fn initialize(&mut self, state: &State) -> Result<(), ModuleError> {
71-
let _name = self.name().to_string();
7273
let resource = identifiers::get_resource(IDENTIFIER, state)
7374
.await
7475
.into_module_report(MODULE_NAME)?;
@@ -119,26 +120,28 @@ impl ModuleStrategy for DriverPackageCleanupModule {
119120
}
120121
}
121122

122-
fn uninstall_registry_only(
123-
object: DriverPackage,
124-
to_uninstall: &DriverPackageToUninstall,
125-
) -> Result<(), UninstallError> {
126-
let key_path = Path::new(object.key_name());
127-
let key_parent = key_path.parent().unwrap();
128-
let key_name = key_path.file_name().unwrap();
129-
let flags = winreg::enums::KEY_WRITE;
123+
#[derive(Deserialize, Debug)]
124+
#[serde(deny_unknown_fields)]
125+
pub struct DriverPackageToUninstall {
126+
friendly_name: String,
127+
display_name: Option<String>,
128+
display_version: Option<String>,
129+
publisher: Option<String>,
130+
uninstall_method: UninstallMethod,
131+
}
130132

131-
let uninstall_key = RegKey::predef(HKEY_LOCAL_MACHINE)
132-
.open_subkey_with_flags(key_parent, flags)
133-
.into_report()
134-
.attach_printable_lazy(|| key_parent.to_string_lossy().to_string())
135-
.into_uninstall_report(to_uninstall)?;
133+
impl ToUninstall<DriverPackage> for DriverPackageToUninstall {
134+
fn matches(&self, other: &DriverPackage) -> bool {
135+
regex_cache::cached_match(other.display_name(), self.display_name.as_deref())
136+
&& regex_cache::cached_match(other.display_version(), self.display_version.as_deref())
137+
&& regex_cache::cached_match(other.publisher(), self.publisher.as_deref())
138+
}
139+
}
136140

137-
uninstall_key
138-
.delete_subkey_all(key_name)
139-
.into_report()
140-
.attach_printable_lazy(|| key_path.to_string_lossy().to_string())
141-
.into_uninstall_report(to_uninstall)
141+
impl std::fmt::Display for DriverPackageToUninstall {
142+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
143+
write!(f, "{}", self.friendly_name)
144+
}
142145
}
143146

144147
#[derive(Default)]
@@ -179,6 +182,22 @@ impl Dumper for DriverPackageDumper {
179182
}
180183
}
181184

185+
#[derive(Deserialize, Debug)]
186+
#[serde(rename = "Win32_Process")]
187+
#[serde(rename_all = "PascalCase")]
188+
struct ProcessInfo {
189+
process_id: u32,
190+
parent_process_id: u32,
191+
command_line: Option<String>,
192+
}
193+
194+
impl ProcessInfo {
195+
fn query() -> CResult<Vec<Self>, WMIError> {
196+
let wmi_con = WMIConnection::new(COMLibrary::new()?)?;
197+
wmi_con.query()
198+
}
199+
}
200+
182201
fn is_of_interest(driver_package: &DriverPackage) -> bool {
183202
use crate::services::interest::is_of_interest_iter as candidate_iter;
184203
driver_package.display_name().is_some()
@@ -287,7 +306,7 @@ async fn uninstall_deferred(
287306

288307
tokio::time::sleep(std::time::Duration::from_secs_f32(0.5)).await;
289308

290-
let processes = get_process_infos().unwrap();
309+
let processes = ProcessInfo::query().unwrap();
291310
let process_delegate = processes
292311
.iter()
293312
.filter(|p| p.parent_process_id == id)
@@ -353,49 +372,26 @@ async fn wait_for_process_async(child: Child) -> CResult<ExitStatus, std::io::Er
353372
.unwrap()
354373
}
355374

356-
#[derive(Deserialize, Debug)]
357-
enum UninstallMethod {
358-
Normal,
359-
Deferred,
360-
RegistryOnly,
361-
}
362-
363-
#[derive(Deserialize, Debug)]
364-
#[serde(deny_unknown_fields)]
365-
pub struct DriverPackageToUninstall {
366-
friendly_name: String,
367-
display_name: Option<String>,
368-
display_version: Option<String>,
369-
publisher: Option<String>,
370-
uninstall_method: UninstallMethod,
371-
}
372-
373-
impl ToUninstall<DriverPackage> for DriverPackageToUninstall {
374-
fn matches(&self, other: &DriverPackage) -> bool {
375-
regex_cache::cached_match(other.display_name(), self.display_name.as_deref())
376-
&& regex_cache::cached_match(other.display_version(), self.display_version.as_deref())
377-
&& regex_cache::cached_match(other.publisher(), self.publisher.as_deref())
378-
}
379-
}
380-
381-
impl std::fmt::Display for DriverPackageToUninstall {
382-
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
383-
write!(f, "{}", self.friendly_name)
384-
}
385-
}
375+
fn uninstall_registry_only(
376+
object: DriverPackage,
377+
to_uninstall: &DriverPackageToUninstall,
378+
) -> Result<(), UninstallError> {
379+
let key_path = Path::new(object.key_name());
380+
let key_parent = key_path.parent().unwrap();
381+
let key_name = key_path.file_name().unwrap();
382+
let flags = winreg::enums::KEY_WRITE;
386383

387-
#[derive(Deserialize, Debug)]
388-
#[serde(rename = "Win32_Process")]
389-
#[serde(rename_all = "PascalCase")]
390-
struct ProcessInfo {
391-
process_id: u32,
392-
parent_process_id: u32,
393-
command_line: Option<String>,
394-
}
384+
let uninstall_key = RegKey::predef(HKEY_LOCAL_MACHINE)
385+
.open_subkey_with_flags(key_parent, flags)
386+
.into_report()
387+
.attach_printable_lazy(|| key_parent.to_string_lossy().to_string())
388+
.into_uninstall_report(to_uninstall)?;
395389

396-
fn get_process_infos() -> CResult<Vec<ProcessInfo>, WMIError> {
397-
let wmi_con = WMIConnection::new(COMLibrary::new()?)?;
398-
wmi_con.query()
390+
uninstall_key
391+
.delete_subkey_all(key_name)
392+
.into_report()
393+
.attach_printable_lazy(|| key_path.to_string_lossy().to_string())
394+
.into_uninstall_report(to_uninstall)
399395
}
400396

401397
fn to_command(command: &str) -> std::process::Command {

src/cleanup_modules/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ pub trait Module {
2929
}
3030

3131
#[derive(Debug, Error)]
32-
#[error("module '{name}' has encountered issues while running")]
32+
#[error("{name} has encountered issues while running")]
3333
pub struct ModuleError {
3434
name: &'static str,
3535
}

0 commit comments

Comments
 (0)