config.go 6.3 KB

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