convert.go 5.3 KB

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