config.go 7.1 KB

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