showcase
- v0.2.4
- 37 commits
- 1 branch
- 6 tags
- updated
- CI 2/2
diff.go
2.8 KB · 103 lines
1package gitx23import (4 "context"5 "strconv"6 "strings"7)89const maxDiffLines = 5000 // per commit; the rest is counted but not kept1011type FileDiff struct {12 Path, OldPath string // OldPath is set for renames13 Status string // "added", "deleted", "renamed" or ""14 Added, Deleted int15 Binary, Truncated bool16 Lines []DiffLine17}1819type DiffLine struct {20 Kind byte // ' ', '+', '-' or '@' for a hunk header21 Old, New int // line numbers, 0 if none22 Text string23}2425// Diff returns the changes a commit made, against its first parent (or the26// empty tree for a root commit).27func (r Repo) Diff(ctx context.Context, hash string) ([]FileDiff, error) {28 out, err := r.run(ctx, "show", "--format=", "--patch", "-M", "--no-color", "--no-ext-diff",29 "--diff-merges=first-parent", "--end-of-options", hash)30 if err != nil {31 return nil, err32 }33 var files []FileDiff34 var f *FileDiff35 kept, oldN, newN := 0, 0, 036 inHunk := false37 for _, line := range strings.Split(string(out), "\n") {38 switch {39 case strings.HasPrefix(line, "diff --git "):40 files = append(files, FileDiff{})41 f, inHunk = &files[len(files)-1], false42 if s := line[len("diff --git "):]; len(s)%2 == 1 { // "a/P b/P"43 f.Path = s[len(s)/2+3:]44 }45 case f == nil:46 case inHunk && line != "" && strings.ContainsRune(" +-\\", rune(line[0])):47 d := DiffLine{Kind: line[0], Text: line[1:]}48 switch d.Kind {49 case '+':50 f.Added++51 d.New, newN = newN, newN+152 case '-':53 f.Deleted++54 d.Old, oldN = oldN, oldN+155 case ' ':56 d.Old, d.New, oldN, newN = oldN, newN, oldN+1, newN+157 default:58 continue // "\ No newline at end of file"59 }60 if kept < maxDiffLines {61 f.Lines, kept = append(f.Lines, d), kept+162 } else {63 f.Truncated = true64 }65 case strings.HasPrefix(line, "@@ "):66 inHunk = true67 oldN, newN = hunkStart(line, '-'), hunkStart(line, '+')68 if kept < maxDiffLines {69 f.Lines, kept = append(f.Lines, DiffLine{Kind: '@', Text: line}), kept+170 }71 case inHunk:72 case strings.HasPrefix(line, "new file"):73 f.Status = "added"74 case strings.HasPrefix(line, "deleted file"):75 f.Status = "deleted"76 case strings.HasPrefix(line, "rename from "):77 f.Status, f.OldPath = "renamed", line[len("rename from "):]78 case strings.HasPrefix(line, "rename to "):79 f.Path = line[len("rename to "):]80 case strings.HasPrefix(line, "+++ b/"):81 f.Path = line[len("+++ b/"):]82 case strings.HasPrefix(line, "--- a/") && f.Path == "":83 f.Path = line[len("--- a/"):]84 case strings.HasPrefix(line, "Binary files "):85 f.Binary = true86 }87 }88 return files, nil89}9091// hunkStart reads the start line after sign in "@@ -1,2 +3,4 @@".92func hunkStart(h string, sign byte) int {93 i := strings.IndexByte(h, sign)94 if i < 0 {95 return 096 }97 s := h[i+1:]98 if j := strings.IndexAny(s, ", "); j >= 0 {99 s = s[:j]100 }101 n, _ := strconv.Atoi(s)102 return n103}