forked from harness/harness-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
309 lines (274 loc) · 7.11 KB
/
utils.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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
package main
import (
"encoding/json"
"fmt"
"io"
"os"
"regexp"
"strings"
"github.com/AlecAivazis/survey/v2"
"github.com/fatih/color"
log "github.com/sirupsen/logrus"
"github.com/urfave/cli/v2"
"gopkg.in/yaml.v3"
)
func ConfirmInput(question string) bool {
confirm := false
prompt := &survey.Confirm{
Message: question,
}
_ = survey.AskOne(prompt, &confirm)
return confirm
}
func TextInput(question string) string {
var text = ""
prompt := &survey.Input{
Message: question,
}
err := survey.AskOne(prompt, &text, survey.WithValidator(survey.Required))
if err != nil {
log.Error(err.Error())
os.Exit(0)
}
return text
}
func GetUrlWithQueryParams(environment string, service string, endpoint string, queryParams map[string]string) string {
params := ""
totalItems := len(queryParams)
currentIndex := 0
for k, v := range queryParams {
currentIndex++
if v != "" {
if currentIndex == totalItems {
params = params + k + "=" + v
} else {
params = params + k + "=" + v + "&"
}
}
}
// remove trailing & char
lastChar := params[len(params)-1]
if lastChar == '&' {
params = strings.TrimSuffix(params, string('&'))
}
return fmt.Sprintf("%s/%s?%s", service, endpoint, params)
}
func printJson(v any) {
marsheld, err := json.MarshalIndent(v, "", " ")
if err != nil {
log.Fatalf("Marshaling error: %s", err)
}
fmt.Println("Data: ", string(marsheld))
}
func writeToFile(text string, filename string, overwrite bool) {
exactFilePath := getUserHomePath() + "/" + filename
var permissions = os.O_APPEND | os.O_CREATE | os.O_WRONLY
if overwrite {
permissions = os.O_APPEND | os.O_CREATE | os.O_WRONLY | os.O_TRUNC
}
f, err := os.OpenFile(exactFilePath, permissions, 0644)
if overwrite {
f.WriteString("")
}
f.WriteString(text)
if err != nil {
log.Fatal(err)
}
f.Close()
}
func readFromFile(filepath string) (s string, r []byte) {
var _fileContents = ""
file, _ := os.OpenFile(filepath, os.O_RDONLY, 0644)
defer file.Close()
byteValue, readError := io.ReadAll(file)
if readError != nil {
//log.Println("Error reading from file:", fileError)
}
_fileContents = string(byteValue)
return _fileContents, byteValue
}
func saveCredentials(c *cli.Context) (err error) {
baseURL := c.String("base-url")
if baseURL == "" {
baseURL = cliCdRequestData.BaseUrl
}
if cliCdRequestData.BaseUrl == "" {
baseURL = HARNESS_PROD_URL
}
authCredentials := SecretStore{
ApiKey: cliCdRequestData.AuthToken,
AccountId: cliCdRequestData.Account,
BaseURL: baseURL,
}
jsonObj, err := json.MarshalIndent(authCredentials, "", " ")
if err != nil {
fmt.Println("Error creating secrets json:", err)
return
}
writeToFile(string(jsonObj), SECRETS_STORE_PATH, true)
println(getColoredText("Login successfully done. Yay!", color.FgGreen))
return nil
}
func hydrateCredsFromPersistence(params ...interface{}) {
c := params[0].(*cli.Context)
var hydrateOnlyURL = false
if len(params) > 1 {
if value, ok := params[1].(bool); ok {
hydrateOnlyURL = value
}
}
if cliCdRequestData.AuthToken != "" && cliCdRequestData.Account != "" && !hydrateOnlyURL {
return
}
exactFilePath := getUserHomePath() + "/" + SECRETS_STORE_PATH
credsJson, err := os.ReadFile(exactFilePath)
if err != nil {
fmt.Println("Error reading creds file:", err)
return
}
var secretstore SecretStore
err = json.Unmarshal(credsJson, &secretstore)
if err != nil {
fmt.Println("Error:", err)
Login(c)
return
}
if hydrateOnlyURL {
baseURL := c.String("base-url")
if baseURL == "" {
cliCdRequestData.BaseUrl = secretstore.BaseURL
} else {
cliCdRequestData.BaseUrl = baseURL
}
} else {
cliCdRequestData.AuthToken = secretstore.ApiKey
cliCdRequestData.Account = secretstore.AccountId
cliCdRequestData.BaseUrl = secretstore.BaseURL
}
return
}
func getNGBaseURL(c *cli.Context) string {
baseURL := c.String("base-url")
if baseURL == "" {
if cliCdRequestData.BaseUrl == "" {
baseURL = HARNESS_PROD_URL
} else {
baseURL = cliCdRequestData.BaseUrl
}
}
baseURL = strings.TrimRight(baseURL, "/") //remove trailing slash
baseURL = baseURL + NG_BASE_URL
return baseURL
}
func getBaseUrl(c *cli.Context, serviceUrl string) string {
baseURL := c.String("base-url")
if baseURL == "" {
if cliCdRequestData.BaseUrl == "" {
baseURL = HARNESS_PROD_URL
} else {
baseURL = cliCdRequestData.BaseUrl
}
}
baseURL = strings.TrimRight(baseURL, "/") //remove trailing slash
baseURL = baseURL + serviceUrl
return baseURL
}
func getJsonFromYaml(content string) map[string]interface{} {
requestBody := make(map[string]interface{})
err := yaml.Unmarshal([]byte(content), requestBody)
if err != nil {
return nil
}
return requestBody
}
func GetNestedValue(data map[string]interface{}, keys ...string) interface{} {
if len(keys) == 0 {
return nil
}
value, ok := data[keys[0]]
if !ok {
return nil
}
for _, key := range keys[1:] {
nested, ok := value.(map[string]interface{})
if !ok {
return nil
}
value, ok = nested[key]
if !ok {
return nil
}
}
return value
}
func getUserHomePath() string {
homeDir, err := os.UserHomeDir()
if err != nil {
fmt.Println("Failed to get user's home directory:", err)
return ""
}
return homeDir
}
func valueToString(value interface{}) string {
switch v := value.(type) {
case string:
return v
case int, int8, int16, int32, int64:
return fmt.Sprintf("%d", v)
case uint, uint8, uint16, uint32, uint64:
return fmt.Sprintf("%d", v)
case float32:
return fmt.Sprintf("%f", v)
case float64:
return fmt.Sprintf("%f", v)
default:
return ""
}
}
func getColoredText(text string, textColor color.Attribute) string {
colored := color.New(textColor).SprintFunc()
return colored(text)
}
func getEntity(baseUrl string, reqURL string, projectIdentifier string, orgIdentifier string, extraParams map[string]string) bool {
queryParams := map[string]string{
"accountIdentifier": cliCdRequestData.Account,
"routingId": cliCdRequestData.Account,
"projectIdentifier": projectIdentifier,
"orgIdentifier": orgIdentifier,
}
queryParams = mergeMaps(queryParams, extraParams)
urlWithQueryParams := GetUrlWithQueryParams("", baseUrl, reqURL, queryParams)
_, fetchEntityError := Get(urlWithQueryParams, cliCdRequestData.AuthToken)
if fetchEntityError != nil {
return false
} else {
return true
}
}
func mergeMaps(map1 map[string]string, map2 map[string]string) map[string]string {
mergedMap := func() map[string]string {
result := make(map[string]string)
for k, v := range map1 {
result[k] = v
}
for k, v := range map2 {
result[k] = v
}
return result
}()
return mergedMap
}
// replaces placeholder values in the given yaml content
func replacePlaceholderValues(haystack string, needle string, value string) string {
return strings.ReplaceAll(haystack, needle, value)
}
func fetchCloudType(str string) string {
gcpRegexPattern := `type:\s+GoogleCloudFunctions`
awsRegexPattern := `type:\s+AwsLambda`
if isGcpMatch, err1 := regexp.MatchString(gcpRegexPattern, str); err1 == nil && isGcpMatch {
return GCP
} else if isAwsMatch, err2 := regexp.MatchString(awsRegexPattern, str); err2 == nil && isAwsMatch {
return AWS
}
return ""
}