equality_diff.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. package assertions
  2. import (
  3. "fmt"
  4. "github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch"
  5. )
  6. func composePrettyDiff(expected, actual string) string {
  7. diff := diffmatchpatch.New()
  8. diffs := diff.DiffMain(expected, actual, false)
  9. if prettyDiffIsLikelyToBeHelpful(diffs) {
  10. return fmt.Sprintf("\nDiff: '%s'", diff.DiffPrettyText(diffs))
  11. }
  12. return ""
  13. }
  14. // prettyDiffIsLikelyToBeHelpful returns true if the diff listing contains
  15. // more 'equal' segments than 'deleted'/'inserted' segments.
  16. func prettyDiffIsLikelyToBeHelpful(diffs []diffmatchpatch.Diff) bool {
  17. equal, deleted, inserted := measureDiffTypeLengths(diffs)
  18. return equal > deleted && equal > inserted
  19. }
  20. func measureDiffTypeLengths(diffs []diffmatchpatch.Diff) (equal, deleted, inserted int) {
  21. for _, segment := range diffs {
  22. switch segment.Type {
  23. case diffmatchpatch.DiffEqual:
  24. equal += len(segment.Text)
  25. case diffmatchpatch.DiffDelete:
  26. deleted += len(segment.Text)
  27. case diffmatchpatch.DiffInsert:
  28. inserted += len(segment.Text)
  29. }
  30. }
  31. return equal, deleted, inserted
  32. }