This repository has been archived by the owner on Jul 19, 2023. It is now read-only.
/
githubConnector.go
262 lines (215 loc) · 7.55 KB
/
githubConnector.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
package githubConnector
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"path"
"regexp"
"github.com/allero-io/allero/pkg/connectors"
"github.com/allero-io/allero/pkg/fileManager"
"github.com/google/go-github/github"
)
type GithubConnector struct {
client *github.Client
}
type GithubConnectorDependencies struct {
Client *github.Client
}
type GithubRepositoryApiResponse struct {
Repository *github.Repository
Error error
}
func New(deps *GithubConnectorDependencies) *GithubConnector {
return &GithubConnector{
client: deps.Client,
}
}
func (gc *GithubConnector) Get(ownersWithRepos []*connectors.OwnerWithRepo) (int, error) {
repositoriesChan := gc.getAllRepositories(ownersWithRepos)
githubJsonObject := make(map[string]*GithubOwner)
reposFetchCounter := 0
for repo := range repositoriesChan {
if repo.Error != nil {
return reposFetchCounter, repo.Error
}
reposFetchCounter += 1
err := gc.addRepo(githubJsonObject, repo.Repository)
if err != nil {
fmt.Println(err)
continue
}
err = gc.processWorkflowFiles(githubJsonObject, repo.Repository)
if err != nil {
fmt.Println(err)
continue
}
}
githubJson, err := json.MarshalIndent(githubJsonObject, "", " ")
if err != nil {
return reposFetchCounter, err
}
alleroHomedir := fileManager.GetAlleroHomedir()
return reposFetchCounter, fileManager.WriteToFile(fmt.Sprintf("%s/repo_files/github.json", alleroHomedir), githubJson)
}
func (gc *GithubConnector) addRepo(githubJsonObject map[string]*GithubOwner, repo *github.Repository) error {
if _, ok := githubJsonObject[*repo.Owner.Login]; !ok {
githubJsonObject[*repo.Owner.Login] = &GithubOwner{
Name: *repo.Owner.Login,
Type: *repo.Owner.Type,
ID: int(*repo.Owner.ID),
Repositories: make(map[string]*GithubRepository),
}
}
languages, err := gc.getProgrammingLanguages(repo)
if err != nil {
return err
}
escapedRepoName := connectors.EscapeJsonKey(*repo.Name)
githubJsonObject[*repo.Owner.Login].Repositories[escapedRepoName] = &GithubRepository{
Name: *repo.Name,
FullName: *repo.FullName,
ID: int(*repo.ID),
ProgrammingLanguages: languages,
GithubActionsWorkflows: make(map[string]*connectors.PipelineFile),
JfrogPipelines: make(map[string]*connectors.PipelineFile),
}
return nil
}
func (gc *GithubConnector) getProgrammingLanguages(repo *github.Repository) ([]string, error) {
languagesMapping, _, err := gc.client.Repositories.ListLanguages(context.Background(), *repo.Owner.Login, *repo.Name)
if err != nil {
return nil, err
}
var languages []string
for language := range languagesMapping {
languages = append(languages, language)
}
return languages, nil
}
func (gc *GithubConnector) processWorkflowFiles(githubJsonObject map[string]*GithubOwner, repo *github.Repository) error {
workflowFilesChan, _ := gc.getWorkflowFilesEntities(repo)
var processingError error
for workflowFile := range workflowFilesChan {
content, _, _, err := gc.client.Repositories.GetContents(context.Background(), *repo.Owner.Login, *repo.Name, workflowFile.RelativePath, nil)
if err != nil {
processingError = fmt.Errorf("failed to get content for file %s from repository %s", workflowFile.RelativePath, *repo.FullName)
continue
}
byteContent, err := base64.StdEncoding.DecodeString(*content.Content)
if err != nil {
processingError = fmt.Errorf("failed to decode content for file %s from repository %s", workflowFile.RelativePath, *repo.FullName)
continue
}
jsonContentBytes, err := connectors.YamlToJson(byteContent)
if err != nil {
processingError = err
continue
}
jsonContent := make(map[string]interface{})
err = json.Unmarshal(jsonContentBytes, &jsonContent)
if err != nil {
processingError = err
continue
}
workflowFile.Content = jsonContent
escapedFilename := connectors.EscapeJsonKey(workflowFile.Filename)
if workflowFile.Origin == "github_actions" {
githubJsonObject[*repo.Owner.Login].Repositories[*repo.Name].GithubActionsWorkflows[escapedFilename] = workflowFile
} else if workflowFile.Origin == "jfrog_pipelines" {
githubJsonObject[*repo.Owner.Login].Repositories[*repo.Name].JfrogPipelines[escapedFilename] = workflowFile
} else {
processingError = fmt.Errorf("unsupported CICD platform %s for file %s from repository %s", workflowFile.Origin, workflowFile.RelativePath, *repo.FullName)
continue
}
}
return processingError
}
func (gc *GithubConnector) getWorkflowFilesEntities(repo *github.Repository) (chan *connectors.PipelineFile, error) {
workflowFilesEntitiesChan := make(chan *connectors.PipelineFile)
var getEntitiesErr error
go func() {
defer close(workflowFilesEntitiesChan)
tree, _, err := gc.client.Git.GetTree(context.Background(), *repo.Owner.Login, *repo.Name, *repo.DefaultBranch, true)
if err != nil {
return
}
for _, cicdPlatform := range connectors.SUPPORTED_CICD_PLATFORMS {
if !cicdPlatform.GithubValid {
continue
}
relevantFilesPaths := gc.matchedFiles(tree, cicdPlatform.RelevantFilesRegex)
for _, filePath := range relevantFilesPaths {
workflowFilesEntitiesChan <- &connectors.PipelineFile{
RelativePath: filePath,
Filename: path.Base(filePath),
Origin: cicdPlatform.Name,
}
}
}
}()
return workflowFilesEntitiesChan, getEntitiesErr
}
func (gc *GithubConnector) matchedFiles(tree *github.Tree, regex string) []string {
var matchedFiles []string
for _, fileEntry := range tree.Entries {
// skip if entry is a folder
if *fileEntry.Type == "tree" {
continue
}
filepath := *fileEntry.Path
if matched, _ := regexp.MatchString(regex, filepath); matched {
matchedFiles = append(matchedFiles, filepath)
}
}
return matchedFiles
}
func (gc *GithubConnector) getAllRepositories(ownersWithRepos []*connectors.OwnerWithRepo) chan *GithubRepositoryApiResponse {
repositoriesChan := make(chan *GithubRepositoryApiResponse)
go func() {
defer close(repositoriesChan)
for _, ownerWithRepo := range ownersWithRepos {
fullName := ownerWithRepo.Owner + "/" + ownerWithRepo.Repo
if ownerWithRepo.Repo != "" {
fmt.Printf("Start fetching github repository %s/%s\n", ownerWithRepo.Owner, ownerWithRepo.Repo)
repoMetadata, _, err := gc.client.Repositories.Get(context.Background(), ownerWithRepo.Owner, ownerWithRepo.Repo)
if err != nil {
err = fmt.Errorf("unable to get github repository %s", fullName)
}
repositoriesChan <- &GithubRepositoryApiResponse{
Repository: repoMetadata,
Error: err,
}
fmt.Printf("Finished fetching github repository %s/%s\n", ownerWithRepo.Owner, ownerWithRepo.Repo)
} else {
ownerType, err := gc.getGithubOwnerType(ownerWithRepo.Owner)
if err != nil {
err = fmt.Errorf("unable to get data on github owner %s", ownerWithRepo.Owner)
repositoriesChan <- &GithubRepositoryApiResponse{
Repository: nil,
Error: err,
}
} else {
ownerRepos, err := ListByOwnerWithPagination(gc.client, ownerWithRepo.Owner, ownerType)
if err != nil {
err = fmt.Errorf("unable to get repositories from github owner %s", ownerWithRepo.Owner)
}
for repo := range ownerRepos {
repositoriesChan <- &GithubRepositoryApiResponse{
Repository: repo,
Error: err,
}
}
}
}
}
}()
return repositoriesChan
}
func (gc *GithubConnector) getGithubOwnerType(owner string) (string, error) {
metadata, _, err := gc.client.Users.Get(context.Background(), owner)
if err != nil || metadata == nil {
return "", err
}
return *metadata.Type, err
}