config.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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/v2/cli"
  22. "github.com/compose-spec/compose-go/v2/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, po ...cli.ProjectOptionsFn) (*types.Project, error) {
  45. po = append(po,
  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. return o.ProjectOptions.ToProject(ctx, dockerCli, services, po...)
  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, cli.WithoutEnvironmentResolution)
  139. if err != nil {
  140. return err
  141. }
  142. err = project.ForEachService(project.ServiceNames(), func(serviceName string, _ *types.ServiceConfig) error {
  143. fmt.Fprintln(dockerCli.Out(), serviceName)
  144. return nil
  145. })
  146. return err
  147. }
  148. func runVolumes(ctx context.Context, dockerCli command.Cli, opts configOptions) error {
  149. project, err := opts.ToProject(ctx, dockerCli, nil, cli.WithoutEnvironmentResolution)
  150. if err != nil {
  151. return err
  152. }
  153. for n := range project.Volumes {
  154. fmt.Fprintln(dockerCli.Out(), n)
  155. }
  156. return nil
  157. }
  158. func runHash(ctx context.Context, dockerCli command.Cli, opts configOptions) error {
  159. var services []string
  160. if opts.hash != "*" {
  161. services = append(services, strings.Split(opts.hash, ",")...)
  162. }
  163. project, err := opts.ToProject(ctx, dockerCli, nil, cli.WithoutEnvironmentResolution)
  164. if err != nil {
  165. return err
  166. }
  167. if err := applyPlatforms(project, true); err != nil {
  168. return err
  169. }
  170. if len(services) == 0 {
  171. services = project.ServiceNames()
  172. }
  173. sorted := services
  174. sort.Slice(sorted, func(i, j int) bool {
  175. return sorted[i] < sorted[j]
  176. })
  177. for _, name := range sorted {
  178. s, err := project.GetService(name)
  179. if err != nil {
  180. return err
  181. }
  182. hash, err := compose.ServiceHash(s)
  183. if err != nil {
  184. return err
  185. }
  186. fmt.Fprintf(dockerCli.Out(), "%s %s\n", name, hash)
  187. }
  188. return nil
  189. }
  190. func runProfiles(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) error {
  191. set := map[string]struct{}{}
  192. project, err := opts.ToProject(ctx, dockerCli, services, cli.WithoutEnvironmentResolution)
  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(dockerCli.Out(), p)
  208. }
  209. return nil
  210. }
  211. func runConfigImages(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) error {
  212. project, err := opts.ToProject(ctx, dockerCli, services, cli.WithoutEnvironmentResolution)
  213. if err != nil {
  214. return err
  215. }
  216. for _, s := range project.Services {
  217. fmt.Fprintln(dockerCli.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. }