config.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. "bytes"
  16. "context"
  17. "fmt"
  18. "os"
  19. "sort"
  20. "strings"
  21. "github.com/compose-spec/compose-go/cli"
  22. "github.com/compose-spec/compose-go/types"
  23. "github.com/docker/cli/cli/command"
  24. "github.com/spf13/cobra"
  25. "github.com/docker/compose/v2/pkg/api"
  26. "github.com/docker/compose/v2/pkg/compose"
  27. )
  28. type configOptions struct {
  29. *ProjectOptions
  30. Format string
  31. Output string
  32. quiet bool
  33. resolveImageDigests bool
  34. noInterpolate bool
  35. noNormalize bool
  36. noResolvePath bool
  37. services bool
  38. volumes bool
  39. profiles bool
  40. images bool
  41. hash string
  42. noConsistency bool
  43. }
  44. func (o *configOptions) ToProject(ctx context.Context, dockerCli command.Cli, services []string, po ...cli.ProjectOptionsFn) (*types.Project, error) {
  45. po = append(po,
  46. cli.WithInterpolation(!o.noInterpolate),
  47. cli.WithResolvedPaths(!o.noResolvePath),
  48. cli.WithNormalization(!o.noNormalize),
  49. cli.WithConsistency(!o.noConsistency),
  50. cli.WithDefaultProfiles(o.Profiles...),
  51. cli.WithDiscardEnvFile,
  52. cli.WithContext(ctx))
  53. return o.ProjectOptions.ToProject(dockerCli, services, po...)
  54. }
  55. func configCommand(p *ProjectOptions, dockerCli command.Cli, backend api.Service) *cobra.Command {
  56. opts := configOptions{
  57. ProjectOptions: p,
  58. }
  59. cmd := &cobra.Command{
  60. Aliases: []string{"convert"}, // for backward compatibility with Cloud integrations
  61. Use: "config [OPTIONS] [SERVICE...]",
  62. Short: "Parse, resolve and render compose file in canonical format",
  63. PreRunE: Adapt(func(ctx context.Context, args []string) error {
  64. if opts.quiet {
  65. devnull, err := os.Open(os.DevNull)
  66. if err != nil {
  67. return err
  68. }
  69. os.Stdout = devnull
  70. }
  71. if p.Compatibility {
  72. opts.noNormalize = true
  73. }
  74. return nil
  75. }),
  76. RunE: Adapt(func(ctx context.Context, args []string) error {
  77. if opts.services {
  78. return runServices(ctx, dockerCli, opts)
  79. }
  80. if opts.volumes {
  81. return runVolumes(ctx, dockerCli, opts)
  82. }
  83. if opts.hash != "" {
  84. return runHash(ctx, dockerCli, opts)
  85. }
  86. if opts.profiles {
  87. return runProfiles(ctx, dockerCli, opts, args)
  88. }
  89. if opts.images {
  90. return runConfigImages(ctx, dockerCli, opts, args)
  91. }
  92. return runConfig(ctx, dockerCli, backend, opts, args)
  93. }),
  94. ValidArgsFunction: completeServiceNames(dockerCli, p),
  95. }
  96. flags := cmd.Flags()
  97. flags.StringVar(&opts.Format, "format", "yaml", "Format the output. Values: [yaml | json]")
  98. flags.BoolVar(&opts.resolveImageDigests, "resolve-image-digests", false, "Pin image tags to digests.")
  99. flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Only validate the configuration, don't print anything.")
  100. flags.BoolVar(&opts.noInterpolate, "no-interpolate", false, "Don't interpolate environment variables.")
  101. flags.BoolVar(&opts.noNormalize, "no-normalize", false, "Don't normalize compose model.")
  102. flags.BoolVar(&opts.noResolvePath, "no-path-resolution", false, "Don't resolve file paths.")
  103. flags.BoolVar(&opts.noConsistency, "no-consistency", false, "Don't check model consistency - warning: may produce invalid Compose output")
  104. flags.BoolVar(&opts.services, "services", false, "Print the service names, one per line.")
  105. flags.BoolVar(&opts.volumes, "volumes", false, "Print the volume names, one per line.")
  106. flags.BoolVar(&opts.profiles, "profiles", false, "Print the profile names, one per line.")
  107. flags.BoolVar(&opts.images, "images", false, "Print the image names, one per line.")
  108. flags.StringVar(&opts.hash, "hash", "", "Print the service config hash, one per line.")
  109. flags.StringVarP(&opts.Output, "output", "o", "", "Save to file (default to stdout)")
  110. return cmd
  111. }
  112. func runConfig(ctx context.Context, dockerCli command.Cli, backend api.Service, opts configOptions, services []string) error {
  113. var content []byte
  114. project, err := opts.ToProject(ctx, dockerCli, services)
  115. if err != nil {
  116. return err
  117. }
  118. content, err = backend.Config(ctx, project, api.ConfigOptions{
  119. Format: opts.Format,
  120. Output: opts.Output,
  121. ResolveImageDigests: opts.resolveImageDigests,
  122. })
  123. if err != nil {
  124. return err
  125. }
  126. if !opts.noInterpolate {
  127. content = escapeDollarSign(content)
  128. }
  129. if opts.quiet {
  130. return nil
  131. }
  132. if opts.Output != "" && len(content) > 0 {
  133. return os.WriteFile(opts.Output, content, 0o666)
  134. }
  135. _, err = fmt.Fprint(dockerCli.Out(), string(content))
  136. return err
  137. }
  138. func runServices(ctx context.Context, dockerCli command.Cli, opts configOptions) error {
  139. project, err := opts.ToProject(ctx, dockerCli, nil, cli.WithoutEnvironmentResolution)
  140. if err != nil {
  141. return err
  142. }
  143. return project.WithServices(project.ServiceNames(), func(s types.ServiceConfig) error {
  144. fmt.Fprintln(dockerCli.Out(), s.Name)
  145. return nil
  146. })
  147. }
  148. func runVolumes(ctx context.Context, dockerCli command.Cli, opts configOptions) error {
  149. project, err := opts.ToProject(ctx, dockerCli, nil, cli.WithoutEnvironmentResolution)
  150. if err != nil {
  151. return err
  152. }
  153. for n := range project.Volumes {
  154. fmt.Fprintln(dockerCli.Out(), n)
  155. }
  156. return nil
  157. }
  158. func runHash(ctx context.Context, dockerCli command.Cli, opts configOptions) error {
  159. var services []string
  160. if opts.hash != "*" {
  161. services = append(services, strings.Split(opts.hash, ",")...)
  162. }
  163. project, err := opts.ToProject(ctx, dockerCli, nil, cli.WithoutEnvironmentResolution)
  164. if err != nil {
  165. return err
  166. }
  167. if err := applyPlatforms(project, true); err != nil {
  168. return err
  169. }
  170. sorted := services
  171. sort.Slice(sorted, func(i, j int) bool {
  172. return sorted[i] < sorted[j]
  173. })
  174. for _, name := range sorted {
  175. s, err := project.GetService(name)
  176. if err != nil {
  177. return err
  178. }
  179. hash, err := compose.ServiceHash(s)
  180. if err != nil {
  181. return err
  182. }
  183. fmt.Fprintf(dockerCli.Out(), "%s %s\n", s.Name, hash)
  184. }
  185. return nil
  186. }
  187. func runProfiles(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) error {
  188. set := map[string]struct{}{}
  189. project, err := opts.ToProject(ctx, dockerCli, services, cli.WithoutEnvironmentResolution)
  190. if err != nil {
  191. return err
  192. }
  193. for _, s := range project.AllServices() {
  194. for _, p := range s.Profiles {
  195. set[p] = struct{}{}
  196. }
  197. }
  198. profiles := make([]string, 0, len(set))
  199. for p := range set {
  200. profiles = append(profiles, p)
  201. }
  202. sort.Strings(profiles)
  203. for _, p := range profiles {
  204. fmt.Fprintln(dockerCli.Out(), p)
  205. }
  206. return nil
  207. }
  208. func runConfigImages(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) error {
  209. project, err := opts.ToProject(ctx, dockerCli, services, cli.WithoutEnvironmentResolution)
  210. if err != nil {
  211. return err
  212. }
  213. for _, s := range project.Services {
  214. fmt.Fprintln(dockerCli.Out(), api.GetImageNameOrDefault(s, project.Name))
  215. }
  216. return nil
  217. }
  218. func escapeDollarSign(marshal []byte) []byte {
  219. dollar := []byte{'$'}
  220. escDollar := []byte{'$', '$'}
  221. return bytes.ReplaceAll(marshal, dollar, escDollar)
  222. }