compose.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  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)
  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. pwd, err := os.Getwd()
  335. if err != nil {
  336. return nil, err
  337. }
  338. return cli.NewProjectOptions(o.ConfigPaths,
  339. append(po,
  340. cli.WithWorkingDirectory(o.ProjectDir),
  341. // First apply os.Environment, always win
  342. cli.WithOsEnv,
  343. // set PWD as this variable is not consistently supported on Windows
  344. cli.WithEnv([]string{"PWD=" + pwd}),
  345. // Load PWD/.env if present and no explicit --env-file has been set
  346. cli.WithEnvFiles(o.EnvFiles...),
  347. // read dot env file to populate project environment
  348. cli.WithDotEnv,
  349. // get compose file path set by COMPOSE_FILE
  350. cli.WithConfigFileEnv,
  351. // if none was selected, get default compose.yaml file from current dir or parent folder
  352. cli.WithDefaultConfigPath,
  353. // .. and then, a project directory != PWD maybe has been set so let's load .env file
  354. cli.WithEnvFiles(o.EnvFiles...),
  355. cli.WithDotEnv,
  356. // eventually COMPOSE_PROFILES should have been set
  357. cli.WithDefaultProfiles(o.Profiles...),
  358. cli.WithName(o.ProjectName))...)
  359. }
  360. // PluginName is the name of the plugin
  361. const PluginName = "compose"
  362. // RunningAsStandalone detects when running as a standalone program
  363. func RunningAsStandalone() bool {
  364. return len(os.Args) < 2 || os.Args[1] != metadata.MetadataSubcommandName && os.Args[1] != PluginName
  365. }
  366. // RootCommand returns the compose command with its child commands
  367. func RootCommand(dockerCli command.Cli, backend Backend) *cobra.Command { //nolint:gocyclo
  368. // filter out useless commandConn.CloseWrite warning message that can occur
  369. // when using a remote context that is unreachable: "commandConn.CloseWrite: commandconn: failed to wait: signal: killed"
  370. // https://github.com/docker/cli/blob/e1f24d3c93df6752d3c27c8d61d18260f141310c/cli/connhelper/commandconn/commandconn.go#L203-L215
  371. logrus.AddHook(logutil.NewFilter([]logrus.Level{
  372. logrus.WarnLevel,
  373. },
  374. "commandConn.CloseWrite:",
  375. "commandConn.CloseRead:",
  376. ))
  377. experiments := experimental.NewState()
  378. opts := ProjectOptions{}
  379. var (
  380. ansi string
  381. noAnsi bool
  382. verbose bool
  383. version bool
  384. parallel int
  385. dryRun bool
  386. )
  387. c := &cobra.Command{
  388. Short: "Docker Compose",
  389. Long: "Define and run multi-container applications with Docker",
  390. Use: PluginName,
  391. TraverseChildren: true,
  392. // By default (no Run/RunE in parent c) for typos in subcommands, cobra displays the help of parent c but exit(0) !
  393. RunE: func(cmd *cobra.Command, args []string) error {
  394. if len(args) == 0 {
  395. return cmd.Help()
  396. }
  397. if version {
  398. return versionCommand(dockerCli).Execute()
  399. }
  400. _ = cmd.Help()
  401. return dockercli.StatusError{
  402. StatusCode: 1,
  403. Status: fmt.Sprintf("unknown docker command: %q", "compose "+args[0]),
  404. }
  405. },
  406. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  407. ctx := cmd.Context()
  408. parent := cmd.Root()
  409. if parent != nil {
  410. parentPrerun := parent.PersistentPreRunE
  411. if parentPrerun != nil {
  412. err := parentPrerun(cmd, args)
  413. if err != nil {
  414. return err
  415. }
  416. }
  417. }
  418. if verbose {
  419. logrus.SetLevel(logrus.TraceLevel)
  420. }
  421. err := setEnvWithDotEnv(opts)
  422. if err != nil {
  423. return err
  424. }
  425. if noAnsi {
  426. if ansi != "auto" {
  427. return errors.New(`cannot specify DEPRECATED "--no-ansi" and "--ansi". Please use only "--ansi"`)
  428. }
  429. ansi = "never"
  430. fmt.Fprint(os.Stderr, "option '--no-ansi' is DEPRECATED ! Please use '--ansi' instead.\n")
  431. }
  432. if v, ok := os.LookupEnv("COMPOSE_ANSI"); ok && !cmd.Flags().Changed("ansi") {
  433. ansi = v
  434. }
  435. formatter.SetANSIMode(dockerCli, ansi)
  436. if noColor, ok := os.LookupEnv("NO_COLOR"); ok && noColor != "" {
  437. ui.NoColor()
  438. formatter.SetANSIMode(dockerCli, formatter.Never)
  439. }
  440. switch ansi {
  441. case "never":
  442. ui.Mode = ui.ModePlain
  443. case "always":
  444. ui.Mode = ui.ModeTTY
  445. }
  446. switch opts.Progress {
  447. case "", 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 composeCmd.Name() != PluginName {
  488. if !composeCmd.HasParent() {
  489. return fmt.Errorf("error parsing command line, expected %q", PluginName)
  490. }
  491. composeCmd = composeCmd.Parent()
  492. }
  493. if v, ok := os.LookupEnv(ComposeParallelLimit); ok && !composeCmd.Flags().Changed("parallel") {
  494. i, err := strconv.Atoi(v)
  495. if err != nil {
  496. return fmt.Errorf("%s must be an integer (found: %q)", ComposeParallelLimit, v)
  497. }
  498. parallel = i
  499. }
  500. if parallel > 0 {
  501. logrus.Debugf("Limiting max concurrency to %d jobs", parallel)
  502. backend.MaxConcurrency(parallel)
  503. }
  504. // dry run detection
  505. ctx, err = backend.DryRunMode(ctx, dryRun)
  506. if err != nil {
  507. return err
  508. }
  509. cmd.SetContext(ctx)
  510. // (6) Desktop integration
  511. var desktopCli *desktop.Client
  512. if !dryRun {
  513. if desktopCli, err = desktop.NewFromDockerClient(ctx, dockerCli); desktopCli != nil {
  514. logrus.Debugf("Enabled Docker Desktop integration (experimental) @ %s", desktopCli.Endpoint())
  515. backend.SetDesktopClient(desktopCli)
  516. } else if err != nil {
  517. // not fatal, Compose will still work but behave as though
  518. // it's not running as part of Docker Desktop
  519. logrus.Debugf("failed to enable Docker Desktop integration: %v", err)
  520. } else {
  521. logrus.Trace("Docker Desktop integration not enabled")
  522. }
  523. }
  524. // (7) experimental features
  525. if err := experiments.Load(ctx, desktopCli); err != nil {
  526. logrus.Debugf("Failed to query feature flags from Desktop: %v", err)
  527. }
  528. backend.SetExperiments(experiments)
  529. return nil
  530. },
  531. }
  532. c.AddCommand(
  533. upCommand(&opts, dockerCli, backend),
  534. downCommand(&opts, dockerCli, backend),
  535. startCommand(&opts, dockerCli, backend),
  536. restartCommand(&opts, dockerCli, backend),
  537. stopCommand(&opts, dockerCli, backend),
  538. psCommand(&opts, dockerCli, backend),
  539. listCommand(dockerCli, backend),
  540. logsCommand(&opts, dockerCli, backend),
  541. configCommand(&opts, dockerCli),
  542. killCommand(&opts, dockerCli, backend),
  543. runCommand(&opts, dockerCli, backend),
  544. removeCommand(&opts, dockerCli, backend),
  545. execCommand(&opts, dockerCli, backend),
  546. attachCommand(&opts, dockerCli, backend),
  547. exportCommand(&opts, dockerCli, backend),
  548. commitCommand(&opts, dockerCli, backend),
  549. pauseCommand(&opts, dockerCli, backend),
  550. unpauseCommand(&opts, dockerCli, backend),
  551. topCommand(&opts, dockerCli, backend),
  552. eventsCommand(&opts, dockerCli, backend),
  553. portCommand(&opts, dockerCli, backend),
  554. imagesCommand(&opts, dockerCli, backend),
  555. versionCommand(dockerCli),
  556. buildCommand(&opts, dockerCli, backend),
  557. pushCommand(&opts, dockerCli, backend),
  558. pullCommand(&opts, dockerCli, backend),
  559. createCommand(&opts, dockerCli, backend),
  560. copyCommand(&opts, dockerCli, backend),
  561. waitCommand(&opts, dockerCli, backend),
  562. scaleCommand(&opts, dockerCli, backend),
  563. statsCommand(&opts, dockerCli),
  564. watchCommand(&opts, dockerCli, backend),
  565. publishCommand(&opts, dockerCli, backend),
  566. alphaCommand(&opts, dockerCli, backend),
  567. bridgeCommand(&opts, dockerCli),
  568. volumesCommand(&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. }