compose.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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. "fmt"
  16. "os"
  17. "strings"
  18. "github.com/compose-spec/compose-go/cli"
  19. "github.com/compose-spec/compose-go/types"
  20. "github.com/morikuni/aec"
  21. "github.com/pkg/errors"
  22. "github.com/spf13/cobra"
  23. "github.com/spf13/pflag"
  24. "github.com/docker/compose-cli/api/context/store"
  25. "github.com/docker/compose-cli/cli/formatter"
  26. "github.com/docker/compose-cli/cli/metrics"
  27. )
  28. // Warning is a global warning to be displayed to user on command failure
  29. var Warning string
  30. type projectOptions struct {
  31. ProjectName string
  32. Profiles []string
  33. ConfigPaths []string
  34. WorkDir string
  35. ProjectDir string
  36. EnvFile string
  37. }
  38. func (o *projectOptions) addProjectFlags(f *pflag.FlagSet) {
  39. f.StringArrayVar(&o.Profiles, "profile", []string{}, "Specify a profile to enable")
  40. f.StringVarP(&o.ProjectName, "project-name", "p", "", "Project name")
  41. f.StringArrayVarP(&o.ConfigPaths, "file", "f", []string{}, "Compose configuration files")
  42. f.StringVar(&o.EnvFile, "env-file", "", "Specify an alternate environment file.")
  43. f.StringVar(&o.ProjectDir, "project-directory", "", "Specify an alternate working directory\n(default: the path of the Compose file)")
  44. f.StringVar(&o.WorkDir, "workdir", "", "DEPRECATED! USE --project-directory INSTEAD.\nSpecify an alternate working directory\n(default: the path of the Compose file)")
  45. _ = f.MarkHidden("workdir")
  46. }
  47. func (o *projectOptions) toProjectName() (string, error) {
  48. if o.ProjectName != "" {
  49. return o.ProjectName, nil
  50. }
  51. project, err := o.toProject(nil)
  52. if err != nil {
  53. return "", err
  54. }
  55. return project.Name, nil
  56. }
  57. func (o *projectOptions) toProject(services []string, po ...cli.ProjectOptionsFn) (*types.Project, error) {
  58. options, err := o.toProjectOptions(po...)
  59. if err != nil {
  60. return nil, err
  61. }
  62. project, err := cli.ProjectFromOptions(options)
  63. if err != nil {
  64. return nil, metrics.WrapComposeError(err)
  65. }
  66. s, err := project.GetServices(services...)
  67. if err != nil {
  68. return nil, err
  69. }
  70. o.Profiles = append(o.Profiles, s.GetProfiles()...)
  71. if profiles, ok := options.Environment["COMPOSE_PROFILES"]; ok {
  72. o.Profiles = append(o.Profiles, strings.Split(profiles, ",")...)
  73. }
  74. project.ApplyProfiles(o.Profiles)
  75. err = project.ForServices(services)
  76. return project, err
  77. }
  78. func (o *projectOptions) toProjectOptions(po ...cli.ProjectOptionsFn) (*cli.ProjectOptions, error) {
  79. return cli.NewProjectOptions(o.ConfigPaths,
  80. append(po,
  81. cli.WithEnvFile(o.EnvFile),
  82. cli.WithDotEnv,
  83. cli.WithOsEnv,
  84. cli.WithWorkingDirectory(o.ProjectDir),
  85. cli.WithName(o.ProjectName))...)
  86. }
  87. // Command returns the compose command with its child commands
  88. func Command(contextType string) *cobra.Command {
  89. opts := projectOptions{}
  90. var ansi string
  91. var noAnsi bool
  92. command := &cobra.Command{
  93. Short: "Docker Compose",
  94. Use: "compose",
  95. TraverseChildren: true,
  96. // By default (no Run/RunE in parent command) for typos in subcommands, cobra displays the help of parent command but exit(0) !
  97. RunE: func(cmd *cobra.Command, args []string) error {
  98. if len(args) == 0 {
  99. return cmd.Help()
  100. }
  101. _ = cmd.Help()
  102. return fmt.Errorf("unknown docker command: %q", "compose "+args[0])
  103. },
  104. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  105. if noAnsi {
  106. if ansi != "auto" {
  107. return errors.New(`cannot specify DEPRECATED "--no-ansi" and "--ansi". Please use only "--ansi"`)
  108. }
  109. ansi = "never"
  110. fmt.Fprint(os.Stderr, aec.Apply("option '--no-ansi' is DEPRECATED ! Please use '--ansi' instead.\n", aec.RedF))
  111. }
  112. formatter.SetANSIMode(ansi)
  113. if opts.WorkDir != "" {
  114. if opts.ProjectDir != "" {
  115. return errors.New(`cannot specify DEPRECATED "--workdir" and "--project-directory". Please use only "--project-directory" instead`)
  116. }
  117. opts.ProjectDir = opts.WorkDir
  118. fmt.Fprint(os.Stderr, aec.Apply("option '--workdir' is DEPRECATED at root level! Please use '--project-directory' instead.\n", aec.RedF))
  119. }
  120. if contextType == store.DefaultContextType || contextType == store.LocalContextType {
  121. Warning = "The new 'docker compose' command is currently experimental. " +
  122. "To provide feedback or request new features please open issues at https://github.com/docker/compose-cli"
  123. }
  124. return nil
  125. },
  126. }
  127. command.AddCommand(
  128. upCommand(&opts, contextType),
  129. downCommand(&opts, contextType),
  130. startCommand(&opts),
  131. restartCommand(&opts),
  132. stopCommand(&opts),
  133. psCommand(&opts),
  134. listCommand(contextType),
  135. logsCommand(&opts, contextType),
  136. convertCommand(&opts),
  137. killCommand(&opts),
  138. runCommand(&opts),
  139. removeCommand(&opts),
  140. execCommand(&opts),
  141. pauseCommand(&opts),
  142. unpauseCommand(&opts),
  143. topCommand(&opts),
  144. eventsCommand(&opts),
  145. portCommand(&opts),
  146. imagesCommand(&opts),
  147. versionCommand(),
  148. )
  149. if contextType == store.LocalContextType || contextType == store.DefaultContextType {
  150. command.AddCommand(
  151. buildCommand(&opts),
  152. pushCommand(&opts),
  153. pullCommand(&opts),
  154. createCommand(&opts),
  155. )
  156. }
  157. command.Flags().SetInterspersed(false)
  158. opts.addProjectFlags(command.Flags())
  159. command.Flags().StringVar(&ansi, "ansi", "auto", `Control when to print ANSI control characters ("never"|"always"|"auto")`)
  160. command.Flags().BoolVar(&noAnsi, "no-ansi", false, `Do not print ANSI control characters (DEPRECATED)`)
  161. command.Flags().MarkHidden("no-ansi") //nolint:errcheck
  162. return command
  163. }