compose.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  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/tracing"
  38. "github.com/docker/compose/v2/pkg/api"
  39. "github.com/docker/compose/v2/pkg/compose"
  40. ui "github.com/docker/compose/v2/pkg/progress"
  41. "github.com/docker/compose/v2/pkg/remote"
  42. "github.com/docker/compose/v2/pkg/utils"
  43. "github.com/morikuni/aec"
  44. "github.com/sirupsen/logrus"
  45. "github.com/spf13/cobra"
  46. "github.com/spf13/pflag"
  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. 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. // Command defines a compose CLI command as a func with args
  84. type Command func(context.Context, []string) error
  85. // CobraCommand defines a cobra command function
  86. type CobraCommand func(context.Context, *cobra.Command, []string) error
  87. // AdaptCmd adapt a CobraCommand func to cobra library
  88. func AdaptCmd(fn CobraCommand) func(cmd *cobra.Command, args []string) error {
  89. return func(cmd *cobra.Command, args []string) error {
  90. ctx, cancel := context.WithCancel(cmd.Context())
  91. s := make(chan os.Signal, 1)
  92. signal.Notify(s, syscall.SIGTERM, syscall.SIGINT)
  93. go func() {
  94. <-s
  95. cancel()
  96. signal.Stop(s)
  97. close(s)
  98. }()
  99. err := fn(ctx, cmd, args)
  100. if api.IsErrCanceled(err) || errors.Is(ctx.Err(), context.Canceled) {
  101. err = dockercli.StatusError{
  102. StatusCode: 130,
  103. }
  104. }
  105. if ui.Mode == ui.ModeJSON {
  106. err = makeJSONError(err)
  107. }
  108. return err
  109. }
  110. }
  111. // Adapt a Command func to cobra library
  112. func Adapt(fn Command) func(cmd *cobra.Command, args []string) error {
  113. return AdaptCmd(func(ctx context.Context, cmd *cobra.Command, args []string) error {
  114. return fn(ctx, args)
  115. })
  116. }
  117. type ProjectOptions struct {
  118. ProjectName string
  119. Profiles []string
  120. ConfigPaths []string
  121. WorkDir string
  122. ProjectDir string
  123. EnvFiles []string
  124. Compatibility bool
  125. Progress string
  126. Offline bool
  127. All bool
  128. }
  129. // ProjectFunc does stuff within a types.Project
  130. type ProjectFunc func(ctx context.Context, project *types.Project) error
  131. // ProjectServicesFunc does stuff within a types.Project and a selection of services
  132. type ProjectServicesFunc func(ctx context.Context, project *types.Project, services []string) error
  133. // WithProject creates a cobra run command from a ProjectFunc based on configured project options and selected services
  134. func (o *ProjectOptions) WithProject(fn ProjectFunc, dockerCli command.Cli) func(cmd *cobra.Command, args []string) error {
  135. return o.WithServices(dockerCli, func(ctx context.Context, project *types.Project, services []string) error {
  136. return fn(ctx, project)
  137. })
  138. }
  139. // WithServices creates a cobra run command from a ProjectFunc based on configured project options and selected services
  140. func (o *ProjectOptions) WithServices(dockerCli command.Cli, fn ProjectServicesFunc) func(cmd *cobra.Command, args []string) error {
  141. return Adapt(func(ctx context.Context, args []string) error {
  142. backend, err := compose.NewComposeService(dockerCli)
  143. if err != nil {
  144. return err
  145. }
  146. project, metrics, err := o.ToProject(ctx, dockerCli, backend, args, cli.WithoutEnvironmentResolution)
  147. if err != nil {
  148. return err
  149. }
  150. ctx = context.WithValue(ctx, tracing.MetricsKey{}, metrics)
  151. project, err = project.WithServicesEnvironmentResolved(true)
  152. if err != nil {
  153. return err
  154. }
  155. return fn(ctx, project, args)
  156. })
  157. }
  158. type jsonErrorData struct {
  159. Error bool `json:"error,omitempty"`
  160. Message string `json:"message,omitempty"`
  161. }
  162. func errorAsJSON(message string) string {
  163. errorMessage := &jsonErrorData{
  164. Error: true,
  165. Message: message,
  166. }
  167. marshal, err := json.Marshal(errorMessage)
  168. if err == nil {
  169. return string(marshal)
  170. } else {
  171. return message
  172. }
  173. }
  174. func makeJSONError(err error) error {
  175. if err == nil {
  176. return nil
  177. }
  178. var statusErr dockercli.StatusError
  179. if errors.As(err, &statusErr) {
  180. return dockercli.StatusError{
  181. StatusCode: statusErr.StatusCode,
  182. Status: errorAsJSON(statusErr.Status),
  183. }
  184. }
  185. return fmt.Errorf("%s", errorAsJSON(err.Error()))
  186. }
  187. func (o *ProjectOptions) addProjectFlags(f *pflag.FlagSet) {
  188. f.StringArrayVar(&o.Profiles, "profile", []string{}, "Specify a profile to enable")
  189. f.StringVarP(&o.ProjectName, "project-name", "p", "", "Project name")
  190. f.StringArrayVarP(&o.ConfigPaths, "file", "f", []string{}, "Compose configuration files")
  191. f.StringArrayVar(&o.EnvFiles, "env-file", defaultStringArrayVar(ComposeEnvFiles), "Specify an alternate environment file")
  192. f.StringVar(&o.ProjectDir, "project-directory", "", "Specify an alternate working directory\n(default: the path of the, first specified, Compose file)")
  193. 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)")
  194. f.BoolVar(&o.Compatibility, "compatibility", false, "Run compose in backward compatibility mode")
  195. f.StringVar(&o.Progress, "progress", os.Getenv(ComposeProgress), fmt.Sprintf(`Set type of progress output (%s)`, strings.Join(printerModes, ", ")))
  196. f.BoolVar(&o.All, "all-resources", false, "Include all resources, even those not used by services")
  197. _ = f.MarkHidden("workdir")
  198. }
  199. // get default value for a command line flag that is set by a coma-separated value in environment variable
  200. func defaultStringArrayVar(env string) []string {
  201. return strings.FieldsFunc(os.Getenv(env), func(c rune) bool {
  202. return c == ','
  203. })
  204. }
  205. func (o *ProjectOptions) projectOrName(ctx context.Context, dockerCli command.Cli, services ...string) (*types.Project, string, error) {
  206. name := o.ProjectName
  207. var project *types.Project
  208. if len(o.ConfigPaths) > 0 || o.ProjectName == "" {
  209. backend, err := compose.NewComposeService(dockerCli)
  210. if err != nil {
  211. return nil, "", err
  212. }
  213. p, _, err := o.ToProject(ctx, dockerCli, backend, services, cli.WithDiscardEnvFile, cli.WithoutEnvironmentResolution)
  214. if err != nil {
  215. envProjectName := os.Getenv(ComposeProjectName)
  216. if envProjectName != "" {
  217. return nil, envProjectName, nil
  218. }
  219. return nil, "", err
  220. }
  221. project = p
  222. name = p.Name
  223. }
  224. return project, name, nil
  225. }
  226. func (o *ProjectOptions) toProjectName(ctx context.Context, dockerCli command.Cli) (string, error) {
  227. if o.ProjectName != "" {
  228. return o.ProjectName, nil
  229. }
  230. envProjectName := os.Getenv(ComposeProjectName)
  231. if envProjectName != "" {
  232. return envProjectName, nil
  233. }
  234. backend, err := compose.NewComposeService(dockerCli)
  235. if err != nil {
  236. return "", err
  237. }
  238. project, _, err := o.ToProject(ctx, dockerCli, backend, nil)
  239. if err != nil {
  240. return "", err
  241. }
  242. return project.Name, nil
  243. }
  244. func (o *ProjectOptions) ToModel(ctx context.Context, dockerCli command.Cli, services []string, po ...cli.ProjectOptionsFn) (map[string]any, error) {
  245. remotes := o.remoteLoaders(dockerCli)
  246. for _, r := range remotes {
  247. po = append(po, cli.WithResourceLoader(r))
  248. }
  249. options, err := o.toProjectOptions(po...)
  250. if err != nil {
  251. return nil, err
  252. }
  253. if o.Compatibility || utils.StringToBool(options.Environment[ComposeCompatibility]) {
  254. api.Separator = "_"
  255. }
  256. return options.LoadModel(ctx)
  257. }
  258. // ToProject loads a Compose project using the LoadProject API.
  259. // Accepts optional cli.ProjectOptionsFn to control loader behavior.
  260. func (o *ProjectOptions) ToProject(ctx context.Context, dockerCli command.Cli, backend api.Compose, services []string, po ...cli.ProjectOptionsFn) (*types.Project, tracing.Metrics, error) {
  261. var metrics tracing.Metrics
  262. remotes := o.remoteLoaders(dockerCli)
  263. // Setup metrics listener to collect project data
  264. metricsListener := func(event string, metadata map[string]any) {
  265. switch event {
  266. case "extends":
  267. metrics.CountExtends++
  268. case "include":
  269. paths := metadata["path"].(types.StringList)
  270. for _, path := range paths {
  271. var isRemote bool
  272. for _, r := range remotes {
  273. if r.Accept(path) {
  274. isRemote = true
  275. break
  276. }
  277. }
  278. if isRemote {
  279. metrics.CountIncludesRemote++
  280. } else {
  281. metrics.CountIncludesLocal++
  282. }
  283. }
  284. }
  285. }
  286. loadOpts := api.ProjectLoadOptions{
  287. ProjectName: o.ProjectName,
  288. ConfigPaths: o.ConfigPaths,
  289. WorkingDir: o.ProjectDir,
  290. EnvFiles: o.EnvFiles,
  291. Profiles: o.Profiles,
  292. Services: services,
  293. Offline: o.Offline,
  294. All: o.All,
  295. Compatibility: o.Compatibility,
  296. ProjectOptionsFns: po,
  297. LoadListeners: []api.LoadListener{metricsListener},
  298. }
  299. project, err := backend.LoadProject(ctx, loadOpts)
  300. if err != nil {
  301. return nil, metrics, err
  302. }
  303. return project, metrics, nil
  304. }
  305. func (o *ProjectOptions) remoteLoaders(dockerCli command.Cli) []loader.ResourceLoader {
  306. if o.Offline {
  307. return nil
  308. }
  309. git := remote.NewGitRemoteLoader(dockerCli, o.Offline)
  310. oci := remote.NewOCIRemoteLoader(dockerCli, o.Offline)
  311. return []loader.ResourceLoader{git, oci}
  312. }
  313. func (o *ProjectOptions) toProjectOptions(po ...cli.ProjectOptionsFn) (*cli.ProjectOptions, error) {
  314. opts := []cli.ProjectOptionsFn{
  315. cli.WithWorkingDirectory(o.ProjectDir),
  316. // First apply os.Environment, always win
  317. cli.WithOsEnv,
  318. }
  319. if _, present := os.LookupEnv("PWD"); !present {
  320. if pwd, err := os.Getwd(); err != nil {
  321. return nil, err
  322. } else {
  323. opts = append(opts, cli.WithEnv([]string{"PWD=" + pwd}))
  324. }
  325. }
  326. opts = append(opts,
  327. // Load PWD/.env if present and no explicit --env-file has been set
  328. cli.WithEnvFiles(o.EnvFiles...),
  329. // read dot env file to populate project environment
  330. cli.WithDotEnv,
  331. // get compose file path set by COMPOSE_FILE
  332. cli.WithConfigFileEnv,
  333. // if none was selected, get default compose.yaml file from current dir or parent folder
  334. cli.WithDefaultConfigPath,
  335. // .. and then, a project directory != PWD maybe has been set so let's load .env file
  336. cli.WithEnvFiles(o.EnvFiles...),
  337. cli.WithDotEnv,
  338. // eventually COMPOSE_PROFILES should have been set
  339. cli.WithDefaultProfiles(o.Profiles...),
  340. cli.WithName(o.ProjectName),
  341. )
  342. return cli.NewProjectOptions(o.ConfigPaths, append(po, opts...)...)
  343. }
  344. // PluginName is the name of the plugin
  345. const PluginName = "compose"
  346. // RunningAsStandalone detects when running as a standalone program
  347. func RunningAsStandalone() bool {
  348. return len(os.Args) < 2 || os.Args[1] != metadata.MetadataSubcommandName && os.Args[1] != PluginName
  349. }
  350. type BackendOptions struct {
  351. Options []compose.Option
  352. }
  353. func (o *BackendOptions) Add(option compose.Option) {
  354. o.Options = append(o.Options, option)
  355. }
  356. // RootCommand returns the compose command with its child commands
  357. func RootCommand(dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { //nolint:gocyclo
  358. // filter out useless commandConn.CloseWrite warning message that can occur
  359. // when using a remote context that is unreachable: "commandConn.CloseWrite: commandconn: failed to wait: signal: killed"
  360. // https://github.com/docker/cli/blob/e1f24d3c93df6752d3c27c8d61d18260f141310c/cli/connhelper/commandconn/commandconn.go#L203-L215
  361. logrus.AddHook(logutil.NewFilter([]logrus.Level{
  362. logrus.WarnLevel,
  363. },
  364. "commandConn.CloseWrite:",
  365. "commandConn.CloseRead:",
  366. ))
  367. opts := ProjectOptions{}
  368. var (
  369. ansi string
  370. noAnsi bool
  371. verbose bool
  372. version bool
  373. parallel int
  374. dryRun bool
  375. )
  376. c := &cobra.Command{
  377. Short: "Docker Compose",
  378. Long: "Define and run multi-container applications with Docker",
  379. Use: PluginName,
  380. TraverseChildren: true,
  381. // By default (no Run/RunE in parent c) for typos in subcommands, cobra displays the help of parent c but exit(0) !
  382. RunE: func(cmd *cobra.Command, args []string) error {
  383. if len(args) == 0 {
  384. return cmd.Help()
  385. }
  386. if version {
  387. return versionCommand(dockerCli).Execute()
  388. }
  389. _ = cmd.Help()
  390. return dockercli.StatusError{
  391. StatusCode: 1,
  392. Status: fmt.Sprintf("unknown docker command: %q", "compose "+args[0]),
  393. }
  394. },
  395. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  396. parent := cmd.Root()
  397. if parent != nil {
  398. parentPrerun := parent.PersistentPreRunE
  399. if parentPrerun != nil {
  400. err := parentPrerun(cmd, args)
  401. if err != nil {
  402. return err
  403. }
  404. }
  405. }
  406. if verbose {
  407. logrus.SetLevel(logrus.TraceLevel)
  408. }
  409. err := setEnvWithDotEnv(opts)
  410. if err != nil {
  411. return err
  412. }
  413. if noAnsi {
  414. if ansi != "auto" {
  415. return errors.New(`cannot specify DEPRECATED "--no-ansi" and "--ansi". Please use only "--ansi"`)
  416. }
  417. ansi = "never"
  418. fmt.Fprint(os.Stderr, "option '--no-ansi' is DEPRECATED ! Please use '--ansi' instead.\n")
  419. }
  420. if v, ok := os.LookupEnv("COMPOSE_ANSI"); ok && !cmd.Flags().Changed("ansi") {
  421. ansi = v
  422. }
  423. formatter.SetANSIMode(dockerCli, ansi)
  424. if noColor, ok := os.LookupEnv("NO_COLOR"); ok && noColor != "" {
  425. ui.NoColor()
  426. formatter.SetANSIMode(dockerCli, formatter.Never)
  427. }
  428. switch ansi {
  429. case "never":
  430. ui.Mode = ui.ModePlain
  431. case "always":
  432. ui.Mode = ui.ModeTTY
  433. }
  434. var ep ui.EventProcessor
  435. switch opts.Progress {
  436. case "", ui.ModeAuto:
  437. switch {
  438. case ansi == "never":
  439. ui.Mode = ui.ModePlain
  440. ep = ui.NewPlainWriter(dockerCli.Err())
  441. case dockerCli.Out().IsTerminal():
  442. ep = ui.NewTTYWriter(dockerCli.Err())
  443. default:
  444. ep = ui.NewPlainWriter(dockerCli.Err())
  445. }
  446. case ui.ModeTTY:
  447. if ansi == "never" {
  448. return fmt.Errorf("can't use --progress tty while ANSI support is disabled")
  449. }
  450. ui.Mode = ui.ModeTTY
  451. ep = ui.NewTTYWriter(dockerCli.Err())
  452. case ui.ModePlain:
  453. if ansi == "always" {
  454. return fmt.Errorf("can't use --progress plain while ANSI support is forced")
  455. }
  456. ui.Mode = ui.ModePlain
  457. ep = ui.NewPlainWriter(dockerCli.Err())
  458. case ui.ModeQuiet, "none":
  459. ui.Mode = ui.ModeQuiet
  460. ep = ui.NewQuietWriter()
  461. case ui.ModeJSON:
  462. ui.Mode = ui.ModeJSON
  463. logrus.SetFormatter(&logrus.JSONFormatter{})
  464. ep = ui.NewJSONWriter(dockerCli.Err())
  465. default:
  466. return fmt.Errorf("unsupported --progress value %q", opts.Progress)
  467. }
  468. backendOptions.Add(compose.WithEventProcessor(ep))
  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. backendOptions.Add(compose.WithMaxConcurrency(parallel))
  503. }
  504. // dry run detection
  505. if dryRun {
  506. backendOptions.Add(compose.WithDryRun)
  507. }
  508. return nil
  509. },
  510. }
  511. c.AddCommand(
  512. upCommand(&opts, dockerCli, backendOptions),
  513. downCommand(&opts, dockerCli, backendOptions),
  514. startCommand(&opts, dockerCli, backendOptions),
  515. restartCommand(&opts, dockerCli, backendOptions),
  516. stopCommand(&opts, dockerCli, backendOptions),
  517. psCommand(&opts, dockerCli, backendOptions),
  518. listCommand(dockerCli, backendOptions),
  519. logsCommand(&opts, dockerCli, backendOptions),
  520. configCommand(&opts, dockerCli),
  521. killCommand(&opts, dockerCli, backendOptions),
  522. runCommand(&opts, dockerCli, backendOptions),
  523. removeCommand(&opts, dockerCli, backendOptions),
  524. execCommand(&opts, dockerCli, backendOptions),
  525. attachCommand(&opts, dockerCli, backendOptions),
  526. exportCommand(&opts, dockerCli, backendOptions),
  527. commitCommand(&opts, dockerCli, backendOptions),
  528. pauseCommand(&opts, dockerCli, backendOptions),
  529. unpauseCommand(&opts, dockerCli, backendOptions),
  530. topCommand(&opts, dockerCli, backendOptions),
  531. eventsCommand(&opts, dockerCli, backendOptions),
  532. portCommand(&opts, dockerCli, backendOptions),
  533. imagesCommand(&opts, dockerCli, backendOptions),
  534. versionCommand(dockerCli),
  535. buildCommand(&opts, dockerCli, backendOptions),
  536. pushCommand(&opts, dockerCli, backendOptions),
  537. pullCommand(&opts, dockerCli, backendOptions),
  538. createCommand(&opts, dockerCli, backendOptions),
  539. copyCommand(&opts, dockerCli, backendOptions),
  540. waitCommand(&opts, dockerCli, backendOptions),
  541. scaleCommand(&opts, dockerCli, backendOptions),
  542. statsCommand(&opts, dockerCli),
  543. watchCommand(&opts, dockerCli, backendOptions),
  544. publishCommand(&opts, dockerCli, backendOptions),
  545. alphaCommand(&opts, dockerCli, backendOptions),
  546. bridgeCommand(&opts, dockerCli),
  547. volumesCommand(&opts, dockerCli, backendOptions),
  548. )
  549. c.Flags().SetInterspersed(false)
  550. opts.addProjectFlags(c.Flags())
  551. c.RegisterFlagCompletionFunc( //nolint:errcheck
  552. "project-name",
  553. completeProjectNames(dockerCli, backendOptions),
  554. )
  555. c.RegisterFlagCompletionFunc( //nolint:errcheck
  556. "project-directory",
  557. func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
  558. return []string{}, cobra.ShellCompDirectiveFilterDirs
  559. },
  560. )
  561. c.RegisterFlagCompletionFunc( //nolint:errcheck
  562. "file",
  563. func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
  564. return []string{"yaml", "yml"}, cobra.ShellCompDirectiveFilterFileExt
  565. },
  566. )
  567. c.RegisterFlagCompletionFunc( //nolint:errcheck
  568. "profile",
  569. completeProfileNames(dockerCli, &opts),
  570. )
  571. c.RegisterFlagCompletionFunc( //nolint:errcheck
  572. "progress",
  573. cobra.FixedCompletions(printerModes, cobra.ShellCompDirectiveNoFileComp),
  574. )
  575. c.Flags().StringVar(&ansi, "ansi", "auto", `Control when to print ANSI control characters ("never"|"always"|"auto")`)
  576. c.Flags().IntVar(&parallel, "parallel", -1, `Control max parallelism, -1 for unlimited`)
  577. c.Flags().BoolVarP(&version, "version", "v", false, "Show the Docker Compose version information")
  578. c.PersistentFlags().BoolVar(&dryRun, "dry-run", false, "Execute command in dry run mode")
  579. c.Flags().MarkHidden("version") //nolint:errcheck
  580. c.Flags().BoolVar(&noAnsi, "no-ansi", false, `Do not print ANSI control characters (DEPRECATED)`)
  581. c.Flags().MarkHidden("no-ansi") //nolint:errcheck
  582. c.Flags().BoolVar(&verbose, "verbose", false, "Show more output")
  583. c.Flags().MarkHidden("verbose") //nolint:errcheck
  584. return c
  585. }
  586. func setEnvWithDotEnv(opts ProjectOptions) error {
  587. options, err := cli.NewProjectOptions(opts.ConfigPaths,
  588. cli.WithWorkingDirectory(opts.ProjectDir),
  589. cli.WithOsEnv,
  590. cli.WithEnvFiles(opts.EnvFiles...),
  591. cli.WithDotEnv,
  592. )
  593. if err != nil {
  594. return nil
  595. }
  596. envFromFile, err := dotenv.GetEnvFromFile(composegoutils.GetAsEqualsMap(os.Environ()), options.EnvFiles)
  597. if err != nil {
  598. return nil
  599. }
  600. for k, v := range envFromFile {
  601. if _, ok := os.LookupEnv(k); !ok && strings.HasPrefix(k, "COMPOSE_") {
  602. if err = os.Setenv(k, v); err != nil {
  603. return nil
  604. }
  605. }
  606. }
  607. return err
  608. }
  609. var printerModes = []string{
  610. ui.ModeAuto,
  611. ui.ModeTTY,
  612. ui.ModePlain,
  613. ui.ModeJSON,
  614. ui.ModeQuiet,
  615. }