compose.go 22 KB

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