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