compose.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  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. "encoding/json"
  17. "errors"
  18. "fmt"
  19. "os"
  20. "os/signal"
  21. "path/filepath"
  22. "strconv"
  23. "strings"
  24. "syscall"
  25. "github.com/compose-spec/compose-go/v2/cli"
  26. "github.com/compose-spec/compose-go/v2/loader"
  27. "github.com/compose-spec/compose-go/v2/types"
  28. "github.com/docker/buildx/util/logutil"
  29. dockercli "github.com/docker/cli/cli"
  30. "github.com/docker/cli/cli-plugins/manager"
  31. "github.com/docker/cli/cli/command"
  32. "github.com/docker/compose/v2/cmd/formatter"
  33. "github.com/docker/compose/v2/internal/desktop"
  34. "github.com/docker/compose/v2/internal/experimental"
  35. "github.com/docker/compose/v2/internal/tracing"
  36. "github.com/docker/compose/v2/pkg/api"
  37. "github.com/docker/compose/v2/pkg/compose"
  38. ui "github.com/docker/compose/v2/pkg/progress"
  39. "github.com/docker/compose/v2/pkg/remote"
  40. "github.com/docker/compose/v2/pkg/utils"
  41. buildkit "github.com/moby/buildkit/util/progress/progressui"
  42. "github.com/morikuni/aec"
  43. "github.com/sirupsen/logrus"
  44. "github.com/spf13/cobra"
  45. "github.com/spf13/pflag"
  46. )
  47. const (
  48. // ComposeParallelLimit set the limit running concurrent operation on docker engine
  49. ComposeParallelLimit = "COMPOSE_PARALLEL_LIMIT"
  50. // ComposeProjectName define the project name to be used, instead of guessing from parent directory
  51. ComposeProjectName = "COMPOSE_PROJECT_NAME"
  52. // ComposeCompatibility try to mimic compose v1 as much as possible
  53. ComposeCompatibility = "COMPOSE_COMPATIBILITY"
  54. // ComposeRemoveOrphans remove “orphaned" containers, i.e. containers tagged for current project but not declared as service
  55. ComposeRemoveOrphans = "COMPOSE_REMOVE_ORPHANS"
  56. // ComposeIgnoreOrphans ignore "orphaned" containers
  57. ComposeIgnoreOrphans = "COMPOSE_IGNORE_ORPHANS"
  58. // ComposeEnvFiles defines the env files to use if --env-file isn't used
  59. ComposeEnvFiles = "COMPOSE_ENV_FILES"
  60. // ComposeMenu defines if the navigation menu should be rendered. Can be also set via --menu
  61. ComposeMenu = "COMPOSE_MENU"
  62. )
  63. type Backend interface {
  64. api.Service
  65. SetDesktopClient(cli *desktop.Client)
  66. SetExperiments(experiments *experimental.State)
  67. }
  68. // Command defines a compose CLI command as a func with args
  69. type Command func(context.Context, []string) error
  70. // CobraCommand defines a cobra command function
  71. type CobraCommand func(context.Context, *cobra.Command, []string) error
  72. // AdaptCmd adapt a CobraCommand func to cobra library
  73. func AdaptCmd(fn CobraCommand) func(cmd *cobra.Command, args []string) error {
  74. return func(cmd *cobra.Command, args []string) error {
  75. ctx, cancel := context.WithCancel(cmd.Context())
  76. s := make(chan os.Signal, 1)
  77. signal.Notify(s, syscall.SIGTERM, syscall.SIGINT)
  78. go func() {
  79. <-s
  80. cancel()
  81. signal.Stop(s)
  82. close(s)
  83. }()
  84. err := fn(ctx, cmd, args)
  85. var composeErr compose.Error
  86. if api.IsErrCanceled(err) || errors.Is(ctx.Err(), context.Canceled) {
  87. err = dockercli.StatusError{
  88. StatusCode: 130,
  89. Status: compose.CanceledStatus,
  90. }
  91. }
  92. if errors.As(err, &composeErr) {
  93. err = dockercli.StatusError{
  94. StatusCode: composeErr.GetMetricsFailureCategory().ExitCode,
  95. Status: err.Error(),
  96. }
  97. }
  98. if ui.Mode == ui.ModeJSON {
  99. err = makeJSONError(err)
  100. }
  101. return err
  102. }
  103. }
  104. // Adapt a Command func to cobra library
  105. func Adapt(fn Command) func(cmd *cobra.Command, args []string) error {
  106. return AdaptCmd(func(ctx context.Context, cmd *cobra.Command, args []string) error {
  107. return fn(ctx, args)
  108. })
  109. }
  110. type ProjectOptions struct {
  111. ProjectName string
  112. Profiles []string
  113. ConfigPaths []string
  114. WorkDir string
  115. ProjectDir string
  116. EnvFiles []string
  117. Compatibility bool
  118. Progress string
  119. Offline bool
  120. All bool
  121. }
  122. // ProjectFunc does stuff within a types.Project
  123. type ProjectFunc func(ctx context.Context, project *types.Project) error
  124. // ProjectServicesFunc does stuff within a types.Project and a selection of services
  125. type ProjectServicesFunc func(ctx context.Context, project *types.Project, services []string) error
  126. // WithProject creates a cobra run command from a ProjectFunc based on configured project options and selected services
  127. func (o *ProjectOptions) WithProject(fn ProjectFunc, dockerCli command.Cli) func(cmd *cobra.Command, args []string) error {
  128. return o.WithServices(dockerCli, func(ctx context.Context, project *types.Project, services []string) error {
  129. return fn(ctx, project)
  130. })
  131. }
  132. // WithServices creates a cobra run command from a ProjectFunc based on configured project options and selected services
  133. func (o *ProjectOptions) WithServices(dockerCli command.Cli, fn ProjectServicesFunc) func(cmd *cobra.Command, args []string) error {
  134. return Adapt(func(ctx context.Context, args []string) error {
  135. options := []cli.ProjectOptionsFn{
  136. cli.WithResolvedPaths(true),
  137. cli.WithDiscardEnvFile,
  138. }
  139. project, metrics, err := o.ToProject(ctx, dockerCli, args, options...)
  140. if err != nil {
  141. return err
  142. }
  143. ctx = context.WithValue(ctx, tracing.MetricsKey{}, metrics)
  144. return fn(ctx, project, args)
  145. })
  146. }
  147. type jsonErrorData struct {
  148. Error bool `json:"error,omitempty"`
  149. Message string `json:"message,omitempty"`
  150. }
  151. func errorAsJSON(message string) string {
  152. errorMessage := &jsonErrorData{
  153. Error: true,
  154. Message: message,
  155. }
  156. marshal, err := json.Marshal(errorMessage)
  157. if err == nil {
  158. return string(marshal)
  159. } else {
  160. return message
  161. }
  162. }
  163. func makeJSONError(err error) error {
  164. if err == nil {
  165. return nil
  166. }
  167. var statusErr dockercli.StatusError
  168. if errors.As(err, &statusErr) {
  169. return dockercli.StatusError{
  170. StatusCode: statusErr.StatusCode,
  171. Status: errorAsJSON(statusErr.Status),
  172. }
  173. }
  174. return fmt.Errorf("%s", errorAsJSON(err.Error()))
  175. }
  176. func (o *ProjectOptions) addProjectFlags(f *pflag.FlagSet) {
  177. f.StringArrayVar(&o.Profiles, "profile", []string{}, "Specify a profile to enable")
  178. f.StringVarP(&o.ProjectName, "project-name", "p", "", "Project name")
  179. f.StringArrayVarP(&o.ConfigPaths, "file", "f", []string{}, "Compose configuration files")
  180. f.StringArrayVar(&o.EnvFiles, "env-file", defaultStringArrayVar(ComposeEnvFiles), "Specify an alternate environment file")
  181. f.StringVar(&o.ProjectDir, "project-directory", "", "Specify an alternate working directory\n(default: the path of the, first specified, Compose file)")
  182. f.StringVar(&o.WorkDir, "workdir", "", "DEPRECATED! USE --project-directory INSTEAD.\nSpecify an alternate working directory\n(default: the path of the, first specified, Compose file)")
  183. f.BoolVar(&o.Compatibility, "compatibility", false, "Run compose in backward compatibility mode")
  184. f.StringVar(&o.Progress, "progress", string(buildkit.AutoMode), fmt.Sprintf(`Set type of progress output (%s)`, strings.Join(printerModes, ", ")))
  185. f.BoolVar(&o.All, "all-resources", false, "Include all resources, even those not used by services")
  186. _ = f.MarkHidden("workdir")
  187. }
  188. // get default value for a command line flag that is set by a coma-separated value in environment variable
  189. func defaultStringArrayVar(env string) []string {
  190. return strings.FieldsFunc(os.Getenv(env), func(c rune) bool {
  191. return c == ','
  192. })
  193. }
  194. func (o *ProjectOptions) projectOrName(ctx context.Context, dockerCli command.Cli, services ...string) (*types.Project, string, error) {
  195. name := o.ProjectName
  196. var project *types.Project
  197. if len(o.ConfigPaths) > 0 || o.ProjectName == "" {
  198. p, _, err := o.ToProject(ctx, dockerCli, services, cli.WithDiscardEnvFile)
  199. if err != nil {
  200. envProjectName := os.Getenv(ComposeProjectName)
  201. if envProjectName != "" {
  202. return nil, envProjectName, nil
  203. }
  204. return nil, "", err
  205. }
  206. project = p
  207. name = p.Name
  208. }
  209. return project, name, nil
  210. }
  211. func (o *ProjectOptions) toProjectName(ctx context.Context, dockerCli command.Cli) (string, error) {
  212. if o.ProjectName != "" {
  213. return o.ProjectName, nil
  214. }
  215. envProjectName := os.Getenv(ComposeProjectName)
  216. if envProjectName != "" {
  217. return envProjectName, nil
  218. }
  219. project, _, err := o.ToProject(ctx, dockerCli, nil)
  220. if err != nil {
  221. return "", err
  222. }
  223. return project.Name, nil
  224. }
  225. func (o *ProjectOptions) ToModel(ctx context.Context, dockerCli command.Cli, services []string, po ...cli.ProjectOptionsFn) (map[string]any, error) {
  226. remotes := o.remoteLoaders(dockerCli)
  227. for _, r := range remotes {
  228. po = append(po, cli.WithResourceLoader(r))
  229. }
  230. options, err := o.toProjectOptions(po...)
  231. if err != nil {
  232. return nil, err
  233. }
  234. if o.Compatibility || utils.StringToBool(options.Environment[ComposeCompatibility]) {
  235. api.Separator = "_"
  236. }
  237. return options.LoadModel(ctx)
  238. }
  239. func (o *ProjectOptions) ToProject(ctx context.Context, dockerCli command.Cli, services []string, po ...cli.ProjectOptionsFn) (*types.Project, tracing.Metrics, error) { //nolint:gocyclo
  240. var metrics tracing.Metrics
  241. remotes := o.remoteLoaders(dockerCli)
  242. for _, r := range remotes {
  243. po = append(po, cli.WithResourceLoader(r))
  244. }
  245. options, err := o.toProjectOptions(po...)
  246. if err != nil {
  247. return nil, metrics, compose.WrapComposeError(err)
  248. }
  249. options.WithListeners(func(event string, metadata map[string]any) {
  250. switch event {
  251. case "extends":
  252. metrics.CountExtends++
  253. case "include":
  254. paths := metadata["path"].(types.StringList)
  255. for _, path := range paths {
  256. var isRemote bool
  257. for _, r := range remotes {
  258. if r.Accept(path) {
  259. isRemote = true
  260. break
  261. }
  262. }
  263. if isRemote {
  264. metrics.CountIncludesRemote++
  265. } else {
  266. metrics.CountIncludesLocal++
  267. }
  268. }
  269. }
  270. })
  271. if o.Compatibility || utils.StringToBool(options.Environment[ComposeCompatibility]) {
  272. api.Separator = "_"
  273. }
  274. project, err := options.LoadProject(ctx)
  275. if err != nil {
  276. return nil, metrics, compose.WrapComposeError(err)
  277. }
  278. if project.Name == "" {
  279. return nil, metrics, errors.New("project name can't be empty. Use `--project-name` to set a valid name")
  280. }
  281. project, err = project.WithServicesEnabled(services...)
  282. if err != nil {
  283. return nil, metrics, err
  284. }
  285. for name, s := range project.Services {
  286. s.CustomLabels = map[string]string{
  287. api.ProjectLabel: project.Name,
  288. api.ServiceLabel: name,
  289. api.VersionLabel: api.ComposeVersion,
  290. api.WorkingDirLabel: project.WorkingDir,
  291. api.ConfigFilesLabel: strings.Join(project.ComposeFiles, ","),
  292. api.OneoffLabel: "False", // default, will be overridden by `run` command
  293. }
  294. if len(o.EnvFiles) != 0 {
  295. s.CustomLabels[api.EnvironmentFileLabel] = strings.Join(o.EnvFiles, ",")
  296. }
  297. project.Services[name] = s
  298. }
  299. if !o.All {
  300. project = project.WithoutUnnecessaryResources()
  301. }
  302. project, err = project.WithSelectedServices(services)
  303. return project, metrics, err
  304. }
  305. func (o *ProjectOptions) remoteLoaders(dockerCli command.Cli) []loader.ResourceLoader {
  306. if o.Offline {
  307. return nil
  308. }
  309. git := remote.NewGitRemoteLoader(o.Offline)
  310. oci := remote.NewOCIRemoteLoader(dockerCli, o.Offline)
  311. return []loader.ResourceLoader{git, oci}
  312. }
  313. func (o *ProjectOptions) toProjectOptions(po ...cli.ProjectOptionsFn) (*cli.ProjectOptions, error) {
  314. return cli.NewProjectOptions(o.ConfigPaths,
  315. append(po,
  316. cli.WithWorkingDirectory(o.ProjectDir),
  317. // First apply os.Environment, always win
  318. cli.WithOsEnv,
  319. // Load PWD/.env if present and no explicit --env-file has been set
  320. cli.WithEnvFiles(o.EnvFiles...),
  321. // read dot env file to populate project environment
  322. cli.WithDotEnv,
  323. // get compose file path set by COMPOSE_FILE
  324. cli.WithConfigFileEnv,
  325. // if none was selected, get default compose.yaml file from current dir or parent folder
  326. cli.WithDefaultConfigPath,
  327. // .. and then, a project directory != PWD maybe has been set so let's load .env file
  328. cli.WithEnvFiles(o.EnvFiles...),
  329. cli.WithDotEnv,
  330. // eventually COMPOSE_PROFILES should have been set
  331. cli.WithDefaultProfiles(o.Profiles...),
  332. cli.WithName(o.ProjectName))...)
  333. }
  334. // PluginName is the name of the plugin
  335. const PluginName = "compose"
  336. // RunningAsStandalone detects when running as a standalone program
  337. func RunningAsStandalone() bool {
  338. return len(os.Args) < 2 || os.Args[1] != manager.MetadataSubcommandName && os.Args[1] != PluginName
  339. }
  340. // RootCommand returns the compose command with its child commands
  341. func RootCommand(dockerCli command.Cli, backend Backend) *cobra.Command { //nolint:gocyclo
  342. // filter out useless commandConn.CloseWrite warning message that can occur
  343. // when using a remote context that is unreachable: "commandConn.CloseWrite: commandconn: failed to wait: signal: killed"
  344. // https://github.com/docker/cli/blob/e1f24d3c93df6752d3c27c8d61d18260f141310c/cli/connhelper/commandconn/commandconn.go#L203-L215
  345. logrus.AddHook(logutil.NewFilter([]logrus.Level{
  346. logrus.WarnLevel,
  347. },
  348. "commandConn.CloseWrite:",
  349. "commandConn.CloseRead:",
  350. ))
  351. experiments := experimental.NewState()
  352. opts := ProjectOptions{}
  353. var (
  354. ansi string
  355. noAnsi bool
  356. verbose bool
  357. version bool
  358. parallel int
  359. dryRun bool
  360. )
  361. c := &cobra.Command{
  362. Short: "Docker Compose",
  363. Long: "Define and run multi-container applications with Docker",
  364. Use: PluginName,
  365. TraverseChildren: true,
  366. // By default (no Run/RunE in parent c) for typos in subcommands, cobra displays the help of parent c but exit(0) !
  367. RunE: func(cmd *cobra.Command, args []string) error {
  368. if len(args) == 0 {
  369. return cmd.Help()
  370. }
  371. if version {
  372. return versionCommand(dockerCli).Execute()
  373. }
  374. _ = cmd.Help()
  375. return dockercli.StatusError{
  376. StatusCode: compose.CommandSyntaxFailure.ExitCode,
  377. Status: fmt.Sprintf("unknown docker command: %q", "compose "+args[0]),
  378. }
  379. },
  380. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  381. ctx := cmd.Context()
  382. parent := cmd.Root()
  383. if parent != nil {
  384. parentPrerun := parent.PersistentPreRunE
  385. if parentPrerun != nil {
  386. err := parentPrerun(cmd, args)
  387. if err != nil {
  388. return err
  389. }
  390. }
  391. }
  392. if verbose {
  393. logrus.SetLevel(logrus.TraceLevel)
  394. }
  395. if noAnsi {
  396. if ansi != "auto" {
  397. return errors.New(`cannot specify DEPRECATED "--no-ansi" and "--ansi". Please use only "--ansi"`)
  398. }
  399. ansi = "never"
  400. fmt.Fprint(os.Stderr, "option '--no-ansi' is DEPRECATED ! Please use '--ansi' instead.\n")
  401. }
  402. if v, ok := os.LookupEnv("COMPOSE_ANSI"); ok && !cmd.Flags().Changed("ansi") {
  403. ansi = v
  404. }
  405. formatter.SetANSIMode(dockerCli, ansi)
  406. if noColor, ok := os.LookupEnv("NO_COLOR"); ok && noColor != "" {
  407. ui.NoColor()
  408. formatter.SetANSIMode(dockerCli, formatter.Never)
  409. }
  410. switch ansi {
  411. case "never":
  412. ui.Mode = ui.ModePlain
  413. case "always":
  414. ui.Mode = ui.ModeTTY
  415. }
  416. switch opts.Progress {
  417. case ui.ModeAuto:
  418. ui.Mode = ui.ModeAuto
  419. if ansi == "never" {
  420. ui.Mode = ui.ModePlain
  421. }
  422. case ui.ModeTTY:
  423. if ansi == "never" {
  424. return fmt.Errorf("can't use --progress tty while ANSI support is disabled")
  425. }
  426. ui.Mode = ui.ModeTTY
  427. case ui.ModePlain:
  428. if ansi == "always" {
  429. return fmt.Errorf("can't use --progress plain while ANSI support is forced")
  430. }
  431. ui.Mode = ui.ModePlain
  432. case ui.ModeQuiet, "none":
  433. ui.Mode = ui.ModeQuiet
  434. case ui.ModeJSON:
  435. ui.Mode = ui.ModeJSON
  436. default:
  437. return fmt.Errorf("unsupported --progress value %q", opts.Progress)
  438. }
  439. // (4) options validation / normalization
  440. if opts.WorkDir != "" {
  441. if opts.ProjectDir != "" {
  442. return errors.New(`cannot specify DEPRECATED "--workdir" and "--project-directory". Please use only "--project-directory" instead`)
  443. }
  444. opts.ProjectDir = opts.WorkDir
  445. fmt.Fprint(os.Stderr, aec.Apply("option '--workdir' is DEPRECATED at root level! Please use '--project-directory' instead.\n", aec.RedF))
  446. }
  447. for i, file := range opts.EnvFiles {
  448. if !filepath.IsAbs(file) {
  449. file, err := filepath.Abs(file)
  450. if err != nil {
  451. return err
  452. }
  453. opts.EnvFiles[i] = file
  454. }
  455. }
  456. composeCmd := cmd
  457. for {
  458. if composeCmd.Name() == PluginName {
  459. break
  460. }
  461. if !composeCmd.HasParent() {
  462. return fmt.Errorf("error parsing command line, expected %q", PluginName)
  463. }
  464. composeCmd = composeCmd.Parent()
  465. }
  466. if v, ok := os.LookupEnv(ComposeParallelLimit); ok && !composeCmd.Flags().Changed("parallel") {
  467. i, err := strconv.Atoi(v)
  468. if err != nil {
  469. return fmt.Errorf("%s must be an integer (found: %q)", ComposeParallelLimit, v)
  470. }
  471. parallel = i
  472. }
  473. if parallel > 0 {
  474. logrus.Debugf("Limiting max concurrency to %d jobs", parallel)
  475. backend.MaxConcurrency(parallel)
  476. }
  477. // dry run detection
  478. ctx, err := backend.DryRunMode(ctx, dryRun)
  479. if err != nil {
  480. return err
  481. }
  482. cmd.SetContext(ctx)
  483. // (6) Desktop integration
  484. var desktopCli *desktop.Client
  485. if !dryRun {
  486. if desktopCli, err = desktop.NewFromDockerClient(ctx, dockerCli); desktopCli != nil {
  487. logrus.Debugf("Enabled Docker Desktop integration (experimental) @ %s", desktopCli.Endpoint())
  488. backend.SetDesktopClient(desktopCli)
  489. } else if err != nil {
  490. // not fatal, Compose will still work but behave as though
  491. // it's not running as part of Docker Desktop
  492. logrus.Debugf("failed to enable Docker Desktop integration: %v", err)
  493. } else {
  494. logrus.Trace("Docker Desktop integration not enabled")
  495. }
  496. }
  497. // (7) experimental features
  498. if err := experiments.Load(ctx, desktopCli); err != nil {
  499. logrus.Debugf("Failed to query feature flags from Desktop: %v", err)
  500. }
  501. backend.SetExperiments(experiments)
  502. return nil
  503. },
  504. }
  505. c.AddCommand(
  506. upCommand(&opts, dockerCli, backend, experiments),
  507. downCommand(&opts, dockerCli, backend),
  508. startCommand(&opts, dockerCli, backend),
  509. restartCommand(&opts, dockerCli, backend),
  510. stopCommand(&opts, dockerCli, backend),
  511. psCommand(&opts, dockerCli, backend),
  512. listCommand(dockerCli, backend),
  513. logsCommand(&opts, dockerCli, backend),
  514. configCommand(&opts, dockerCli),
  515. killCommand(&opts, dockerCli, backend),
  516. runCommand(&opts, dockerCli, backend),
  517. removeCommand(&opts, dockerCli, backend),
  518. execCommand(&opts, dockerCli, backend),
  519. attachCommand(&opts, dockerCli, backend),
  520. pauseCommand(&opts, dockerCli, backend),
  521. unpauseCommand(&opts, dockerCli, backend),
  522. topCommand(&opts, dockerCli, backend),
  523. eventsCommand(&opts, dockerCli, backend),
  524. portCommand(&opts, dockerCli, backend),
  525. imagesCommand(&opts, dockerCli, backend),
  526. versionCommand(dockerCli),
  527. buildCommand(&opts, dockerCli, backend),
  528. pushCommand(&opts, dockerCli, backend),
  529. pullCommand(&opts, dockerCli, backend),
  530. createCommand(&opts, dockerCli, backend),
  531. copyCommand(&opts, dockerCli, backend),
  532. waitCommand(&opts, dockerCli, backend),
  533. scaleCommand(&opts, dockerCli, backend),
  534. statsCommand(&opts, dockerCli),
  535. watchCommand(&opts, dockerCli, backend),
  536. alphaCommand(&opts, dockerCli, backend),
  537. )
  538. c.Flags().SetInterspersed(false)
  539. opts.addProjectFlags(c.Flags())
  540. c.RegisterFlagCompletionFunc( //nolint:errcheck
  541. "project-name",
  542. completeProjectNames(backend),
  543. )
  544. c.RegisterFlagCompletionFunc( //nolint:errcheck
  545. "project-directory",
  546. func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
  547. return []string{}, cobra.ShellCompDirectiveFilterDirs
  548. },
  549. )
  550. c.RegisterFlagCompletionFunc( //nolint:errcheck
  551. "file",
  552. func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
  553. return []string{"yaml", "yml"}, cobra.ShellCompDirectiveFilterFileExt
  554. },
  555. )
  556. c.RegisterFlagCompletionFunc( //nolint:errcheck
  557. "profile",
  558. completeProfileNames(dockerCli, &opts),
  559. )
  560. c.Flags().StringVar(&ansi, "ansi", "auto", `Control when to print ANSI control characters ("never"|"always"|"auto")`)
  561. c.Flags().IntVar(&parallel, "parallel", -1, `Control max parallelism, -1 for unlimited`)
  562. c.Flags().BoolVarP(&version, "version", "v", false, "Show the Docker Compose version information")
  563. c.PersistentFlags().BoolVar(&dryRun, "dry-run", false, "Execute command in dry run mode")
  564. c.Flags().MarkHidden("version") //nolint:errcheck
  565. c.Flags().BoolVar(&noAnsi, "no-ansi", false, `Do not print ANSI control characters (DEPRECATED)`)
  566. c.Flags().MarkHidden("no-ansi") //nolint:errcheck
  567. c.Flags().BoolVar(&verbose, "verbose", false, "Show more output")
  568. c.Flags().MarkHidden("verbose") //nolint:errcheck
  569. return c
  570. }
  571. var printerModes = []string{
  572. ui.ModeAuto,
  573. ui.ModeTTY,
  574. ui.ModePlain,
  575. ui.ModeJSON,
  576. ui.ModeQuiet,
  577. }
  578. func SetUnchangedOption(name string, experimentalFlag bool) bool {
  579. var value bool
  580. // If the var is defined we use that value first
  581. if envVar, ok := os.LookupEnv(name); ok {
  582. value = utils.StringToBool(envVar)
  583. } else {
  584. // if not, we try to get it from experimental feature flag
  585. value = experimentalFlag
  586. }
  587. return value
  588. }