convert.go 6.3 KB

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