attach.go 2.3 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/api"
  18. "github.com/spf13/cobra"
  19. )
  20. type attachOpts struct {
  21. *composeOptions
  22. service string
  23. index int
  24. detachKeys string
  25. // todo docker container attach also has:
  26. // --no-stdin // whole point of attach is for STDIN (can already attach to STDOUT and STDERR via docker compose up)
  27. // --sig-proxy
  28. }
  29. func attachCommand(p *ProjectOptions, dockerCli command.Cli, backend api.Service) *cobra.Command {
  30. opts := attachOpts{
  31. composeOptions: &composeOptions{
  32. ProjectOptions: p,
  33. },
  34. }
  35. runCmd := &cobra.Command{
  36. Use: "attach [OPTIONS] SERVICE",
  37. Short: "Attach local standard input, output, and error streams to a service's running container.",
  38. Args: cobra.MinimumNArgs(1),
  39. PreRunE: Adapt(func(ctx context.Context, args []string) error {
  40. opts.service = args[0]
  41. return nil
  42. }),
  43. RunE: Adapt(func(ctx context.Context, args []string) error {
  44. return runAttach(ctx, dockerCli, backend, opts)
  45. }),
  46. ValidArgsFunction: completeServiceNames(dockerCli, p),
  47. }
  48. runCmd.Flags().IntVar(&opts.index, "index", 0, "index of the container if service has multiple replicas.")
  49. runCmd.Flags().StringVarP(&opts.detachKeys, "detach-keys", "", "", "Override the key sequence for detaching from a container.")
  50. return runCmd
  51. }
  52. func runAttach(ctx context.Context, dockerCli command.Cli, backend api.Service, opts attachOpts) error {
  53. projectName, err := opts.toProjectName(dockerCli)
  54. if err != nil {
  55. return err
  56. }
  57. attachOpts := api.AttachOptions{
  58. Service: opts.service,
  59. Index: opts.index,
  60. DetachKeys: opts.detachKeys,
  61. }
  62. return backend.Attach(ctx, projectName, attachOpts)
  63. }