config.go 6.7 KB

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