use crate::command::{CommandExecutor, DockerCommand};
use crate::error::Result;
use async_trait::async_trait;
use serde::Deserialize;
use std::collections::HashMap;
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct ContainerPruneResult {
#[serde(default)]
pub containers_deleted: Vec<String>,
#[serde(default)]
pub space_reclaimed: u64,
}
#[derive(Debug, Clone)]
pub struct ContainerPruneCommand {
force: bool,
filter: HashMap<String, String>,
pub executor: CommandExecutor,
}
impl ContainerPruneCommand {
#[must_use]
pub fn new() -> Self {
Self {
force: false,
filter: HashMap::new(),
executor: CommandExecutor::new(),
}
}
#[must_use]
pub fn force(mut self) -> Self {
self.force = true;
self
}
#[must_use]
pub fn filter(mut self, key: &str, value: &str) -> Self {
self.filter.insert(key.to_string(), value.to_string());
self
}
#[must_use]
pub fn until(mut self, duration: &str) -> Self {
self.filter
.insert("until".to_string(), duration.to_string());
self
}
#[must_use]
pub fn with_label(mut self, key: &str, value: Option<&str>) -> Self {
let label_filter = if let Some(val) = value {
format!("{key}={val}")
} else {
key.to_string()
};
self.filter.insert("label".to_string(), label_filter);
self
}
pub async fn run(&self) -> Result<ContainerPruneResult> {
self.execute().await
}
}
impl Default for ContainerPruneCommand {
fn default() -> Self {
Self::new()
}
}
#[async_trait]
impl DockerCommand for ContainerPruneCommand {
type Output = ContainerPruneResult;
fn build_command_args(&self) -> Vec<String> {
let mut args = vec!["container".to_string(), "prune".to_string()];
if self.force {
args.push("--force".to_string());
}
for (key, value) in &self.filter {
args.push("--filter".to_string());
if key == "label" {
args.push(value.clone());
} else {
args.push(format!("{key}={value}"));
}
}
args.extend(self.executor.raw_args.clone());
args
}
fn get_executor(&self) -> &CommandExecutor {
&self.executor
}
fn get_executor_mut(&mut self) -> &mut CommandExecutor {
&mut self.executor
}
async fn execute(&self) -> Result<Self::Output> {
let args = self.build_command_args();
let command_name = args[0].clone();
let command_args = args[1..].to_vec();
let output = self
.executor
.execute_command(&command_name, command_args)
.await?;
let stdout = &output.stdout;
let mut result = ContainerPruneResult {
containers_deleted: Vec::new(),
space_reclaimed: 0,
};
for line in stdout.lines() {
if line.starts_with("Deleted Containers:") {
continue;
}
if line.starts_with("Total reclaimed space:") {
if let Some(space_str) = line.split(':').nth(1) {
result.space_reclaimed = parse_size(space_str.trim());
}
} else if !line.is_empty() && !line.contains("will be removed") {
let id = line.trim();
if id.len() == 12 || id.len() == 64 {
result.containers_deleted.push(id.to_string());
}
}
}
Ok(result)
}
}
#[allow(clippy::cast_possible_truncation)]
#[allow(clippy::cast_sign_loss)]
#[allow(clippy::cast_precision_loss)]
fn parse_size(size_str: &str) -> u64 {
let size_str = size_str.trim();
let mut numeric_part = String::new();
let mut unit_part = String::new();
let mut found_dot = false;
for ch in size_str.chars() {
if ch.is_ascii_digit() || (ch == '.' && !found_dot) {
numeric_part.push(ch);
if ch == '.' {
found_dot = true;
}
} else if ch.is_ascii_alphabetic() {
unit_part.push(ch);
}
}
let value: f64 = numeric_part.parse().unwrap_or(0.0);
let multiplier = match unit_part.to_uppercase().as_str() {
"KB" | "K" => 1_024,
"MB" | "M" => 1_024 * 1_024,
"GB" | "G" => 1_024 * 1_024 * 1_024,
"TB" | "T" => 1_024_u64.pow(4),
_ => 1, };
(value * multiplier as f64) as u64
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_container_prune_builder() {
let cmd = ContainerPruneCommand::new()
.force()
.until("24h")
.with_label("temp", Some("true"));
let args = cmd.build_command_args();
assert_eq!(args[0], "container");
assert!(args.contains(&"prune".to_string()));
assert!(args.contains(&"--force".to_string()));
assert!(args.contains(&"--filter".to_string()));
}
}