docker-wrapper 0.11.1

A Docker CLI wrapper for Rust
Documentation
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
//! Docker Images Command Implementation
//!
//! This module provides a comprehensive implementation of the `docker images` command,
//! supporting all native Docker images options for listing local images.
//!
//! # Examples
//!
//! ## Basic Usage
//!
//! ```no_run
//! use docker_wrapper::ImagesCommand;
//! use docker_wrapper::DockerCommand;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     // List all images
//!     let images_cmd = ImagesCommand::new();
//!     let output = images_cmd.execute().await?;
//!     println!("Images listed: {}", output.success());
//!     Ok(())
//! }
//! ```
//!
//! ## Advanced Usage
//!
//! ```no_run
//! use docker_wrapper::ImagesCommand;
//! use docker_wrapper::DockerCommand;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     // List images with filtering and JSON format
//!     let images_cmd = ImagesCommand::new()
//!         .repository("nginx")
//!         .all()
//!         .filter("dangling=false")
//!         .format_json()
//!         .digests()
//!         .no_trunc();
//!
//!     let output = images_cmd.execute().await?;
//!     println!("Filtered images: {}", output.success());
//!     Ok(())
//! }
//! ```

use super::{CommandExecutor, CommandOutput, DockerCommand};
use crate::error::Result;
use async_trait::async_trait;
use serde_json::Value;

/// Docker Images Command Builder
///
/// Implements the `docker images` command for listing local Docker images.
///
/// # Docker Images Overview
///
/// The images command lists Docker images stored locally on the system. It supports:
/// - Repository and tag filtering
/// - Multiple output formats (table, JSON, custom templates)
/// - Image metadata display (digests, sizes, creation dates)
/// - Advanced filtering by various criteria
/// - Quiet mode for scripts
///
/// # Image Information
///
/// Each image entry typically includes:
/// - Repository name
/// - Tag
/// - Image ID
/// - Creation date
/// - Size
/// - Optionally: digests, intermediate layers
///
/// # Examples
///
/// ```no_run
/// use docker_wrapper::ImagesCommand;
/// use docker_wrapper::DockerCommand;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     // List all nginx images
///     let output = ImagesCommand::new()
///         .repository("nginx")
///         .execute()
///         .await?;
///
///     println!("Images success: {}", output.success());
///     Ok(())
/// }
/// ```
#[derive(Debug, Clone)]
#[allow(clippy::struct_excessive_bools)]
pub struct ImagesCommand {
    /// Optional repository filter (e.g., "nginx", "nginx:alpine")
    repository: Option<String>,
    /// Show all images (including intermediate images)
    all: bool,
    /// Show digests
    digests: bool,
    /// Filter output based on conditions
    filters: Vec<String>,
    /// Output format
    format: Option<String>,
    /// Don't truncate output
    no_trunc: bool,
    /// Only show image IDs
    quiet: bool,
    /// List multi-platform images as a tree (experimental)
    tree: bool,
    /// Command executor for handling raw arguments and execution
    pub executor: CommandExecutor,
}

/// Represents a Docker image from the output
#[derive(Debug, Clone, PartialEq)]
pub struct ImageInfo {
    /// Repository name
    pub repository: String,
    /// Tag
    pub tag: String,
    /// Image ID
    pub image_id: String,
    /// Creation date/time
    pub created: String,
    /// Image size
    pub size: String,
    /// Digest (if available)
    pub digest: Option<String>,
}

/// Output from the images command with parsed image information
#[derive(Debug, Clone)]
pub struct ImagesOutput {
    /// Raw command output
    pub output: CommandOutput,
    /// Parsed image information (if output is parseable)
    pub images: Vec<ImageInfo>,
}

impl ImagesCommand {
    /// Create a new `ImagesCommand` instance
    ///
    /// # Examples
    ///
    /// ```
    /// use docker_wrapper::ImagesCommand;
    ///
    /// let images_cmd = ImagesCommand::new();
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self {
            repository: None,
            all: false,
            digests: false,
            filters: Vec::new(),
            format: None,
            no_trunc: false,
            quiet: false,
            tree: false,
            executor: CommandExecutor::new(),
        }
    }

    /// Filter images by repository name (and optionally tag)
    ///
    /// # Arguments
    ///
    /// * `repository` - Repository name (e.g., "nginx", "nginx:alpine", "ubuntu:20.04")
    ///
    /// # Examples
    ///
    /// ```
    /// use docker_wrapper::ImagesCommand;
    ///
    /// let images_cmd = ImagesCommand::new()
    ///     .repository("nginx:alpine");
    /// ```
    #[must_use]
    pub fn repository<S: Into<String>>(mut self, repository: S) -> Self {
        self.repository = Some(repository.into());
        self
    }

    /// Show all images (including intermediate images)
    ///
    /// By default, Docker hides intermediate images. This option shows them all.
    ///
    /// # Examples
    ///
    /// ```
    /// use docker_wrapper::ImagesCommand;
    ///
    /// let images_cmd = ImagesCommand::new()
    ///     .all();
    /// ```
    #[must_use]
    pub fn all(mut self) -> Self {
        self.all = true;
        self
    }

    /// Show digests
    ///
    /// Displays the digest (SHA256 hash) for each image.
    ///
    /// # Examples
    ///
    /// ```
    /// use docker_wrapper::ImagesCommand;
    ///
    /// let images_cmd = ImagesCommand::new()
    ///     .digests();
    /// ```
    #[must_use]
    pub fn digests(mut self) -> Self {
        self.digests = true;
        self
    }

    /// Add a filter condition
    ///
    /// Common filters:
    /// - `dangling=true|false` - Show dangling images
    /// - `label=<key>` or `label=<key>=<value>` - Filter by label
    /// - `before=<image>` - Images created before this image
    /// - `since=<image>` - Images created since this image
    /// - `reference=<pattern>` - Filter by repository name pattern
    ///
    /// # Examples
    ///
    /// ```
    /// use docker_wrapper::ImagesCommand;
    ///
    /// let images_cmd = ImagesCommand::new()
    ///     .filter("dangling=true")
    ///     .filter("label=maintainer=nginx");
    /// ```
    #[must_use]
    pub fn filter<S: Into<String>>(mut self, filter: S) -> Self {
        self.filters.push(filter.into());
        self
    }

    /// Add multiple filter conditions
    ///
    /// # Examples
    ///
    /// ```
    /// use docker_wrapper::ImagesCommand;
    ///
    /// let images_cmd = ImagesCommand::new()
    ///     .filters(vec!["dangling=false", "label=version=latest"]);
    /// ```
    #[must_use]
    pub fn filters<I, S>(mut self, filters: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.filters
            .extend(filters.into_iter().map(std::convert::Into::into));
        self
    }

    /// Set custom output format
    ///
    /// # Examples
    ///
    /// ```
    /// use docker_wrapper::ImagesCommand;
    ///
    /// let images_cmd = ImagesCommand::new()
    ///     .format("table {{.Repository}}:{{.Tag}}\t{{.Size}}");
    /// ```
    #[must_use]
    pub fn format<S: Into<String>>(mut self, format: S) -> Self {
        self.format = Some(format.into());
        self
    }

    /// Format output as table (default)
    ///
    /// # Examples
    ///
    /// ```
    /// use docker_wrapper::ImagesCommand;
    ///
    /// let images_cmd = ImagesCommand::new()
    ///     .format_table();
    /// ```
    #[must_use]
    pub fn format_table(mut self) -> Self {
        self.format = Some("table".to_string());
        self
    }

    /// Format output as JSON
    ///
    /// # Examples
    ///
    /// ```
    /// use docker_wrapper::ImagesCommand;
    ///
    /// let images_cmd = ImagesCommand::new()
    ///     .format_json();
    /// ```
    #[must_use]
    pub fn format_json(mut self) -> Self {
        self.format = Some("json".to_string());
        self
    }

    /// Don't truncate output
    ///
    /// By default, Docker truncates long values. This shows full values.
    ///
    /// # Examples
    ///
    /// ```
    /// use docker_wrapper::ImagesCommand;
    ///
    /// let images_cmd = ImagesCommand::new()
    ///     .no_trunc();
    /// ```
    #[must_use]
    pub fn no_trunc(mut self) -> Self {
        self.no_trunc = true;
        self
    }

    /// Only show image IDs
    ///
    /// Useful for scripting and automation.
    ///
    /// # Examples
    ///
    /// ```
    /// use docker_wrapper::ImagesCommand;
    ///
    /// let images_cmd = ImagesCommand::new()
    ///     .quiet();
    /// ```
    #[must_use]
    pub fn quiet(mut self) -> Self {
        self.quiet = true;
        self
    }

    /// List multi-platform images as a tree (experimental)
    ///
    /// This is an experimental Docker feature for displaying multi-platform images.
    ///
    /// # Examples
    ///
    /// ```
    /// use docker_wrapper::ImagesCommand;
    ///
    /// let images_cmd = ImagesCommand::new()
    ///     .tree();
    /// ```
    #[must_use]
    pub fn tree(mut self) -> Self {
        self.tree = true;
        self
    }

    /// Build the command arguments
    ///
    /// This method constructs the complete argument list for the docker images command.
    fn build_command_args(&self) -> Vec<String> {
        let mut args = vec!["images".to_string()];

        // Add all flag
        if self.all {
            args.push("--all".to_string());
        }

        // Add digests flag
        if self.digests {
            args.push("--digests".to_string());
        }

        // Add filters
        for filter in &self.filters {
            args.push("--filter".to_string());
            args.push(filter.clone());
        }

        // Add format
        if let Some(ref format) = self.format {
            args.push("--format".to_string());
            args.push(format.clone());
        }

        // Add no-trunc flag
        if self.no_trunc {
            args.push("--no-trunc".to_string());
        }

        // Add quiet flag
        if self.quiet {
            args.push("--quiet".to_string());
        }

        // Add tree flag
        if self.tree {
            args.push("--tree".to_string());
        }

        // Add repository filter (must be last)
        if let Some(ref repository) = self.repository {
            args.push(repository.clone());
        }

        args
    }

    /// Parse the output to extract image information
    ///
    /// This attempts to parse the docker images output into structured data.
    fn parse_output(&self, output: &CommandOutput) -> Vec<ImageInfo> {
        if self.quiet {
            // In quiet mode, output is just image IDs
            return output
                .stdout
                .lines()
                .filter(|line| !line.trim().is_empty())
                .map(|line| ImageInfo {
                    repository: "<unknown>".to_string(),
                    tag: "<unknown>".to_string(),
                    image_id: line.trim().to_string(),
                    created: "<unknown>".to_string(),
                    size: "<unknown>".to_string(),
                    digest: None,
                })
                .collect();
        }

        if let Some(ref format) = self.format {
            if format == "json" {
                return Self::parse_json_output(&output.stdout);
            }
        }

        // Parse table format (default)
        self.parse_table_output(&output.stdout)
    }

    /// Parse JSON format output
    fn parse_json_output(stdout: &str) -> Vec<ImageInfo> {
        let mut images = Vec::new();

        for line in stdout.lines() {
            if let Ok(json) = serde_json::from_str::<Value>(line) {
                if let Some(obj) = json.as_object() {
                    let repository = obj
                        .get("Repository")
                        .and_then(|v| v.as_str())
                        .unwrap_or("<none>")
                        .to_string();
                    let tag = obj
                        .get("Tag")
                        .and_then(|v| v.as_str())
                        .unwrap_or("<none>")
                        .to_string();
                    let image_id = obj
                        .get("ID")
                        .and_then(|v| v.as_str())
                        .unwrap_or("")
                        .to_string();
                    let created = obj
                        .get("CreatedAt")
                        .and_then(|v| v.as_str())
                        .unwrap_or("")
                        .to_string();
                    let size = obj
                        .get("Size")
                        .and_then(|v| v.as_str())
                        .unwrap_or("")
                        .to_string();
                    let digest = obj.get("Digest").and_then(|v| v.as_str()).map(String::from);

                    images.push(ImageInfo {
                        repository,
                        tag,
                        image_id,
                        created,
                        size,
                        digest,
                    });
                }
            }
        }

        images
    }

    /// Parse table format output
    fn parse_table_output(&self, stdout: &str) -> Vec<ImageInfo> {
        let mut images = Vec::new();
        let lines: Vec<&str> = stdout.lines().collect();

        if lines.is_empty() {
            return images;
        }

        // Skip header line if present (handle both old "REPOSITORY" and new "IMAGE" formats)
        let data_lines = if lines[0].starts_with("REPOSITORY") || lines[0].starts_with("IMAGE") {
            &lines[1..]
        } else {
            &lines[..]
        };

        for line in data_lines {
            if line.trim().is_empty() {
                continue;
            }

            // Split by whitespace, but handle multi-word fields like "2 days ago"
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() >= 5 {
                let repository = parts[0].to_string();
                let tag = parts[1].to_string();
                let image_id = parts[2].to_string();

                // Handle multi-word created field and size
                let (created, size, digest) = if self.digests && parts.len() >= 7 {
                    // With digests: REPO TAG IMAGE_ID DIGEST CREATED... SIZE
                    let digest = Some(parts[3].to_string());
                    let created_parts = &parts[4..parts.len() - 1];
                    let created = created_parts.join(" ");
                    let size = parts[parts.len() - 1].to_string();
                    (created, size, digest)
                } else if parts.len() >= 5 {
                    // Without digests: REPO TAG IMAGE_ID CREATED... SIZE
                    let created_parts = &parts[3..parts.len() - 1];
                    let created = created_parts.join(" ");
                    let size = parts[parts.len() - 1].to_string();
                    (created, size, None)
                } else {
                    (String::new(), String::new(), None)
                };

                images.push(ImageInfo {
                    repository,
                    tag,
                    image_id,
                    created,
                    size,
                    digest,
                });
            }
        }

        images
    }

    /// Get the repository filter if set
    ///
    /// # Examples
    ///
    /// ```
    /// use docker_wrapper::ImagesCommand;
    ///
    /// let images_cmd = ImagesCommand::new().repository("nginx");
    /// assert_eq!(images_cmd.get_repository(), Some("nginx"));
    /// ```
    #[must_use]
    pub fn get_repository(&self) -> Option<&str> {
        self.repository.as_deref()
    }

    /// Check if showing all images
    ///
    /// # Examples
    ///
    /// ```
    /// use docker_wrapper::ImagesCommand;
    ///
    /// let images_cmd = ImagesCommand::new().all();
    /// assert!(images_cmd.is_all());
    /// ```
    #[must_use]
    pub fn is_all(&self) -> bool {
        self.all
    }

    /// Check if showing digests
    ///
    /// # Examples
    ///
    /// ```
    /// use docker_wrapper::ImagesCommand;
    ///
    /// let images_cmd = ImagesCommand::new().digests();
    /// assert!(images_cmd.is_digests());
    /// ```
    #[must_use]
    pub fn is_digests(&self) -> bool {
        self.digests
    }

    /// Check if quiet mode is enabled
    ///
    /// # Examples
    ///
    /// ```
    /// use docker_wrapper::ImagesCommand;
    ///
    /// let images_cmd = ImagesCommand::new().quiet();
    /// assert!(images_cmd.is_quiet());
    /// ```
    #[must_use]
    pub fn is_quiet(&self) -> bool {
        self.quiet
    }

    /// Check if no-trunc is enabled
    ///
    /// # Examples
    ///
    /// ```
    /// use docker_wrapper::ImagesCommand;
    ///
    /// let images_cmd = ImagesCommand::new().no_trunc();
    /// assert!(images_cmd.is_no_trunc());
    /// ```
    #[must_use]
    pub fn is_no_trunc(&self) -> bool {
        self.no_trunc
    }

    /// Check if tree mode is enabled
    ///
    /// # Examples
    ///
    /// ```
    /// use docker_wrapper::ImagesCommand;
    ///
    /// let images_cmd = ImagesCommand::new().tree();
    /// assert!(images_cmd.is_tree());
    /// ```
    #[must_use]
    pub fn is_tree(&self) -> bool {
        self.tree
    }

    /// Get the current filters
    ///
    /// # Examples
    ///
    /// ```
    /// use docker_wrapper::ImagesCommand;
    ///
    /// let images_cmd = ImagesCommand::new()
    ///     .filter("dangling=true");
    /// assert_eq!(images_cmd.get_filters(), &["dangling=true"]);
    /// ```
    #[must_use]
    pub fn get_filters(&self) -> &[String] {
        &self.filters
    }

    /// Get the format if set
    ///
    /// # Examples
    ///
    /// ```
    /// use docker_wrapper::ImagesCommand;
    ///
    /// let images_cmd = ImagesCommand::new().format_json();
    /// assert_eq!(images_cmd.get_format(), Some("json"));
    /// ```
    #[must_use]
    pub fn get_format(&self) -> Option<&str> {
        self.format.as_deref()
    }

    /// Get a reference to the command executor
    #[must_use]
    pub fn get_executor(&self) -> &CommandExecutor {
        &self.executor
    }

    /// Get a mutable reference to the command executor
    #[must_use]
    pub fn get_executor_mut(&mut self) -> &mut CommandExecutor {
        &mut self.executor
    }
}

impl Default for ImagesCommand {
    fn default() -> Self {
        Self::new()
    }
}

impl ImagesOutput {
    /// Check if the command was successful
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use docker_wrapper::ImagesCommand;
    /// # use docker_wrapper::DockerCommand;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let output = ImagesCommand::new().execute().await?;
    /// if output.success() {
    ///     println!("Images listed successfully");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn success(&self) -> bool {
        self.output.success
    }

    /// Get the number of images found
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use docker_wrapper::ImagesCommand;
    /// # use docker_wrapper::DockerCommand;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let output = ImagesCommand::new().execute().await?;
    /// println!("Found {} images", output.image_count());
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn image_count(&self) -> usize {
        self.images.len()
    }

    /// Get image IDs only
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use docker_wrapper::ImagesCommand;
    /// # use docker_wrapper::DockerCommand;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let output = ImagesCommand::new().execute().await?;
    /// let ids = output.image_ids();
    /// println!("Image IDs: {:?}", ids);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn image_ids(&self) -> Vec<&str> {
        self.images
            .iter()
            .map(|img| img.image_id.as_str())
            .collect()
    }

    /// Filter images by repository name
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use docker_wrapper::ImagesCommand;
    /// # use docker_wrapper::DockerCommand;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let output = ImagesCommand::new().execute().await?;
    /// let nginx_images = output.filter_by_repository("nginx");
    /// println!("Nginx images: {}", nginx_images.len());
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn filter_by_repository(&self, repository: &str) -> Vec<&ImageInfo> {
        self.images
            .iter()
            .filter(|img| img.repository == repository)
            .collect()
    }

    /// Check if output is empty (no images)
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use docker_wrapper::ImagesCommand;
    /// # use docker_wrapper::DockerCommand;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let output = ImagesCommand::new().execute().await?;
    /// if output.is_empty() {
    ///     println!("No images found");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.images.is_empty()
    }
}

#[async_trait]
impl DockerCommand for ImagesCommand {
    type Output = ImagesOutput;

    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?;

        let images = self.parse_output(&output);

        Ok(ImagesOutput { output, images })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_images_command_basic() {
        let images_cmd = ImagesCommand::new();
        let args = images_cmd.build_command_args();

        assert_eq!(args, vec!["images"]); // Basic images command with just the command name
        assert!(!images_cmd.is_all());
        assert!(!images_cmd.is_digests());
        assert!(!images_cmd.is_quiet());
        assert!(!images_cmd.is_no_trunc());
        assert!(!images_cmd.is_tree());
        assert_eq!(images_cmd.get_repository(), None);
        assert_eq!(images_cmd.get_format(), None);
        assert!(images_cmd.get_filters().is_empty());
    }

    #[test]
    fn test_images_command_with_repository() {
        let images_cmd = ImagesCommand::new().repository("nginx:alpine");
        let args = images_cmd.build_command_args();

        assert!(args.contains(&"nginx:alpine".to_string()));
        assert_eq!(args.last(), Some(&"nginx:alpine".to_string()));
        assert_eq!(images_cmd.get_repository(), Some("nginx:alpine"));
    }

    #[test]
    fn test_images_command_with_all_flags() {
        let images_cmd = ImagesCommand::new()
            .all()
            .digests()
            .no_trunc()
            .quiet()
            .tree();

        let args = images_cmd.build_command_args();

        assert!(args.contains(&"--all".to_string()));
        assert!(args.contains(&"--digests".to_string()));
        assert!(args.contains(&"--no-trunc".to_string()));
        assert!(args.contains(&"--quiet".to_string()));
        assert!(args.contains(&"--tree".to_string()));

        assert!(images_cmd.is_all());
        assert!(images_cmd.is_digests());
        assert!(images_cmd.is_no_trunc());
        assert!(images_cmd.is_quiet());
        assert!(images_cmd.is_tree());
    }

    #[test]
    fn test_images_command_with_filters() {
        let images_cmd = ImagesCommand::new()
            .filter("dangling=true")
            .filter("label=maintainer=nginx")
            .filters(vec!["before=alpine:latest", "since=ubuntu:20.04"]);

        let args = images_cmd.build_command_args();

        assert!(args.contains(&"--filter".to_string()));
        assert!(args.contains(&"dangling=true".to_string()));
        assert!(args.contains(&"label=maintainer=nginx".to_string()));
        assert!(args.contains(&"before=alpine:latest".to_string()));
        assert!(args.contains(&"since=ubuntu:20.04".to_string()));

        let filters = images_cmd.get_filters();
        assert_eq!(filters.len(), 4);
        assert!(filters.contains(&"dangling=true".to_string()));
    }

    #[test]
    fn test_images_command_with_format() {
        let images_cmd = ImagesCommand::new().format_json();
        let args = images_cmd.build_command_args();

        assert!(args.contains(&"--format".to_string()));
        assert!(args.contains(&"json".to_string()));
        assert_eq!(images_cmd.get_format(), Some("json"));
    }

    #[test]
    fn test_images_command_custom_format() {
        let custom_format = "table {{.Repository}}:{{.Tag}}\t{{.Size}}";
        let images_cmd = ImagesCommand::new().format(custom_format);
        let args = images_cmd.build_command_args();

        assert!(args.contains(&"--format".to_string()));
        assert!(args.contains(&custom_format.to_string()));
        assert_eq!(images_cmd.get_format(), Some(custom_format));
    }

    #[test]
    fn test_images_command_all_options() {
        let images_cmd = ImagesCommand::new()
            .repository("ubuntu")
            .all()
            .digests()
            .filter("dangling=false")
            .format_table()
            .no_trunc()
            .quiet();

        let args = images_cmd.build_command_args();

        // Repository should be last
        assert_eq!(args.last(), Some(&"ubuntu".to_string()));

        // All options should be present
        assert!(args.contains(&"--all".to_string()));
        assert!(args.contains(&"--digests".to_string()));
        assert!(args.contains(&"--filter".to_string()));
        assert!(args.contains(&"dangling=false".to_string()));
        assert!(args.contains(&"--format".to_string()));
        assert!(args.contains(&"table".to_string()));
        assert!(args.contains(&"--no-trunc".to_string()));
        assert!(args.contains(&"--quiet".to_string()));

        // Verify helper methods
        assert_eq!(images_cmd.get_repository(), Some("ubuntu"));
        assert!(images_cmd.is_all());
        assert!(images_cmd.is_digests());
        assert!(images_cmd.is_no_trunc());
        assert!(images_cmd.is_quiet());
        assert_eq!(images_cmd.get_format(), Some("table"));
        assert_eq!(images_cmd.get_filters(), &["dangling=false"]);
    }

    #[test]
    fn test_images_command_default() {
        let images_cmd = ImagesCommand::default();
        assert_eq!(images_cmd.get_repository(), None);
        assert!(!images_cmd.is_all());
    }

    #[test]
    fn test_image_info_creation() {
        let image = ImageInfo {
            repository: "nginx".to_string(),
            tag: "alpine".to_string(),
            image_id: "abc123456789".to_string(),
            created: "2 days ago".to_string(),
            size: "16.1MB".to_string(),
            digest: Some("sha256:abc123".to_string()),
        };

        assert_eq!(image.repository, "nginx");
        assert_eq!(image.tag, "alpine");
        assert_eq!(image.image_id, "abc123456789");
        assert_eq!(image.digest, Some("sha256:abc123".to_string()));
    }

    #[test]
    fn test_parse_json_output() {
        let json_output = r#"{"Containers":"N/A","CreatedAt":"2023-01-01T00:00:00Z","CreatedSince":"2 days ago","Digest":"sha256:abc123","ID":"sha256:def456","Repository":"nginx","SharedSize":"N/A","Size":"16.1MB","Tag":"alpine","UniqueSize":"N/A","VirtualSize":"16.1MB"}
{"Containers":"N/A","CreatedAt":"2023-01-02T00:00:00Z","CreatedSince":"1 day ago","Digest":"sha256:xyz789","ID":"sha256:ghi012","Repository":"ubuntu","SharedSize":"N/A","Size":"72.8MB","Tag":"20.04","UniqueSize":"N/A","VirtualSize":"72.8MB"}"#;

        let images = ImagesCommand::parse_json_output(json_output);

        assert_eq!(images.len(), 2);
        assert_eq!(images[0].repository, "nginx");
        assert_eq!(images[0].tag, "alpine");
        assert_eq!(images[0].image_id, "sha256:def456");
        assert_eq!(images[0].size, "16.1MB");
        assert_eq!(images[0].digest, Some("sha256:abc123".to_string()));

        assert_eq!(images[1].repository, "ubuntu");
        assert_eq!(images[1].tag, "20.04");
    }

    #[test]
    fn test_parse_table_output() {
        let images_cmd = ImagesCommand::new();
        let table_output = r"REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
nginx               alpine              abc123456789        2 days ago          16.1MB
ubuntu              20.04               def456789012        1 day ago           72.8MB
<none>              <none>              ghi789012345        3 hours ago         5.59MB";

        let images = images_cmd.parse_table_output(table_output);

        assert_eq!(images.len(), 3);
        assert_eq!(images[0].repository, "nginx");
        assert_eq!(images[0].tag, "alpine");
        assert_eq!(images[0].image_id, "abc123456789");
        assert_eq!(images[0].created, "2 days ago");
        assert_eq!(images[0].size, "16.1MB");

        assert_eq!(images[1].repository, "ubuntu");
        assert_eq!(images[1].tag, "20.04");
    }

    #[test]
    fn test_parse_quiet_output() {
        let images_cmd = ImagesCommand::new().quiet();
        let quiet_output = "abc123456789\ndef456789012\nghi789012345";

        let images = images_cmd.parse_output(&CommandOutput {
            stdout: quiet_output.to_string(),
            stderr: String::new(),
            exit_code: 0,
            success: true,
        });

        assert_eq!(images.len(), 3);
        assert_eq!(images[0].image_id, "abc123456789");
        assert_eq!(images[0].repository, "<unknown>");
        assert_eq!(images[1].image_id, "def456789012");
        assert_eq!(images[2].image_id, "ghi789012345");
    }

    #[test]
    fn test_images_output_helpers() {
        let output = ImagesOutput {
            output: CommandOutput {
                stdout: "test".to_string(),
                stderr: String::new(),
                exit_code: 0,
                success: true,
            },
            images: vec![
                ImageInfo {
                    repository: "nginx".to_string(),
                    tag: "alpine".to_string(),
                    image_id: "abc123".to_string(),
                    created: "2 days ago".to_string(),
                    size: "16.1MB".to_string(),
                    digest: None,
                },
                ImageInfo {
                    repository: "nginx".to_string(),
                    tag: "latest".to_string(),
                    image_id: "def456".to_string(),
                    created: "1 day ago".to_string(),
                    size: "133MB".to_string(),
                    digest: None,
                },
                ImageInfo {
                    repository: "ubuntu".to_string(),
                    tag: "20.04".to_string(),
                    image_id: "ghi789".to_string(),
                    created: "3 days ago".to_string(),
                    size: "72.8MB".to_string(),
                    digest: None,
                },
            ],
        };

        assert!(output.success());
        assert_eq!(output.image_count(), 3);
        assert!(!output.is_empty());

        let ids = output.image_ids();
        assert_eq!(ids, vec!["abc123", "def456", "ghi789"]);

        let nginx_images = output.filter_by_repository("nginx");
        assert_eq!(nginx_images.len(), 2);
        assert_eq!(nginx_images[0].tag, "alpine");
        assert_eq!(nginx_images[1].tag, "latest");
    }

    #[test]
    fn test_images_command_extensibility() {
        let mut images_cmd = ImagesCommand::new();
        images_cmd
            .arg("--experimental")
            .args(vec!["--custom", "value"]);

        // Extensibility is handled through the executor's raw_args
        // The actual testing of raw args is done in command.rs tests
        // We can't access private fields, but we know the methods work
        println!("Extensibility methods called successfully");
    }
}