github.com/ali-iotechsys/cli@v20.10.0+incompatible/cli/command/container/commit.go (about)

     1  package container
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	"github.com/docker/cli/cli"
     8  	"github.com/docker/cli/cli/command"
     9  	"github.com/docker/cli/opts"
    10  	"github.com/docker/docker/api/types"
    11  	"github.com/spf13/cobra"
    12  )
    13  
    14  type commitOptions struct {
    15  	container string
    16  	reference string
    17  
    18  	pause   bool
    19  	comment string
    20  	author  string
    21  	changes opts.ListOpts
    22  }
    23  
    24  // NewCommitCommand creates a new cobra.Command for `docker commit`
    25  func NewCommitCommand(dockerCli command.Cli) *cobra.Command {
    26  	var options commitOptions
    27  
    28  	cmd := &cobra.Command{
    29  		Use:   "commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]",
    30  		Short: "Create a new image from a container's changes",
    31  		Args:  cli.RequiresRangeArgs(1, 2),
    32  		RunE: func(cmd *cobra.Command, args []string) error {
    33  			options.container = args[0]
    34  			if len(args) > 1 {
    35  				options.reference = args[1]
    36  			}
    37  			return runCommit(dockerCli, &options)
    38  		},
    39  	}
    40  
    41  	flags := cmd.Flags()
    42  	flags.SetInterspersed(false)
    43  
    44  	flags.BoolVarP(&options.pause, "pause", "p", true, "Pause container during commit")
    45  	flags.StringVarP(&options.comment, "message", "m", "", "Commit message")
    46  	flags.StringVarP(&options.author, "author", "a", "", "Author (e.g., \"John Hannibal Smith <hannibal@a-team.com>\")")
    47  
    48  	options.changes = opts.NewListOpts(nil)
    49  	flags.VarP(&options.changes, "change", "c", "Apply Dockerfile instruction to the created image")
    50  
    51  	return cmd
    52  }
    53  
    54  func runCommit(dockerCli command.Cli, options *commitOptions) error {
    55  	ctx := context.Background()
    56  
    57  	name := options.container
    58  	reference := options.reference
    59  
    60  	commitOptions := types.ContainerCommitOptions{
    61  		Reference: reference,
    62  		Comment:   options.comment,
    63  		Author:    options.author,
    64  		Changes:   options.changes.GetAll(),
    65  		Pause:     options.pause,
    66  	}
    67  
    68  	response, err := dockerCli.Client().ContainerCommit(ctx, name, commitOptions)
    69  	if err != nil {
    70  		return err
    71  	}
    72  
    73  	fmt.Fprintln(dockerCli.Out(), response.ID)
    74  	return nil
    75  }