group.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package output
  2. import (
  3. "bytes"
  4. "io"
  5. "github.com/go-task/task/v3/internal/templater"
  6. )
  7. type Group struct {
  8. Begin, End string
  9. ErrorOnly bool
  10. }
  11. func (g Group) WrapWriter(stdOut, _ io.Writer, _ string, cache *templater.Cache) (io.Writer, io.Writer, CloseFunc) {
  12. gw := &groupWriter{writer: stdOut}
  13. if g.Begin != "" {
  14. gw.begin = templater.Replace(g.Begin, cache) + "\n"
  15. }
  16. if g.End != "" {
  17. gw.end = templater.Replace(g.End, cache) + "\n"
  18. }
  19. return gw, gw, func(err error) error {
  20. if g.ErrorOnly && err == nil {
  21. return nil
  22. }
  23. return gw.close()
  24. }
  25. }
  26. type groupWriter struct {
  27. writer io.Writer
  28. buff bytes.Buffer
  29. begin, end string
  30. }
  31. func (gw *groupWriter) Write(p []byte) (int, error) {
  32. return gw.buff.Write(p)
  33. }
  34. func (gw *groupWriter) close() error {
  35. if gw.buff.Len() == 0 {
  36. // don't print begin/end messages if there's no buffered entries
  37. return nil
  38. }
  39. if _, err := io.WriteString(gw.writer, gw.begin); err != nil {
  40. return err
  41. }
  42. gw.buff.WriteString(gw.end)
  43. _, err := io.Copy(gw.writer, &gw.buff)
  44. return err
  45. }