compose.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  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/manager"
  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/desktop"
  38. "github.com/docker/compose/v2/internal/experimental"
  39. "github.com/docker/compose/v2/internal/tracing"
  40. "github.com/docker/compose/v2/pkg/api"
  41. ui "github.com/docker/compose/v2/pkg/progress"
  42. "github.com/docker/compose/v2/pkg/remote"
  43. "github.com/docker/compose/v2/pkg/utils"
  44. buildkit "github.com/moby/buildkit/util/progress/progressui"
  45. "github.com/morikuni/aec"
  46. "github.com/sirupsen/logrus"
  47. "github.com/spf13/cobra"
  48. "github.com/spf13/pflag"
  49. )
  50. const (
  51. // ComposeParallelLimit set the limit running concurrent operation on docker engine
  52. ComposeParallelLimit = "COMPOSE_PARALLEL_LIMIT"
  53. // ComposeProjectName define the project name to be used, instead of guessing from parent directory
  54. ComposeProjectName = "COMPOSE_PROJECT_NAME"
  55. // ComposeCompatibility try to mimic compose v1 as much as possible
  56. ComposeCompatibility = "COMPOSE_COMPATIBILITY"
  57. // ComposeRemoveOrphans remove "orphaned" containers, i.e. containers tagged for current project but not declared as service
  58. ComposeRemoveOrphans = "COMPOSE_REMOVE_ORPHANS"
  59. // ComposeIgnoreOrphans ignore "orphaned" containers
  60. ComposeIgnoreOrphans = "COMPOSE_IGNORE_ORPHANS"
  61. // ComposeEnvFiles defines the env files to use if --env-file isn't used
  62. ComposeEnvFiles = "COMPOSE_ENV_FILES"
  63. // ComposeMenu defines if the navigation menu should be rendered. Can be also set via --menu
  64. ComposeMenu = "COMPOSE_MENU"
  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, lookup func(key string) (string, bool)) (map[string]string, error) {
  68. lines, err := kvfile.ParseFromReader(r, lookup)
  69. if err != nil {
  70. return nil, fmt.Errorf("failed to parse env_file %s: %w", filename, err)
  71. }
  72. vars := types.Mapping{}
  73. for _, line := range lines {
  74. key, value, _ := strings.Cut(line, "=")
  75. vars[key] = value
  76. }
  77. return vars, nil
  78. }
  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. }
  84. type Backend interface {
  85. api.Service
  86. SetDesktopClient(cli *desktop.Client)
  87. SetExperiments(experiments *experimental.State)
  88. }
  89. // Command defines a compose CLI command as a func with args
  90. type Command func(context.Context, []string) error
  91. // CobraCommand defines a cobra command function
  92. type CobraCommand func(context.Context, *cobra.Command, []string) error
  93. // AdaptCmd adapt a CobraCommand func to cobra library
  94. func AdaptCmd(fn CobraCommand) func(cmd *cobra.Command, args []string) error {
  95. return func(cmd *cobra.Command, args []string) error {
  96. ctx, cancel := context.WithCancel(cmd.Context())
  97. s := make(chan os.Signal, 1)
  98. signal.Notify(s, syscall.SIGTERM, syscall.SIGINT)
  99. go func() {
  100. <-s
  101. cancel()
  102. signal.Stop(s)
  103. close(s)
  104. }()
  105. err := fn(ctx, cmd, args)
  106. if api.IsErrCanceled(err) || errors.Is(ctx.Err(), context.Canceled) {
  107. err = dockercli.StatusError{
  108. StatusCode: 130,
  109. }
  110. }
  111. if ui.Mode == ui.ModeJSON {
  112. err = makeJSONError(err)
  113. }
  114. return err
  115. }
  116. }
  117. // Adapt a Command func to cobra library
  118. func Adapt(fn Command) func(cmd *cobra.Command, args []string) error {
  119. return AdaptCmd(func(ctx context.Context, cmd *cobra.Command, args []string) error {
  120. return fn(ctx, args)
  121. })
  122. }
  123. type ProjectOptions struct {
  124. ProjectName string
  125. Profiles []string
  126. ConfigPaths []string
  127. WorkDir string
  128. ProjectDir string
  129. EnvFiles []string
  130. Compatibility bool
  131. Progress string
  132. Offline bool
  133. All bool
  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, args []string) error {
  148. options := []cli.ProjectOptionsFn{
  149. cli.WithResolvedPaths(true),
  150. cli.WithDiscardEnvFile,
  151. }
  152. project, metrics, err := o.ToProject(ctx, dockerCli, args, options...)
  153. if err != nil {
  154. return err
  155. }
  156. ctx = context.WithValue(ctx, tracing.MetricsKey{}, metrics)
  157. return fn(ctx, project, args)
  158. })
  159. }
  160. type jsonErrorData struct {
  161. Error bool `json:"error,omitempty"`
  162. Message string `json:"message,omitempty"`
  163. }
  164. func errorAsJSON(message string) string {
  165. errorMessage := &jsonErrorData{
  166. Error: true,
  167. Message: message,
  168. }
  169. marshal, err := json.Marshal(errorMessage)
  170. if err == nil {
  171. return string(marshal)
  172. } else {
  173. return message
  174. }
  175. }
  176. func makeJSONError(err error) error {
  177. if err == nil {
  178. return nil
  179. }
  180. var statusErr dockercli.StatusError
  181. if errors.As(err, &statusErr) {
  182. return dockercli.StatusError{
  183. StatusCode: statusErr.StatusCode,
  184. Status: errorAsJSON(statusErr.Status),
  185. }
  186. }
  187. return fmt.Errorf("%s", errorAsJSON(err.Error()))
  188. }
  189. func (o *ProjectOptions) addProjectFlags(f *pflag.FlagSet) {
  190. f.StringArrayVar(&o.Profiles, "profile", []string{}, "Specify a profile to enable")
  191. f.StringVarP(&o.ProjectName, "project-name", "p", "", "Project name")
  192. f.StringArrayVarP(&o.ConfigPaths, "file", "f", []string{}, "Compose configuration files")
  193. f.StringArrayVar(&o.EnvFiles, "env-file", defaultStringArrayVar(ComposeEnvFiles), "Specify an alternate environment file")
  194. f.StringVar(&o.ProjectDir, "project-directory", "", "Specify an alternate working directory\n(default: the path of the, first specified, Compose file)")
  195. 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)")
  196. f.BoolVar(&o.Compatibility, "compatibility", false, "Run compose in backward compatibility mode")
  197. f.StringVar(&o.Progress, "progress", string(buildkit.AutoMode), fmt.Sprintf(`Set type of progress output (%s)`, strings.Join(printerModes, ", ")))
  198. f.BoolVar(&o.All, "all-resources", false, "Include all resources, even those not used by services")
  199. _ = f.MarkHidden("workdir")
  200. }
  201. // get default value for a command line flag that is set by a coma-separated value in environment variable
  202. func defaultStringArrayVar(env string) []string {
  203. return strings.FieldsFunc(os.Getenv(env), func(c rune) bool {
  204. return c == ','
  205. })
  206. }
  207. func (o *ProjectOptions) projectOrName(ctx context.Context, dockerCli command.Cli, services ...string) (*types.Project, string, error) {
  208. name := o.ProjectName
  209. var project *types.Project
  210. if len(o.ConfigPaths) > 0 || o.ProjectName == "" {
  211. p, _, err := o.ToProject(ctx, dockerCli, services, cli.WithDiscardEnvFile)
  212. if err != nil {
  213. envProjectName := os.Getenv(ComposeProjectName)
  214. if envProjectName != "" {
  215. return nil, envProjectName, nil
  216. }
  217. return nil, "", err
  218. }
  219. project = p
  220. name = p.Name
  221. }
  222. return project, name, nil
  223. }
  224. func (o *ProjectOptions) toProjectName(ctx context.Context, dockerCli command.Cli) (string, error) {
  225. if o.ProjectName != "" {
  226. return o.ProjectName, nil
  227. }
  228. envProjectName := os.Getenv(ComposeProjectName)
  229. if envProjectName != "" {
  230. return envProjectName, nil
  231. }
  232. project, _, err := o.ToProject(ctx, dockerCli, nil)
  233. if err != nil {
  234. return "", err
  235. }
  236. return project.Name, nil
  237. }
  238. func (o *ProjectOptions) ToModel(ctx context.Context, dockerCli command.Cli, services []string, po ...cli.ProjectOptionsFn) (map[string]any, error) {
  239. remotes := o.remoteLoaders(dockerCli)
  240. for _, r := range remotes {
  241. po = append(po, cli.WithResourceLoader(r))
  242. }
  243. options, err := o.toProjectOptions(po...)
  244. if err != nil {
  245. return nil, err
  246. }
  247. if o.Compatibility || utils.StringToBool(options.Environment[ComposeCompatibility]) {
  248. api.Separator = "_"
  249. }
  250. return options.LoadModel(ctx)
  251. }
  252. func (o *ProjectOptions) ToProject(ctx context.Context, dockerCli command.Cli, services []string, po ...cli.ProjectOptionsFn) (*types.Project, tracing.Metrics, error) { //nolint:gocyclo
  253. var metrics tracing.Metrics
  254. remotes := o.remoteLoaders(dockerCli)
  255. for _, r := range remotes {
  256. po = append(po, cli.WithResourceLoader(r))
  257. }
  258. options, err := o.toProjectOptions(po...)
  259. if err != nil {
  260. return nil, metrics, err
  261. }
  262. options.WithListeners(func(event string, metadata map[string]any) {
  263. switch event {
  264. case "extends":
  265. metrics.CountExtends++
  266. case "include":
  267. paths := metadata["path"].(types.StringList)
  268. for _, path := range paths {
  269. var isRemote bool
  270. for _, r := range remotes {
  271. if r.Accept(path) {
  272. isRemote = true
  273. break
  274. }
  275. }
  276. if isRemote {
  277. metrics.CountIncludesRemote++
  278. } else {
  279. metrics.CountIncludesLocal++
  280. }
  281. }
  282. }
  283. })
  284. if o.Compatibility || utils.StringToBool(options.Environment[ComposeCompatibility]) {
  285. api.Separator = "_"
  286. }
  287. project, err := options.LoadProject(ctx)
  288. if err != nil {
  289. return nil, metrics, err
  290. }
  291. if project.Name == "" {
  292. return nil, metrics, errors.New("project name can't be empty. Use `--project-name` to set a valid name")
  293. }
  294. project, err = project.WithServicesEnabled(services...)
  295. if err != nil {
  296. return nil, metrics, err
  297. }
  298. for name, s := range project.Services {
  299. s.CustomLabels = map[string]string{
  300. api.ProjectLabel: project.Name,
  301. api.ServiceLabel: name,
  302. api.VersionLabel: api.ComposeVersion,
  303. api.WorkingDirLabel: project.WorkingDir,
  304. api.ConfigFilesLabel: strings.Join(project.ComposeFiles, ","),
  305. api.OneoffLabel: "False", // default, will be overridden by `run` command
  306. }
  307. if len(o.EnvFiles) != 0 {
  308. s.CustomLabels[api.EnvironmentFileLabel] = strings.Join(o.EnvFiles, ",")
  309. }
  310. project.Services[name] = s
  311. }
  312. project, err = project.WithSelectedServices(services)
  313. if err != nil {
  314. return nil, tracing.Metrics{}, err
  315. }
  316. if !o.All {
  317. project = project.WithoutUnnecessaryResources()
  318. }
  319. return project, metrics, err
  320. }
  321. func (o *ProjectOptions) remoteLoaders(dockerCli command.Cli) []loader.ResourceLoader {
  322. if o.Offline {
  323. return nil
  324. }
  325. git := remote.NewGitRemoteLoader(dockerCli, o.Offline)
  326. oci := remote.NewOCIRemoteLoader(dockerCli, o.Offline)
  327. return []loader.ResourceLoader{git, oci}
  328. }
  329. func (o *ProjectOptions) toProjectOptions(po ...cli.ProjectOptionsFn) (*cli.ProjectOptions, error) {
  330. return cli.NewProjectOptions(o.ConfigPaths,
  331. append(po,
  332. cli.WithWorkingDirectory(o.ProjectDir),
  333. // First apply os.Environment, always win
  334. cli.WithOsEnv,
  335. // Load PWD/.env if present and no explicit --env-file has been set
  336. cli.WithEnvFiles(o.EnvFiles...),
  337. // read dot env file to populate project environment
  338. cli.WithDotEnv,
  339. // get compose file path set by COMPOSE_FILE
  340. cli.WithConfigFileEnv,
  341. // if none was selected, get default compose.yaml file from current dir or parent folder
  342. cli.WithDefaultConfigPath,
  343. // .. and then, a project directory != PWD maybe has been set so let's load .env file
  344. cli.WithEnvFiles(o.EnvFiles...),
  345. cli.WithDotEnv,
  346. // eventually COMPOSE_PROFILES should have been set
  347. cli.WithDefaultProfiles(o.Profiles...),
  348. cli.WithName(o.ProjectName))...)
  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] != manager.MetadataSubcommandName && os.Args[1] != PluginName
  355. }
  356. // RootCommand returns the compose command with its child commands
  357. func RootCommand(dockerCli command.Cli, backend Backend) *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. experiments := experimental.NewState()
  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. ctx := cmd.Context()
  398. parent := cmd.Root()
  399. if parent != nil {
  400. parentPrerun := parent.PersistentPreRunE
  401. if parentPrerun != nil {
  402. err := parentPrerun(cmd, args)
  403. if err != nil {
  404. return err
  405. }
  406. }
  407. }
  408. if verbose {
  409. logrus.SetLevel(logrus.TraceLevel)
  410. }
  411. err := setEnvWithDotEnv(opts)
  412. if err != nil {
  413. return err
  414. }
  415. if noAnsi {
  416. if ansi != "auto" {
  417. return errors.New(`cannot specify DEPRECATED "--no-ansi" and "--ansi". Please use only "--ansi"`)
  418. }
  419. ansi = "never"
  420. fmt.Fprint(os.Stderr, "option '--no-ansi' is DEPRECATED ! Please use '--ansi' instead.\n")
  421. }
  422. if v, ok := os.LookupEnv("COMPOSE_ANSI"); ok && !cmd.Flags().Changed("ansi") {
  423. ansi = v
  424. }
  425. formatter.SetANSIMode(dockerCli, ansi)
  426. if noColor, ok := os.LookupEnv("NO_COLOR"); ok && noColor != "" {
  427. ui.NoColor()
  428. formatter.SetANSIMode(dockerCli, formatter.Never)
  429. }
  430. switch ansi {
  431. case "never":
  432. ui.Mode = ui.ModePlain
  433. case "always":
  434. ui.Mode = ui.ModeTTY
  435. }
  436. switch opts.Progress {
  437. case ui.ModeAuto:
  438. ui.Mode = ui.ModeAuto
  439. if ansi == "never" {
  440. ui.Mode = ui.ModePlain
  441. }
  442. case ui.ModeTTY:
  443. if ansi == "never" {
  444. return fmt.Errorf("can't use --progress tty while ANSI support is disabled")
  445. }
  446. ui.Mode = ui.ModeTTY
  447. case ui.ModePlain:
  448. if ansi == "always" {
  449. return fmt.Errorf("can't use --progress plain while ANSI support is forced")
  450. }
  451. ui.Mode = ui.ModePlain
  452. case ui.ModeQuiet, "none":
  453. ui.Mode = ui.ModeQuiet
  454. case ui.ModeJSON:
  455. ui.Mode = ui.ModeJSON
  456. logrus.SetFormatter(&logrus.JSONFormatter{})
  457. default:
  458. return fmt.Errorf("unsupported --progress value %q", opts.Progress)
  459. }
  460. // (4) options validation / normalization
  461. if opts.WorkDir != "" {
  462. if opts.ProjectDir != "" {
  463. return errors.New(`cannot specify DEPRECATED "--workdir" and "--project-directory". Please use only "--project-directory" instead`)
  464. }
  465. opts.ProjectDir = opts.WorkDir
  466. fmt.Fprint(os.Stderr, aec.Apply("option '--workdir' is DEPRECATED at root level! Please use '--project-directory' instead.\n", aec.RedF))
  467. }
  468. for i, file := range opts.EnvFiles {
  469. if !filepath.IsAbs(file) {
  470. file, err := filepath.Abs(file)
  471. if err != nil {
  472. return err
  473. }
  474. opts.EnvFiles[i] = file
  475. }
  476. }
  477. composeCmd := cmd
  478. for {
  479. if composeCmd.Name() == PluginName {
  480. break
  481. }
  482. if !composeCmd.HasParent() {
  483. return fmt.Errorf("error parsing command line, expected %q", PluginName)
  484. }
  485. composeCmd = composeCmd.Parent()
  486. }
  487. if v, ok := os.LookupEnv(ComposeParallelLimit); ok && !composeCmd.Flags().Changed("parallel") {
  488. i, err := strconv.Atoi(v)
  489. if err != nil {
  490. return fmt.Errorf("%s must be an integer (found: %q)", ComposeParallelLimit, v)
  491. }
  492. parallel = i
  493. }
  494. if parallel > 0 {
  495. logrus.Debugf("Limiting max concurrency to %d jobs", parallel)
  496. backend.MaxConcurrency(parallel)
  497. }
  498. // dry run detection
  499. ctx, err = backend.DryRunMode(ctx, dryRun)
  500. if err != nil {
  501. return err
  502. }
  503. cmd.SetContext(ctx)
  504. // (6) Desktop integration
  505. var desktopCli *desktop.Client
  506. if !dryRun {
  507. if desktopCli, err = desktop.NewFromDockerClient(ctx, dockerCli); desktopCli != nil {
  508. logrus.Debugf("Enabled Docker Desktop integration (experimental) @ %s", desktopCli.Endpoint())
  509. backend.SetDesktopClient(desktopCli)
  510. } else if err != nil {
  511. // not fatal, Compose will still work but behave as though
  512. // it's not running as part of Docker Desktop
  513. logrus.Debugf("failed to enable Docker Desktop integration: %v", err)
  514. } else {
  515. logrus.Trace("Docker Desktop integration not enabled")
  516. }
  517. }
  518. // (7) experimental features
  519. if err := experiments.Load(ctx, desktopCli); err != nil {
  520. logrus.Debugf("Failed to query feature flags from Desktop: %v", err)
  521. }
  522. backend.SetExperiments(experiments)
  523. return nil
  524. },
  525. }
  526. c.AddCommand(
  527. upCommand(&opts, dockerCli, backend),
  528. downCommand(&opts, dockerCli, backend),
  529. startCommand(&opts, dockerCli, backend),
  530. restartCommand(&opts, dockerCli, backend),
  531. stopCommand(&opts, dockerCli, backend),
  532. psCommand(&opts, dockerCli, backend),
  533. listCommand(dockerCli, backend),
  534. logsCommand(&opts, dockerCli, backend),
  535. configCommand(&opts, dockerCli),
  536. killCommand(&opts, dockerCli, backend),
  537. runCommand(&opts, dockerCli, backend),
  538. removeCommand(&opts, dockerCli, backend),
  539. execCommand(&opts, dockerCli, backend),
  540. attachCommand(&opts, dockerCli, backend),
  541. exportCommand(&opts, dockerCli, backend),
  542. commitCommand(&opts, dockerCli, backend),
  543. pauseCommand(&opts, dockerCli, backend),
  544. unpauseCommand(&opts, dockerCli, backend),
  545. topCommand(&opts, dockerCli, backend),
  546. eventsCommand(&opts, dockerCli, backend),
  547. portCommand(&opts, dockerCli, backend),
  548. imagesCommand(&opts, dockerCli, backend),
  549. versionCommand(dockerCli),
  550. buildCommand(&opts, dockerCli, backend),
  551. pushCommand(&opts, dockerCli, backend),
  552. pullCommand(&opts, dockerCli, backend),
  553. createCommand(&opts, dockerCli, backend),
  554. copyCommand(&opts, dockerCli, backend),
  555. waitCommand(&opts, dockerCli, backend),
  556. scaleCommand(&opts, dockerCli, backend),
  557. statsCommand(&opts, dockerCli),
  558. watchCommand(&opts, dockerCli, backend),
  559. alphaCommand(&opts, dockerCli, backend),
  560. )
  561. c.Flags().SetInterspersed(false)
  562. opts.addProjectFlags(c.Flags())
  563. c.RegisterFlagCompletionFunc( //nolint:errcheck
  564. "project-name",
  565. completeProjectNames(backend),
  566. )
  567. c.RegisterFlagCompletionFunc( //nolint:errcheck
  568. "project-directory",
  569. func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
  570. return []string{}, cobra.ShellCompDirectiveFilterDirs
  571. },
  572. )
  573. c.RegisterFlagCompletionFunc( //nolint:errcheck
  574. "file",
  575. func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
  576. return []string{"yaml", "yml"}, cobra.ShellCompDirectiveFilterFileExt
  577. },
  578. )
  579. c.RegisterFlagCompletionFunc( //nolint:errcheck
  580. "profile",
  581. completeProfileNames(dockerCli, &opts),
  582. )
  583. c.Flags().StringVar(&ansi, "ansi", "auto", `Control when to print ANSI control characters ("never"|"always"|"auto")`)
  584. c.Flags().IntVar(&parallel, "parallel", -1, `Control max parallelism, -1 for unlimited`)
  585. c.Flags().BoolVarP(&version, "version", "v", false, "Show the Docker Compose version information")
  586. c.PersistentFlags().BoolVar(&dryRun, "dry-run", false, "Execute command in dry run mode")
  587. c.Flags().MarkHidden("version") //nolint:errcheck
  588. c.Flags().BoolVar(&noAnsi, "no-ansi", false, `Do not print ANSI control characters (DEPRECATED)`)
  589. c.Flags().MarkHidden("no-ansi") //nolint:errcheck
  590. c.Flags().BoolVar(&verbose, "verbose", false, "Show more output")
  591. c.Flags().MarkHidden("verbose") //nolint:errcheck
  592. return c
  593. }
  594. func setEnvWithDotEnv(opts ProjectOptions) error {
  595. options, err := cli.NewProjectOptions(opts.ConfigPaths,
  596. cli.WithWorkingDirectory(opts.ProjectDir),
  597. cli.WithOsEnv,
  598. cli.WithEnvFiles(opts.EnvFiles...),
  599. cli.WithDotEnv,
  600. )
  601. if err != nil {
  602. return nil
  603. }
  604. envFromFile, err := dotenv.GetEnvFromFile(composegoutils.GetAsEqualsMap(os.Environ()), options.EnvFiles)
  605. if err != nil {
  606. return nil
  607. }
  608. for k, v := range envFromFile {
  609. if _, ok := os.LookupEnv(k); !ok {
  610. if err = os.Setenv(k, v); err != nil {
  611. return nil
  612. }
  613. }
  614. }
  615. return err
  616. }
  617. var printerModes = []string{
  618. ui.ModeAuto,
  619. ui.ModeTTY,
  620. ui.ModePlain,
  621. ui.ModeJSON,
  622. ui.ModeQuiet,
  623. }
  624. func SetUnchangedOption(name string, experimentalFlag bool) bool {
  625. var value bool
  626. // If the var is defined we use that value first
  627. if envVar, ok := os.LookupEnv(name); ok {
  628. value = utils.StringToBool(envVar)
  629. } else {
  630. // if not, we try to get it from experimental feature flag
  631. value = experimentalFlag
  632. }
  633. return value
  634. }