Skip to content

Commit

Permalink
feat(subcmd/clean): add --keep-downloadable and `--keep-downloadabl…
Browse files Browse the repository at this point in the history
…e-and-installed` arguments
  • Loading branch information
eatradish committed Feb 15, 2025
1 parent a6794c0 commit a853944
Showing 1 changed file with 65 additions and 4 deletions.
69 changes: 65 additions & 4 deletions src/subcommand/clean.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
use std::fs::remove_dir_all;
use std::path::PathBuf;

use crate::subcommand::utils::create_progress_spinner;
use crate::success;
use crate::{config::Config, fl};
use clap::Args;
use oma_pm::apt::{AptConfig, OmaApt, OmaAptArgs};
use tracing::info;
use tracing::{debug, info};

use crate::{error::OutputError, utils::root};

use crate::args::CliExecuter;

#[derive(Debug, Args)]
pub struct Clean {
/// Keep downloadable packages
#[arg(long, conflicts_with = "keep_downloadable_and_installed")]
keep_downloadable: bool,
/// Keep downloadable and installed packages
#[arg(long, conflicts_with = "keep_downloadable")]
keep_downloadable_and_installed: bool,
/// Set sysroot target directory
#[arg(from_global)]
sysroot: PathBuf,
Expand All @@ -30,6 +37,8 @@ impl CliExecuter for Clean {
sysroot,
apt_options,
dry_run,
keep_downloadable,
keep_downloadable_and_installed,
} = self;

if dry_run {
Expand All @@ -54,9 +63,57 @@ impl CliExecuter for Clean {

let pb = create_progress_spinner(no_progress, fl!("cleaning"));

for i in dir.flatten() {
if i.path().extension().and_then(|x| x.to_str()) == Some("deb") {
std::fs::remove_file(i.path()).ok();
let partial = download_dir.join("partial");

remove_dir_all(download_dir.join("partial")).map_err(|e| OutputError {
description: format!("Failed to read dir: {}", partial.display()),
source: Some(Box::new(e)),
})?;

for i in dir
.flatten()
.filter(|x| x.path().extension().is_some_and(|name| name == "deb"))
{
if !keep_downloadable && !keep_downloadable_and_installed {
remove_deb(&i);
}

let file_name = i.file_name();
let file_name = file_name.to_string_lossy();
let mut file_name = file_name.splitn(3, '_');

let Some((pkg, version)) = Some(()).and_then(|_| {
let package = file_name.next()?;
let version = file_name.next()?;

Some((package, version))
}) else {
debug!(
"Failed to get package name: {}, will delete this file",
i.path().display()
);
remove_deb(&i);
continue;
};

let version = version.replace("%3a", ":");

let Some(version) = apt.cache.get(pkg).and_then(|pkg| pkg.get_version(&version)) else {
remove_deb(&i);
continue;
};

if !version.is_installed()
&& !version.is_downloadable()
&& keep_downloadable_and_installed
{
remove_deb(&i);
continue;
}

if !version.is_downloadable() && keep_downloadable {
remove_deb(&i);
continue;
}
}

Expand All @@ -69,3 +126,7 @@ impl CliExecuter for Clean {
Ok(0)
}
}

fn remove_deb(i: &std::fs::DirEntry) {
std::fs::remove_file(i.path()).ok();
}

0 comments on commit a853944

Please sign in to comment.