compose.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. )
  52. return command
  53. }
  54. func checkComposeSupport(ctx context.Context) error {
  55. c, err := client.New(ctx)
  56. if err == nil {
  57. composeService := c.ComposeService()
  58. if composeService == nil {
  59. return errors.New("compose not implemented in current context")
  60. }
  61. return nil
  62. }
  63. currentContext := apicontext.CurrentContext(ctx)
  64. s := store.ContextStore(ctx)
  65. cc, err := s.Get(currentContext)
  66. if err != nil {
  67. return err
  68. }
  69. switch cc.Type() {
  70. case store.AwsContextType:
  71. return errors.New("use 'docker ecs compose' on context type " + cc.Type())
  72. default:
  73. return errors.Wrapf(errdefs.ErrNotImplemented, "compose command not supported on context type %q", cc.Type())
  74. }
  75. }