/
cloud.go
257 lines (217 loc) · 7.02 KB
/
cloud.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
package cloud
import (
"encoding/json"
"fmt"
"os"
"strings"
bitbucket "github.com/ktrysmt/go-bitbucket"
logrus "github.com/sirupsen/logrus"
gjson "github.com/tidwall/gjson"
common "github.com/parinithshekar/gitsink/common"
config "github.com/parinithshekar/gitsink/common/config"
utils "github.com/parinithshekar/gitsink/common/utils"
logger "github.com/parinithshekar/gitsink/wrap/logrus/v1"
)
var (
log = logger.New()
)
// Teams interface declares methods to implement in the API object
type Teams interface {
Projects(string) (interface{}, error)
Repositories(string) (interface{}, error)
}
// Repositories interface declares methods to implement in the API object
type Repositories interface {
ListForAccount(*bitbucket.RepositoriesOptions) (*bitbucket.RepositoriesRes, error)
}
// Cloud struct defines data fields in bitbucket-cloud object
type Cloud struct {
accountID string
accessToken string
kind string
filters struct {
include []string
exclude []string
}
API struct {
Teams Teams
Repositories Repositories
}
}
// setAPIClient builds and returns an object to facilitate calls to the API
func (cloud *Cloud) setAPIClient() {
accountID, accessToken, _ := cloud.Credentials()
client := bitbucket.NewBasicAuth(accountID, accessToken)
cloud.API.Teams = client.Teams
cloud.API.Repositories = client.Repositories
}
// Credentials fetches amd returns the accountID and accessToken from environment variables
func (cloud Cloud) Credentials() (string, string, error) {
accountID := os.Getenv(cloud.accountID)
accessToken := os.Getenv(cloud.accessToken)
accountID, exists := os.LookupEnv(cloud.accountID)
if !exists {
log.WithFields(logrus.Fields{
"accountID": cloud.accountID,
}).Errorf("Account ID not found")
return "", "", fmt.Errorf("Account ID not found")
}
accessToken, exists = os.LookupEnv(cloud.accessToken)
if !exists {
log.WithFields(logrus.Fields{
"accessToken": cloud.accessToken,
}).Errorf("Access Token not found")
return "", "", fmt.Errorf("Access Token not found")
}
return accountID, accessToken, nil
}
// New returns a new bitbucket-cloud object
func New(source config.Source) (*Cloud, error) {
var cloud *Cloud = new(Cloud)
_, exists := os.LookupEnv(source.AccountID)
if !exists {
log.WithFields(logrus.Fields{
"accountID": source.AccountID,
}).Errorf("Account ID not found")
return nil, fmt.Errorf("Account ID not found")
}
cloud.accountID = source.AccountID
_, exists = os.LookupEnv(source.AccessToken)
if !exists {
log.WithFields(logrus.Fields{
"accessToken": source.AccessToken,
}).Errorf("Access Token not found")
return nil, fmt.Errorf("Access Token not found")
}
cloud.accessToken = source.AccessToken
cloud.kind = source.Kind
cloud.filters.include = source.Repositories.Include
cloud.filters.exclude = source.Repositories.Exclude
cloud.setAPIClient()
return cloud, nil
}
// Authenticate checks the account ID and access tokens' validity for the kind defined
func (cloud Cloud) Authenticate() (bool, error) {
kindSplit := strings.SplitN(cloud.kind, "/", 2)
kindType := kindSplit[0]
kindKey := kindSplit[1]
accountID, _, err := cloud.Credentials()
if err != nil {
log.Errorf("Failed to authenticate")
return false, err
}
switch kindType {
case "project":
/*
The go-bitbucket SDK does not cover all API endpoints for some reason
Will have to get list of projects and search for the project key
*/
// Get list of projects user has access to
result, err := cloud.API.Teams.Projects(accountID)
if err != nil {
log.Errorf("Failed to get projects")
return false, err
}
// Check if mentioned project is in the list
passed := false
values := result.(map[string]interface{})["values"].([]interface{})
for _, v := range values {
passed = kindKey == v.(map[string]interface{})["key"]
if passed {
return passed, nil
}
}
log.WithFields(logrus.Fields{
"project": kindKey,
}).Errorf("Project not found. Check user access")
return false, fmt.Errorf("Project not found. Check user access")
case "user":
// Check if current user can access the repos of the user mentioned (kindKey) in config
_, err := cloud.API.Teams.Repositories(kindKey)
if err != nil {
log.WithFields(logrus.Fields{
"user": kindKey,
}).Errorf("User authentication failed")
return false, err
}
return true, nil
default:
// Mentioned kind is unsupported
log.WithFields(logrus.Fields{
"kind": kindType,
}).Errorf("Unsupported kind")
return false, fmt.Errorf("Unsupported kind")
}
}
// Repositories queries the API and returns a list of repositories mentioned by the kind
func (cloud Cloud) Repositories(metadata bool) ([]common.Repository, error) {
kindSplit := strings.SplitN(cloud.kind, "/", 2)
kindType := kindSplit[0]
kindKey := kindSplit[1]
accountID, _, err := cloud.Credentials()
if err != nil {
log.Errorf("Failed to get repositories")
return nil, err
}
switch kindType {
case "project":
ro := bitbucket.RepositoriesOptions{Owner: accountID, Role: "member"}
result, err := cloud.API.Repositories.ListForAccount(&ro)
if err != nil {
log.WithFields(logrus.Fields{
"project": kindKey,
}).Errorf("Failed to get project repositories")
return nil, err
}
repositories := []common.Repository{}
for _, repo := range result.Items {
if repo.Project.Key == kindKey {
repoBytes, _ := json.MarshalIndent(repo, "", " ")
repoJSON := string(repoBytes)
// fmt.Println(repoJSON)
// Get all metadata for the repository
httpCloneLink := gjson.Get(repoJSON, `Links.clone.#(name%"http*").href`).String()
slug := gjson.Get(repoJSON, `Slug`).String()
description := gjson.Get(repoJSON, `Description`).String()
newRepo := common.Repository{
Slug: slug,
Source: httpCloneLink,
Description: description,
}
repositories = append(repositories, newRepo)
}
}
repositories = utils.FilterRepos(repositories, cloud.filters.include, cloud.filters.exclude)
return repositories, nil
case "user":
ro := bitbucket.RepositoriesOptions{Owner: kindKey, Role: "member"}
result, err := cloud.API.Repositories.ListForAccount(&ro)
if err != nil {
log.WithFields(logrus.Fields{
"user": kindKey,
}).Errorf("Failed to get user repositories")
return nil, err
}
repositories := []common.Repository{}
for _, repo := range result.Items {
repoBytes, _ := json.MarshalIndent(repo, "", " ")
repoJSON := string(repoBytes)
httpCloneLink := gjson.Get(repoJSON, `Links.clone.#(name%"http*").href`).String()
slug := gjson.Get(repoJSON, `Slug`).String()
description := gjson.Get(repoJSON, `Description`).String()
newRepo := common.Repository{
Slug: slug,
Source: httpCloneLink,
Description: description,
}
repositories = append(repositories, newRepo)
}
repositories = utils.FilterRepos(repositories, cloud.filters.include, cloud.filters.exclude)
return repositories, nil
default:
log.WithFields(logrus.Fields{
"kind": kindType,
}).Errorf("Unsupported kind")
return nil, fmt.Errorf("Unsupported kind")
}
}