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