commit.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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/api/types"
  7. "github.com/docker/docker/cli"
  8. dockeropts "github.com/docker/docker/opts"
  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. 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 *client.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. }