config.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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/v2/cli"
  22. "github.com/compose-spec/compose-go/v2/types"
  23. "github.com/docker/cli/cli/command"
  24. "github.com/spf13/cobra"
  25. "github.com/docker/compose/v2/internal/tracing"
  26. "github.com/docker/compose/v2/pkg/api"
  27. "github.com/docker/compose/v2/pkg/compose"
  28. )
  29. type configOptions struct {
  30. *ProjectOptions
  31. Format string
  32. Output string
  33. quiet bool
  34. resolveImageDigests bool
  35. noInterpolate bool
  36. noNormalize bool
  37. noResolvePath bool
  38. services bool
  39. volumes bool
  40. profiles bool
  41. images bool
  42. hash string
  43. noConsistency bool
  44. }
  45. func (o *configOptions) ToProject(ctx context.Context, dockerCli command.Cli, services []string, po ...cli.ProjectOptionsFn) (*types.Project, tracing.Metrics, error) {
  46. po = append(po,
  47. cli.WithInterpolation(!o.noInterpolate),
  48. cli.WithResolvedPaths(!o.noResolvePath),
  49. cli.WithNormalization(!o.noNormalize),
  50. cli.WithConsistency(!o.noConsistency),
  51. cli.WithDefaultProfiles(o.Profiles...),
  52. cli.WithDiscardEnvFile)
  53. return o.ProjectOptions.ToProject(ctx, 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. err = project.ForEachService(project.ServiceNames(), func(serviceName string, _ *types.ServiceConfig) error {
  144. fmt.Fprintln(dockerCli.Out(), serviceName)
  145. return nil
  146. })
  147. return err
  148. }
  149. func runVolumes(ctx context.Context, dockerCli command.Cli, opts configOptions) error {
  150. project, _, err := opts.ToProject(ctx, dockerCli, nil, cli.WithoutEnvironmentResolution)
  151. if err != nil {
  152. return err
  153. }
  154. for n := range project.Volumes {
  155. fmt.Fprintln(dockerCli.Out(), n)
  156. }
  157. return nil
  158. }
  159. func runHash(ctx context.Context, dockerCli command.Cli, opts configOptions) error {
  160. var services []string
  161. if opts.hash != "*" {
  162. services = append(services, strings.Split(opts.hash, ",")...)
  163. }
  164. project, _, err := opts.ToProject(ctx, dockerCli, nil, cli.WithoutEnvironmentResolution)
  165. if err != nil {
  166. return err
  167. }
  168. if err := applyPlatforms(project, true); err != nil {
  169. return err
  170. }
  171. if len(services) == 0 {
  172. services = project.ServiceNames()
  173. }
  174. sorted := services
  175. sort.Slice(sorted, func(i, j int) bool {
  176. return sorted[i] < sorted[j]
  177. })
  178. for _, name := range sorted {
  179. s, err := project.GetService(name)
  180. if err != nil {
  181. return err
  182. }
  183. hash, err := compose.ServiceHash(s)
  184. if err != nil {
  185. return err
  186. }
  187. fmt.Fprintf(dockerCli.Out(), "%s %s\n", name, hash)
  188. }
  189. return nil
  190. }
  191. func runProfiles(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) error {
  192. set := map[string]struct{}{}
  193. project, _, err := opts.ToProject(ctx, dockerCli, services, cli.WithoutEnvironmentResolution)
  194. if err != nil {
  195. return err
  196. }
  197. for _, s := range project.AllServices() {
  198. for _, p := range s.Profiles {
  199. set[p] = struct{}{}
  200. }
  201. }
  202. profiles := make([]string, 0, len(set))
  203. for p := range set {
  204. profiles = append(profiles, p)
  205. }
  206. sort.Strings(profiles)
  207. for _, p := range profiles {
  208. fmt.Fprintln(dockerCli.Out(), p)
  209. }
  210. return nil
  211. }
  212. func runConfigImages(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) error {
  213. project, _, err := opts.ToProject(ctx, dockerCli, services, cli.WithoutEnvironmentResolution)
  214. if err != nil {
  215. return err
  216. }
  217. for _, s := range project.Services {
  218. fmt.Fprintln(dockerCli.Out(), api.GetImageNameOrDefault(s, project.Name))
  219. }
  220. return nil
  221. }
  222. func escapeDollarSign(marshal []byte) []byte {
  223. dollar := []byte{'$'}
  224. escDollar := []byte{'$', '$'}
  225. return bytes.ReplaceAll(marshal, dollar, escDollar)
  226. }