io.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 streams
  14. import (
  15. "github.com/golang/protobuf/ptypes"
  16. streamsv1 "github.com/docker/compose-cli/protos/streams/v1"
  17. )
  18. // IO implements an io.ReadWriter that forwards everything to the stream
  19. type IO struct {
  20. Stream *Stream
  21. }
  22. func (io *IO) Read(p []byte) (int, error) {
  23. a, err := io.Stream.Recv()
  24. if err != nil {
  25. return 0, err
  26. }
  27. var m streamsv1.BytesMessage
  28. err = ptypes.UnmarshalAny(a, &m)
  29. if err != nil {
  30. return 0, err
  31. }
  32. return copy(p, m.Value), nil
  33. }
  34. func (io *IO) Write(p []byte) (n int, err error) {
  35. if len(p) == 0 {
  36. return 0, nil
  37. }
  38. message := streamsv1.BytesMessage{
  39. Type: streamsv1.IOStream_STDOUT,
  40. Value: p,
  41. }
  42. m, err := ptypes.MarshalAny(&message)
  43. if err != nil {
  44. return 0, err
  45. }
  46. return len(message.Value), io.Stream.SendMsg(m)
  47. }