1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
//! Docker rmi command implementation.
//!
//! This module provides the `docker rmi` command for removing Docker images.
use super::{CommandExecutor, CommandOutput, DockerCommand};
use crate::error::Result;
use async_trait::async_trait;
/// Docker rmi command builder
///
/// Remove one or more images.
///
/// # Example
///
/// ```no_run
/// use docker_wrapper::RmiCommand;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// // Remove a single image
/// RmiCommand::new("old-image:v1.0")
/// .run()
/// .await?;
///
/// // Force remove multiple images
/// RmiCommand::new_multiple(vec!["image1", "image2", "image3"])
/// .force()
/// .run()
/// .await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct RmiCommand {
/// Image names or IDs to remove
images: Vec<String>,
/// Force removal of images
force: bool,
/// Do not delete untagged parents
no_prune: bool,
/// Command executor
pub executor: CommandExecutor,
}
impl RmiCommand {
/// Create a new rmi command for a single image
///
/// # Example
///
/// ```
/// use docker_wrapper::RmiCommand;
///
/// let cmd = RmiCommand::new("old-image:latest");
/// ```
#[must_use]
pub fn new(image: impl Into<String>) -> Self {
Self {
images: vec![image.into()],
force: false,
no_prune: false,
executor: CommandExecutor::new(),
}
}
/// Create a new rmi command for multiple images
///
/// # Example
///
/// ```
/// use docker_wrapper::RmiCommand;
///
/// let cmd = RmiCommand::new_multiple(vec!["image1:latest", "image2:v1.0"]);
/// ```
#[must_use]
pub fn new_multiple(images: Vec<impl Into<String>>) -> Self {
Self {
images: images.into_iter().map(Into::into).collect(),
force: false,
no_prune: false,
executor: CommandExecutor::new(),
}
}
/// Add another image to remove
#[must_use]
pub fn image(mut self, image: impl Into<String>) -> Self {
self.images.push(image.into());
self
}
/// Force removal of the images
///
/// # Example
///
/// ```
/// use docker_wrapper::RmiCommand;
///
/// let cmd = RmiCommand::new("stubborn-image:latest")
/// .force();
/// ```
#[must_use]
pub fn force(mut self) -> Self {
self.force = true;
self
}
/// Do not delete untagged parents
#[must_use]
pub fn no_prune(mut self) -> Self {
self.no_prune = true;
self
}
/// Execute the rmi command
///
/// # Errors
/// Returns an error if:
/// - The Docker daemon is not running
/// - Any of the specified images don't exist
/// - Images are in use by containers (unless force is used)
///
/// # Example
///
/// ```no_run
/// use docker_wrapper::RmiCommand;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let result = RmiCommand::new("unused-image:latest")
/// .run()
/// .await?;
///
/// if result.success() {
/// println!("Removed {} images", result.removed_images().len());
/// }
/// # Ok(())
/// # }
/// ```
pub async fn run(&self) -> Result<RmiResult> {
let output = self.execute().await?;
// Parse removed images from output
let removed_images = Self::parse_removed_images(&output.stdout);
Ok(RmiResult {
output,
removed_images,
})
}
/// Parse removed image IDs from the command output
fn parse_removed_images(stdout: &str) -> Vec<String> {
let mut removed = Vec::new();
for line in stdout.lines() {
let line = line.trim();
if line.starts_with("Deleted:") {
if let Some(id) = line.strip_prefix("Deleted:") {
removed.push(id.trim().to_string());
}
} else if line.starts_with("Untagged:") {
if let Some(tag) = line.strip_prefix("Untagged:") {
removed.push(tag.trim().to_string());
}
}
}
removed
}
}
#[async_trait]
impl DockerCommand for RmiCommand {
type Output = CommandOutput;
fn build_command_args(&self) -> Vec<String> {
let mut args = vec!["rmi".to_string()];
if self.force {
args.push("--force".to_string());
}
if self.no_prune {
args.push("--no-prune".to_string());
}
// Add image names/IDs
args.extend(self.images.clone());
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> {
if self.images.is_empty() {
return Err(crate::error::Error::invalid_config(
"No images specified for removal",
));
}
let args = self.build_command_args();
let command_name = args[0].clone();
let command_args = args[1..].to_vec();
self.executor
.execute_command(&command_name, command_args)
.await
}
}
/// Result from the rmi command
#[derive(Debug, Clone)]
pub struct RmiResult {
/// Raw command output
pub output: CommandOutput,
/// List of removed image IDs/tags
pub removed_images: Vec<String>,
}
impl RmiResult {
/// Check if the removal was successful
#[must_use]
pub fn success(&self) -> bool {
self.output.success
}
/// Get the list of removed images
#[must_use]
pub fn removed_images(&self) -> &[String] {
&self.removed_images
}
/// Get the count of removed images
#[must_use]
pub fn removed_count(&self) -> usize {
self.removed_images.len()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_rmi_single_image() {
let cmd = RmiCommand::new("test-image:latest");
let args = cmd.build_command_args();
assert_eq!(args, vec!["rmi", "test-image:latest"]);
}
#[test]
fn test_rmi_multiple_images() {
let cmd = RmiCommand::new_multiple(vec!["image1:latest", "image2:v1.0", "image3"]);
let args = cmd.build_command_args();
assert_eq!(args, vec!["rmi", "image1:latest", "image2:v1.0", "image3"]);
}
#[test]
fn test_rmi_with_force() {
let cmd = RmiCommand::new("stubborn-image:latest").force();
let args = cmd.build_command_args();
assert_eq!(args, vec!["rmi", "--force", "stubborn-image:latest"]);
}
#[test]
fn test_rmi_with_no_prune() {
let cmd = RmiCommand::new("test-image:latest").no_prune();
let args = cmd.build_command_args();
assert_eq!(args, vec!["rmi", "--no-prune", "test-image:latest"]);
}
#[test]
fn test_rmi_all_options() {
let cmd = RmiCommand::new("test-image:latest")
.image("another-image:v1.0")
.force()
.no_prune();
let args = cmd.build_command_args();
assert_eq!(
args,
vec![
"rmi",
"--force",
"--no-prune",
"test-image:latest",
"another-image:v1.0"
]
);
}
#[test]
fn test_parse_removed_images() {
let output =
"Untagged: test-image:latest\nDeleted: sha256:abc123def456\nDeleted: sha256:789xyz123";
let removed = RmiCommand::parse_removed_images(output);
assert_eq!(
removed,
vec![
"test-image:latest",
"sha256:abc123def456",
"sha256:789xyz123"
]
);
}
#[test]
fn test_parse_removed_images_empty() {
let removed = RmiCommand::parse_removed_images("");
assert!(removed.is_empty());
}
}