compose.go 20 KB

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