convert.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. "context"
  16. "fmt"
  17. "github.com/docker/compose-cli/api/compose"
  18. "github.com/spf13/cobra"
  19. "github.com/docker/compose-cli/api/client"
  20. )
  21. type convertOptions struct {
  22. *projectOptions
  23. Format string
  24. Output string
  25. }
  26. var addFlagsFuncs []func(cmd *cobra.Command, opts *convertOptions)
  27. func convertCommand(p *projectOptions) *cobra.Command {
  28. opts := convertOptions{
  29. projectOptions: p,
  30. }
  31. convertCmd := &cobra.Command{
  32. Aliases: []string{"config"},
  33. Use: "convert SERVICES",
  34. Short: "Converts the compose file to platform's canonical format",
  35. RunE: func(cmd *cobra.Command, args []string) error {
  36. return runConvert(cmd.Context(), opts, args)
  37. },
  38. }
  39. flags := convertCmd.Flags()
  40. flags.StringVar(&opts.Format, "format", "yaml", "Format the output. Values: [yaml | json]")
  41. // add flags for hidden backends
  42. for _, f := range addFlagsFuncs {
  43. f(convertCmd, &opts)
  44. }
  45. return convertCmd
  46. }
  47. func runConvert(ctx context.Context, opts convertOptions, services []string) error {
  48. var json []byte
  49. c, err := client.NewWithDefaultLocalBackend(ctx)
  50. if err != nil {
  51. return err
  52. }
  53. project, err := opts.toProject(services)
  54. if err != nil {
  55. return err
  56. }
  57. json, err = c.ComposeService().Convert(ctx, project, compose.ConvertOptions{
  58. Format: opts.Format,
  59. Output: opts.Output,
  60. })
  61. if err != nil {
  62. return err
  63. }
  64. if opts.Output != "" {
  65. fmt.Print("model saved to ")
  66. }
  67. fmt.Println(string(json))
  68. return nil
  69. }