compose.go 22 KB

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