verify.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Package verify offers convenience routenes for content verification.
  2. package verify
  3. import (
  4. "bytes"
  5. "fmt"
  6. "strings"
  7. )
  8. // travel is the verification state
  9. type travel struct {
  10. diffs []differ
  11. }
  12. // differ is a verification failure.
  13. type differ struct {
  14. // path is the expression to the content.
  15. path string
  16. // msg has a reason.
  17. msg string
  18. }
  19. // segment is a differ.path component used for lazy formatting.
  20. type segment struct {
  21. format string
  22. x interface{}
  23. }
  24. func (t *travel) differ(path []*segment, msg string, args ...interface{}) {
  25. var buf bytes.Buffer
  26. for _, s := range path {
  27. buf.WriteString(fmt.Sprintf(s.format, s.x))
  28. }
  29. t.diffs = append(t.diffs, differ{
  30. msg: fmt.Sprintf(msg, args...),
  31. path: buf.String(),
  32. })
  33. }
  34. func (t *travel) report(name string) string {
  35. if len(t.diffs) == 0 {
  36. return ""
  37. }
  38. var buf bytes.Buffer
  39. buf.WriteString("verification for ")
  40. buf.WriteString(name)
  41. buf.WriteByte(':')
  42. for _, d := range t.diffs {
  43. buf.WriteByte('\n')
  44. if d.path != "" {
  45. buf.WriteString(d.path)
  46. buf.WriteString(": ")
  47. }
  48. lines := strings.Split(d.msg, "\n")
  49. buf.WriteString(lines[0])
  50. for _, l := range lines[1:] {
  51. buf.WriteByte('\n')
  52. buf.WriteString(strings.Repeat(" ", len(d.path)+2))
  53. buf.WriteString(l)
  54. }
  55. }
  56. return buf.String()
  57. }