convert.go 6.5 KB

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