config.go 6.8 KB

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