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