convert.go 6.1 KB

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