compose.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  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. 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 = api.ComposeCompatibility
  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. opts := ProjectOptions{}
  369. var (
  370. ansi string
  371. noAnsi bool
  372. verbose bool
  373. version bool
  374. parallel int
  375. dryRun bool
  376. )
  377. c := &cobra.Command{
  378. Short: "Docker Compose",
  379. Long: "Define and run multi-container applications with Docker",
  380. Use: PluginName,
  381. TraverseChildren: true,
  382. // By default (no Run/RunE in parent c) for typos in subcommands, cobra displays the help of parent c but exit(0) !
  383. RunE: func(cmd *cobra.Command, args []string) error {
  384. if len(args) == 0 {
  385. return cmd.Help()
  386. }
  387. if version {
  388. return versionCommand(dockerCli).Execute()
  389. }
  390. _ = cmd.Help()
  391. return dockercli.StatusError{
  392. StatusCode: 1,
  393. Status: fmt.Sprintf("unknown docker command: %q", "compose "+args[0]),
  394. }
  395. },
  396. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  397. parent := cmd.Root()
  398. if parent != nil {
  399. parentPrerun := parent.PersistentPreRunE
  400. if parentPrerun != nil {
  401. err := parentPrerun(cmd, args)
  402. if err != nil {
  403. return err
  404. }
  405. }
  406. }
  407. if verbose {
  408. logrus.SetLevel(logrus.TraceLevel)
  409. }
  410. err := setEnvWithDotEnv(opts, dockerCli)
  411. if err != nil {
  412. return err
  413. }
  414. if noAnsi {
  415. if ansi != "auto" {
  416. return errors.New(`cannot specify DEPRECATED "--no-ansi" and "--ansi". Please use only "--ansi"`)
  417. }
  418. ansi = "never"
  419. fmt.Fprint(os.Stderr, "option '--no-ansi' is DEPRECATED ! Please use '--ansi' instead.\n")
  420. }
  421. if v, ok := os.LookupEnv("COMPOSE_ANSI"); ok && !cmd.Flags().Changed("ansi") {
  422. ansi = v
  423. }
  424. formatter.SetANSIMode(dockerCli, ansi)
  425. if noColor, ok := os.LookupEnv("NO_COLOR"); ok && noColor != "" {
  426. display.NoColor()
  427. formatter.SetANSIMode(dockerCli, formatter.Never)
  428. }
  429. switch ansi {
  430. case "never":
  431. display.Mode = display.ModePlain
  432. case "always":
  433. display.Mode = display.ModeTTY
  434. }
  435. detached, _ := cmd.Flags().GetBool("detach")
  436. var ep api.EventProcessor
  437. switch opts.Progress {
  438. case "", display.ModeAuto:
  439. switch {
  440. case ansi == "never":
  441. display.Mode = display.ModePlain
  442. ep = display.Plain(dockerCli.Err())
  443. case dockerCli.Out().IsTerminal():
  444. ep = display.Full(dockerCli.Err(), stdinfo(dockerCli), detached)
  445. default:
  446. ep = display.Plain(dockerCli.Err())
  447. }
  448. case display.ModeTTY:
  449. if ansi == "never" {
  450. return fmt.Errorf("can't use --progress tty while ANSI support is disabled")
  451. }
  452. display.Mode = display.ModeTTY
  453. ep = display.Full(dockerCli.Err(), stdinfo(dockerCli), detached)
  454. case display.ModePlain:
  455. if ansi == "always" {
  456. return fmt.Errorf("can't use --progress plain while ANSI support is forced")
  457. }
  458. display.Mode = display.ModePlain
  459. ep = display.Plain(dockerCli.Err())
  460. case display.ModeQuiet, "none":
  461. display.Mode = display.ModeQuiet
  462. ep = display.Quiet()
  463. case display.ModeJSON:
  464. display.Mode = display.ModeJSON
  465. logrus.SetFormatter(&logrus.JSONFormatter{})
  466. ep = display.JSON(dockerCli.Err())
  467. default:
  468. return fmt.Errorf("unsupported --progress value %q", opts.Progress)
  469. }
  470. backendOptions.Add(compose.WithEventProcessor(ep))
  471. // (4) options validation / normalization
  472. if opts.WorkDir != "" {
  473. if opts.ProjectDir != "" {
  474. return errors.New(`cannot specify DEPRECATED "--workdir" and "--project-directory". Please use only "--project-directory" instead`)
  475. }
  476. opts.ProjectDir = opts.WorkDir
  477. fmt.Fprint(os.Stderr, aec.Apply("option '--workdir' is DEPRECATED at root level! Please use '--project-directory' instead.\n", aec.RedF))
  478. }
  479. for i, file := range opts.EnvFiles {
  480. file = composepaths.ExpandUser(file)
  481. if !filepath.IsAbs(file) {
  482. file, err := filepath.Abs(file)
  483. if err != nil {
  484. return err
  485. }
  486. opts.EnvFiles[i] = file
  487. } else {
  488. opts.EnvFiles[i] = file
  489. }
  490. }
  491. composeCmd := cmd
  492. for composeCmd.Name() != PluginName {
  493. if !composeCmd.HasParent() {
  494. return fmt.Errorf("error parsing command line, expected %q", PluginName)
  495. }
  496. composeCmd = composeCmd.Parent()
  497. }
  498. if v, ok := os.LookupEnv(ComposeParallelLimit); ok && !composeCmd.Flags().Changed("parallel") {
  499. i, err := strconv.Atoi(v)
  500. if err != nil {
  501. return fmt.Errorf("%s must be an integer (found: %q)", ComposeParallelLimit, v)
  502. }
  503. parallel = i
  504. }
  505. if parallel > 0 {
  506. logrus.Debugf("Limiting max concurrency to %d jobs", parallel)
  507. backendOptions.Add(compose.WithMaxConcurrency(parallel))
  508. }
  509. // dry run detection
  510. if dryRun {
  511. backendOptions.Add(compose.WithDryRun)
  512. }
  513. return nil
  514. },
  515. }
  516. c.AddCommand(
  517. upCommand(&opts, dockerCli, backendOptions),
  518. downCommand(&opts, dockerCli, backendOptions),
  519. startCommand(&opts, dockerCli, backendOptions),
  520. restartCommand(&opts, dockerCli, backendOptions),
  521. stopCommand(&opts, dockerCli, backendOptions),
  522. psCommand(&opts, dockerCli, backendOptions),
  523. listCommand(dockerCli, backendOptions),
  524. logsCommand(&opts, dockerCli, backendOptions),
  525. configCommand(&opts, dockerCli),
  526. killCommand(&opts, dockerCli, backendOptions),
  527. runCommand(&opts, dockerCli, backendOptions),
  528. removeCommand(&opts, dockerCli, backendOptions),
  529. execCommand(&opts, dockerCli, backendOptions),
  530. attachCommand(&opts, dockerCli, backendOptions),
  531. exportCommand(&opts, dockerCli, backendOptions),
  532. commitCommand(&opts, dockerCli, backendOptions),
  533. pauseCommand(&opts, dockerCli, backendOptions),
  534. unpauseCommand(&opts, dockerCli, backendOptions),
  535. topCommand(&opts, dockerCli, backendOptions),
  536. eventsCommand(&opts, dockerCli, backendOptions),
  537. portCommand(&opts, dockerCli, backendOptions),
  538. imagesCommand(&opts, dockerCli, backendOptions),
  539. versionCommand(dockerCli),
  540. buildCommand(&opts, dockerCli, backendOptions),
  541. pushCommand(&opts, dockerCli, backendOptions),
  542. pullCommand(&opts, dockerCli, backendOptions),
  543. createCommand(&opts, dockerCli, backendOptions),
  544. copyCommand(&opts, dockerCli, backendOptions),
  545. waitCommand(&opts, dockerCli, backendOptions),
  546. scaleCommand(&opts, dockerCli, backendOptions),
  547. statsCommand(&opts, dockerCli),
  548. watchCommand(&opts, dockerCli, backendOptions),
  549. publishCommand(&opts, dockerCli, backendOptions),
  550. alphaCommand(&opts, dockerCli, backendOptions),
  551. bridgeCommand(&opts, dockerCli),
  552. volumesCommand(&opts, dockerCli, backendOptions),
  553. )
  554. c.Flags().SetInterspersed(false)
  555. opts.addProjectFlags(c.Flags())
  556. c.RegisterFlagCompletionFunc( //nolint:errcheck
  557. "project-name",
  558. completeProjectNames(dockerCli, backendOptions),
  559. )
  560. c.RegisterFlagCompletionFunc( //nolint:errcheck
  561. "project-directory",
  562. func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
  563. return []string{}, cobra.ShellCompDirectiveFilterDirs
  564. },
  565. )
  566. c.RegisterFlagCompletionFunc( //nolint:errcheck
  567. "file",
  568. func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
  569. return []string{"yaml", "yml"}, cobra.ShellCompDirectiveFilterFileExt
  570. },
  571. )
  572. c.RegisterFlagCompletionFunc( //nolint:errcheck
  573. "profile",
  574. completeProfileNames(dockerCli, &opts),
  575. )
  576. c.RegisterFlagCompletionFunc( //nolint:errcheck
  577. "progress",
  578. cobra.FixedCompletions(printerModes, cobra.ShellCompDirectiveNoFileComp),
  579. )
  580. c.Flags().StringVar(&ansi, "ansi", "auto", `Control when to print ANSI control characters ("never"|"always"|"auto")`)
  581. c.Flags().IntVar(&parallel, "parallel", -1, `Control max parallelism, -1 for unlimited`)
  582. c.Flags().BoolVarP(&version, "version", "v", false, "Show the Docker Compose version information")
  583. c.PersistentFlags().BoolVar(&dryRun, "dry-run", false, "Execute command in dry run mode")
  584. c.Flags().MarkHidden("version") //nolint:errcheck
  585. c.Flags().BoolVar(&noAnsi, "no-ansi", false, `Do not print ANSI control characters (DEPRECATED)`)
  586. c.Flags().MarkHidden("no-ansi") //nolint:errcheck
  587. c.Flags().BoolVar(&verbose, "verbose", false, "Show more output")
  588. c.Flags().MarkHidden("verbose") //nolint:errcheck
  589. return c
  590. }
  591. func stdinfo(dockerCli command.Cli) io.Writer {
  592. if stdioToStdout {
  593. return dockerCli.Out()
  594. }
  595. return dockerCli.Err()
  596. }
  597. func setEnvWithDotEnv(opts ProjectOptions, dockerCli command.Cli) error {
  598. // Check if we're using a remote config (OCI or Git)
  599. // If so, skip env loading as remote loaders haven't been initialized yet
  600. // and trying to process the path would fail
  601. remoteLoaders := opts.remoteLoaders(dockerCli)
  602. for _, path := range opts.ConfigPaths {
  603. for _, loader := range remoteLoaders {
  604. if loader.Accept(path) {
  605. // Remote config - skip env loading for now
  606. // It will be loaded later when the project is fully initialized
  607. return nil
  608. }
  609. }
  610. }
  611. options, err := cli.NewProjectOptions(opts.ConfigPaths,
  612. cli.WithWorkingDirectory(opts.ProjectDir),
  613. cli.WithOsEnv,
  614. cli.WithEnvFiles(opts.EnvFiles...),
  615. cli.WithDotEnv,
  616. )
  617. if err != nil {
  618. return err
  619. }
  620. envFromFile, err := dotenv.GetEnvFromFile(composegoutils.GetAsEqualsMap(os.Environ()), options.EnvFiles)
  621. if err != nil {
  622. return err
  623. }
  624. for k, v := range envFromFile {
  625. if _, ok := os.LookupEnv(k); !ok && strings.HasPrefix(k, "COMPOSE_") {
  626. if err := os.Setenv(k, v); err != nil {
  627. return err
  628. }
  629. }
  630. }
  631. return nil
  632. }
  633. var printerModes = []string{
  634. display.ModeAuto,
  635. display.ModeTTY,
  636. display.ModePlain,
  637. display.ModeJSON,
  638. display.ModeQuiet,
  639. }