github.com/panekj/cli@v0.0.0-20230304125325-467dd2f3797e/cli/command/image/history.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/spf13/cobra"
    11  )
    12  
    13  type historyOptions struct {
    14  	image string
    15  
    16  	human   bool
    17  	quiet   bool
    18  	noTrunc bool
    19  	format  string
    20  }
    21  
    22  // NewHistoryCommand creates a new `docker history` command
    23  func NewHistoryCommand(dockerCli command.Cli) *cobra.Command {
    24  	var opts historyOptions
    25  
    26  	cmd := &cobra.Command{
    27  		Use:   "history [OPTIONS] IMAGE",
    28  		Short: "Show the history of an image",
    29  		Args:  cli.ExactArgs(1),
    30  		RunE: func(cmd *cobra.Command, args []string) error {
    31  			opts.image = args[0]
    32  			return runHistory(dockerCli, opts)
    33  		},
    34  		Annotations: map[string]string{
    35  			"aliases": "docker image history, docker history",
    36  		},
    37  	}
    38  
    39  	flags := cmd.Flags()
    40  
    41  	flags.BoolVarP(&opts.human, "human", "H", true, "Print sizes and dates in human readable format")
    42  	flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Only show image IDs")
    43  	flags.BoolVar(&opts.noTrunc, "no-trunc", false, "Don't truncate output")
    44  	flags.StringVar(&opts.format, "format", "", flagsHelper.FormatHelp)
    45  
    46  	return cmd
    47  }
    48  
    49  func runHistory(dockerCli command.Cli, opts historyOptions) error {
    50  	ctx := context.Background()
    51  
    52  	history, err := dockerCli.Client().ImageHistory(ctx, opts.image)
    53  	if err != nil {
    54  		return err
    55  	}
    56  
    57  	format := opts.format
    58  	if len(format) == 0 {
    59  		format = formatter.TableFormatKey
    60  	}
    61  
    62  	historyCtx := formatter.Context{
    63  		Output: dockerCli.Out(),
    64  		Format: NewHistoryFormat(format, opts.quiet, opts.human),
    65  		Trunc:  !opts.noTrunc,
    66  	}
    67  	return HistoryWrite(historyCtx, opts.human, history)
    68  }