cloudflare/pint
Publicmirrored from https://github.com/cloudflare/pintAvailable
internal/discovery/git_blame.go
67lines · modecode
| 1 | package discovery |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "sort" |
| 6 | |
| 7 | "github.com/cloudflare/pint/internal/git" |
| 8 | ) |
| 9 | |
| 10 | type GitBlameLines struct { |
| 11 | lines []Line |
| 12 | } |
| 13 | |
| 14 | func (gbl GitBlameLines) Results() []Line { |
| 15 | return gbl.lines |
| 16 | } |
| 17 | |
| 18 | func (gbl GitBlameLines) HasLines(lines []int) bool { |
| 19 | for _, line := range lines { |
| 20 | for _, lc := range gbl.lines { |
| 21 | if lc.Position == line { |
| 22 | return true |
| 23 | } |
| 24 | } |
| 25 | } |
| 26 | return false |
| 27 | } |
| 28 | |
| 29 | func NewGitBlameLineFinder(cmd git.CommandRunner, allowedCommits []string) *GitBlameLineFinder { |
| 30 | return &GitBlameLineFinder{gitCmd: cmd, allowedCommits: allowedCommits} |
| 31 | } |
| 32 | |
| 33 | type GitBlameLineFinder struct { |
| 34 | gitCmd git.CommandRunner |
| 35 | allowedCommits []string |
| 36 | } |
| 37 | |
| 38 | func (gbd *GitBlameLineFinder) Find(path string) (LineFindResults, error) { |
| 39 | results := GitBlameLines{} |
| 40 | |
| 41 | lbs, err := git.Blame(path, gbd.gitCmd) |
| 42 | if err != nil { |
| 43 | return nil, fmt.Errorf("failed to run git blame for %s: %w", path, err) |
| 44 | } |
| 45 | |
| 46 | for _, lb := range lbs { |
| 47 | if !gbd.isCommitAllowed(lb.Commit) { |
| 48 | continue |
| 49 | } |
| 50 | results.lines = append(results.lines, Line{Path: path, Position: lb.Line, Commit: lb.Commit}) |
| 51 | } |
| 52 | |
| 53 | sort.Slice(results.lines, func(i, j int) bool { |
| 54 | return results.lines[i].Position < results.lines[j].Position |
| 55 | }) |
| 56 | |
| 57 | return results, nil |
| 58 | } |
| 59 | |
| 60 | func (gbd *GitBlameLineFinder) isCommitAllowed(commit string) bool { |
| 61 | for _, c := range gbd.allowedCommits { |
| 62 | if c == commit { |
| 63 | return true |
| 64 | } |
| 65 | } |
| 66 | return false |
| 67 | } |
| 68 | |