export.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. "io"
  18. "strings"
  19. "github.com/docker/cli/cli/command"
  20. "github.com/docker/compose/v2/pkg/api"
  21. "github.com/docker/compose/v2/pkg/progress"
  22. "github.com/pkg/errors"
  23. )
  24. func (s *composeService) Export(ctx context.Context, projectName string, options api.ExportOptions) error {
  25. return progress.RunWithTitle(ctx, func(ctx context.Context) error {
  26. return s.export(ctx, projectName, options)
  27. }, s.stdinfo(), "Exporting")
  28. }
  29. func (s *composeService) export(ctx context.Context, projectName string, options api.ExportOptions) error {
  30. projectName = strings.ToLower(projectName)
  31. container, err := s.getSpecifiedContainer(ctx, projectName, oneOffInclude, false, options.Service, options.Index)
  32. if err != nil {
  33. return err
  34. }
  35. if options.Output == "" && s.dockerCli.Out().IsTerminal() {
  36. return errors.New("output option is required when exporting to terminal")
  37. }
  38. if err := command.ValidateOutputPath(options.Output); err != nil {
  39. return errors.Wrap(err, "failed to export container")
  40. }
  41. clnt := s.dockerCli.Client()
  42. w := progress.ContextWriter(ctx)
  43. name := getCanonicalContainerName(container)
  44. msg := fmt.Sprintf("export %s to %s", name, options.Output)
  45. w.Event(progress.Event{
  46. ID: name,
  47. Text: msg,
  48. Status: progress.Working,
  49. StatusText: "Exporting",
  50. })
  51. responseBody, err := clnt.ContainerExport(ctx, container.ID)
  52. if err != nil {
  53. return err
  54. }
  55. defer responseBody.Close()
  56. if !s.dryRun {
  57. if options.Output == "" {
  58. _, err := io.Copy(s.dockerCli.Out(), responseBody)
  59. return err
  60. }
  61. if err = command.CopyToFile(options.Output, responseBody); err != nil {
  62. return err
  63. }
  64. }
  65. w.Event(progress.Event{
  66. ID: name,
  67. Text: msg,
  68. Status: progress.Done,
  69. StatusText: "Exported",
  70. })
  71. return nil
  72. }