compose.go 23 KB

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