diff.go 822 B

1234567891011121314151617181920212223242526272829303132
  1. package diff
  2. import (
  3. "strings"
  4. "github.com/aymanbagabas/go-udiff"
  5. )
  6. // GenerateDiff creates a unified diff from two file contents.
  7. func GenerateDiff(beforeContent, afterContent, fileName string) (string, int, int) {
  8. beforeContent = strings.ReplaceAll(beforeContent, "\r\n", "\n")
  9. afterContent = strings.ReplaceAll(afterContent, "\r\n", "\n")
  10. fileName = strings.TrimPrefix(fileName, "/")
  11. var (
  12. unified = udiff.Unified("a/"+fileName, "b/"+fileName, beforeContent, afterContent)
  13. additions = 0
  14. removals = 0
  15. )
  16. lines := strings.SplitSeq(unified, "\n")
  17. for line := range lines {
  18. if strings.HasPrefix(line, "+") && !strings.HasPrefix(line, "+++") {
  19. additions++
  20. } else if strings.HasPrefix(line, "-") && !strings.HasPrefix(line, "---") {
  21. removals++
  22. }
  23. }
  24. return unified, additions, removals
  25. }