printer.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. // Extracting fmt.Sprintf to a separate variable circumvents go vet, which, as of go 1.10 is run with go test.
  33. var fmt_Sprintf = fmt.Sprintf
  34. func (self *Printer) Indent() {
  35. self.prefix += pad
  36. }
  37. func (self *Printer) Dedent() {
  38. if len(self.prefix) >= padLength {
  39. self.prefix = self.prefix[:len(self.prefix)-padLength]
  40. }
  41. }
  42. func NewPrinter(out io.Writer) *Printer {
  43. self := new(Printer)
  44. self.out = out
  45. return self
  46. }
  47. const space = " "
  48. const pad = space + space
  49. const padLength = len(pad)