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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
//! Docker ps command implementation.
//!
//! This module provides a comprehensive implementation of the `docker ps` command
//! with support for all native options and an extensible architecture for any additional options.
use super::{CommandExecutor, DockerCommand};
use crate::error::Result;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
/// Docker ps command builder with fluent API
#[derive(Debug, Clone)]
#[allow(clippy::struct_excessive_bools)]
pub struct PsCommand {
/// Command executor for extensibility
pub executor: CommandExecutor,
/// Show all containers (default shows just running)
all: bool,
/// Filter output based on conditions provided
filters: Vec<String>,
/// Format output using a custom template
format: Option<String>,
/// Show n last created containers (includes all states)
last: Option<i32>,
/// Show the latest created container (includes all states)
latest: bool,
/// Don't truncate output
no_trunc: bool,
/// Only display container IDs
quiet: bool,
/// Display total file sizes
size: bool,
}
/// Container information returned by docker ps
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ContainerInfo {
/// Container ID
pub id: String,
/// Container image
pub image: String,
/// Command being run
pub command: String,
/// Creation time
pub created: String,
/// Container status
pub status: String,
/// Port mappings
pub ports: String,
/// Container names
pub names: String,
}
/// Output format for ps command
#[derive(Debug, Clone)]
pub enum PsFormat {
/// Default table format
Table,
/// JSON format
Json,
/// Custom Go template
Template(String),
/// Raw output (when using quiet mode)
Raw,
}
/// Output from docker ps command
#[derive(Debug, Clone)]
pub struct PsOutput {
/// The raw stdout from the command
pub stdout: String,
/// The raw stderr from the command
pub stderr: String,
/// Exit code from the command
pub exit_code: i32,
/// Parsed container information (when possible)
pub containers: Vec<ContainerInfo>,
}
impl PsOutput {
/// Check if the command executed successfully
#[must_use]
pub fn success(&self) -> bool {
self.exit_code == 0
}
/// Get combined output (stdout + stderr)
#[must_use]
pub fn combined_output(&self) -> String {
if self.stderr.is_empty() {
self.stdout.clone()
} else if self.stdout.is_empty() {
self.stderr.clone()
} else {
format!("{}\n{}", self.stdout, self.stderr)
}
}
/// Check if stdout is empty (ignoring whitespace)
#[must_use]
pub fn stdout_is_empty(&self) -> bool {
self.stdout.trim().is_empty()
}
/// Check if stderr is empty (ignoring whitespace)
#[must_use]
pub fn stderr_is_empty(&self) -> bool {
self.stderr.trim().is_empty()
}
/// Get container IDs only (useful when using quiet mode)
#[must_use]
pub fn container_ids(&self) -> Vec<String> {
self.stdout
.lines()
.map(|line| line.trim().to_string())
.filter(|line| !line.is_empty())
.collect()
}
/// Get number of containers found
#[must_use]
pub fn container_count(&self) -> usize {
self.containers.len()
}
}
impl PsCommand {
/// Create a new ps command
///
/// # Examples
///
/// ```
/// use docker_wrapper::PsCommand;
///
/// let ps_cmd = PsCommand::new();
/// ```
#[must_use]
pub fn new() -> Self {
Self {
executor: CommandExecutor::new(),
all: false,
filters: Vec::new(),
format: None,
last: None,
latest: false,
no_trunc: false,
quiet: false,
size: false,
}
}
/// Show all containers (default shows just running)
///
/// # Examples
///
/// ```
/// use docker_wrapper::PsCommand;
///
/// let ps_cmd = PsCommand::new().all();
/// ```
#[must_use]
pub fn all(mut self) -> Self {
self.all = true;
self
}
/// Filter output based on conditions provided
///
/// # Examples
///
/// ```
/// use docker_wrapper::PsCommand;
///
/// let ps_cmd = PsCommand::new()
/// .filter("status=running")
/// .filter("name=my-container");
/// ```
#[must_use]
pub fn filter(mut self, filter: impl Into<String>) -> Self {
self.filters.push(filter.into());
self
}
/// Add multiple filters
///
/// # Examples
///
/// ```
/// use docker_wrapper::PsCommand;
///
/// let filters = vec!["status=running".to_string(), "name=web".to_string()];
/// let ps_cmd = PsCommand::new().filters(filters);
/// ```
#[must_use]
pub fn filters(mut self, filters: Vec<String>) -> Self {
self.filters.extend(filters);
self
}
/// Format output using table format
///
/// # Examples
///
/// ```
/// use docker_wrapper::PsCommand;
///
/// let ps_cmd = PsCommand::new().format_table();
/// ```
#[must_use]
pub fn format_table(mut self) -> Self {
self.format = Some("table".to_string());
self
}
/// Format output using JSON format
///
/// # Examples
///
/// ```
/// use docker_wrapper::PsCommand;
///
/// let ps_cmd = PsCommand::new().format_json();
/// ```
#[must_use]
pub fn format_json(mut self) -> Self {
self.format = Some("json".to_string());
self
}
/// Format output using a custom Go template
///
/// # Examples
///
/// ```
/// use docker_wrapper::PsCommand;
///
/// let ps_cmd = PsCommand::new()
/// .format_template("table {{.ID}}\\t{{.Names}}\\t{{.Status}}");
/// ```
#[must_use]
pub fn format_template(mut self, template: impl Into<String>) -> Self {
self.format = Some(template.into());
self
}
/// Show n last created containers (includes all states)
///
/// # Examples
///
/// ```
/// use docker_wrapper::PsCommand;
///
/// let ps_cmd = PsCommand::new().last(5);
/// ```
#[must_use]
pub fn last(mut self, n: i32) -> Self {
self.last = Some(n);
self
}
/// Show the latest created container (includes all states)
///
/// # Examples
///
/// ```
/// use docker_wrapper::PsCommand;
///
/// let ps_cmd = PsCommand::new().latest();
/// ```
#[must_use]
pub fn latest(mut self) -> Self {
self.latest = true;
self
}
/// Don't truncate output
///
/// # Examples
///
/// ```
/// use docker_wrapper::PsCommand;
///
/// let ps_cmd = PsCommand::new().no_trunc();
/// ```
#[must_use]
pub fn no_trunc(mut self) -> Self {
self.no_trunc = true;
self
}
/// Only display container IDs
///
/// # Examples
///
/// ```
/// use docker_wrapper::PsCommand;
///
/// let ps_cmd = PsCommand::new().quiet();
/// ```
#[must_use]
pub fn quiet(mut self) -> Self {
self.quiet = true;
self
}
/// Display total file sizes
///
/// # Examples
///
/// ```
/// use docker_wrapper::PsCommand;
///
/// let ps_cmd = PsCommand::new().size();
/// ```
#[must_use]
pub fn size(mut self) -> Self {
self.size = true;
self
}
/// Parse container info from table output (best effort)
fn parse_table_output(output: &str) -> Vec<ContainerInfo> {
let lines: Vec<&str> = output.lines().collect();
if lines.len() < 2 {
return Vec::new(); // No header or data
}
let mut containers = Vec::new();
// Skip header line
for line in lines.iter().skip(1) {
if line.trim().is_empty() {
continue;
}
// Basic parsing - this is best effort since docker ps output can vary
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() >= 6 {
containers.push(ContainerInfo {
id: parts[0].to_string(),
image: parts[1].to_string(),
command: (*parts.get(2).unwrap_or(&"")).to_string(),
created: (*parts.get(3).unwrap_or(&"")).to_string(),
status: (*parts.get(4).unwrap_or(&"")).to_string(),
ports: (*parts.get(5).unwrap_or(&"")).to_string(),
names: (*parts.get(6).unwrap_or(&"")).to_string(),
});
}
}
containers
}
/// Parse container info from JSON output
fn parse_json_output(output: &str) -> Vec<ContainerInfo> {
// Try to parse as JSON array
if let Ok(containers) = serde_json::from_str::<Vec<serde_json::Value>>(output) {
return containers
.into_iter()
.filter_map(|container| {
Some(ContainerInfo {
id: container.get("ID")?.as_str()?.to_string(),
image: container.get("Image")?.as_str()?.to_string(),
command: container.get("Command")?.as_str()?.to_string(),
created: container.get("CreatedAt")?.as_str()?.to_string(),
status: container.get("Status")?.as_str()?.to_string(),
ports: container.get("Ports")?.as_str().unwrap_or("").to_string(),
names: container.get("Names")?.as_str()?.to_string(),
})
})
.collect();
}
Vec::new()
}
/// Gets the command executor
#[must_use]
pub fn get_executor(&self) -> &CommandExecutor {
&self.executor
}
/// Gets the command executor mutably
pub fn get_executor_mut(&mut self) -> &mut CommandExecutor {
&mut self.executor
}
/// Builds the command arguments for Docker ps
#[must_use]
pub fn build_command_args(&self) -> Vec<String> {
let mut args = vec!["ps".to_string()];
if self.all {
args.push("--all".to_string());
}
for filter in &self.filters {
args.push("--filter".to_string());
args.push(filter.clone());
}
if let Some(ref format) = self.format {
args.push("--format".to_string());
args.push(format.clone());
}
if let Some(last) = self.last {
args.push("--last".to_string());
args.push(last.to_string());
}
if self.latest {
args.push("--latest".to_string());
}
if self.no_trunc {
args.push("--no-trunc".to_string());
}
if self.quiet {
args.push("--quiet".to_string());
}
if self.size {
args.push("--size".to_string());
}
// Add any additional raw arguments
args.extend(self.executor.raw_args.clone());
args
}
}
impl Default for PsCommand {
fn default() -> Self {
Self::new()
}
}
#[async_trait]
impl DockerCommand for PsCommand {
type Output = PsOutput;
fn get_executor(&self) -> &CommandExecutor {
&self.executor
}
fn get_executor_mut(&mut self) -> &mut CommandExecutor {
&mut self.executor
}
fn build_command_args(&self) -> Vec<String> {
self.build_command_args()
}
async fn execute(&self) -> Result<Self::Output> {
let args = self.build_command_args();
let output = self.execute_command(args).await?;
// Parse containers based on format
let containers = if self.quiet {
// In quiet mode, we just get container IDs
Vec::new()
} else if let Some(ref format) = self.format {
if format == "json" {
Self::parse_json_output(&output.stdout)
} else {
Self::parse_table_output(&output.stdout)
}
} else {
// Default table format
Self::parse_table_output(&output.stdout)
};
Ok(PsOutput {
stdout: output.stdout,
stderr: output.stderr,
exit_code: output.exit_code,
containers,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_ps_command_builder() {
let cmd = PsCommand::new()
.all()
.filter("status=running")
.filter("name=web")
.format_json()
.no_trunc()
.size();
let args = cmd.build_command_args();
assert!(args.contains(&"--all".to_string()));
assert!(args.contains(&"--filter".to_string()));
assert!(args.contains(&"status=running".to_string()));
assert!(args.contains(&"name=web".to_string()));
assert!(args.contains(&"--format".to_string()));
assert!(args.contains(&"json".to_string()));
assert!(args.contains(&"--no-trunc".to_string()));
assert!(args.contains(&"--size".to_string()));
}
#[test]
fn test_ps_command_quiet() {
let cmd = PsCommand::new().quiet().all();
let args = cmd.build_command_args();
assert!(args.contains(&"--quiet".to_string()));
assert!(args.contains(&"--all".to_string()));
}
#[test]
fn test_ps_command_latest() {
let cmd = PsCommand::new().latest();
let args = cmd.build_command_args();
assert!(args.contains(&"--latest".to_string()));
}
#[test]
fn test_ps_command_last() {
let cmd = PsCommand::new().last(5);
let args = cmd.build_command_args();
assert!(args.contains(&"--last".to_string()));
assert!(args.contains(&"5".to_string()));
}
#[test]
fn test_ps_command_multiple_filters() {
let filters = vec!["status=running".to_string(), "name=web".to_string()];
let cmd = PsCommand::new().filters(filters);
let args = cmd.build_command_args();
// Should have two --filter entries
let filter_count = args.iter().filter(|&arg| arg == "--filter").count();
assert_eq!(filter_count, 2);
assert!(args.contains(&"status=running".to_string()));
assert!(args.contains(&"name=web".to_string()));
}
#[test]
fn test_ps_command_format_variants() {
let cmd1 = PsCommand::new().format_table();
assert!(cmd1.build_command_args().contains(&"table".to_string()));
let cmd2 = PsCommand::new().format_json();
assert!(cmd2.build_command_args().contains(&"json".to_string()));
let cmd3 = PsCommand::new().format_template("{{.ID}}");
assert!(cmd3.build_command_args().contains(&"{{.ID}}".to_string()));
}
#[test]
fn test_ps_output_helpers() {
let output = PsOutput {
stdout: "container1\ncontainer2\n".to_string(),
stderr: String::new(),
exit_code: 0,
containers: Vec::new(),
};
assert!(output.success());
assert!(!output.stdout_is_empty());
assert!(output.stderr_is_empty());
let ids = output.container_ids();
assert_eq!(ids.len(), 2);
assert_eq!(ids[0], "container1");
assert_eq!(ids[1], "container2");
}
#[test]
fn test_ps_command_extensibility() {
let mut cmd = PsCommand::new();
// Test extensibility methods
cmd.flag("--some-flag");
cmd.option("--some-option", "value");
cmd.arg("extra-arg");
let args = cmd.build_command_args();
assert!(args.contains(&"--some-flag".to_string()));
assert!(args.contains(&"--some-option".to_string()));
assert!(args.contains(&"value".to_string()));
assert!(args.contains(&"extra-arg".to_string()));
}
#[test]
fn test_container_info_creation() {
let info = ContainerInfo {
id: "abc123".to_string(),
image: "nginx:latest".to_string(),
command: "\"/docker-entrypoint.sh nginx -g 'daemon off;'\"".to_string(),
created: "2 minutes ago".to_string(),
status: "Up 2 minutes".to_string(),
ports: "0.0.0.0:8080->80/tcp".to_string(),
names: "web-server".to_string(),
};
assert_eq!(info.id, "abc123");
assert_eq!(info.image, "nginx:latest");
assert_eq!(info.names, "web-server");
}
}