1
0

compose.go 22 KB

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