cloudflare/pint
Publicmirrored from https://github.com/cloudflare/pintAvailable
internal/discovery/git_branch.go
79lines · modecode
| 1 | package discovery |
| 2 | |
| 3 | import ( |
| 4 | "regexp" |
| 5 | "strings" |
| 6 | |
| 7 | "github.com/cloudflare/pint/internal/git" |
| 8 | |
| 9 | "github.com/rs/zerolog/log" |
| 10 | ) |
| 11 | |
| 12 | func NewGitBranchFileFinder(gitCmd git.CommandRunner, include []*regexp.Regexp, baseBranch string) GitBranchFileFinder { |
| 13 | return GitBranchFileFinder{gitCmd: gitCmd, include: include, baseBranch: baseBranch} |
| 14 | } |
| 15 | |
| 16 | type GitBranchFileFinder struct { |
| 17 | gitCmd git.CommandRunner |
| 18 | include []*regexp.Regexp |
| 19 | baseBranch string |
| 20 | } |
| 21 | |
| 22 | func (gd GitBranchFileFinder) Find(pattern ...string) (FileFindResults, error) { |
| 23 | cr, err := git.CommitRange(gd.gitCmd, gd.baseBranch) |
| 24 | if err != nil { |
| 25 | return nil, err |
| 26 | } |
| 27 | |
| 28 | log.Debug().Str("from", cr.From).Str("to", cr.To).Msg("Got commit range from git") |
| 29 | |
| 30 | out, err := gd.gitCmd("log", "--no-merges", "--pretty=format:%H", "--name-status", "--diff-filter=d", cr.String()) |
| 31 | if err != nil { |
| 32 | return nil, err |
| 33 | } |
| 34 | |
| 35 | results := FileCommits{ |
| 36 | pathCommits: map[string][]string{}, |
| 37 | } |
| 38 | |
| 39 | var commit string |
| 40 | for _, line := range strings.Split(string(out), "\n") { |
| 41 | parts := strings.Split(removeRedundantSpaces(line), " ") |
| 42 | if len(parts) == 1 && parts[0] != "" { |
| 43 | commit = parts[0] |
| 44 | } else if len(parts) >= 2 { |
| 45 | path := parts[len(parts)-1] |
| 46 | log.Debug(). |
| 47 | Str("path", path). |
| 48 | Str("commit", commit). |
| 49 | Bool("allowed", gd.isPathAllowed(path)). |
| 50 | Msg("Git file change") |
| 51 | if !gd.isPathAllowed(path) { |
| 52 | continue |
| 53 | } |
| 54 | if _, ok := results.pathCommits[path]; !ok { |
| 55 | results.pathCommits[path] = []string{} |
| 56 | } |
| 57 | results.pathCommits[path] = append(results.pathCommits[path], commit) |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | return results, nil |
| 62 | } |
| 63 | |
| 64 | func (gd GitBranchFileFinder) isPathAllowed(path string) bool { |
| 65 | if len(gd.include) == 0 { |
| 66 | return true |
| 67 | } |
| 68 | |
| 69 | for _, pattern := range gd.include { |
| 70 | if pattern.MatchString(path) { |
| 71 | return true |
| 72 | } |
| 73 | } |
| 74 | return false |
| 75 | } |
| 76 | |
| 77 | func removeRedundantSpaces(line string) string { |
| 78 | return strings.Join(strings.Fields(line), " ") |
| 79 | } |
| 80 | |