compose.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. Copyright 2020 Docker, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package compose
  14. import (
  15. "context"
  16. "github.com/compose-spec/compose-go/cli"
  17. "github.com/pkg/errors"
  18. "github.com/spf13/cobra"
  19. "github.com/docker/api/client"
  20. apicontext "github.com/docker/api/context"
  21. "github.com/docker/api/context/store"
  22. "github.com/docker/api/errdefs"
  23. )
  24. type composeOptions struct {
  25. Name string
  26. WorkingDir string
  27. ConfigPaths []string
  28. Environment []string
  29. }
  30. func (o *composeOptions) toProjectOptions() (*cli.ProjectOptions, error) {
  31. return cli.NewProjectOptions(o.ConfigPaths,
  32. cli.WithOsEnv,
  33. cli.WithEnv(o.Environment),
  34. cli.WithWorkingDirectory(o.WorkingDir),
  35. cli.WithName(o.Name))
  36. }
  37. // Command returns the compose command with its child commands
  38. func Command() *cobra.Command {
  39. command := &cobra.Command{
  40. Short: "Docker Compose",
  41. Use: "compose",
  42. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  43. return checkComposeSupport(cmd.Context())
  44. },
  45. }
  46. command.AddCommand(
  47. upCommand(),
  48. downCommand(),
  49. psCommand(),
  50. logsCommand(),
  51. convertCommand(),
  52. )
  53. return command
  54. }
  55. func checkComposeSupport(ctx context.Context) error {
  56. c, err := client.New(ctx)
  57. if err == nil {
  58. composeService := c.ComposeService()
  59. if composeService == nil {
  60. return errors.New("compose not implemented in current context")
  61. }
  62. return nil
  63. }
  64. if errdefs.IsNotFoundError(err) {
  65. currentContext := apicontext.CurrentContext(ctx)
  66. s := store.ContextStore(ctx)
  67. cc, err := s.Get(currentContext)
  68. if err != nil {
  69. return err
  70. }
  71. if cc.Type() == store.AwsContextType {
  72. return errors.Errorf(`%q context type has been renamed. Recreate the context by running:
  73. $ docker context create %s <name>`, cc.Type(), store.EcsContextType)
  74. }
  75. return errors.Wrapf(errdefs.ErrNotImplemented, "compose command not supported on context type %q", cc.Type())
  76. }
  77. return err
  78. }