compose.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  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/metadata"
  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. "github.com/morikuni/aec"
  45. "github.com/sirupsen/logrus"
  46. "github.com/spf13/cobra"
  47. "github.com/spf13/pflag"
  48. )
  49. const (
  50. // ComposeParallelLimit set the limit running concurrent operation on docker engine
  51. ComposeParallelLimit = "COMPOSE_PARALLEL_LIMIT"
  52. // ComposeProjectName define the project name to be used, instead of guessing from parent directory
  53. ComposeProjectName = "COMPOSE_PROJECT_NAME"
  54. // ComposeCompatibility try to mimic compose v1 as much as possible
  55. ComposeCompatibility = "COMPOSE_COMPATIBILITY"
  56. // ComposeRemoveOrphans remove "orphaned" containers, i.e. containers tagged for current project but not declared as service
  57. ComposeRemoveOrphans = "COMPOSE_REMOVE_ORPHANS"
  58. // ComposeIgnoreOrphans ignore "orphaned" containers
  59. ComposeIgnoreOrphans = "COMPOSE_IGNORE_ORPHANS"
  60. // ComposeEnvFiles defines the env files to use if --env-file isn't used
  61. ComposeEnvFiles = "COMPOSE_ENV_FILES"
  62. // ComposeMenu defines if the navigation menu should be rendered. Can be also set via --menu
  63. ComposeMenu = "COMPOSE_MENU"
  64. // ComposeProgress defines type of progress output, if --progress isn't used
  65. ComposeProgress = "COMPOSE_PROGRESS"
  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, vars map[string]string, lookup func(key string) (string, bool)) error {
  69. lines, err := kvfile.ParseFromReader(r, lookup)
  70. if err != nil {
  71. return fmt.Errorf("failed to parse env_file %s: %w", filename, err)
  72. }
  73. for _, line := range lines {
  74. key, value, _ := strings.Cut(line, "=")
  75. vars[key] = value
  76. }
  77. return 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", os.Getenv(ComposeProgress), 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, cli.WithoutEnvironmentResolution)
  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. opts := []cli.ProjectOptionsFn{
  335. cli.WithWorkingDirectory(o.ProjectDir),
  336. // First apply os.Environment, always win
  337. cli.WithOsEnv,
  338. }
  339. if _, present := os.LookupEnv("PWD"); !present {
  340. if pwd, err := os.Getwd(); err != nil {
  341. return nil, err
  342. } else {
  343. opts = append(opts, cli.WithEnv([]string{"PWD=" + pwd}))
  344. }
  345. }
  346. opts = append(opts,
  347. // Load PWD/.env if present and no explicit --env-file has been set
  348. cli.WithEnvFiles(o.EnvFiles...),
  349. // read dot env file to populate project environment
  350. cli.WithDotEnv,
  351. // get compose file path set by COMPOSE_FILE
  352. cli.WithConfigFileEnv,
  353. // if none was selected, get default compose.yaml file from current dir or parent folder
  354. cli.WithDefaultConfigPath,
  355. // .. and then, a project directory != PWD maybe has been set so let's load .env file
  356. cli.WithEnvFiles(o.EnvFiles...),
  357. cli.WithDotEnv,
  358. // eventually COMPOSE_PROFILES should have been set
  359. cli.WithDefaultProfiles(o.Profiles...),
  360. cli.WithName(o.ProjectName),
  361. )
  362. return cli.NewProjectOptions(o.ConfigPaths, append(po, opts...)...)
  363. }
  364. // PluginName is the name of the plugin
  365. const PluginName = "compose"
  366. // RunningAsStandalone detects when running as a standalone program
  367. func RunningAsStandalone() bool {
  368. return len(os.Args) < 2 || os.Args[1] != metadata.MetadataSubcommandName && os.Args[1] != PluginName
  369. }
  370. // RootCommand returns the compose command with its child commands
  371. func RootCommand(dockerCli command.Cli, backend Backend) *cobra.Command { //nolint:gocyclo
  372. // filter out useless commandConn.CloseWrite warning message that can occur
  373. // when using a remote context that is unreachable: "commandConn.CloseWrite: commandconn: failed to wait: signal: killed"
  374. // https://github.com/docker/cli/blob/e1f24d3c93df6752d3c27c8d61d18260f141310c/cli/connhelper/commandconn/commandconn.go#L203-L215
  375. logrus.AddHook(logutil.NewFilter([]logrus.Level{
  376. logrus.WarnLevel,
  377. },
  378. "commandConn.CloseWrite:",
  379. "commandConn.CloseRead:",
  380. ))
  381. experiments := experimental.NewState()
  382. opts := ProjectOptions{}
  383. var (
  384. ansi string
  385. noAnsi bool
  386. verbose bool
  387. version bool
  388. parallel int
  389. dryRun bool
  390. )
  391. c := &cobra.Command{
  392. Short: "Docker Compose",
  393. Long: "Define and run multi-container applications with Docker",
  394. Use: PluginName,
  395. TraverseChildren: true,
  396. // By default (no Run/RunE in parent c) for typos in subcommands, cobra displays the help of parent c but exit(0) !
  397. RunE: func(cmd *cobra.Command, args []string) error {
  398. if len(args) == 0 {
  399. return cmd.Help()
  400. }
  401. if version {
  402. return versionCommand(dockerCli).Execute()
  403. }
  404. _ = cmd.Help()
  405. return dockercli.StatusError{
  406. StatusCode: 1,
  407. Status: fmt.Sprintf("unknown docker command: %q", "compose "+args[0]),
  408. }
  409. },
  410. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  411. ctx := cmd.Context()
  412. parent := cmd.Root()
  413. if parent != nil {
  414. parentPrerun := parent.PersistentPreRunE
  415. if parentPrerun != nil {
  416. err := parentPrerun(cmd, args)
  417. if err != nil {
  418. return err
  419. }
  420. }
  421. }
  422. if verbose {
  423. logrus.SetLevel(logrus.TraceLevel)
  424. }
  425. err := setEnvWithDotEnv(opts)
  426. if err != nil {
  427. return err
  428. }
  429. if noAnsi {
  430. if ansi != "auto" {
  431. return errors.New(`cannot specify DEPRECATED "--no-ansi" and "--ansi". Please use only "--ansi"`)
  432. }
  433. ansi = "never"
  434. fmt.Fprint(os.Stderr, "option '--no-ansi' is DEPRECATED ! Please use '--ansi' instead.\n")
  435. }
  436. if v, ok := os.LookupEnv("COMPOSE_ANSI"); ok && !cmd.Flags().Changed("ansi") {
  437. ansi = v
  438. }
  439. formatter.SetANSIMode(dockerCli, ansi)
  440. if noColor, ok := os.LookupEnv("NO_COLOR"); ok && noColor != "" {
  441. ui.NoColor()
  442. formatter.SetANSIMode(dockerCli, formatter.Never)
  443. }
  444. switch ansi {
  445. case "never":
  446. ui.Mode = ui.ModePlain
  447. case "always":
  448. ui.Mode = ui.ModeTTY
  449. }
  450. switch opts.Progress {
  451. case "", ui.ModeAuto:
  452. if ansi == "never" {
  453. ui.Mode = ui.ModePlain
  454. }
  455. case ui.ModeTTY:
  456. if ansi == "never" {
  457. return fmt.Errorf("can't use --progress tty while ANSI support is disabled")
  458. }
  459. ui.Mode = ui.ModeTTY
  460. case ui.ModePlain:
  461. if ansi == "always" {
  462. return fmt.Errorf("can't use --progress plain while ANSI support is forced")
  463. }
  464. ui.Mode = ui.ModePlain
  465. case ui.ModeQuiet, "none":
  466. ui.Mode = ui.ModeQuiet
  467. case ui.ModeJSON:
  468. ui.Mode = ui.ModeJSON
  469. logrus.SetFormatter(&logrus.JSONFormatter{})
  470. default:
  471. return fmt.Errorf("unsupported --progress value %q", opts.Progress)
  472. }
  473. // (4) options validation / normalization
  474. if opts.WorkDir != "" {
  475. if opts.ProjectDir != "" {
  476. return errors.New(`cannot specify DEPRECATED "--workdir" and "--project-directory". Please use only "--project-directory" instead`)
  477. }
  478. opts.ProjectDir = opts.WorkDir
  479. fmt.Fprint(os.Stderr, aec.Apply("option '--workdir' is DEPRECATED at root level! Please use '--project-directory' instead.\n", aec.RedF))
  480. }
  481. for i, file := range opts.EnvFiles {
  482. if !filepath.IsAbs(file) {
  483. file, err := filepath.Abs(file)
  484. if err != nil {
  485. return err
  486. }
  487. opts.EnvFiles[i] = file
  488. }
  489. }
  490. composeCmd := cmd
  491. for composeCmd.Name() != PluginName {
  492. if !composeCmd.HasParent() {
  493. return fmt.Errorf("error parsing command line, expected %q", PluginName)
  494. }
  495. composeCmd = composeCmd.Parent()
  496. }
  497. if v, ok := os.LookupEnv(ComposeParallelLimit); ok && !composeCmd.Flags().Changed("parallel") {
  498. i, err := strconv.Atoi(v)
  499. if err != nil {
  500. return fmt.Errorf("%s must be an integer (found: %q)", ComposeParallelLimit, v)
  501. }
  502. parallel = i
  503. }
  504. if parallel > 0 {
  505. logrus.Debugf("Limiting max concurrency to %d jobs", parallel)
  506. backend.MaxConcurrency(parallel)
  507. }
  508. // dry run detection
  509. ctx, err = backend.DryRunMode(ctx, dryRun)
  510. if err != nil {
  511. return err
  512. }
  513. cmd.SetContext(ctx)
  514. // (6) Desktop integration
  515. var desktopCli *desktop.Client
  516. if !dryRun {
  517. if desktopCli, err = desktop.NewFromDockerClient(ctx, dockerCli); desktopCli != nil {
  518. logrus.Debugf("Enabled Docker Desktop integration (experimental) @ %s", desktopCli.Endpoint())
  519. backend.SetDesktopClient(desktopCli)
  520. } else if err != nil {
  521. // not fatal, Compose will still work but behave as though
  522. // it's not running as part of Docker Desktop
  523. logrus.Debugf("failed to enable Docker Desktop integration: %v", err)
  524. } else {
  525. logrus.Trace("Docker Desktop integration not enabled")
  526. }
  527. }
  528. // (7) experimental features
  529. if err := experiments.Load(ctx, desktopCli); err != nil {
  530. logrus.Debugf("Failed to query feature flags from Desktop: %v", err)
  531. }
  532. backend.SetExperiments(experiments)
  533. return nil
  534. },
  535. }
  536. c.AddCommand(
  537. upCommand(&opts, dockerCli, backend),
  538. downCommand(&opts, dockerCli, backend),
  539. startCommand(&opts, dockerCli, backend),
  540. restartCommand(&opts, dockerCli, backend),
  541. stopCommand(&opts, dockerCli, backend),
  542. psCommand(&opts, dockerCli, backend),
  543. listCommand(dockerCli, backend),
  544. logsCommand(&opts, dockerCli, backend),
  545. configCommand(&opts, dockerCli),
  546. killCommand(&opts, dockerCli, backend),
  547. runCommand(&opts, dockerCli, backend),
  548. removeCommand(&opts, dockerCli, backend),
  549. execCommand(&opts, dockerCli, backend),
  550. attachCommand(&opts, dockerCli, backend),
  551. exportCommand(&opts, dockerCli, backend),
  552. commitCommand(&opts, dockerCli, backend),
  553. pauseCommand(&opts, dockerCli, backend),
  554. unpauseCommand(&opts, dockerCli, backend),
  555. topCommand(&opts, dockerCli, backend),
  556. eventsCommand(&opts, dockerCli, backend),
  557. portCommand(&opts, dockerCli, backend),
  558. imagesCommand(&opts, dockerCli, backend),
  559. versionCommand(dockerCli),
  560. buildCommand(&opts, dockerCli, backend),
  561. pushCommand(&opts, dockerCli, backend),
  562. pullCommand(&opts, dockerCli, backend),
  563. createCommand(&opts, dockerCli, backend),
  564. copyCommand(&opts, dockerCli, backend),
  565. waitCommand(&opts, dockerCli, backend),
  566. scaleCommand(&opts, dockerCli, backend),
  567. statsCommand(&opts, dockerCli),
  568. watchCommand(&opts, dockerCli, backend),
  569. publishCommand(&opts, dockerCli, backend),
  570. alphaCommand(&opts, dockerCli, backend),
  571. bridgeCommand(&opts, dockerCli),
  572. volumesCommand(&opts, dockerCli, backend),
  573. )
  574. c.Flags().SetInterspersed(false)
  575. opts.addProjectFlags(c.Flags())
  576. c.RegisterFlagCompletionFunc( //nolint:errcheck
  577. "project-name",
  578. completeProjectNames(backend),
  579. )
  580. c.RegisterFlagCompletionFunc( //nolint:errcheck
  581. "project-directory",
  582. func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
  583. return []string{}, cobra.ShellCompDirectiveFilterDirs
  584. },
  585. )
  586. c.RegisterFlagCompletionFunc( //nolint:errcheck
  587. "file",
  588. func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
  589. return []string{"yaml", "yml"}, cobra.ShellCompDirectiveFilterFileExt
  590. },
  591. )
  592. c.RegisterFlagCompletionFunc( //nolint:errcheck
  593. "profile",
  594. completeProfileNames(dockerCli, &opts),
  595. )
  596. c.RegisterFlagCompletionFunc( //nolint:errcheck
  597. "progress",
  598. cobra.FixedCompletions(printerModes, cobra.ShellCompDirectiveNoFileComp),
  599. )
  600. c.Flags().StringVar(&ansi, "ansi", "auto", `Control when to print ANSI control characters ("never"|"always"|"auto")`)
  601. c.Flags().IntVar(&parallel, "parallel", -1, `Control max parallelism, -1 for unlimited`)
  602. c.Flags().BoolVarP(&version, "version", "v", false, "Show the Docker Compose version information")
  603. c.PersistentFlags().BoolVar(&dryRun, "dry-run", false, "Execute command in dry run mode")
  604. c.Flags().MarkHidden("version") //nolint:errcheck
  605. c.Flags().BoolVar(&noAnsi, "no-ansi", false, `Do not print ANSI control characters (DEPRECATED)`)
  606. c.Flags().MarkHidden("no-ansi") //nolint:errcheck
  607. c.Flags().BoolVar(&verbose, "verbose", false, "Show more output")
  608. c.Flags().MarkHidden("verbose") //nolint:errcheck
  609. return c
  610. }
  611. func setEnvWithDotEnv(opts ProjectOptions) error {
  612. options, err := cli.NewProjectOptions(opts.ConfigPaths,
  613. cli.WithWorkingDirectory(opts.ProjectDir),
  614. cli.WithOsEnv,
  615. cli.WithEnvFiles(opts.EnvFiles...),
  616. cli.WithDotEnv,
  617. )
  618. if err != nil {
  619. return nil
  620. }
  621. envFromFile, err := dotenv.GetEnvFromFile(composegoutils.GetAsEqualsMap(os.Environ()), options.EnvFiles)
  622. if err != nil {
  623. return nil
  624. }
  625. for k, v := range envFromFile {
  626. if _, ok := os.LookupEnv(k); !ok && strings.HasPrefix(k, "COMPOSE_") {
  627. if err = os.Setenv(k, v); err != nil {
  628. return nil
  629. }
  630. }
  631. }
  632. return err
  633. }
  634. var printerModes = []string{
  635. ui.ModeAuto,
  636. ui.ModeTTY,
  637. ui.ModePlain,
  638. ui.ModeJSON,
  639. ui.ModeQuiet,
  640. }
  641. func SetUnchangedOption(name string, experimentalFlag bool) bool {
  642. var value bool
  643. // If the var is defined we use that value first
  644. if envVar, ok := os.LookupEnv(name); ok {
  645. value = utils.StringToBool(envVar)
  646. } else {
  647. // if not, we try to get it from experimental feature flag
  648. value = experimentalFlag
  649. }
  650. return value
  651. }