-
Notifications
You must be signed in to change notification settings - Fork 74
/
params.go
704 lines (640 loc) · 25 KB
/
params.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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
package utils
import (
"context"
"errors"
"fmt"
"github.com/jfrog/jfrog-cli-security/jas"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/jfrog/frogbot/v2/utils/outputwriter"
xrutils "github.com/jfrog/jfrog-cli-security/utils"
"github.com/jfrog/build-info-go/utils"
"github.com/jfrog/froggit-go/vcsclient"
"github.com/jfrog/froggit-go/vcsutils"
coreconfig "github.com/jfrog/jfrog-cli-core/v2/utils/config"
"github.com/jfrog/jfrog-client-go/utils/log"
"gopkg.in/yaml.v3"
)
const (
frogbotConfigDir = ".frogbot"
FrogbotConfigFile = "frogbot-config.yml"
)
var (
errFrogbotConfigNotFound = fmt.Errorf("%s wasn't found in the Frogbot directory and its subdirectories. Assuming all the configuration is stored as environment variables", FrogbotConfigFile)
// Possible Config file path's to Frogbot Management repository
osFrogbotConfigPath = filepath.Join(frogbotConfigDir, FrogbotConfigFile)
)
type FrogbotDetails struct {
Repositories RepoAggregator
ServerDetails *coreconfig.ServerDetails
GitClient vcsclient.VcsClient
ReleasesRepo string
}
type RepoAggregator []Repository
// NewRepoAggregator returns an initialized RepoAggregator with an empty repository
func newRepoAggregator() RepoAggregator {
return RepoAggregator{{Params: Params{Scan: Scan{Projects: []Project{{}}}}}}
}
type Repository struct {
Params `yaml:"params,omitempty"`
OutputWriter outputwriter.OutputWriter
Server coreconfig.ServerDetails
}
func (r *Repository) setOutputWriterDetails() {
r.OutputWriter = outputwriter.GetCompatibleOutputWriter(r.Params.GitProvider)
r.OutputWriter.SetAvoidExtraMessages(r.Params.AvoidExtraMessages)
r.OutputWriter.SetPullRequestCommentTitle(r.Params.PullRequestCommentTitle)
}
type Params struct {
Scan `yaml:"scan,omitempty"`
Git `yaml:"git,omitempty"`
JFrogPlatform `yaml:"jfrogPlatform,omitempty"`
}
func (p *Params) setDefaultsIfNeeded(gitParamsFromEnv *Git, commandName string) error {
if err := p.Git.setDefaultsIfNeeded(gitParamsFromEnv, commandName); err != nil {
return err
}
if err := p.JFrogPlatform.setDefaultsIfNeeded(); err != nil {
return err
}
return p.Scan.setDefaultsIfNeeded()
}
type Project struct {
InstallCommand string `yaml:"installCommand,omitempty"`
PipRequirementsFile string `yaml:"pipRequirementsFile,omitempty"`
WorkingDirs []string `yaml:"workingDirs,omitempty"`
PathExclusions []string `yaml:"pathExclusions,omitempty"`
UseWrapper *bool `yaml:"useWrapper,omitempty"`
DepsRepo string `yaml:"repository,omitempty"`
InstallCommandName string
InstallCommandArgs []string
IsRecursiveScan bool
}
func (p *Project) setDefaultsIfNeeded() error {
if len(p.WorkingDirs) == 0 {
workingDir := getTrimmedEnv(WorkingDirectoryEnv)
if workingDir == "" {
// If no working directories are provided, and none exist in the environment variable, we designate the project's root directory as our sole working directory.
// We then execute a recursive scan across the entire project, commencing from the root.
workingDir = RootDir
p.IsRecursiveScan = true
}
p.WorkingDirs = append(p.WorkingDirs, workingDir)
}
if len(p.PathExclusions) == 0 {
if p.PathExclusions, _ = readArrayParamFromEnv(PathExclusionsEnv, ";"); len(p.PathExclusions) == 0 {
p.PathExclusions = jas.DefaultExcludePatterns
}
}
if p.UseWrapper == nil {
useWrapper, err := getBoolEnv(UseWrapperEnv, true)
if err != nil {
return err
}
p.UseWrapper = &useWrapper
}
if p.InstallCommand == "" {
p.InstallCommand = getTrimmedEnv(InstallCommandEnv)
}
if p.InstallCommand != "" {
setProjectInstallCommand(p.InstallCommand, p)
}
if p.PipRequirementsFile == "" {
p.PipRequirementsFile = getTrimmedEnv(RequirementsFileEnv)
}
if p.DepsRepo == "" {
p.DepsRepo = getTrimmedEnv(DepsRepoEnv)
}
return nil
}
type Scan struct {
IncludeAllVulnerabilities bool `yaml:"includeAllVulnerabilities,omitempty"`
FixableOnly bool `yaml:"fixableOnly,omitempty"`
FailOnSecurityIssues *bool `yaml:"failOnSecurityIssues,omitempty"`
AvoidPreviousPrCommentsDeletion bool `yaml:"avoidPreviousPrCommentsDeletion,omitempty"`
MinSeverity string `yaml:"minSeverity,omitempty"`
AllowedLicenses []string `yaml:"allowedLicenses,omitempty"`
Projects []Project `yaml:"projects,omitempty"`
EmailDetails `yaml:",inline"`
}
type EmailDetails struct {
SmtpServer string
SmtpPort string
SmtpUser string
SmtpPassword string
EmailReceivers []string `yaml:"emailReceivers,omitempty"`
}
func (s *Scan) SetEmailDetails() error {
smtpServerAndPort := getTrimmedEnv(SmtpServerEnv)
if smtpServerAndPort == "" {
return nil
}
splittedServerAndPort := strings.Split(smtpServerAndPort, ":")
if len(splittedServerAndPort) < 2 {
return fmt.Errorf("failed while setting your email details. Could not extract the smtp server and its port from the %s environment variable. Expected format: `smtp.server.com:port`, received: %s", SmtpServerEnv, smtpServerAndPort)
}
s.SmtpServer = splittedServerAndPort[0]
s.SmtpPort = splittedServerAndPort[1]
s.SmtpUser = getTrimmedEnv(SmtpUserEnv)
s.SmtpPassword = getTrimmedEnv(SmtpPasswordEnv)
if s.SmtpUser == "" {
return fmt.Errorf("failed while setting your email details. SMTP username is expected, but the %s environment variable is empty", SmtpUserEnv)
}
if s.SmtpPassword == "" {
return fmt.Errorf("failed while setting your email details. SMTP password is expected, but the %s environment variable is empty", SmtpPasswordEnv)
}
if len(s.EmailReceivers) == 0 {
if emailReceiversEnv := getTrimmedEnv(EmailReceiversEnv); emailReceiversEnv != "" {
s.EmailReceivers = strings.Split(emailReceiversEnv, ",")
}
}
return nil
}
func (s *Scan) setDefaultsIfNeeded() (err error) {
e := &ErrMissingEnv{}
if !s.IncludeAllVulnerabilities {
if s.IncludeAllVulnerabilities, err = getBoolEnv(IncludeAllVulnerabilitiesEnv, false); err != nil {
return
}
}
if !s.AvoidPreviousPrCommentsDeletion {
if s.AvoidPreviousPrCommentsDeletion, err = getBoolEnv(AvoidPreviousPrCommentsDeletionEnv, false); err != nil {
return
}
}
if !s.FixableOnly {
if s.FixableOnly, err = getBoolEnv(FixableOnlyEnv, false); err != nil {
return
}
}
if s.FailOnSecurityIssues == nil {
var failOnSecurityIssues bool
if failOnSecurityIssues, err = getBoolEnv(FailOnSecurityIssuesEnv, true); err != nil {
return
}
s.FailOnSecurityIssues = &failOnSecurityIssues
}
if s.MinSeverity == "" {
if err = readParamFromEnv(MinSeverityEnv, &s.MinSeverity); err != nil && !e.IsMissingEnvErr(err) {
return
}
}
if s.MinSeverity, err = xrutils.GetSeveritiesFormat(s.MinSeverity); err != nil {
return
}
if len(s.Projects) == 0 {
s.Projects = append(s.Projects, Project{})
}
if len(s.AllowedLicenses) == 0 {
if s.AllowedLicenses, err = readArrayParamFromEnv(AllowedLicensesEnv, ","); err != nil && !e.IsMissingEnvErr(err) {
return
}
}
for i := range s.Projects {
if err = s.Projects[i].setDefaultsIfNeeded(); err != nil {
return
}
}
err = s.SetEmailDetails()
return
}
type JFrogPlatform struct {
Watches []string `yaml:"watches,omitempty"`
JFrogProjectKey string `yaml:"jfrogProjectKey,omitempty"`
}
func (jp *JFrogPlatform) setDefaultsIfNeeded() (err error) {
e := &ErrMissingEnv{}
if len(jp.Watches) == 0 {
if jp.Watches, err = readArrayParamFromEnv(jfrogWatchesEnv, WatchesDelimiter); err != nil && !e.IsMissingEnvErr(err) {
return
}
}
if jp.JFrogProjectKey == "" {
if err = readParamFromEnv(jfrogProjectEnv, &jp.JFrogProjectKey); err != nil && !e.IsMissingEnvErr(err) {
return
}
// We don't want to return an error from this function if the error is of type ErrMissingEnv because JFrogPlatform environment variables are not mandatory.
err = nil
}
return
}
type Git struct {
GitProvider vcsutils.VcsProvider
vcsclient.VcsInfo
RepoOwner string
RepoName string `yaml:"repoName,omitempty"`
Branches []string `yaml:"branches,omitempty"`
BranchNameTemplate string `yaml:"branchNameTemplate,omitempty"`
CommitMessageTemplate string `yaml:"commitMessageTemplate,omitempty"`
PullRequestTitleTemplate string `yaml:"pullRequestTitleTemplate,omitempty"`
PullRequestCommentTitle string `yaml:"pullRequestCommentTitle,omitempty"`
AvoidExtraMessages bool `yaml:"avoidExtraMessages,omitempty"`
EmailAuthor string `yaml:"emailAuthor,omitempty"`
AggregateFixes bool `yaml:"aggregateFixes,omitempty"`
PullRequestDetails vcsclient.PullRequestInfo
RepositoryCloneUrl string
}
func (g *Git) setDefaultsIfNeeded(gitParamsFromEnv *Git, commandName string) (err error) {
g.RepoOwner = gitParamsFromEnv.RepoOwner
g.GitProvider = gitParamsFromEnv.GitProvider
g.VcsInfo = gitParamsFromEnv.VcsInfo
g.PullRequestDetails = gitParamsFromEnv.PullRequestDetails
if g.RepoName == "" {
if gitParamsFromEnv.RepoName == "" {
return fmt.Errorf("repository name is missing. please set the repository name in your %s file or as the %s environment variable", FrogbotConfigFile, GitRepoEnv)
}
g.RepoName = gitParamsFromEnv.RepoName
}
if g.EmailAuthor == "" {
if g.EmailAuthor = getTrimmedEnv(GitEmailAuthorEnv); g.EmailAuthor == "" {
g.EmailAuthor = frogbotAuthorEmail
}
}
if commandName == ScanPullRequest {
if err = g.extractScanPullRequestEnvParams(gitParamsFromEnv); err != nil {
return
}
}
if commandName == ScanRepository || commandName == ScanMultipleRepositories {
if err = g.extractScanRepositoryEnvParams(gitParamsFromEnv); err != nil {
return
}
}
return
}
func (g *Git) extractScanPullRequestEnvParams(gitParamsFromEnv *Git) (err error) {
// The Pull Request ID is a mandatory requirement for Frogbot to properly identify and scan the relevant pull request
if gitParamsFromEnv.PullRequestDetails.ID == 0 {
return errors.New("no Pull Request ID has been provided. Please configure it by using the `JF_GIT_PULL_REQUEST_ID` environment variable")
}
if g.PullRequestCommentTitle == "" {
g.PullRequestCommentTitle = getTrimmedEnv(PullRequestCommentTitleEnv)
}
g.AvoidExtraMessages, err = getBoolEnv(AvoidExtraMessages, false)
return
}
func (g *Git) extractScanRepositoryEnvParams(gitParamsFromEnv *Git) (err error) {
// Continue to extract ScanRepository related env params
noBranchesProvidedViaConfig := len(g.Branches) == 0
noBranchesProvidedViaEnv := len(gitParamsFromEnv.Branches) == 0
if noBranchesProvidedViaConfig {
if noBranchesProvidedViaEnv {
return errors.New("no branches were provided. Please set your branches using the `JF_GIT_BASE_BRANCH` environment variable or by configuring them in the frogbot-config.yml file")
}
g.Branches = gitParamsFromEnv.Branches
}
if g.BranchNameTemplate == "" {
branchTemplate := getTrimmedEnv(BranchNameTemplateEnv)
if err = validateHashPlaceHolder(branchTemplate); err != nil {
return
}
g.BranchNameTemplate = branchTemplate
}
if g.CommitMessageTemplate == "" {
g.CommitMessageTemplate = getTrimmedEnv(CommitMessageTemplateEnv)
}
if g.PullRequestTitleTemplate == "" {
g.PullRequestTitleTemplate = getTrimmedEnv(PullRequestTitleTemplateEnv)
}
if !g.AggregateFixes {
if g.AggregateFixes, err = getBoolEnv(GitAggregateFixesEnv, false); err != nil {
return
}
}
return
}
func validateHashPlaceHolder(template string) error {
if template == "" {
return nil
}
if !strings.Contains(template, BranchHashPlaceHolder) {
return fmt.Errorf("branch name template must contain %s, provided: %s", BranchHashPlaceHolder, template)
}
return nil
}
func GetFrogbotDetails(commandName string) (frogbotDetails *FrogbotDetails, err error) {
// Get server and git details
jfrogServer, err := extractJFrogCredentialsFromEnvs()
if err != nil {
return
}
gitParamsFromEnv, err := extractGitParamsFromEnvs(commandName)
if err != nil {
return
}
defer func() {
err = errors.Join(err, SanitizeEnv())
}()
// Build a version control client for REST API requests
client, err := vcsclient.
NewClientBuilder(gitParamsFromEnv.GitProvider).
ApiEndpoint(strings.TrimSuffix(gitParamsFromEnv.APIEndpoint, "/")).
Token(gitParamsFromEnv.Token).
Project(gitParamsFromEnv.Project).
Logger(log.GetLogger()).
Username(gitParamsFromEnv.Username).
Build()
if err != nil {
return
}
configAggregator, err := getConfigAggregator(client, gitParamsFromEnv, jfrogServer, commandName)
if err != nil {
return
}
frogbotDetails = &FrogbotDetails{Repositories: configAggregator, GitClient: client, ServerDetails: jfrogServer, ReleasesRepo: os.Getenv(jfrogReleasesRepoEnv)}
return
}
// getConfigAggregator returns a RepoAggregator based on frogbot-config.yml and environment variables.
func getConfigAggregator(gitClient vcsclient.VcsClient, gitParamsFromEnv *Git, jfrogServer *coreconfig.ServerDetails, commandName string) (RepoAggregator, error) {
configFileContent, err := getConfigFileContent(gitClient, gitParamsFromEnv, commandName)
if err != nil {
return nil, err
}
if configFileContent != nil {
log.Debug(fmt.Sprintf("The content of %s that will be used is:\n%s", FrogbotConfigFile, string(configFileContent)))
}
return BuildRepoAggregator(gitClient, configFileContent, gitParamsFromEnv, jfrogServer, commandName)
}
// getConfigFileContent retrieves the content of the frogbot-config.yml file
func getConfigFileContent(gitClient vcsclient.VcsClient, gitParamsFromEnv *Git, commandName string) ([]byte, error) {
var errMissingConfig *ErrMissingConfig
if commandName == ScanRepository || commandName == ScanMultipleRepositories {
configFileContent, err := ReadConfigFromFileSystem(osFrogbotConfigPath)
if err != nil && !errors.As(err, &errMissingConfig) {
return nil, err
}
if configFileContent != nil {
return configFileContent, nil
}
}
configFileContent, err := readConfigFromTarget(gitClient, gitParamsFromEnv)
if errors.As(err, &errMissingConfig) {
// Avoid returning an error if the frogbot-config.yml file is missing.
// If an error occurs because the file is missing, we will create an environment variable-based configuration aggregator instead.
return nil, nil
}
return configFileContent, err
}
// BuildRepoAggregator receives the content of a frogbot-config.yml file, along with the Git (built from environment variables) and ServerDetails parameters.
// Returns a RepoAggregator instance with all the defaults and necessary fields.
func BuildRepoAggregator(gitClient vcsclient.VcsClient, configFileContent []byte, gitParamsFromEnv *Git, server *coreconfig.ServerDetails, commandName string) (resultAggregator RepoAggregator, err error) {
var cleanAggregator RepoAggregator
// Unmarshal the frogbot-config.yml file if exists
if cleanAggregator, err = unmarshalFrogbotConfigYaml(configFileContent); err != nil {
return
}
for _, repository := range cleanAggregator {
repository.Server = *server
if err = repository.Params.setDefaultsIfNeeded(gitParamsFromEnv, commandName); err != nil {
return
}
repository.setOutputWriterDetails()
repository.OutputWriter.SetSizeLimit(gitClient)
resultAggregator = append(resultAggregator, repository)
}
return
}
// unmarshalFrogbotConfigYaml uses the yaml.Unmarshaler interface to parse the yamlContent.
// If there is no config file, the function returns a RepoAggregator with an empty repository.
func unmarshalFrogbotConfigYaml(yamlContent []byte) (result RepoAggregator, err error) {
if len(yamlContent) == 0 {
result = newRepoAggregator()
return
}
err = yaml.Unmarshal(yamlContent, &result)
return
}
func extractJFrogCredentialsFromEnvs() (*coreconfig.ServerDetails, error) {
server := coreconfig.ServerDetails{}
platformUrl := strings.TrimSuffix(getTrimmedEnv(JFrogUrlEnv), "/")
xrUrl := strings.TrimSuffix(getTrimmedEnv(jfrogXrayUrlEnv), "/")
rtUrl := strings.TrimSuffix(getTrimmedEnv(jfrogArtifactoryUrlEnv), "/")
if xrUrl != "" && rtUrl != "" {
server.XrayUrl = xrUrl + "/"
server.ArtifactoryUrl = rtUrl + "/"
} else {
if platformUrl == "" {
return nil, fmt.Errorf("%s or %s and %s environment variables are missing", JFrogUrlEnv, jfrogXrayUrlEnv, jfrogArtifactoryUrlEnv)
}
server.Url = platformUrl + "/"
server.XrayUrl = platformUrl + "/xray/"
server.ArtifactoryUrl = platformUrl + "/artifactory/"
}
password := getTrimmedEnv(JFrogPasswordEnv)
user := getTrimmedEnv(JFrogUserEnv)
if password != "" && user != "" {
server.User = user
server.Password = password
} else if accessToken := getTrimmedEnv(JFrogTokenEnv); accessToken != "" {
server.AccessToken = accessToken
} else {
return nil, fmt.Errorf("%s and %s or %s environment variables are missing", JFrogUserEnv, JFrogPasswordEnv, JFrogTokenEnv)
}
return &server, nil
}
func extractGitParamsFromEnvs(commandName string) (*Git, error) {
e := &ErrMissingEnv{}
var err error
gitEnvParams := &Git{}
// Branch & Repo names are mandatory variables.
// Must be set in the frogbot-config.yml or as an environment variables.
// Validation performed later
// Set the base branch name
var branch string
if err = readParamFromEnv(GitBaseBranchEnv, &branch); err != nil && !e.IsMissingEnvErr(err) {
return nil, err
}
if branch != "" {
gitEnvParams.Branches = []string{branch}
}
// Non-mandatory Git Api Endpoint, if not set, default values will be used.
if err = readParamFromEnv(GitApiEndpointEnv, &gitEnvParams.APIEndpoint); err != nil && !e.IsMissingEnvErr(err) {
return nil, err
}
if err = verifyValidApiEndpoint(gitEnvParams.APIEndpoint); err != nil {
return nil, err
}
// [Mandatory] Set the Git provider
if gitEnvParams.GitProvider, err = extractVcsProviderFromEnv(); err != nil {
return nil, err
}
// [Mandatory] Set the git repository owner name (organization)
if err = readParamFromEnv(GitRepoOwnerEnv, &gitEnvParams.RepoOwner); err != nil {
return nil, err
}
// [Mandatory] Set the access token to the git provider
if err = readParamFromEnv(GitTokenEnv, &gitEnvParams.Token); err != nil {
return nil, err
}
// [Mandatory] Set the repository name, except for multi repository.
if err = readParamFromEnv(GitRepoEnv, &gitEnvParams.RepoName); err != nil && commandName != ScanMultipleRepositories {
return nil, err
}
// Set Bitbucket Server username
// Mandatory only for Bitbucket Server, this authentication detail is required for performing git operations.
if err = readParamFromEnv(GitUsernameEnv, &gitEnvParams.Username); err != nil && !e.IsMissingEnvErr(err) {
return nil, err
}
// Set Azure Repos Project name
// Mandatory for Azure Repos only
if err = readParamFromEnv(GitProjectEnv, &gitEnvParams.Project); err != nil && gitEnvParams.GitProvider == vcsutils.AzureRepos {
return nil, err
}
if envPrId := getTrimmedEnv(GitPullRequestIDEnv); envPrId != "" {
var convertedPrId int
if convertedPrId, err = strconv.Atoi(envPrId); err != nil {
return nil, fmt.Errorf("failed parsing %s environment variable as a number. The received environment is : %s", GitPullRequestIDEnv, envPrId)
}
gitEnvParams.PullRequestDetails = vcsclient.PullRequestInfo{ID: int64(convertedPrId)}
}
return gitEnvParams, nil
}
func verifyValidApiEndpoint(apiEndpoint string) error {
// Empty string will resolve to default values.
if apiEndpoint == "" {
return nil
}
parsedUrl, err := url.Parse(apiEndpoint)
if err != nil {
return err
}
if parsedUrl.Scheme == "" {
return errors.New("the given API endpoint is invalid. Please note that the API endpoint format should be provided with the 'HTTPS' protocol as a prefix")
}
return nil
}
func readArrayParamFromEnv(envKey, delimiter string) ([]string, error) {
var envValue string
var err error
e := &ErrMissingEnv{}
if err = readParamFromEnv(envKey, &envValue); err != nil && !e.IsMissingEnvErr(err) {
return nil, err
}
if envValue == "" {
return nil, &ErrMissingEnv{VariableName: envKey}
}
// Remove spaces if exists
envValue = strings.ReplaceAll(envValue, " ", "")
return strings.Split(envValue, delimiter), nil
}
func readParamFromEnv(envKey string, paramValue *string) error {
*paramValue = getTrimmedEnv(envKey)
if *paramValue == "" {
return &ErrMissingEnv{VariableName: envKey}
}
return nil
}
func getTrimmedEnv(envKey string) string {
return strings.TrimSpace(os.Getenv(envKey))
}
func extractVcsProviderFromEnv() (vcsutils.VcsProvider, error) {
vcsProvider := getTrimmedEnv(GitProvider)
switch vcsProvider {
case string(GitHub):
return vcsutils.GitHub, nil
case string(GitLab):
return vcsutils.GitLab, nil
// For backward compatibility, we are accepting also "bitbucket server"
case string(BitbucketServer), "bitbucket server":
return vcsutils.BitbucketServer, nil
case string(AzureRepos):
return vcsutils.AzureRepos, nil
}
return 0, fmt.Errorf("%s should be one of: '%s', '%s', '%s' or '%s'", GitProvider, GitHub, GitLab, BitbucketServer, AzureRepos)
}
func SanitizeEnv() error {
for _, env := range os.Environ() {
if !strings.HasPrefix(env, "JF_") {
continue
}
envSplit := strings.Split(env, "=")
if err := os.Unsetenv(envSplit[0]); err != nil {
return err
}
}
return nil
}
// ReadConfigFromFileSystem looks for .frogbot/frogbot-config.yml from the given path and return its content. The path is relative and starts from the root of the project.
// If the config file is not found in the relative path, it will search in parent dirs.
func ReadConfigFromFileSystem(configRelativePath string) (configFileContent []byte, err error) {
log.Debug("Reading config from file system. Looking for", osFrogbotConfigPath)
fullConfigDirPath, err := filepath.Abs(configRelativePath)
if err != nil {
return nil, err
}
// Look for the frogbot-config.yml file in fullConfigPath
exist, err := utils.IsFileExists(fullConfigDirPath, false)
if !exist || err != nil {
// Look for the frogbot-config.yml in fullConfigPath parents dirs
log.Debug(FrogbotConfigFile, "wasn't found in "+fullConfigDirPath+". Searching for it in upstream directories")
if fullConfigDirPath, err = utils.FindFileInDirAndParents(fullConfigDirPath, configRelativePath); err != nil {
return nil, &ErrMissingConfig{errFrogbotConfigNotFound.Error()}
}
fullConfigDirPath = filepath.Join(fullConfigDirPath, configRelativePath)
}
log.Debug(FrogbotConfigFile, "found in", fullConfigDirPath)
configFileContent, err = os.ReadFile(filepath.Clean(fullConfigDirPath))
if err != nil {
err = fmt.Errorf("an error occurd while reading the %s file at: %s\n%s", FrogbotConfigFile, configRelativePath, err.Error())
}
return
}
func setProjectInstallCommand(installCommand string, project *Project) {
parts := strings.Fields(installCommand)
if len(parts) > 1 {
project.InstallCommandArgs = parts[1:]
}
project.InstallCommandName = parts[0]
}
func getBoolEnv(envKey string, defaultValue bool) (bool, error) {
envValue := getTrimmedEnv(envKey)
if envValue != "" {
parsedEnv, err := strconv.ParseBool(envValue)
if err != nil {
return false, fmt.Errorf("the value of the %s environment is expected to be either TRUE or FALSE. The value received however is %s", envKey, envValue)
}
return parsedEnv, nil
}
return defaultValue, nil
}
// readConfigFromTarget reads the .frogbot/frogbot-config.yml from the target repository
func readConfigFromTarget(client vcsclient.VcsClient, gitParamsFromEnv *Git) (configContent []byte, err error) {
// Extract repository details from Git parameters
repoName := gitParamsFromEnv.RepoName
repoOwner := gitParamsFromEnv.RepoOwner
branches := gitParamsFromEnv.Branches
if repoName == "" && repoOwner == "" {
return
}
log.Debug("Attempting to download", FrogbotConfigFile, "from", repoOwner+"/"+repoName)
var branch string
if len(branches) == 0 {
log.Debug(GitBaseBranchEnv, "is missing. Assuming that the", FrogbotConfigFile, "file exists on default branch")
} else {
// We encounter this scenario when the JF_GIT_BASE_BRANCH is defined. In this situation, we have only one branch.
branch = branches[0]
log.Debug("The", FrogbotConfigFile, "will be downloaded from", branch, "branch")
}
// Construct the path to the frogbot-config.yml file in the repository
gitFrogbotConfigPath := fmt.Sprintf("%s/%s", frogbotConfigDir, FrogbotConfigFile)
// Download the frogbot-config.yml file from the repository
var statusCode int
configContent, statusCode, err = client.DownloadFileFromRepo(context.Background(), repoOwner, repoName, branch, gitFrogbotConfigPath)
// Handle different HTTP status codes
switch statusCode {
case http.StatusOK:
log.Info(fmt.Sprintf("Successfully downloaded %s file from <%s/%s/%s>", FrogbotConfigFile, repoOwner, repoName, branch))
case http.StatusNotFound:
log.Debug(fmt.Sprintf("The %s file wasn't recognized in <%s/%s>", gitFrogbotConfigPath, repoOwner, repoName))
// If .frogbot/frogbot-config.yml isn't found, return an ErrMissingConfig
configContent = nil
err = &ErrMissingConfig{errFrogbotConfigNotFound.Error()}
case http.StatusUnauthorized:
log.Warn("Your credentials seem to be invalid. If you are using an on-premises Git provider, please set the API endpoint of your Git provider using the 'JF_GIT_API_ENDPOINT' environment variable (example: 'https://gitlab.example.com'). Additionally, make sure that the provided credentials have the required Git permissions.")
}
return
}