cloudflare/pint

Public

mirrored from https://github.com/cloudflare/pintAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v0.10.1

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

internal/discovery/git_branch.go

89lines · modecode

1package discovery
2
3import (
4 "regexp"
5 "strings"
6
7 "github.com/cloudflare/pint/internal/git"
8
9 "github.com/rs/zerolog/log"
10)
11
12func NewGitBranchFileFinder(gitCmd git.CommandRunner, include []*regexp.Regexp, baseBranch string) GitBranchFileFinder {
13 return GitBranchFileFinder{gitCmd: gitCmd, include: include, baseBranch: baseBranch}
14}
15
16type GitBranchFileFinder struct {
17 gitCmd git.CommandRunner
18 include []*regexp.Regexp
19 baseBranch string
20}
21
22func (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", "--reverse", "--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 op := parts[0]
46 srcPath := parts[1]
47 dstPath := parts[len(parts)-1]
48 log.Debug().
49 Str("path", dstPath).
50 Str("commit", commit).
51 Bool("allowed", gd.isPathAllowed(dstPath)).
52 Msg("Git file change")
53 if !gd.isPathAllowed(dstPath) {
54 continue
55 }
56 if _, ok := results.pathCommits[dstPath]; !ok {
57 results.pathCommits[dstPath] = []string{}
58 }
59 // check if we're dealing with a rename and if so we need to
60 // rename results in pathCommits
61 if strings.HasPrefix(op, "R") {
62 if v, ok := results.pathCommits[srcPath]; ok {
63 results.pathCommits[dstPath] = append(results.pathCommits[dstPath], v...)
64 delete(results.pathCommits, srcPath)
65 }
66 }
67 results.pathCommits[dstPath] = append(results.pathCommits[dstPath], commit)
68 }
69 }
70
71 return results, nil
72}
73
74func (gd GitBranchFileFinder) isPathAllowed(path string) bool {
75 if len(gd.include) == 0 {
76 return true
77 }
78
79 for _, pattern := range gd.include {
80 if pattern.MatchString(path) {
81 return true
82 }
83 }
84 return false
85}
86
87func removeRedundantSpaces(line string) string {
88 return strings.Join(strings.Fields(line), " ")
89}
90