writer.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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 progress
  14. import (
  15. "context"
  16. "os"
  17. "sync"
  18. "github.com/containerd/console"
  19. "github.com/moby/term"
  20. "golang.org/x/sync/errgroup"
  21. )
  22. // Writer can write multiple progress events
  23. type Writer interface {
  24. Start(context.Context) error
  25. Stop()
  26. Event(Event)
  27. TailMsgf(string, ...interface{})
  28. }
  29. type writerKey struct{}
  30. // WithContextWriter adds the writer to the context
  31. func WithContextWriter(ctx context.Context, writer Writer) context.Context {
  32. return context.WithValue(ctx, writerKey{}, writer)
  33. }
  34. // ContextWriter returns the writer from the context
  35. func ContextWriter(ctx context.Context) Writer {
  36. s, ok := ctx.Value(writerKey{}).(Writer)
  37. if !ok {
  38. return &noopWriter{}
  39. }
  40. return s
  41. }
  42. type progressFunc func(context.Context) (string, error)
  43. // Run will run a writer and the progress function
  44. // in parallel
  45. func Run(ctx context.Context, pf progressFunc) (string, error) {
  46. eg, _ := errgroup.WithContext(ctx)
  47. w, err := NewWriter(os.Stderr)
  48. var result string
  49. if err != nil {
  50. return "", err
  51. }
  52. eg.Go(func() error {
  53. return w.Start(context.Background())
  54. })
  55. ctx = WithContextWriter(ctx, w)
  56. eg.Go(func() error {
  57. defer w.Stop()
  58. s, err := pf(ctx)
  59. if err == nil {
  60. result = s
  61. }
  62. return err
  63. })
  64. err = eg.Wait()
  65. return result, err
  66. }
  67. // NewWriter returns a new multi-progress writer
  68. func NewWriter(out console.File) (Writer, error) {
  69. _, isTerminal := term.GetFdInfo(out)
  70. if isTerminal {
  71. con, err := console.ConsoleFromFile(out)
  72. if err != nil {
  73. return nil, err
  74. }
  75. return &ttyWriter{
  76. out: con,
  77. eventIDs: []string{},
  78. events: map[string]Event{},
  79. repeated: false,
  80. done: make(chan bool),
  81. mtx: &sync.RWMutex{},
  82. }, nil
  83. }
  84. return &plainWriter{
  85. out: out,
  86. done: make(chan bool),
  87. }, nil
  88. }