generate.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. Copyright 2023 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. "os"
  18. "github.com/docker/compose/v2/pkg/api"
  19. "github.com/spf13/cobra"
  20. )
  21. type generateOptions struct {
  22. *ProjectOptions
  23. Format string
  24. }
  25. func generateCommand(p *ProjectOptions, backend api.Service) *cobra.Command {
  26. opts := generateOptions{
  27. ProjectOptions: p,
  28. }
  29. cmd := &cobra.Command{
  30. Use: "generate [OPTIONS] [CONTAINERS...]",
  31. Short: "EXPERIMENTAL - Generate a Compose file from existing containers",
  32. PreRunE: Adapt(func(ctx context.Context, args []string) error {
  33. return nil
  34. }),
  35. RunE: Adapt(func(ctx context.Context, args []string) error {
  36. return runGenerate(ctx, backend, opts, args)
  37. }),
  38. }
  39. cmd.Flags().StringVar(&opts.ProjectName, "name", "", "Project name to set in the Compose file")
  40. cmd.Flags().StringVar(&opts.ProjectDir, "project-dir", "", "Directory to use for the project")
  41. cmd.Flags().StringVar(&opts.Format, "format", "yaml", "Format the output. Values: [yaml | json]")
  42. return cmd
  43. }
  44. func runGenerate(ctx context.Context, backend api.Service, opts generateOptions, containers []string) error {
  45. _, _ = fmt.Fprintln(os.Stderr, "generate command is EXPERIMENTAL")
  46. if len(containers) == 0 {
  47. return fmt.Errorf("at least one container must be specified")
  48. }
  49. project, err := backend.Generate(ctx, api.GenerateOptions{
  50. Containers: containers,
  51. ProjectName: opts.ProjectName,
  52. })
  53. if err != nil {
  54. return err
  55. }
  56. var content []byte
  57. switch opts.Format {
  58. case "json":
  59. content, err = project.MarshalJSON()
  60. case "yaml":
  61. content, err = project.MarshalYAML()
  62. default:
  63. return fmt.Errorf("unsupported format %q", opts.Format)
  64. }
  65. if err != nil {
  66. return err
  67. }
  68. fmt.Println(string(content))
  69. return nil
  70. }