github.com/panekj/cli@v0.0.0-20230304125325-467dd2f3797e/cli/command/image/list.go (about) 1 package image 2 3 import ( 4 "context" 5 6 "github.com/docker/cli/cli" 7 "github.com/docker/cli/cli/command" 8 "github.com/docker/cli/cli/command/formatter" 9 flagsHelper "github.com/docker/cli/cli/flags" 10 "github.com/docker/cli/opts" 11 "github.com/docker/docker/api/types" 12 "github.com/spf13/cobra" 13 ) 14 15 type imagesOptions struct { 16 matchName string 17 18 quiet bool 19 all bool 20 noTrunc bool 21 showDigests bool 22 format string 23 filter opts.FilterOpt 24 } 25 26 // NewImagesCommand creates a new `docker images` command 27 func NewImagesCommand(dockerCli command.Cli) *cobra.Command { 28 options := imagesOptions{filter: opts.NewFilterOpt()} 29 30 cmd := &cobra.Command{ 31 Use: "images [OPTIONS] [REPOSITORY[:TAG]]", 32 Short: "List images", 33 Args: cli.RequiresMaxArgs(1), 34 RunE: func(cmd *cobra.Command, args []string) error { 35 if len(args) > 0 { 36 options.matchName = args[0] 37 } 38 return runImages(dockerCli, options) 39 }, 40 Annotations: map[string]string{ 41 "category-top": "7", 42 "aliases": "docker image ls, docker image list, docker images", 43 }, 44 } 45 46 flags := cmd.Flags() 47 48 flags.BoolVarP(&options.quiet, "quiet", "q", false, "Only show image IDs") 49 flags.BoolVarP(&options.all, "all", "a", false, "Show all images (default hides intermediate images)") 50 flags.BoolVar(&options.noTrunc, "no-trunc", false, "Don't truncate output") 51 flags.BoolVar(&options.showDigests, "digests", false, "Show digests") 52 flags.StringVar(&options.format, "format", "", flagsHelper.FormatHelp) 53 flags.VarP(&options.filter, "filter", "f", "Filter output based on conditions provided") 54 55 return cmd 56 } 57 58 func newListCommand(dockerCli command.Cli) *cobra.Command { 59 cmd := *NewImagesCommand(dockerCli) 60 cmd.Aliases = []string{"list"} 61 cmd.Use = "ls [OPTIONS] [REPOSITORY[:TAG]]" 62 return &cmd 63 } 64 65 func runImages(dockerCli command.Cli, options imagesOptions) error { 66 ctx := context.Background() 67 68 filters := options.filter.Value() 69 if options.matchName != "" { 70 filters.Add("reference", options.matchName) 71 } 72 73 listOptions := types.ImageListOptions{ 74 All: options.all, 75 Filters: filters, 76 } 77 78 images, err := dockerCli.Client().ImageList(ctx, listOptions) 79 if err != nil { 80 return err 81 } 82 83 format := options.format 84 if len(format) == 0 { 85 if len(dockerCli.ConfigFile().ImagesFormat) > 0 && !options.quiet { 86 format = dockerCli.ConfigFile().ImagesFormat 87 } else { 88 format = formatter.TableFormatKey 89 } 90 } 91 92 imageCtx := formatter.ImageContext{ 93 Context: formatter.Context{ 94 Output: dockerCli.Out(), 95 Format: formatter.NewImageFormat(format, options.quiet, options.showDigests), 96 Trunc: !options.noTrunc, 97 }, 98 Digest: options.showDigests, 99 } 100 return formatter.ImageWrite(imageCtx, images) 101 }