compose.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  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. composepaths "github.com/compose-spec/compose-go/v2/paths"
  30. "github.com/compose-spec/compose-go/v2/types"
  31. composegoutils "github.com/compose-spec/compose-go/v2/utils"
  32. "github.com/docker/buildx/util/logutil"
  33. dockercli "github.com/docker/cli/cli"
  34. "github.com/docker/cli/cli-plugins/metadata"
  35. "github.com/docker/cli/cli/command"
  36. "github.com/docker/cli/pkg/kvfile"
  37. "github.com/morikuni/aec"
  38. "github.com/sirupsen/logrus"
  39. "github.com/spf13/cobra"
  40. "github.com/spf13/pflag"
  41. "github.com/docker/compose/v5/cmd/display"
  42. "github.com/docker/compose/v5/cmd/formatter"
  43. "github.com/docker/compose/v5/internal/tracing"
  44. "github.com/docker/compose/v5/pkg/api"
  45. "github.com/docker/compose/v5/pkg/compose"
  46. "github.com/docker/compose/v5/pkg/remote"
  47. "github.com/docker/compose/v5/pkg/utils"
  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 = api.ComposeCompatibility
  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. var stdioToStdout bool
  80. func init() {
  81. // compose evaluates env file values for interpolation
  82. // `raw` format allows to load env_file with the same parser used by docker run --env-file
  83. dotenv.RegisterFormat("raw", rawEnv)
  84. if v, ok := os.LookupEnv("COMPOSE_STATUS_STDOUT"); ok {
  85. stdioToStdout, _ = strconv.ParseBool(v)
  86. }
  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 display.Mode == display.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. insecureRegistries []string
  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, services []string) error {
  148. backend, err := compose.NewComposeService(dockerCli)
  149. if err != nil {
  150. return err
  151. }
  152. project, metrics, err := o.ToProject(ctx, dockerCli, backend, services, cli.WithoutEnvironmentResolution)
  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, services)
  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.insecureRegistries, "insecure-registry", []string{}, "Use insecure registry to pull Compose OCI artifacts. Doesn't apply to images")
  198. _ = f.MarkHidden("insecure-registry")
  199. f.StringArrayVar(&o.EnvFiles, "env-file", defaultStringArrayVar(ComposeEnvFiles), "Specify an alternate environment file")
  200. f.StringVar(&o.ProjectDir, "project-directory", "", "Specify an alternate working directory\n(default: the path of the, first specified, Compose file)")
  201. 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)")
  202. f.BoolVar(&o.Compatibility, "compatibility", false, "Run compose in backward compatibility mode")
  203. f.StringVar(&o.Progress, "progress", os.Getenv(ComposeProgress), fmt.Sprintf(`Set type of progress output (%s)`, strings.Join(printerModes, ", ")))
  204. f.BoolVar(&o.All, "all-resources", false, "Include all resources, even those not used by services")
  205. _ = f.MarkHidden("workdir")
  206. }
  207. // get default value for a command line flag that is set by a coma-separated value in environment variable
  208. func defaultStringArrayVar(env string) []string {
  209. return strings.FieldsFunc(os.Getenv(env), func(c rune) bool {
  210. return c == ','
  211. })
  212. }
  213. func (o *ProjectOptions) projectOrName(ctx context.Context, dockerCli command.Cli, services ...string) (*types.Project, string, error) {
  214. name := o.ProjectName
  215. var project *types.Project
  216. if len(o.ConfigPaths) > 0 || o.ProjectName == "" {
  217. backend, err := compose.NewComposeService(dockerCli)
  218. if err != nil {
  219. return nil, "", err
  220. }
  221. p, _, err := o.ToProject(ctx, dockerCli, backend, services, cli.WithDiscardEnvFile, cli.WithoutEnvironmentResolution)
  222. if err != nil {
  223. envProjectName := os.Getenv(ComposeProjectName)
  224. if envProjectName != "" {
  225. return nil, envProjectName, nil
  226. }
  227. return nil, "", err
  228. }
  229. project = p
  230. name = p.Name
  231. }
  232. return project, name, nil
  233. }
  234. func (o *ProjectOptions) toProjectName(ctx context.Context, dockerCli command.Cli) (string, error) {
  235. if o.ProjectName != "" {
  236. return o.ProjectName, nil
  237. }
  238. envProjectName := os.Getenv(ComposeProjectName)
  239. if envProjectName != "" {
  240. return envProjectName, nil
  241. }
  242. backend, err := compose.NewComposeService(dockerCli)
  243. if err != nil {
  244. return "", err
  245. }
  246. project, _, err := o.ToProject(ctx, dockerCli, backend, nil)
  247. if err != nil {
  248. return "", err
  249. }
  250. return project.Name, nil
  251. }
  252. func (o *ProjectOptions) ToModel(ctx context.Context, dockerCli command.Cli, services []string, po ...cli.ProjectOptionsFn) (map[string]any, error) {
  253. remotes := o.remoteLoaders(dockerCli)
  254. for _, r := range remotes {
  255. po = append(po, cli.WithResourceLoader(r))
  256. }
  257. options, err := o.toProjectOptions(po...)
  258. if err != nil {
  259. return nil, err
  260. }
  261. if o.Compatibility || utils.StringToBool(options.Environment[ComposeCompatibility]) {
  262. api.Separator = "_"
  263. }
  264. return options.LoadModel(ctx)
  265. }
  266. // ToProject loads a Compose project using the LoadProject API.
  267. // Accepts optional cli.ProjectOptionsFn to control loader behavior.
  268. func (o *ProjectOptions) ToProject(ctx context.Context, dockerCli command.Cli, backend api.Compose, services []string, po ...cli.ProjectOptionsFn) (*types.Project, tracing.Metrics, error) {
  269. var metrics tracing.Metrics
  270. remotes := o.remoteLoaders(dockerCli)
  271. // Setup metrics listener to collect project data
  272. metricsListener := func(event string, metadata map[string]any) {
  273. switch event {
  274. case "extends":
  275. metrics.CountExtends++
  276. case "include":
  277. paths := metadata["path"].(types.StringList)
  278. for _, path := range paths {
  279. var isRemote bool
  280. for _, r := range remotes {
  281. if r.Accept(path) {
  282. isRemote = true
  283. break
  284. }
  285. }
  286. if isRemote {
  287. metrics.CountIncludesRemote++
  288. } else {
  289. metrics.CountIncludesLocal++
  290. }
  291. }
  292. }
  293. }
  294. loadOpts := api.ProjectLoadOptions{
  295. ProjectName: o.ProjectName,
  296. ConfigPaths: o.ConfigPaths,
  297. WorkingDir: o.ProjectDir,
  298. EnvFiles: o.EnvFiles,
  299. Profiles: o.Profiles,
  300. Services: services,
  301. Offline: o.Offline,
  302. All: o.All,
  303. Compatibility: o.Compatibility,
  304. ProjectOptionsFns: po,
  305. LoadListeners: []api.LoadListener{metricsListener},
  306. OCI: api.OCIOptions{
  307. InsecureRegistries: o.insecureRegistries,
  308. },
  309. }
  310. project, err := backend.LoadProject(ctx, loadOpts)
  311. if err != nil {
  312. return nil, metrics, err
  313. }
  314. return project, metrics, nil
  315. }
  316. func (o *ProjectOptions) remoteLoaders(dockerCli command.Cli) []loader.ResourceLoader {
  317. if o.Offline {
  318. return nil
  319. }
  320. git := remote.NewGitRemoteLoader(dockerCli, o.Offline)
  321. oci := remote.NewOCIRemoteLoader(dockerCli, o.Offline, api.OCIOptions{})
  322. return []loader.ResourceLoader{git, oci}
  323. }
  324. func (o *ProjectOptions) toProjectOptions(po ...cli.ProjectOptionsFn) (*cli.ProjectOptions, error) {
  325. opts := []cli.ProjectOptionsFn{
  326. cli.WithWorkingDirectory(o.ProjectDir),
  327. // First apply os.Environment, always win
  328. cli.WithOsEnv,
  329. }
  330. if _, present := os.LookupEnv("PWD"); !present {
  331. if pwd, err := os.Getwd(); err != nil {
  332. return nil, err
  333. } else {
  334. opts = append(opts, cli.WithEnv([]string{"PWD=" + pwd}))
  335. }
  336. }
  337. opts = append(opts,
  338. // Load PWD/.env if present and no explicit --env-file has been set
  339. cli.WithEnvFiles(o.EnvFiles...),
  340. // read dot env file to populate project environment
  341. cli.WithDotEnv,
  342. // get compose file path set by COMPOSE_FILE
  343. cli.WithConfigFileEnv,
  344. // if none was selected, get default compose.yaml file from current dir or parent folder
  345. cli.WithDefaultConfigPath,
  346. // .. and then, a project directory != PWD maybe has been set so let's load .env file
  347. cli.WithEnvFiles(o.EnvFiles...), //nolint:gocritic // intentionally applying cli.WithEnvFiles twice.
  348. cli.WithDotEnv, //nolint:gocritic // intentionally applying cli.WithDotEnv twice.
  349. // eventually COMPOSE_PROFILES should have been set
  350. cli.WithDefaultProfiles(o.Profiles...),
  351. cli.WithName(o.ProjectName),
  352. )
  353. return cli.NewProjectOptions(o.ConfigPaths, append(po, opts...)...)
  354. }
  355. // PluginName is the name of the plugin
  356. const PluginName = "compose"
  357. // RunningAsStandalone detects when running as a standalone program
  358. func RunningAsStandalone() bool {
  359. return len(os.Args) < 2 || os.Args[1] != metadata.MetadataSubcommandName && os.Args[1] != PluginName
  360. }
  361. type BackendOptions struct {
  362. Options []compose.Option
  363. }
  364. func (o *BackendOptions) Add(option compose.Option) {
  365. o.Options = append(o.Options, option)
  366. }
  367. // RootCommand returns the compose command with its child commands
  368. func RootCommand(dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { //nolint:gocyclo
  369. // filter out useless commandConn.CloseWrite warning message that can occur
  370. // when using a remote context that is unreachable: "commandConn.CloseWrite: commandconn: failed to wait: signal: killed"
  371. // https://github.com/docker/cli/blob/e1f24d3c93df6752d3c27c8d61d18260f141310c/cli/connhelper/commandconn/commandconn.go#L203-L215
  372. logrus.AddHook(logutil.NewFilter([]logrus.Level{
  373. logrus.WarnLevel,
  374. },
  375. "commandConn.CloseWrite:",
  376. "commandConn.CloseRead:",
  377. ))
  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. 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. display.NoColor()
  437. formatter.SetANSIMode(dockerCli, formatter.Never)
  438. }
  439. switch ansi {
  440. case "never":
  441. display.Mode = display.ModePlain
  442. case "always":
  443. display.Mode = display.ModeTTY
  444. }
  445. var ep api.EventProcessor
  446. switch opts.Progress {
  447. case "", display.ModeAuto:
  448. switch {
  449. case ansi == "never":
  450. display.Mode = display.ModePlain
  451. ep = display.Plain(dockerCli.Err())
  452. case dockerCli.Out().IsTerminal():
  453. ep = display.Full(dockerCli.Err(), stdinfo(dockerCli))
  454. default:
  455. ep = display.Plain(dockerCli.Err())
  456. }
  457. case display.ModeTTY:
  458. if ansi == "never" {
  459. return fmt.Errorf("can't use --progress tty while ANSI support is disabled")
  460. }
  461. display.Mode = display.ModeTTY
  462. ep = display.Full(dockerCli.Err(), stdinfo(dockerCli))
  463. case display.ModePlain:
  464. if ansi == "always" {
  465. return fmt.Errorf("can't use --progress plain while ANSI support is forced")
  466. }
  467. display.Mode = display.ModePlain
  468. ep = display.Plain(dockerCli.Err())
  469. case display.ModeQuiet, "none":
  470. display.Mode = display.ModeQuiet
  471. ep = display.Quiet()
  472. case display.ModeJSON:
  473. display.Mode = display.ModeJSON
  474. logrus.SetFormatter(&logrus.JSONFormatter{})
  475. ep = display.JSON(dockerCli.Err())
  476. default:
  477. return fmt.Errorf("unsupported --progress value %q", opts.Progress)
  478. }
  479. backendOptions.Add(compose.WithEventProcessor(ep))
  480. // (4) options validation / normalization
  481. if opts.WorkDir != "" {
  482. if opts.ProjectDir != "" {
  483. return errors.New(`cannot specify DEPRECATED "--workdir" and "--project-directory". Please use only "--project-directory" instead`)
  484. }
  485. opts.ProjectDir = opts.WorkDir
  486. fmt.Fprint(os.Stderr, aec.Apply("option '--workdir' is DEPRECATED at root level! Please use '--project-directory' instead.\n", aec.RedF))
  487. }
  488. for i, file := range opts.EnvFiles {
  489. file = composepaths.ExpandUser(file)
  490. if !filepath.IsAbs(file) {
  491. file, err := filepath.Abs(file)
  492. if err != nil {
  493. return err
  494. }
  495. opts.EnvFiles[i] = file
  496. } else {
  497. opts.EnvFiles[i] = file
  498. }
  499. }
  500. composeCmd := cmd
  501. for composeCmd.Name() != PluginName {
  502. if !composeCmd.HasParent() {
  503. return fmt.Errorf("error parsing command line, expected %q", PluginName)
  504. }
  505. composeCmd = composeCmd.Parent()
  506. }
  507. if v, ok := os.LookupEnv(ComposeParallelLimit); ok && !composeCmd.Flags().Changed("parallel") {
  508. i, err := strconv.Atoi(v)
  509. if err != nil {
  510. return fmt.Errorf("%s must be an integer (found: %q)", ComposeParallelLimit, v)
  511. }
  512. parallel = i
  513. }
  514. if parallel > 0 {
  515. logrus.Debugf("Limiting max concurrency to %d jobs", parallel)
  516. backendOptions.Add(compose.WithMaxConcurrency(parallel))
  517. }
  518. // dry run detection
  519. if dryRun {
  520. backendOptions.Add(compose.WithDryRun)
  521. }
  522. return nil
  523. },
  524. }
  525. c.AddCommand(
  526. upCommand(&opts, dockerCli, backendOptions),
  527. downCommand(&opts, dockerCli, backendOptions),
  528. startCommand(&opts, dockerCli, backendOptions),
  529. restartCommand(&opts, dockerCli, backendOptions),
  530. stopCommand(&opts, dockerCli, backendOptions),
  531. psCommand(&opts, dockerCli, backendOptions),
  532. listCommand(dockerCli, backendOptions),
  533. logsCommand(&opts, dockerCli, backendOptions),
  534. configCommand(&opts, dockerCli),
  535. killCommand(&opts, dockerCli, backendOptions),
  536. runCommand(&opts, dockerCli, backendOptions),
  537. removeCommand(&opts, dockerCli, backendOptions),
  538. execCommand(&opts, dockerCli, backendOptions),
  539. attachCommand(&opts, dockerCli, backendOptions),
  540. exportCommand(&opts, dockerCli, backendOptions),
  541. commitCommand(&opts, dockerCli, backendOptions),
  542. pauseCommand(&opts, dockerCli, backendOptions),
  543. unpauseCommand(&opts, dockerCli, backendOptions),
  544. topCommand(&opts, dockerCli, backendOptions),
  545. eventsCommand(&opts, dockerCli, backendOptions),
  546. portCommand(&opts, dockerCli, backendOptions),
  547. imagesCommand(&opts, dockerCli, backendOptions),
  548. versionCommand(dockerCli),
  549. buildCommand(&opts, dockerCli, backendOptions),
  550. pushCommand(&opts, dockerCli, backendOptions),
  551. pullCommand(&opts, dockerCli, backendOptions),
  552. createCommand(&opts, dockerCli, backendOptions),
  553. copyCommand(&opts, dockerCli, backendOptions),
  554. waitCommand(&opts, dockerCli, backendOptions),
  555. scaleCommand(&opts, dockerCli, backendOptions),
  556. statsCommand(&opts, dockerCli),
  557. watchCommand(&opts, dockerCli, backendOptions),
  558. publishCommand(&opts, dockerCli, backendOptions),
  559. alphaCommand(&opts, dockerCli, backendOptions),
  560. bridgeCommand(&opts, dockerCli),
  561. volumesCommand(&opts, dockerCli, backendOptions),
  562. )
  563. c.Flags().SetInterspersed(false)
  564. opts.addProjectFlags(c.Flags())
  565. c.RegisterFlagCompletionFunc( //nolint:errcheck
  566. "project-name",
  567. completeProjectNames(dockerCli, backendOptions),
  568. )
  569. c.RegisterFlagCompletionFunc( //nolint:errcheck
  570. "project-directory",
  571. func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
  572. return []string{}, cobra.ShellCompDirectiveFilterDirs
  573. },
  574. )
  575. c.RegisterFlagCompletionFunc( //nolint:errcheck
  576. "file",
  577. func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
  578. return []string{"yaml", "yml"}, cobra.ShellCompDirectiveFilterFileExt
  579. },
  580. )
  581. c.RegisterFlagCompletionFunc( //nolint:errcheck
  582. "profile",
  583. completeProfileNames(dockerCli, &opts),
  584. )
  585. c.RegisterFlagCompletionFunc( //nolint:errcheck
  586. "progress",
  587. cobra.FixedCompletions(printerModes, cobra.ShellCompDirectiveNoFileComp),
  588. )
  589. c.Flags().StringVar(&ansi, "ansi", "auto", `Control when to print ANSI control characters ("never"|"always"|"auto")`)
  590. c.Flags().IntVar(&parallel, "parallel", -1, `Control max parallelism, -1 for unlimited`)
  591. c.Flags().BoolVarP(&version, "version", "v", false, "Show the Docker Compose version information")
  592. c.PersistentFlags().BoolVar(&dryRun, "dry-run", false, "Execute command in dry run mode")
  593. c.Flags().MarkHidden("version") //nolint:errcheck
  594. c.Flags().BoolVar(&noAnsi, "no-ansi", false, `Do not print ANSI control characters (DEPRECATED)`)
  595. c.Flags().MarkHidden("no-ansi") //nolint:errcheck
  596. c.Flags().BoolVar(&verbose, "verbose", false, "Show more output")
  597. c.Flags().MarkHidden("verbose") //nolint:errcheck
  598. return c
  599. }
  600. func stdinfo(dockerCli command.Cli) io.Writer {
  601. if stdioToStdout {
  602. return dockerCli.Out()
  603. }
  604. return dockerCli.Err()
  605. }
  606. func setEnvWithDotEnv(opts ProjectOptions) error {
  607. options, err := cli.NewProjectOptions(opts.ConfigPaths,
  608. cli.WithWorkingDirectory(opts.ProjectDir),
  609. cli.WithOsEnv,
  610. cli.WithEnvFiles(opts.EnvFiles...),
  611. cli.WithDotEnv,
  612. )
  613. if err != nil {
  614. return err
  615. }
  616. envFromFile, err := dotenv.GetEnvFromFile(composegoutils.GetAsEqualsMap(os.Environ()), options.EnvFiles)
  617. if err != nil {
  618. return err
  619. }
  620. for k, v := range envFromFile {
  621. if _, ok := os.LookupEnv(k); !ok && strings.HasPrefix(k, "COMPOSE_") {
  622. if err := os.Setenv(k, v); err != nil {
  623. return err
  624. }
  625. }
  626. }
  627. return nil
  628. }
  629. var printerModes = []string{
  630. display.ModeAuto,
  631. display.ModeTTY,
  632. display.ModePlain,
  633. display.ModeJSON,
  634. display.ModeQuiet,
  635. }