convert.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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. "bufio"
  16. "context"
  17. "fmt"
  18. "io"
  19. "os"
  20. "sort"
  21. "strings"
  22. "github.com/cnabio/cnab-to-oci/remotes"
  23. "github.com/compose-spec/compose-go/cli"
  24. "github.com/compose-spec/compose-go/types"
  25. "github.com/distribution/distribution/v3/reference"
  26. cliconfig "github.com/docker/cli/cli/config"
  27. "github.com/opencontainers/go-digest"
  28. "github.com/spf13/cobra"
  29. "github.com/docker/compose/v2/pkg/api"
  30. "github.com/docker/compose/v2/pkg/compose"
  31. )
  32. type convertOptions struct {
  33. *projectOptions
  34. Format string
  35. Output string
  36. quiet bool
  37. resolveImageDigests bool
  38. noInterpolate bool
  39. services bool
  40. volumes bool
  41. profiles bool
  42. hash string
  43. }
  44. func convertCommand(p *projectOptions, backend api.Service) *cobra.Command {
  45. opts := convertOptions{
  46. projectOptions: p,
  47. }
  48. cmd := &cobra.Command{
  49. Aliases: []string{"config"},
  50. Use: "convert SERVICES",
  51. Short: "Converts the compose file to platform's canonical format",
  52. PreRunE: Adapt(func(ctx context.Context, args []string) error {
  53. if opts.quiet {
  54. devnull, err := os.Open(os.DevNull)
  55. if err != nil {
  56. return err
  57. }
  58. os.Stdout = devnull
  59. }
  60. return nil
  61. }),
  62. RunE: Adapt(func(ctx context.Context, args []string) error {
  63. if opts.services {
  64. return runServices(opts)
  65. }
  66. if opts.volumes {
  67. return runVolumes(opts)
  68. }
  69. if opts.hash != "" {
  70. return runHash(opts)
  71. }
  72. if opts.profiles {
  73. return runProfiles(opts, args)
  74. }
  75. return runConvert(ctx, backend, opts, args)
  76. }),
  77. ValidArgsFunction: serviceCompletion(p),
  78. }
  79. flags := cmd.Flags()
  80. flags.StringVar(&opts.Format, "format", "yaml", "Format the output. Values: [yaml | json]")
  81. flags.BoolVar(&opts.resolveImageDigests, "resolve-image-digests", false, "Pin image tags to digests.")
  82. flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Only validate the configuration, don't print anything.")
  83. flags.BoolVar(&opts.noInterpolate, "no-interpolate", false, "Don't interpolate environment variables.")
  84. flags.BoolVar(&opts.services, "services", false, "Print the service names, one per line.")
  85. flags.BoolVar(&opts.volumes, "volumes", false, "Print the volume names, one per line.")
  86. flags.BoolVar(&opts.profiles, "profiles", false, "Print the profile names, one per line.")
  87. flags.StringVar(&opts.hash, "hash", "", "Print the service config hash, one per line.")
  88. flags.StringVarP(&opts.Output, "output", "o", "", "Save to file (default to stdout)")
  89. return cmd
  90. }
  91. func runConvert(ctx context.Context, backend api.Service, opts convertOptions, services []string) error {
  92. var json []byte
  93. project, err := opts.toProject(services, cli.WithInterpolation(!opts.noInterpolate), cli.WithResolvedPaths(true))
  94. if err != nil {
  95. return err
  96. }
  97. if opts.resolveImageDigests {
  98. configFile := cliconfig.LoadDefaultConfigFile(os.Stderr)
  99. resolver := remotes.CreateResolver(configFile)
  100. err = project.ResolveImages(func(named reference.Named) (digest.Digest, error) {
  101. _, desc, err := resolver.Resolve(ctx, named.String())
  102. return desc.Digest, err
  103. })
  104. if err != nil {
  105. return err
  106. }
  107. }
  108. json, err = backend.Convert(ctx, project, api.ConvertOptions{
  109. Format: opts.Format,
  110. Output: opts.Output,
  111. })
  112. if err != nil {
  113. return err
  114. }
  115. if opts.quiet {
  116. return nil
  117. }
  118. var out io.Writer = os.Stdout
  119. if opts.Output != "" && len(json) > 0 {
  120. file, err := os.Create(opts.Output)
  121. if err != nil {
  122. return err
  123. }
  124. out = bufio.NewWriter(file)
  125. }
  126. _, err = fmt.Fprint(out, string(json))
  127. return err
  128. }
  129. func runServices(opts convertOptions) error {
  130. project, err := opts.toProject(nil)
  131. if err != nil {
  132. return err
  133. }
  134. return project.WithServices(project.ServiceNames(), func(s types.ServiceConfig) error {
  135. fmt.Println(s.Name)
  136. return nil
  137. })
  138. }
  139. func runVolumes(opts convertOptions) error {
  140. project, err := opts.toProject(nil)
  141. if err != nil {
  142. return err
  143. }
  144. for n := range project.Volumes {
  145. fmt.Println(n)
  146. }
  147. return nil
  148. }
  149. func runHash(opts convertOptions) error {
  150. var services []string
  151. if opts.hash != "*" {
  152. services = append(services, strings.Split(opts.hash, ",")...)
  153. }
  154. project, err := opts.toProject(services)
  155. if err != nil {
  156. return err
  157. }
  158. for _, s := range project.Services {
  159. hash, err := compose.ServiceHash(s)
  160. if err != nil {
  161. return err
  162. }
  163. fmt.Printf("%s %s\n", s.Name, hash)
  164. }
  165. return nil
  166. }
  167. func runProfiles(opts convertOptions, services []string) error {
  168. set := map[string]struct{}{}
  169. project, err := opts.toProject(services)
  170. if err != nil {
  171. return err
  172. }
  173. for _, s := range project.AllServices() {
  174. for _, p := range s.Profiles {
  175. set[p] = struct{}{}
  176. }
  177. }
  178. profiles := make([]string, 0, len(set))
  179. for p := range set {
  180. profiles = append(profiles, p)
  181. }
  182. sort.Strings(profiles)
  183. for _, p := range profiles {
  184. fmt.Println(p)
  185. }
  186. return nil
  187. }