compose.go 20 KB

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