compose.go 21 KB

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