compose.go 20 KB

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