printer.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package reporting
  2. import (
  3. "fmt"
  4. "io"
  5. "strings"
  6. )
  7. type Printer struct {
  8. out io.Writer
  9. prefix string
  10. }
  11. func (self *Printer) Println(message string, values ...interface{}) {
  12. formatted := self.format(message, values...) + newline
  13. self.out.Write([]byte(formatted))
  14. }
  15. func (self *Printer) Print(message string, values ...interface{}) {
  16. formatted := self.format(message, values...)
  17. self.out.Write([]byte(formatted))
  18. }
  19. func (self *Printer) Insert(text string) {
  20. self.out.Write([]byte(text))
  21. }
  22. func (self *Printer) format(message string, values ...interface{}) string {
  23. var formatted string
  24. if len(values) == 0 {
  25. formatted = self.prefix + message
  26. } else {
  27. formatted = self.prefix + fmt.Sprintf(message, values...)
  28. }
  29. indented := strings.Replace(formatted, newline, newline+self.prefix, -1)
  30. return strings.TrimRight(indented, space)
  31. }
  32. func (self *Printer) Indent() {
  33. self.prefix += pad
  34. }
  35. func (self *Printer) Dedent() {
  36. if len(self.prefix) >= padLength {
  37. self.prefix = self.prefix[:len(self.prefix)-padLength]
  38. }
  39. }
  40. func NewPrinter(out io.Writer) *Printer {
  41. self := new(Printer)
  42. self.out = out
  43. return self
  44. }
  45. const space = " "
  46. const pad = space + space
  47. const padLength = len(pad)