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. ui "github.com/docker/compose/v2/pkg/progress"
  42. "github.com/docker/compose/v2/pkg/remote"
  43. "github.com/docker/compose/v2/pkg/utils"
  44. buildkit "github.com/moby/buildkit/util/progress/progressui"
  45. "github.com/morikuni/aec"
  46. "github.com/sirupsen/logrus"
  47. "github.com/spf13/cobra"
  48. "github.com/spf13/pflag"
  49. )
  50. const (
  51. // ComposeParallelLimit set the limit running concurrent operation on docker engine
  52. ComposeParallelLimit = "COMPOSE_PARALLEL_LIMIT"
  53. // ComposeProjectName define the project name to be used, instead of guessing from parent directory
  54. ComposeProjectName = "COMPOSE_PROJECT_NAME"
  55. // ComposeCompatibility try to mimic compose v1 as much as possible
  56. ComposeCompatibility = "COMPOSE_COMPATIBILITY"
  57. // ComposeRemoveOrphans remove "orphaned" containers, i.e. containers tagged for current project but not declared as service
  58. ComposeRemoveOrphans = "COMPOSE_REMOVE_ORPHANS"
  59. // ComposeIgnoreOrphans ignore "orphaned" containers
  60. ComposeIgnoreOrphans = "COMPOSE_IGNORE_ORPHANS"
  61. // ComposeEnvFiles defines the env files to use if --env-file isn't used
  62. ComposeEnvFiles = "COMPOSE_ENV_FILES"
  63. // ComposeMenu defines if the navigation menu should be rendered. Can be also set via --menu
  64. ComposeMenu = "COMPOSE_MENU"
  65. )
  66. // rawEnv load a dot env file using docker/cli key=value parser, without attempt to interpolate or evaluate values
  67. func rawEnv(r io.Reader, filename string, vars map[string]string, lookup func(key string) (string, bool)) error {
  68. lines, err := kvfile.ParseFromReader(r, lookup)
  69. if err != nil {
  70. return fmt.Errorf("failed to parse env_file %s: %w", filename, err)
  71. }
  72. for _, line := range lines {
  73. key, value, _ := strings.Cut(line, "=")
  74. vars[key] = value
  75. }
  76. return nil
  77. }
  78. func init() {
  79. // compose evaluates env file values for interpolation
  80. // `raw` format allows to load env_file with the same parser used by docker run --env-file
  81. dotenv.RegisterFormat("raw", rawEnv)
  82. }
  83. type Backend interface {
  84. api.Service
  85. SetDesktopClient(cli *desktop.Client)
  86. SetExperiments(experiments *experimental.State)
  87. }
  88. // Command defines a compose CLI command as a func with args
  89. type Command func(context.Context, []string) error
  90. // CobraCommand defines a cobra command function
  91. type CobraCommand func(context.Context, *cobra.Command, []string) error
  92. // AdaptCmd adapt a CobraCommand func to cobra library
  93. func AdaptCmd(fn CobraCommand) func(cmd *cobra.Command, args []string) error {
  94. return func(cmd *cobra.Command, args []string) error {
  95. ctx, cancel := context.WithCancel(cmd.Context())
  96. s := make(chan os.Signal, 1)
  97. signal.Notify(s, syscall.SIGTERM, syscall.SIGINT)
  98. go func() {
  99. <-s
  100. cancel()
  101. signal.Stop(s)
  102. close(s)
  103. }()
  104. err := fn(ctx, cmd, args)
  105. if api.IsErrCanceled(err) || errors.Is(ctx.Err(), context.Canceled) {
  106. err = dockercli.StatusError{
  107. StatusCode: 130,
  108. }
  109. }
  110. if ui.Mode == ui.ModeJSON {
  111. err = makeJSONError(err)
  112. }
  113. return err
  114. }
  115. }
  116. // Adapt a Command func to cobra library
  117. func Adapt(fn Command) func(cmd *cobra.Command, args []string) error {
  118. return AdaptCmd(func(ctx context.Context, cmd *cobra.Command, args []string) error {
  119. return fn(ctx, args)
  120. })
  121. }
  122. type ProjectOptions struct {
  123. ProjectName string
  124. Profiles []string
  125. ConfigPaths []string
  126. WorkDir string
  127. ProjectDir string
  128. EnvFiles []string
  129. Compatibility bool
  130. Progress string
  131. Offline bool
  132. All bool
  133. }
  134. // ProjectFunc does stuff within a types.Project
  135. type ProjectFunc func(ctx context.Context, project *types.Project) error
  136. // ProjectServicesFunc does stuff within a types.Project and a selection of services
  137. type ProjectServicesFunc func(ctx context.Context, project *types.Project, services []string) error
  138. // WithProject creates a cobra run command from a ProjectFunc based on configured project options and selected services
  139. func (o *ProjectOptions) WithProject(fn ProjectFunc, dockerCli command.Cli) func(cmd *cobra.Command, args []string) error {
  140. return o.WithServices(dockerCli, func(ctx context.Context, project *types.Project, services []string) error {
  141. return fn(ctx, project)
  142. })
  143. }
  144. // WithServices creates a cobra run command from a ProjectFunc based on configured project options and selected services
  145. func (o *ProjectOptions) WithServices(dockerCli command.Cli, fn ProjectServicesFunc) func(cmd *cobra.Command, args []string) error {
  146. return Adapt(func(ctx context.Context, args []string) error {
  147. options := []cli.ProjectOptionsFn{
  148. cli.WithResolvedPaths(true),
  149. cli.WithoutEnvironmentResolution,
  150. }
  151. project, metrics, err := o.ToProject(ctx, dockerCli, args, options...)
  152. if err != nil {
  153. return err
  154. }
  155. ctx = context.WithValue(ctx, tracing.MetricsKey{}, metrics)
  156. project, err = project.WithServicesEnvironmentResolved(true)
  157. if err != nil {
  158. return err
  159. }
  160. return fn(ctx, project, args)
  161. })
  162. }
  163. type jsonErrorData struct {
  164. Error bool `json:"error,omitempty"`
  165. Message string `json:"message,omitempty"`
  166. }
  167. func errorAsJSON(message string) string {
  168. errorMessage := &jsonErrorData{
  169. Error: true,
  170. Message: message,
  171. }
  172. marshal, err := json.Marshal(errorMessage)
  173. if err == nil {
  174. return string(marshal)
  175. } else {
  176. return message
  177. }
  178. }
  179. func makeJSONError(err error) error {
  180. if err == nil {
  181. return nil
  182. }
  183. var statusErr dockercli.StatusError
  184. if errors.As(err, &statusErr) {
  185. return dockercli.StatusError{
  186. StatusCode: statusErr.StatusCode,
  187. Status: errorAsJSON(statusErr.Status),
  188. }
  189. }
  190. return fmt.Errorf("%s", errorAsJSON(err.Error()))
  191. }
  192. func (o *ProjectOptions) addProjectFlags(f *pflag.FlagSet) {
  193. f.StringArrayVar(&o.Profiles, "profile", []string{}, "Specify a profile to enable")
  194. f.StringVarP(&o.ProjectName, "project-name", "p", "", "Project name")
  195. f.StringArrayVarP(&o.ConfigPaths, "file", "f", []string{}, "Compose configuration files")
  196. f.StringArrayVar(&o.EnvFiles, "env-file", defaultStringArrayVar(ComposeEnvFiles), "Specify an alternate environment file")
  197. f.StringVar(&o.ProjectDir, "project-directory", "", "Specify an alternate working directory\n(default: the path of the, first specified, Compose file)")
  198. 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)")
  199. f.BoolVar(&o.Compatibility, "compatibility", false, "Run compose in backward compatibility mode")
  200. f.StringVar(&o.Progress, "progress", string(buildkit.AutoMode), fmt.Sprintf(`Set type of progress output (%s)`, strings.Join(printerModes, ", ")))
  201. f.BoolVar(&o.All, "all-resources", false, "Include all resources, even those not used by services")
  202. _ = f.MarkHidden("workdir")
  203. }
  204. // get default value for a command line flag that is set by a coma-separated value in environment variable
  205. func defaultStringArrayVar(env string) []string {
  206. return strings.FieldsFunc(os.Getenv(env), func(c rune) bool {
  207. return c == ','
  208. })
  209. }
  210. func (o *ProjectOptions) projectOrName(ctx context.Context, dockerCli command.Cli, services ...string) (*types.Project, string, error) {
  211. name := o.ProjectName
  212. var project *types.Project
  213. if len(o.ConfigPaths) > 0 || o.ProjectName == "" {
  214. p, _, err := o.ToProject(ctx, dockerCli, services, cli.WithDiscardEnvFile)
  215. if err != nil {
  216. envProjectName := os.Getenv(ComposeProjectName)
  217. if envProjectName != "" {
  218. return nil, envProjectName, nil
  219. }
  220. return nil, "", err
  221. }
  222. project = p
  223. name = p.Name
  224. }
  225. return project, name, nil
  226. }
  227. func (o *ProjectOptions) toProjectName(ctx context.Context, dockerCli command.Cli) (string, error) {
  228. if o.ProjectName != "" {
  229. return o.ProjectName, nil
  230. }
  231. envProjectName := os.Getenv(ComposeProjectName)
  232. if envProjectName != "" {
  233. return envProjectName, nil
  234. }
  235. project, _, err := o.ToProject(ctx, dockerCli, nil)
  236. if err != nil {
  237. return "", err
  238. }
  239. return project.Name, nil
  240. }
  241. func (o *ProjectOptions) ToModel(ctx context.Context, dockerCli command.Cli, services []string, po ...cli.ProjectOptionsFn) (map[string]any, error) {
  242. remotes := o.remoteLoaders(dockerCli)
  243. for _, r := range remotes {
  244. po = append(po, cli.WithResourceLoader(r))
  245. }
  246. options, err := o.toProjectOptions(po...)
  247. if err != nil {
  248. return nil, err
  249. }
  250. if o.Compatibility || utils.StringToBool(options.Environment[ComposeCompatibility]) {
  251. api.Separator = "_"
  252. }
  253. return options.LoadModel(ctx)
  254. }
  255. func (o *ProjectOptions) ToProject(ctx context.Context, dockerCli command.Cli, services []string, po ...cli.ProjectOptionsFn) (*types.Project, tracing.Metrics, error) { //nolint:gocyclo
  256. var metrics tracing.Metrics
  257. remotes := o.remoteLoaders(dockerCli)
  258. for _, r := range remotes {
  259. po = append(po, cli.WithResourceLoader(r))
  260. }
  261. options, err := o.toProjectOptions(po...)
  262. if err != nil {
  263. return nil, metrics, err
  264. }
  265. options.WithListeners(func(event string, metadata map[string]any) {
  266. switch event {
  267. case "extends":
  268. metrics.CountExtends++
  269. case "include":
  270. paths := metadata["path"].(types.StringList)
  271. for _, path := range paths {
  272. var isRemote bool
  273. for _, r := range remotes {
  274. if r.Accept(path) {
  275. isRemote = true
  276. break
  277. }
  278. }
  279. if isRemote {
  280. metrics.CountIncludesRemote++
  281. } else {
  282. metrics.CountIncludesLocal++
  283. }
  284. }
  285. }
  286. })
  287. if o.Compatibility || utils.StringToBool(options.Environment[ComposeCompatibility]) {
  288. api.Separator = "_"
  289. }
  290. project, err := options.LoadProject(ctx)
  291. if err != nil {
  292. return nil, metrics, err
  293. }
  294. if project.Name == "" {
  295. return nil, metrics, errors.New("project name can't be empty. Use `--project-name` to set a valid name")
  296. }
  297. project, err = project.WithServicesEnabled(services...)
  298. if err != nil {
  299. return nil, metrics, err
  300. }
  301. for name, s := range project.Services {
  302. s.CustomLabels = map[string]string{
  303. api.ProjectLabel: project.Name,
  304. api.ServiceLabel: name,
  305. api.VersionLabel: api.ComposeVersion,
  306. api.WorkingDirLabel: project.WorkingDir,
  307. api.ConfigFilesLabel: strings.Join(project.ComposeFiles, ","),
  308. api.OneoffLabel: "False", // default, will be overridden by `run` command
  309. }
  310. if len(o.EnvFiles) != 0 {
  311. s.CustomLabels[api.EnvironmentFileLabel] = strings.Join(o.EnvFiles, ",")
  312. }
  313. project.Services[name] = s
  314. }
  315. project, err = project.WithSelectedServices(services)
  316. if err != nil {
  317. return nil, tracing.Metrics{}, err
  318. }
  319. if !o.All {
  320. project = project.WithoutUnnecessaryResources()
  321. }
  322. return project, metrics, err
  323. }
  324. func (o *ProjectOptions) remoteLoaders(dockerCli command.Cli) []loader.ResourceLoader {
  325. if o.Offline {
  326. return nil
  327. }
  328. git := remote.NewGitRemoteLoader(dockerCli, o.Offline)
  329. oci := remote.NewOCIRemoteLoader(dockerCli, o.Offline)
  330. return []loader.ResourceLoader{git, oci}
  331. }
  332. func (o *ProjectOptions) toProjectOptions(po ...cli.ProjectOptionsFn) (*cli.ProjectOptions, error) {
  333. pwd, err := os.Getwd()
  334. if err != nil {
  335. return nil, err
  336. }
  337. return cli.NewProjectOptions(o.ConfigPaths,
  338. append(po,
  339. cli.WithWorkingDirectory(o.ProjectDir),
  340. // First apply os.Environment, always win
  341. cli.WithOsEnv,
  342. // set PWD as this variable is not consistently supported on Windows
  343. cli.WithEnv([]string{"PWD=" + pwd}),
  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: 1,
  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 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. )
  568. c.Flags().SetInterspersed(false)
  569. opts.addProjectFlags(c.Flags())
  570. c.RegisterFlagCompletionFunc( //nolint:errcheck
  571. "project-name",
  572. completeProjectNames(backend),
  573. )
  574. c.RegisterFlagCompletionFunc( //nolint:errcheck
  575. "project-directory",
  576. func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
  577. return []string{}, cobra.ShellCompDirectiveFilterDirs
  578. },
  579. )
  580. c.RegisterFlagCompletionFunc( //nolint:errcheck
  581. "file",
  582. func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
  583. return []string{"yaml", "yml"}, cobra.ShellCompDirectiveFilterFileExt
  584. },
  585. )
  586. c.RegisterFlagCompletionFunc( //nolint:errcheck
  587. "profile",
  588. completeProfileNames(dockerCli, &opts),
  589. )
  590. c.Flags().StringVar(&ansi, "ansi", "auto", `Control when to print ANSI control characters ("never"|"always"|"auto")`)
  591. c.Flags().IntVar(&parallel, "parallel", -1, `Control max parallelism, -1 for unlimited`)
  592. c.Flags().BoolVarP(&version, "version", "v", false, "Show the Docker Compose version information")
  593. c.PersistentFlags().BoolVar(&dryRun, "dry-run", false, "Execute command in dry run mode")
  594. c.Flags().MarkHidden("version") //nolint:errcheck
  595. c.Flags().BoolVar(&noAnsi, "no-ansi", false, `Do not print ANSI control characters (DEPRECATED)`)
  596. c.Flags().MarkHidden("no-ansi") //nolint:errcheck
  597. c.Flags().BoolVar(&verbose, "verbose", false, "Show more output")
  598. c.Flags().MarkHidden("verbose") //nolint:errcheck
  599. return c
  600. }
  601. func setEnvWithDotEnv(opts ProjectOptions) error {
  602. options, err := cli.NewProjectOptions(opts.ConfigPaths,
  603. cli.WithWorkingDirectory(opts.ProjectDir),
  604. cli.WithOsEnv,
  605. cli.WithEnvFiles(opts.EnvFiles...),
  606. cli.WithDotEnv,
  607. )
  608. if err != nil {
  609. return nil
  610. }
  611. envFromFile, err := dotenv.GetEnvFromFile(composegoutils.GetAsEqualsMap(os.Environ()), options.EnvFiles)
  612. if err != nil {
  613. return nil
  614. }
  615. for k, v := range envFromFile {
  616. if _, ok := os.LookupEnv(k); !ok {
  617. if err = os.Setenv(k, v); err != nil {
  618. return nil
  619. }
  620. }
  621. }
  622. return err
  623. }
  624. var printerModes = []string{
  625. ui.ModeAuto,
  626. ui.ModeTTY,
  627. ui.ModePlain,
  628. ui.ModeJSON,
  629. ui.ModeQuiet,
  630. }
  631. func SetUnchangedOption(name string, experimentalFlag bool) bool {
  632. var value bool
  633. // If the var is defined we use that value first
  634. if envVar, ok := os.LookupEnv(name); ok {
  635. value = utils.StringToBool(envVar)
  636. } else {
  637. // if not, we try to get it from experimental feature flag
  638. value = experimentalFlag
  639. }
  640. return value
  641. }