compose.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  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/morikuni/aec"
  37. "github.com/sirupsen/logrus"
  38. "github.com/spf13/cobra"
  39. "github.com/spf13/pflag"
  40. "github.com/docker/compose/v5/cmd/display"
  41. "github.com/docker/compose/v5/cmd/formatter"
  42. "github.com/docker/compose/v5/internal/tracing"
  43. "github.com/docker/compose/v5/pkg/api"
  44. "github.com/docker/compose/v5/pkg/compose"
  45. "github.com/docker/compose/v5/pkg/remote"
  46. "github.com/docker/compose/v5/pkg/utils"
  47. )
  48. const (
  49. // ComposeParallelLimit set the limit running concurrent operation on docker engine
  50. ComposeParallelLimit = "COMPOSE_PARALLEL_LIMIT"
  51. // ComposeProjectName define the project name to be used, instead of guessing from parent directory
  52. ComposeProjectName = "COMPOSE_PROJECT_NAME"
  53. // ComposeCompatibility try to mimic compose v1 as much as possible
  54. ComposeCompatibility = "COMPOSE_COMPATIBILITY"
  55. // ComposeRemoveOrphans remove "orphaned" containers, i.e. containers tagged for current project but not declared as service
  56. ComposeRemoveOrphans = "COMPOSE_REMOVE_ORPHANS"
  57. // ComposeIgnoreOrphans ignore "orphaned" containers
  58. ComposeIgnoreOrphans = "COMPOSE_IGNORE_ORPHANS"
  59. // ComposeEnvFiles defines the env files to use if --env-file isn't used
  60. ComposeEnvFiles = "COMPOSE_ENV_FILES"
  61. // ComposeMenu defines if the navigation menu should be rendered. Can be also set via --menu
  62. ComposeMenu = "COMPOSE_MENU"
  63. // ComposeProgress defines type of progress output, if --progress isn't used
  64. ComposeProgress = "COMPOSE_PROGRESS"
  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. var stdioToStdout bool
  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. if v, ok := os.LookupEnv("COMPOSE_STATUS_STDOUT"); ok {
  84. stdioToStdout, _ = strconv.ParseBool(v)
  85. }
  86. }
  87. // Command defines a compose CLI command as a func with args
  88. type Command func(context.Context, []string) error
  89. // CobraCommand defines a cobra command function
  90. type CobraCommand func(context.Context, *cobra.Command, []string) error
  91. // AdaptCmd adapt a CobraCommand func to cobra library
  92. func AdaptCmd(fn CobraCommand) func(cmd *cobra.Command, args []string) error {
  93. return func(cmd *cobra.Command, args []string) error {
  94. ctx, cancel := context.WithCancel(cmd.Context())
  95. s := make(chan os.Signal, 1)
  96. signal.Notify(s, syscall.SIGTERM, syscall.SIGINT)
  97. go func() {
  98. <-s
  99. cancel()
  100. signal.Stop(s)
  101. close(s)
  102. }()
  103. err := fn(ctx, cmd, args)
  104. if api.IsErrCanceled(err) || errors.Is(ctx.Err(), context.Canceled) {
  105. err = dockercli.StatusError{
  106. StatusCode: 130,
  107. }
  108. }
  109. if display.Mode == display.ModeJSON {
  110. err = makeJSONError(err)
  111. }
  112. return err
  113. }
  114. }
  115. // Adapt a Command func to cobra library
  116. func Adapt(fn Command) func(cmd *cobra.Command, args []string) error {
  117. return AdaptCmd(func(ctx context.Context, cmd *cobra.Command, args []string) error {
  118. return fn(ctx, args)
  119. })
  120. }
  121. type ProjectOptions struct {
  122. ProjectName string
  123. Profiles []string
  124. ConfigPaths []string
  125. WorkDir string
  126. ProjectDir string
  127. EnvFiles []string
  128. Compatibility bool
  129. Progress string
  130. Offline bool
  131. All bool
  132. insecureRegistries []string
  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, services []string) error {
  147. backend, err := compose.NewComposeService(dockerCli)
  148. if err != nil {
  149. return err
  150. }
  151. project, metrics, err := o.ToProject(ctx, dockerCli, backend, services, cli.WithoutEnvironmentResolution)
  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, services)
  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.insecureRegistries, "insecure-registry", []string{}, "Use insecure registry to pull Compose OCI artifacts. Doesn't apply to images")
  197. _ = f.MarkHidden("insecure-registry")
  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", os.Getenv(ComposeProgress), 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. func (o *ProjectOptions) projectOrName(ctx context.Context, dockerCli command.Cli, services ...string) (*types.Project, string, error) {
  213. name := o.ProjectName
  214. var project *types.Project
  215. if len(o.ConfigPaths) > 0 || o.ProjectName == "" {
  216. backend, err := compose.NewComposeService(dockerCli)
  217. if err != nil {
  218. return nil, "", err
  219. }
  220. p, _, err := o.ToProject(ctx, dockerCli, backend, services, cli.WithDiscardEnvFile, cli.WithoutEnvironmentResolution)
  221. if err != nil {
  222. envProjectName := os.Getenv(ComposeProjectName)
  223. if envProjectName != "" {
  224. return nil, envProjectName, nil
  225. }
  226. return nil, "", err
  227. }
  228. project = p
  229. name = p.Name
  230. }
  231. return project, name, nil
  232. }
  233. func (o *ProjectOptions) toProjectName(ctx context.Context, dockerCli command.Cli) (string, error) {
  234. if o.ProjectName != "" {
  235. return o.ProjectName, nil
  236. }
  237. envProjectName := os.Getenv(ComposeProjectName)
  238. if envProjectName != "" {
  239. return envProjectName, nil
  240. }
  241. backend, err := compose.NewComposeService(dockerCli)
  242. if err != nil {
  243. return "", err
  244. }
  245. project, _, err := o.ToProject(ctx, dockerCli, backend, nil)
  246. if err != nil {
  247. return "", err
  248. }
  249. return project.Name, nil
  250. }
  251. func (o *ProjectOptions) ToModel(ctx context.Context, dockerCli command.Cli, services []string, po ...cli.ProjectOptionsFn) (map[string]any, error) {
  252. remotes := o.remoteLoaders(dockerCli)
  253. for _, r := range remotes {
  254. po = append(po, cli.WithResourceLoader(r))
  255. }
  256. options, err := o.toProjectOptions(po...)
  257. if err != nil {
  258. return nil, err
  259. }
  260. if o.Compatibility || utils.StringToBool(options.Environment[ComposeCompatibility]) {
  261. api.Separator = "_"
  262. }
  263. return options.LoadModel(ctx)
  264. }
  265. // ToProject loads a Compose project using the LoadProject API.
  266. // Accepts optional cli.ProjectOptionsFn to control loader behavior.
  267. func (o *ProjectOptions) ToProject(ctx context.Context, dockerCli command.Cli, backend api.Compose, services []string, po ...cli.ProjectOptionsFn) (*types.Project, tracing.Metrics, error) {
  268. var metrics tracing.Metrics
  269. remotes := o.remoteLoaders(dockerCli)
  270. // Setup metrics listener to collect project data
  271. metricsListener := func(event string, metadata map[string]any) {
  272. switch event {
  273. case "extends":
  274. metrics.CountExtends++
  275. case "include":
  276. paths := metadata["path"].(types.StringList)
  277. for _, path := range paths {
  278. var isRemote bool
  279. for _, r := range remotes {
  280. if r.Accept(path) {
  281. isRemote = true
  282. break
  283. }
  284. }
  285. if isRemote {
  286. metrics.CountIncludesRemote++
  287. } else {
  288. metrics.CountIncludesLocal++
  289. }
  290. }
  291. }
  292. }
  293. loadOpts := api.ProjectLoadOptions{
  294. ProjectName: o.ProjectName,
  295. ConfigPaths: o.ConfigPaths,
  296. WorkingDir: o.ProjectDir,
  297. EnvFiles: o.EnvFiles,
  298. Profiles: o.Profiles,
  299. Services: services,
  300. Offline: o.Offline,
  301. All: o.All,
  302. Compatibility: o.Compatibility,
  303. ProjectOptionsFns: po,
  304. LoadListeners: []api.LoadListener{metricsListener},
  305. OCI: api.OCIOptions{
  306. InsecureRegistries: o.insecureRegistries,
  307. },
  308. }
  309. project, err := backend.LoadProject(ctx, loadOpts)
  310. if err != nil {
  311. return nil, metrics, err
  312. }
  313. return project, metrics, nil
  314. }
  315. func (o *ProjectOptions) remoteLoaders(dockerCli command.Cli) []loader.ResourceLoader {
  316. if o.Offline {
  317. return nil
  318. }
  319. git := remote.NewGitRemoteLoader(dockerCli, o.Offline)
  320. oci := remote.NewOCIRemoteLoader(dockerCli, o.Offline, api.OCIOptions{})
  321. return []loader.ResourceLoader{git, oci}
  322. }
  323. func (o *ProjectOptions) toProjectOptions(po ...cli.ProjectOptionsFn) (*cli.ProjectOptions, error) {
  324. opts := []cli.ProjectOptionsFn{
  325. cli.WithWorkingDirectory(o.ProjectDir),
  326. // First apply os.Environment, always win
  327. cli.WithOsEnv,
  328. }
  329. if _, present := os.LookupEnv("PWD"); !present {
  330. if pwd, err := os.Getwd(); err != nil {
  331. return nil, err
  332. } else {
  333. opts = append(opts, cli.WithEnv([]string{"PWD=" + pwd}))
  334. }
  335. }
  336. opts = append(opts,
  337. // Load PWD/.env if present and no explicit --env-file has been set
  338. cli.WithEnvFiles(o.EnvFiles...),
  339. // read dot env file to populate project environment
  340. cli.WithDotEnv,
  341. // get compose file path set by COMPOSE_FILE
  342. cli.WithConfigFileEnv,
  343. // if none was selected, get default compose.yaml file from current dir or parent folder
  344. cli.WithDefaultConfigPath,
  345. // .. and then, a project directory != PWD maybe has been set so let's load .env file
  346. cli.WithEnvFiles(o.EnvFiles...), //nolint:gocritic // intentionally applying cli.WithEnvFiles twice.
  347. cli.WithDotEnv, //nolint:gocritic // intentionally applying cli.WithDotEnv twice.
  348. // eventually COMPOSE_PROFILES should have been set
  349. cli.WithDefaultProfiles(o.Profiles...),
  350. cli.WithName(o.ProjectName),
  351. )
  352. return cli.NewProjectOptions(o.ConfigPaths, append(po, opts...)...)
  353. }
  354. // PluginName is the name of the plugin
  355. const PluginName = "compose"
  356. // RunningAsStandalone detects when running as a standalone program
  357. func RunningAsStandalone() bool {
  358. return len(os.Args) < 2 || os.Args[1] != metadata.MetadataSubcommandName && os.Args[1] != PluginName
  359. }
  360. type BackendOptions struct {
  361. Options []compose.Option
  362. }
  363. func (o *BackendOptions) Add(option compose.Option) {
  364. o.Options = append(o.Options, option)
  365. }
  366. // RootCommand returns the compose command with its child commands
  367. func RootCommand(dockerCli command.Cli, backendOptions *BackendOptions) *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. 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. parent := cmd.Root()
  407. if parent != nil {
  408. parentPrerun := parent.PersistentPreRunE
  409. if parentPrerun != nil {
  410. err := parentPrerun(cmd, args)
  411. if err != nil {
  412. return err
  413. }
  414. }
  415. }
  416. if verbose {
  417. logrus.SetLevel(logrus.TraceLevel)
  418. }
  419. err := setEnvWithDotEnv(opts)
  420. if err != nil {
  421. return err
  422. }
  423. if noAnsi {
  424. if ansi != "auto" {
  425. return errors.New(`cannot specify DEPRECATED "--no-ansi" and "--ansi". Please use only "--ansi"`)
  426. }
  427. ansi = "never"
  428. fmt.Fprint(os.Stderr, "option '--no-ansi' is DEPRECATED ! Please use '--ansi' instead.\n")
  429. }
  430. if v, ok := os.LookupEnv("COMPOSE_ANSI"); ok && !cmd.Flags().Changed("ansi") {
  431. ansi = v
  432. }
  433. formatter.SetANSIMode(dockerCli, ansi)
  434. if noColor, ok := os.LookupEnv("NO_COLOR"); ok && noColor != "" {
  435. display.NoColor()
  436. formatter.SetANSIMode(dockerCli, formatter.Never)
  437. }
  438. switch ansi {
  439. case "never":
  440. display.Mode = display.ModePlain
  441. case "always":
  442. display.Mode = display.ModeTTY
  443. }
  444. var ep api.EventProcessor
  445. switch opts.Progress {
  446. case "", display.ModeAuto:
  447. switch {
  448. case ansi == "never":
  449. display.Mode = display.ModePlain
  450. ep = display.Plain(dockerCli.Err())
  451. case dockerCli.Out().IsTerminal():
  452. ep = display.Full(dockerCli.Err(), stdinfo(dockerCli))
  453. default:
  454. ep = display.Plain(dockerCli.Err())
  455. }
  456. case display.ModeTTY:
  457. if ansi == "never" {
  458. return fmt.Errorf("can't use --progress tty while ANSI support is disabled")
  459. }
  460. display.Mode = display.ModeTTY
  461. ep = display.Full(dockerCli.Err(), stdinfo(dockerCli))
  462. case display.ModePlain:
  463. if ansi == "always" {
  464. return fmt.Errorf("can't use --progress plain while ANSI support is forced")
  465. }
  466. display.Mode = display.ModePlain
  467. ep = display.Plain(dockerCli.Err())
  468. case display.ModeQuiet, "none":
  469. display.Mode = display.ModeQuiet
  470. ep = display.Quiet()
  471. case display.ModeJSON:
  472. display.Mode = display.ModeJSON
  473. logrus.SetFormatter(&logrus.JSONFormatter{})
  474. ep = display.JSON(dockerCli.Err())
  475. default:
  476. return fmt.Errorf("unsupported --progress value %q", opts.Progress)
  477. }
  478. backendOptions.Add(compose.WithEventProcessor(ep))
  479. // (4) options validation / normalization
  480. if opts.WorkDir != "" {
  481. if opts.ProjectDir != "" {
  482. return errors.New(`cannot specify DEPRECATED "--workdir" and "--project-directory". Please use only "--project-directory" instead`)
  483. }
  484. opts.ProjectDir = opts.WorkDir
  485. fmt.Fprint(os.Stderr, aec.Apply("option '--workdir' is DEPRECATED at root level! Please use '--project-directory' instead.\n", aec.RedF))
  486. }
  487. for i, file := range opts.EnvFiles {
  488. if !filepath.IsAbs(file) {
  489. file, err := filepath.Abs(file)
  490. if err != nil {
  491. return err
  492. }
  493. opts.EnvFiles[i] = file
  494. }
  495. }
  496. composeCmd := cmd
  497. for composeCmd.Name() != PluginName {
  498. if !composeCmd.HasParent() {
  499. return fmt.Errorf("error parsing command line, expected %q", PluginName)
  500. }
  501. composeCmd = composeCmd.Parent()
  502. }
  503. if v, ok := os.LookupEnv(ComposeParallelLimit); ok && !composeCmd.Flags().Changed("parallel") {
  504. i, err := strconv.Atoi(v)
  505. if err != nil {
  506. return fmt.Errorf("%s must be an integer (found: %q)", ComposeParallelLimit, v)
  507. }
  508. parallel = i
  509. }
  510. if parallel > 0 {
  511. logrus.Debugf("Limiting max concurrency to %d jobs", parallel)
  512. backendOptions.Add(compose.WithMaxConcurrency(parallel))
  513. }
  514. // dry run detection
  515. if dryRun {
  516. backendOptions.Add(compose.WithDryRun)
  517. }
  518. return nil
  519. },
  520. }
  521. c.AddCommand(
  522. upCommand(&opts, dockerCli, backendOptions),
  523. downCommand(&opts, dockerCli, backendOptions),
  524. startCommand(&opts, dockerCli, backendOptions),
  525. restartCommand(&opts, dockerCli, backendOptions),
  526. stopCommand(&opts, dockerCli, backendOptions),
  527. psCommand(&opts, dockerCli, backendOptions),
  528. listCommand(dockerCli, backendOptions),
  529. logsCommand(&opts, dockerCli, backendOptions),
  530. configCommand(&opts, dockerCli),
  531. killCommand(&opts, dockerCli, backendOptions),
  532. runCommand(&opts, dockerCli, backendOptions),
  533. removeCommand(&opts, dockerCli, backendOptions),
  534. execCommand(&opts, dockerCli, backendOptions),
  535. attachCommand(&opts, dockerCli, backendOptions),
  536. exportCommand(&opts, dockerCli, backendOptions),
  537. commitCommand(&opts, dockerCli, backendOptions),
  538. pauseCommand(&opts, dockerCli, backendOptions),
  539. unpauseCommand(&opts, dockerCli, backendOptions),
  540. topCommand(&opts, dockerCli, backendOptions),
  541. eventsCommand(&opts, dockerCli, backendOptions),
  542. portCommand(&opts, dockerCli, backendOptions),
  543. imagesCommand(&opts, dockerCli, backendOptions),
  544. versionCommand(dockerCli),
  545. buildCommand(&opts, dockerCli, backendOptions),
  546. pushCommand(&opts, dockerCli, backendOptions),
  547. pullCommand(&opts, dockerCli, backendOptions),
  548. createCommand(&opts, dockerCli, backendOptions),
  549. copyCommand(&opts, dockerCli, backendOptions),
  550. waitCommand(&opts, dockerCli, backendOptions),
  551. scaleCommand(&opts, dockerCli, backendOptions),
  552. statsCommand(&opts, dockerCli),
  553. watchCommand(&opts, dockerCli, backendOptions),
  554. publishCommand(&opts, dockerCli, backendOptions),
  555. alphaCommand(&opts, dockerCli, backendOptions),
  556. bridgeCommand(&opts, dockerCli),
  557. volumesCommand(&opts, dockerCli, backendOptions),
  558. )
  559. c.Flags().SetInterspersed(false)
  560. opts.addProjectFlags(c.Flags())
  561. c.RegisterFlagCompletionFunc( //nolint:errcheck
  562. "project-name",
  563. completeProjectNames(dockerCli, backendOptions),
  564. )
  565. c.RegisterFlagCompletionFunc( //nolint:errcheck
  566. "project-directory",
  567. func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
  568. return []string{}, cobra.ShellCompDirectiveFilterDirs
  569. },
  570. )
  571. c.RegisterFlagCompletionFunc( //nolint:errcheck
  572. "file",
  573. func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
  574. return []string{"yaml", "yml"}, cobra.ShellCompDirectiveFilterFileExt
  575. },
  576. )
  577. c.RegisterFlagCompletionFunc( //nolint:errcheck
  578. "profile",
  579. completeProfileNames(dockerCli, &opts),
  580. )
  581. c.RegisterFlagCompletionFunc( //nolint:errcheck
  582. "progress",
  583. cobra.FixedCompletions(printerModes, cobra.ShellCompDirectiveNoFileComp),
  584. )
  585. c.Flags().StringVar(&ansi, "ansi", "auto", `Control when to print ANSI control characters ("never"|"always"|"auto")`)
  586. c.Flags().IntVar(&parallel, "parallel", -1, `Control max parallelism, -1 for unlimited`)
  587. c.Flags().BoolVarP(&version, "version", "v", false, "Show the Docker Compose version information")
  588. c.PersistentFlags().BoolVar(&dryRun, "dry-run", false, "Execute command in dry run mode")
  589. c.Flags().MarkHidden("version") //nolint:errcheck
  590. c.Flags().BoolVar(&noAnsi, "no-ansi", false, `Do not print ANSI control characters (DEPRECATED)`)
  591. c.Flags().MarkHidden("no-ansi") //nolint:errcheck
  592. c.Flags().BoolVar(&verbose, "verbose", false, "Show more output")
  593. c.Flags().MarkHidden("verbose") //nolint:errcheck
  594. return c
  595. }
  596. func stdinfo(dockerCli command.Cli) io.Writer {
  597. if stdioToStdout {
  598. return dockerCli.Out()
  599. }
  600. return dockerCli.Err()
  601. }
  602. func setEnvWithDotEnv(opts ProjectOptions) error {
  603. options, err := cli.NewProjectOptions(opts.ConfigPaths,
  604. cli.WithWorkingDirectory(opts.ProjectDir),
  605. cli.WithOsEnv,
  606. cli.WithEnvFiles(opts.EnvFiles...),
  607. cli.WithDotEnv,
  608. )
  609. if err != nil {
  610. return nil
  611. }
  612. envFromFile, err := dotenv.GetEnvFromFile(composegoutils.GetAsEqualsMap(os.Environ()), options.EnvFiles)
  613. if err != nil {
  614. return nil
  615. }
  616. for k, v := range envFromFile {
  617. if _, ok := os.LookupEnv(k); !ok && strings.HasPrefix(k, "COMPOSE_") {
  618. if err = os.Setenv(k, v); err != nil {
  619. return nil
  620. }
  621. }
  622. }
  623. return err
  624. }
  625. var printerModes = []string{
  626. display.ModeAuto,
  627. display.ModeTTY,
  628. display.ModePlain,
  629. display.ModeJSON,
  630. display.ModeQuiet,
  631. }