本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
2.1KB

  1. // Package diff implements line oriented diffs, similar to the ancient
  2. // Unix diff command.
  3. //
  4. // The current implementation is just a wrapper around Sergi's
  5. // go-diff/diffmatchpatch library, which is a go port of Neil
  6. // Fraser's google-diff-match-patch code
  7. package diff
  8. import (
  9. "bytes"
  10. "time"
  11. "github.com/sergi/go-diff/diffmatchpatch"
  12. )
  13. // Do computes the (line oriented) modifications needed to turn the src
  14. // string into the dst string. The underlying algorithm is Meyers,
  15. // its complexity is O(N*d) where N is min(lines(src), lines(dst)) and d
  16. // is the size of the diff.
  17. func Do(src, dst string) (diffs []diffmatchpatch.Diff) {
  18. // the default timeout is time.Second which may be too small under heavy load
  19. return DoWithTimeout(src, dst, time.Hour)
  20. }
  21. // DoWithTimeout computes the (line oriented) modifications needed to turn the src
  22. // string into the dst string. The `timeout` argument specifies the maximum
  23. // amount of time it is allowed to spend in this function. If the timeout
  24. // is exceeded, the parts of the strings which were not considered are turned into
  25. // a bulk delete+insert and the half-baked suboptimal result is returned at once.
  26. // The underlying algorithm is Meyers, its complexity is O(N*d) where N is
  27. // min(lines(src), lines(dst)) and d is the size of the diff.
  28. func DoWithTimeout (src, dst string, timeout time.Duration) (diffs []diffmatchpatch.Diff) {
  29. dmp := diffmatchpatch.New()
  30. dmp.DiffTimeout = timeout
  31. wSrc, wDst, warray := dmp.DiffLinesToRunes(src, dst)
  32. diffs = dmp.DiffMainRunes(wSrc, wDst, false)
  33. diffs = dmp.DiffCharsToLines(diffs, warray)
  34. return diffs
  35. }
  36. // Dst computes and returns the destination text.
  37. func Dst(diffs []diffmatchpatch.Diff) string {
  38. var text bytes.Buffer
  39. for _, d := range diffs {
  40. if d.Type != diffmatchpatch.DiffDelete {
  41. text.WriteString(d.Text)
  42. }
  43. }
  44. return text.String()
  45. }
  46. // Src computes and returns the source text
  47. func Src(diffs []diffmatchpatch.Diff) string {
  48. var text bytes.Buffer
  49. for _, d := range diffs {
  50. if d.Type != diffmatchpatch.DiffInsert {
  51. text.WriteString(d.Text)
  52. }
  53. }
  54. return text.String()
  55. }
上海开阖软件有限公司 沪ICP备12045867号-1