commit.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package container
  2. import (
  3. "fmt"
  4. "golang.org/x/net/context"
  5. "github.com/docker/docker/api/client"
  6. "github.com/docker/docker/cli"
  7. dockeropts "github.com/docker/docker/opts"
  8. "github.com/docker/engine-api/types"
  9. "github.com/spf13/cobra"
  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 *client.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. cmd.SetFlagErrorFunc(flagErrorFunc)
  35. flags := cmd.Flags()
  36. flags.SetInterspersed(false)
  37. flags.BoolVarP(&opts.pause, "pause", "p", true, "Pause container during commit")
  38. flags.StringVarP(&opts.comment, "message", "m", "", "Commit message")
  39. flags.StringVarP(&opts.author, "author", "a", "", "Author (e.g., \"John Hannibal Smith <hannibal@a-team.com>\")")
  40. opts.changes = dockeropts.NewListOpts(nil)
  41. flags.VarP(&opts.changes, "change", "c", "Apply Dockerfile instruction to the created image")
  42. return cmd
  43. }
  44. func runCommit(dockerCli *client.DockerCli, opts *commitOptions) error {
  45. ctx := context.Background()
  46. name := opts.container
  47. reference := opts.reference
  48. options := types.ContainerCommitOptions{
  49. Reference: reference,
  50. Comment: opts.comment,
  51. Author: opts.author,
  52. Changes: opts.changes.GetAll(),
  53. Pause: opts.pause,
  54. }
  55. response, err := dockerCli.Client().ContainerCommit(ctx, name, options)
  56. if err != nil {
  57. return err
  58. }
  59. fmt.Fprintln(dockerCli.Out(), response.ID)
  60. return nil
  61. }