convert.go 5.6 KB

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