-
Notifications
You must be signed in to change notification settings - Fork 118
/
git_service.go
209 lines (184 loc) · 5.77 KB
/
git_service.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
package gitservice
import (
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"runtime/debug"
"strings"
"sync"
"github.com/bridgecrewio/yor/src/common/logger"
"github.com/bridgecrewio/yor/src/common/structure"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/go-git/go-git/v5/plumbing/transport"
"github.com/pkg/errors"
)
type GitService struct {
gitRootDir string
scanPathFromRoot string
repository *git.Repository
remoteURL string
organization string
repoName string
BlameByFile *sync.Map
PreviousBlameByFile *sync.Map
currentUserEmail string
}
var gitGraphLock sync.Mutex
func NewGitService(rootDir string) (*GitService, error) {
var repository *git.Repository
var err error
rootDirIter, _ := filepath.Abs(rootDir)
for {
repository, err = git.PlainOpen(rootDirIter)
if err == nil {
break
}
newRootDir := filepath.Dir(rootDirIter)
if rootDirIter == newRootDir {
break
}
rootDirIter = newRootDir
}
if err != nil {
return nil, err
}
scanAbsDir, _ := filepath.Abs(rootDir)
scanPathFromRoot, _ := filepath.Rel(rootDirIter, scanAbsDir)
gitService := GitService{
gitRootDir: rootDir,
scanPathFromRoot: scanPathFromRoot,
repository: repository,
BlameByFile: &sync.Map{},
PreviousBlameByFile: &sync.Map{},
}
err = gitService.setOrgAndName()
gitService.currentUserEmail = GetGitUserEmail()
return &gitService, err
}
func (g *GitService) setOrgAndName() error {
// get remotes to find the repository's url
remotes, err := g.repository.Remotes()
if err != nil {
return fmt.Errorf("failed to get remotes, err: %s", err)
}
for _, remote := range remotes {
if remote.Config().Name == "origin" {
g.remoteURL = remote.Config().URLs[0]
// get endpoint structured like '/github.com/bridgecrewio/yor.git
endpoint, err := transport.NewEndpoint(g.remoteURL)
if err != nil {
return err
}
// remove leading '/' from path and trailing '.git. suffix, then split by '/'
endpointPathParts := strings.Split(strings.TrimSuffix(strings.TrimLeft(endpoint.Path, "/"), ".git"), "/")
if len(endpointPathParts) < 2 {
return fmt.Errorf("invalid format of endpoint path: %s", endpoint.Path)
}
g.organization = endpointPathParts[0]
g.repoName = strings.Join(endpointPathParts[1:], "/")
break
}
}
return nil
}
func (g *GitService) ComputeRelativeFilePath(fp string) string {
if strings.HasPrefix(fp, g.gitRootDir) {
res, _ := filepath.Rel(g.gitRootDir, fp)
return filepath.Join(g.scanPathFromRoot, res)
}
scanPathIter := g.scanPathFromRoot
parent := filepath.Dir(fp)
for {
_, child := filepath.Split(scanPathIter)
if parent != child {
break
}
scanPathIter, _ = filepath.Split(scanPathIter)
}
return filepath.Join(scanPathIter, fp)
}
func (g *GitService) GetBlameForFileLines(filePath string, lines structure.Lines) (*GitBlame, error) {
logger.Info(fmt.Sprintf("Getting git blame for %v (%v:%v)", filePath, lines.Start, lines.End))
relativeFilePath := g.ComputeRelativeFilePath(filePath)
blame, ok := g.BlameByFile.Load(filePath)
if ok {
return NewGitBlame(relativeFilePath, filePath, lines, blame.(*git.BlameResult), g), nil
}
var err error
blame, err = g.GetFileBlame(filePath)
if err != nil {
return nil, fmt.Errorf("failed to get blame for latest commit of file %s because of error %s", filePath, err)
}
g.BlameByFile.Store(filePath, blame)
return NewGitBlame(relativeFilePath, filePath, lines, blame.(*git.BlameResult), g), nil
}
func (g *GitService) GetOrganization() string {
return g.organization
}
func (g *GitService) GetRepoName() string {
return g.repoName
}
func wrapGitBlame(selectedCommit *object.Commit, relativeFilePath string) (blame *git.BlameResult, err error) {
// currently there's a bug inside go-git so in order to mitigate it we wrap it with recover
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered in f", r, string(debug.Stack()))
err = errors.Errorf("unknown panic, %v", r)
}
}()
blame, err = git.Blame(selectedCommit, relativeFilePath)
if err != nil {
return nil, fmt.Errorf("failed to get blame for latest commit of file %s because of error %s", relativeFilePath, err)
}
return blame, err
}
func (g *GitService) GetFileBlame(filePath string) (*git.BlameResult, error) {
blame, ok := g.BlameByFile.Load(filePath)
if ok {
return blame.(*git.BlameResult), nil
}
relativeFilePath := g.ComputeRelativeFilePath(filePath)
var selectedCommit *object.Commit
gitGraphLock.Lock() // Git is a graph, different files can lead to graph scans interfering with each other
defer gitGraphLock.Unlock()
head, err := g.repository.Head()
if err != nil {
return nil, fmt.Errorf("failed to get repository HEAD for file %s because of error %s", filePath, err)
}
selectedCommit, err = g.repository.CommitObject(head.Hash())
if err != nil {
return nil, fmt.Errorf("failed to find commit %s ", head.Hash().String())
}
parentIter := selectedCommit.Parents()
previousCommit, err := parentIter.Next()
if err != nil {
return nil, fmt.Errorf("failed to get previous commit: %s", err)
}
blame, err = wrapGitBlame(selectedCommit, relativeFilePath)
if err != nil {
return nil, err
}
previousBlame, err := wrapGitBlame(previousCommit, relativeFilePath)
if err != nil {
return nil, err
}
g.BlameByFile.Store(filePath, blame)
g.PreviousBlameByFile.Store(filePath, previousBlame)
return blame.(*git.BlameResult), nil
}
func GetGitUserEmail() string {
log.SetOutput(io.Discard)
cmd := exec.Command("git", "config", "user.email")
email, err := cmd.Output()
stdout := os.Stdout
log.SetOutput(stdout)
if err != nil {
logger.Debug(fmt.Sprintf("unable to get current git user email: %s", err))
return ""
}
return strings.ReplaceAll(string(email), "\n", "")
}