export.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. "github.com/docker/cli/cli/command"
  17. "github.com/docker/compose/v2/pkg/compose"
  18. "github.com/spf13/cobra"
  19. "github.com/docker/compose/v2/pkg/api"
  20. )
  21. type exportOptions struct {
  22. *ProjectOptions
  23. service string
  24. output string
  25. index int
  26. }
  27. func exportCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command {
  28. options := exportOptions{
  29. ProjectOptions: p,
  30. }
  31. cmd := &cobra.Command{
  32. Use: "export [OPTIONS] SERVICE",
  33. Short: "Export a service container's filesystem as a tar archive",
  34. Args: cobra.MinimumNArgs(1),
  35. PreRunE: Adapt(func(ctx context.Context, args []string) error {
  36. options.service = args[0]
  37. return nil
  38. }),
  39. RunE: Adapt(func(ctx context.Context, args []string) error {
  40. return runExport(ctx, dockerCli, backendOptions, options)
  41. }),
  42. ValidArgsFunction: completeServiceNames(dockerCli, p),
  43. }
  44. flags := cmd.Flags()
  45. flags.IntVar(&options.index, "index", 0, "index of the container if service has multiple replicas.")
  46. flags.StringVarP(&options.output, "output", "o", "", "Write to a file, instead of STDOUT")
  47. return cmd
  48. }
  49. func runExport(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, options exportOptions) error {
  50. projectName, err := options.toProjectName(ctx, dockerCli)
  51. if err != nil {
  52. return err
  53. }
  54. exportOptions := api.ExportOptions{
  55. Service: options.service,
  56. Index: options.index,
  57. Output: options.output,
  58. }
  59. backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...)
  60. if err != nil {
  61. return err
  62. }
  63. return backend.Export(ctx, projectName, exportOptions)
  64. }