convert.go 6.1 KB

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