compose.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  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. project, err = project.WithSelectedServices(services)
  300. if err != nil {
  301. return nil, tracing.Metrics{}, err
  302. }
  303. if !o.All {
  304. project = project.WithoutUnnecessaryResources()
  305. }
  306. return project, metrics, err
  307. }
  308. func (o *ProjectOptions) remoteLoaders(dockerCli command.Cli) []loader.ResourceLoader {
  309. if o.Offline {
  310. return nil
  311. }
  312. git := remote.NewGitRemoteLoader(o.Offline)
  313. oci := remote.NewOCIRemoteLoader(dockerCli, o.Offline)
  314. return []loader.ResourceLoader{git, oci}
  315. }
  316. func (o *ProjectOptions) toProjectOptions(po ...cli.ProjectOptionsFn) (*cli.ProjectOptions, error) {
  317. return cli.NewProjectOptions(o.ConfigPaths,
  318. append(po,
  319. cli.WithWorkingDirectory(o.ProjectDir),
  320. // First apply os.Environment, always win
  321. cli.WithOsEnv,
  322. // Load PWD/.env if present and no explicit --env-file has been set
  323. cli.WithEnvFiles(o.EnvFiles...),
  324. // read dot env file to populate project environment
  325. cli.WithDotEnv,
  326. // get compose file path set by COMPOSE_FILE
  327. cli.WithConfigFileEnv,
  328. // if none was selected, get default compose.yaml file from current dir or parent folder
  329. cli.WithDefaultConfigPath,
  330. // .. and then, a project directory != PWD maybe has been set so let's load .env file
  331. cli.WithEnvFiles(o.EnvFiles...),
  332. cli.WithDotEnv,
  333. // eventually COMPOSE_PROFILES should have been set
  334. cli.WithDefaultProfiles(o.Profiles...),
  335. cli.WithName(o.ProjectName))...)
  336. }
  337. // PluginName is the name of the plugin
  338. const PluginName = "compose"
  339. // RunningAsStandalone detects when running as a standalone program
  340. func RunningAsStandalone() bool {
  341. return len(os.Args) < 2 || os.Args[1] != manager.MetadataSubcommandName && os.Args[1] != PluginName
  342. }
  343. // RootCommand returns the compose command with its child commands
  344. func RootCommand(dockerCli command.Cli, backend Backend) *cobra.Command { //nolint:gocyclo
  345. // filter out useless commandConn.CloseWrite warning message that can occur
  346. // when using a remote context that is unreachable: "commandConn.CloseWrite: commandconn: failed to wait: signal: killed"
  347. // https://github.com/docker/cli/blob/e1f24d3c93df6752d3c27c8d61d18260f141310c/cli/connhelper/commandconn/commandconn.go#L203-L215
  348. logrus.AddHook(logutil.NewFilter([]logrus.Level{
  349. logrus.WarnLevel,
  350. },
  351. "commandConn.CloseWrite:",
  352. "commandConn.CloseRead:",
  353. ))
  354. experiments := experimental.NewState()
  355. opts := ProjectOptions{}
  356. var (
  357. ansi string
  358. noAnsi bool
  359. verbose bool
  360. version bool
  361. parallel int
  362. dryRun bool
  363. )
  364. c := &cobra.Command{
  365. Short: "Docker Compose",
  366. Long: "Define and run multi-container applications with Docker",
  367. Use: PluginName,
  368. TraverseChildren: true,
  369. // By default (no Run/RunE in parent c) for typos in subcommands, cobra displays the help of parent c but exit(0) !
  370. RunE: func(cmd *cobra.Command, args []string) error {
  371. if len(args) == 0 {
  372. return cmd.Help()
  373. }
  374. if version {
  375. return versionCommand(dockerCli).Execute()
  376. }
  377. _ = cmd.Help()
  378. return dockercli.StatusError{
  379. StatusCode: compose.CommandSyntaxFailure.ExitCode,
  380. Status: fmt.Sprintf("unknown docker command: %q", "compose "+args[0]),
  381. }
  382. },
  383. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  384. ctx := cmd.Context()
  385. parent := cmd.Root()
  386. if parent != nil {
  387. parentPrerun := parent.PersistentPreRunE
  388. if parentPrerun != nil {
  389. err := parentPrerun(cmd, args)
  390. if err != nil {
  391. return err
  392. }
  393. }
  394. }
  395. if verbose {
  396. logrus.SetLevel(logrus.TraceLevel)
  397. }
  398. if noAnsi {
  399. if ansi != "auto" {
  400. return errors.New(`cannot specify DEPRECATED "--no-ansi" and "--ansi". Please use only "--ansi"`)
  401. }
  402. ansi = "never"
  403. fmt.Fprint(os.Stderr, "option '--no-ansi' is DEPRECATED ! Please use '--ansi' instead.\n")
  404. }
  405. if v, ok := os.LookupEnv("COMPOSE_ANSI"); ok && !cmd.Flags().Changed("ansi") {
  406. ansi = v
  407. }
  408. formatter.SetANSIMode(dockerCli, ansi)
  409. if noColor, ok := os.LookupEnv("NO_COLOR"); ok && noColor != "" {
  410. ui.NoColor()
  411. formatter.SetANSIMode(dockerCli, formatter.Never)
  412. }
  413. switch ansi {
  414. case "never":
  415. ui.Mode = ui.ModePlain
  416. case "always":
  417. ui.Mode = ui.ModeTTY
  418. }
  419. switch opts.Progress {
  420. case ui.ModeAuto:
  421. ui.Mode = ui.ModeAuto
  422. if ansi == "never" {
  423. ui.Mode = ui.ModePlain
  424. }
  425. case ui.ModeTTY:
  426. if ansi == "never" {
  427. return fmt.Errorf("can't use --progress tty while ANSI support is disabled")
  428. }
  429. ui.Mode = ui.ModeTTY
  430. case ui.ModePlain:
  431. if ansi == "always" {
  432. return fmt.Errorf("can't use --progress plain while ANSI support is forced")
  433. }
  434. ui.Mode = ui.ModePlain
  435. case ui.ModeQuiet, "none":
  436. ui.Mode = ui.ModeQuiet
  437. case ui.ModeJSON:
  438. ui.Mode = ui.ModeJSON
  439. logrus.SetFormatter(&logrus.JSONFormatter{})
  440. default:
  441. return fmt.Errorf("unsupported --progress value %q", opts.Progress)
  442. }
  443. // (4) options validation / normalization
  444. if opts.WorkDir != "" {
  445. if opts.ProjectDir != "" {
  446. return errors.New(`cannot specify DEPRECATED "--workdir" and "--project-directory". Please use only "--project-directory" instead`)
  447. }
  448. opts.ProjectDir = opts.WorkDir
  449. fmt.Fprint(os.Stderr, aec.Apply("option '--workdir' is DEPRECATED at root level! Please use '--project-directory' instead.\n", aec.RedF))
  450. }
  451. for i, file := range opts.EnvFiles {
  452. if !filepath.IsAbs(file) {
  453. file, err := filepath.Abs(file)
  454. if err != nil {
  455. return err
  456. }
  457. opts.EnvFiles[i] = file
  458. }
  459. }
  460. composeCmd := cmd
  461. for {
  462. if composeCmd.Name() == PluginName {
  463. break
  464. }
  465. if !composeCmd.HasParent() {
  466. return fmt.Errorf("error parsing command line, expected %q", PluginName)
  467. }
  468. composeCmd = composeCmd.Parent()
  469. }
  470. if v, ok := os.LookupEnv(ComposeParallelLimit); ok && !composeCmd.Flags().Changed("parallel") {
  471. i, err := strconv.Atoi(v)
  472. if err != nil {
  473. return fmt.Errorf("%s must be an integer (found: %q)", ComposeParallelLimit, v)
  474. }
  475. parallel = i
  476. }
  477. if parallel > 0 {
  478. logrus.Debugf("Limiting max concurrency to %d jobs", parallel)
  479. backend.MaxConcurrency(parallel)
  480. }
  481. // dry run detection
  482. ctx, err := backend.DryRunMode(ctx, dryRun)
  483. if err != nil {
  484. return err
  485. }
  486. cmd.SetContext(ctx)
  487. // (6) Desktop integration
  488. var desktopCli *desktop.Client
  489. if !dryRun {
  490. if desktopCli, err = desktop.NewFromDockerClient(ctx, dockerCli); desktopCli != nil {
  491. logrus.Debugf("Enabled Docker Desktop integration (experimental) @ %s", desktopCli.Endpoint())
  492. backend.SetDesktopClient(desktopCli)
  493. } else if err != nil {
  494. // not fatal, Compose will still work but behave as though
  495. // it's not running as part of Docker Desktop
  496. logrus.Debugf("failed to enable Docker Desktop integration: %v", err)
  497. } else {
  498. logrus.Trace("Docker Desktop integration not enabled")
  499. }
  500. }
  501. // (7) experimental features
  502. if err := experiments.Load(ctx, desktopCli); err != nil {
  503. logrus.Debugf("Failed to query feature flags from Desktop: %v", err)
  504. }
  505. backend.SetExperiments(experiments)
  506. return nil
  507. },
  508. }
  509. c.AddCommand(
  510. upCommand(&opts, dockerCli, backend, experiments),
  511. downCommand(&opts, dockerCli, backend),
  512. startCommand(&opts, dockerCli, backend),
  513. restartCommand(&opts, dockerCli, backend),
  514. stopCommand(&opts, dockerCli, backend),
  515. psCommand(&opts, dockerCli, backend),
  516. listCommand(dockerCli, backend),
  517. logsCommand(&opts, dockerCli, backend),
  518. configCommand(&opts, dockerCli),
  519. killCommand(&opts, dockerCli, backend),
  520. runCommand(&opts, dockerCli, backend),
  521. removeCommand(&opts, dockerCli, backend),
  522. execCommand(&opts, dockerCli, backend),
  523. attachCommand(&opts, dockerCli, backend),
  524. pauseCommand(&opts, dockerCli, backend),
  525. unpauseCommand(&opts, dockerCli, backend),
  526. topCommand(&opts, dockerCli, backend),
  527. eventsCommand(&opts, dockerCli, backend),
  528. portCommand(&opts, dockerCli, backend),
  529. imagesCommand(&opts, dockerCli, backend),
  530. versionCommand(dockerCli),
  531. buildCommand(&opts, dockerCli, backend),
  532. pushCommand(&opts, dockerCli, backend),
  533. pullCommand(&opts, dockerCli, backend),
  534. createCommand(&opts, dockerCli, backend),
  535. copyCommand(&opts, dockerCli, backend),
  536. waitCommand(&opts, dockerCli, backend),
  537. scaleCommand(&opts, dockerCli, backend),
  538. statsCommand(&opts, dockerCli),
  539. watchCommand(&opts, dockerCli, backend),
  540. alphaCommand(&opts, dockerCli, backend),
  541. )
  542. c.Flags().SetInterspersed(false)
  543. opts.addProjectFlags(c.Flags())
  544. c.RegisterFlagCompletionFunc( //nolint:errcheck
  545. "project-name",
  546. completeProjectNames(backend),
  547. )
  548. c.RegisterFlagCompletionFunc( //nolint:errcheck
  549. "project-directory",
  550. func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
  551. return []string{}, cobra.ShellCompDirectiveFilterDirs
  552. },
  553. )
  554. c.RegisterFlagCompletionFunc( //nolint:errcheck
  555. "file",
  556. func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
  557. return []string{"yaml", "yml"}, cobra.ShellCompDirectiveFilterFileExt
  558. },
  559. )
  560. c.RegisterFlagCompletionFunc( //nolint:errcheck
  561. "profile",
  562. completeProfileNames(dockerCli, &opts),
  563. )
  564. c.Flags().StringVar(&ansi, "ansi", "auto", `Control when to print ANSI control characters ("never"|"always"|"auto")`)
  565. c.Flags().IntVar(&parallel, "parallel", -1, `Control max parallelism, -1 for unlimited`)
  566. c.Flags().BoolVarP(&version, "version", "v", false, "Show the Docker Compose version information")
  567. c.PersistentFlags().BoolVar(&dryRun, "dry-run", false, "Execute command in dry run mode")
  568. c.Flags().MarkHidden("version") //nolint:errcheck
  569. c.Flags().BoolVar(&noAnsi, "no-ansi", false, `Do not print ANSI control characters (DEPRECATED)`)
  570. c.Flags().MarkHidden("no-ansi") //nolint:errcheck
  571. c.Flags().BoolVar(&verbose, "verbose", false, "Show more output")
  572. c.Flags().MarkHidden("verbose") //nolint:errcheck
  573. return c
  574. }
  575. var printerModes = []string{
  576. ui.ModeAuto,
  577. ui.ModeTTY,
  578. ui.ModePlain,
  579. ui.ModeJSON,
  580. ui.ModeQuiet,
  581. }
  582. func SetUnchangedOption(name string, experimentalFlag bool) bool {
  583. var value bool
  584. // If the var is defined we use that value first
  585. if envVar, ok := os.LookupEnv(name); ok {
  586. value = utils.StringToBool(envVar)
  587. } else {
  588. // if not, we try to get it from experimental feature flag
  589. value = experimentalFlag
  590. }
  591. return value
  592. }