commit.go 1.9 KB

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