compose.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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/spf13/cobra"
  18. "github.com/docker/compose-cli/client"
  19. "github.com/docker/compose-cli/errdefs"
  20. )
  21. type composeOptions struct {
  22. Name string
  23. WorkingDir string
  24. ConfigPaths []string
  25. Environment []string
  26. }
  27. func (o *composeOptions) toProjectName() (string, error) {
  28. if o.Name != "" {
  29. return o.Name, nil
  30. }
  31. options, err := o.toProjectOptions()
  32. if err != nil {
  33. return "", err
  34. }
  35. project, err := cli.ProjectFromOptions(options)
  36. if err != nil {
  37. return "", err
  38. }
  39. return project.Name, nil
  40. }
  41. func (o *composeOptions) toProjectOptions() (*cli.ProjectOptions, error) {
  42. return cli.NewProjectOptions(o.ConfigPaths,
  43. cli.WithOsEnv,
  44. cli.WithEnv(o.Environment),
  45. cli.WithWorkingDirectory(o.WorkingDir),
  46. cli.WithName(o.Name))
  47. }
  48. // Command returns the compose command with its child commands
  49. func Command() *cobra.Command {
  50. command := &cobra.Command{
  51. Short: "Docker Compose",
  52. Use: "compose",
  53. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  54. return checkComposeSupport(cmd.Context())
  55. },
  56. }
  57. command.AddCommand(
  58. upCommand(),
  59. downCommand(),
  60. psCommand(),
  61. logsCommand(),
  62. convertCommand(),
  63. )
  64. return command
  65. }
  66. func checkComposeSupport(ctx context.Context) error {
  67. _, err := client.New(ctx)
  68. if errdefs.IsNotFoundError(err) {
  69. return errdefs.ErrNotImplemented
  70. }
  71. return err
  72. }