attach.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. noStdin bool
  26. proxy bool
  27. }
  28. func attachCommand(p *ProjectOptions, dockerCli command.Cli, backend api.Service) *cobra.Command {
  29. opts := attachOpts{
  30. composeOptions: &composeOptions{
  31. ProjectOptions: p,
  32. },
  33. }
  34. runCmd := &cobra.Command{
  35. Use: "attach [OPTIONS] SERVICE",
  36. Short: "Attach local standard input, output, and error streams to a service's running container",
  37. Args: cobra.MinimumNArgs(1),
  38. PreRunE: Adapt(func(ctx context.Context, args []string) error {
  39. opts.service = args[0]
  40. return nil
  41. }),
  42. RunE: Adapt(func(ctx context.Context, args []string) error {
  43. return runAttach(ctx, dockerCli, backend, opts)
  44. }),
  45. ValidArgsFunction: completeServiceNames(dockerCli, p),
  46. }
  47. runCmd.Flags().IntVar(&opts.index, "index", 0, "index of the container if service has multiple replicas.")
  48. runCmd.Flags().StringVarP(&opts.detachKeys, "detach-keys", "", "", "Override the key sequence for detaching from a container.")
  49. runCmd.Flags().BoolVar(&opts.noStdin, "no-stdin", false, "Do not attach STDIN")
  50. runCmd.Flags().BoolVar(&opts.proxy, "sig-proxy", true, "Proxy all received signals to the process")
  51. return runCmd
  52. }
  53. func runAttach(ctx context.Context, dockerCli command.Cli, backend api.Service, opts attachOpts) error {
  54. projectName, err := opts.toProjectName(ctx, dockerCli)
  55. if err != nil {
  56. return err
  57. }
  58. attachOpts := api.AttachOptions{
  59. Service: opts.service,
  60. Index: opts.index,
  61. DetachKeys: opts.detachKeys,
  62. NoStdin: opts.noStdin,
  63. Proxy: opts.proxy,
  64. }
  65. return backend.Attach(ctx, projectName, attachOpts)
  66. }