prefix.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. Copyright (c) 2014 VMware, Inc. All Rights Reserved.
  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 "fmt"
  15. type prefixedReport struct {
  16. Report
  17. prefix string
  18. }
  19. func (r prefixedReport) Detail() string {
  20. if d := r.Report.Detail(); d != "" {
  21. return fmt.Sprintf("%s: %s", r.prefix, d)
  22. }
  23. return r.prefix
  24. }
  25. func prefixLoop(upstream <-chan Report, downstream chan<- Report, prefix string) {
  26. defer close(downstream)
  27. for r := range upstream {
  28. downstream <- prefixedReport{
  29. Report: r,
  30. prefix: prefix,
  31. }
  32. }
  33. }
  34. func Prefix(s Sinker, prefix string) Sinker {
  35. fn := func() chan<- Report {
  36. upstream := make(chan Report)
  37. downstream := s.Sink()
  38. go prefixLoop(upstream, downstream, prefix)
  39. return upstream
  40. }
  41. return SinkFunc(fn)
  42. }