compose.go 6.3 KB

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