compose.go 2.1 KB

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