forked from jfrog/jfrog-cli-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
configfile.go
503 lines (452 loc) · 16.7 KB
/
configfile.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
package utils
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/jfrog/jfrog-cli-core/v2/artifactory/utils"
"github.com/jfrog/jfrog-cli-core/v2/utils/config"
"github.com/jfrog/jfrog-cli-core/v2/utils/coreutils"
"github.com/jfrog/jfrog-client-go/utils/errorutils"
"github.com/jfrog/jfrog-client-go/utils/io/fileutils"
"github.com/jfrog/jfrog-client-go/utils/log"
"github.com/urfave/cli"
"gopkg.in/yaml.v2"
)
const BuildConfVersion = 1
const (
// Common flags
global = "global"
resolutionServerId = "server-id-resolve"
deploymentServerId = "server-id-deploy"
resolutionRepo = "repo-resolve"
deploymentRepo = "repo-deploy"
// Maven flags
resolutionReleasesRepo = "repo-resolve-releases"
resolutionSnapshotsRepo = "repo-resolve-snapshots"
deploymentReleasesRepo = "repo-deploy-releases"
deploymentSnapshotsRepo = "repo-deploy-snapshots"
includePatterns = "include-patterns"
excludePatterns = "exclude-patterns"
// Gradle flags
usesPlugin = "uses-plugin"
useWrapper = "use-wrapper"
deployMavenDesc = "deploy-maven-desc"
deployIvyDesc = "deploy-ivy-desc"
ivyDescPattern = "ivy-desc-pattern"
ivyArtifactsPattern = "ivy-artifacts-pattern"
// Nuget flags
nugetV2 = "nuget-v2"
// Errors
resolutionErrorPrefix = "[Resolution]: "
deploymentErrorPrefix = "[Deployment]: "
setServerIdError = "server ID must be set. Use the --server-id-resolve/deploy flag or configure a default server using 'jfrog c add' and 'jfrog c use' commands. "
setRepositoryError = "repository/ies must be set. "
setSnapshotAndReleaseError = "snapshot and release repositories must be set. "
)
type ConfigFile struct {
Interactive bool `yaml:"-"`
Version int `yaml:"version,omitempty"`
ConfigType string `yaml:"type,omitempty"`
Resolver utils.Repository `yaml:"resolver,omitempty"`
Deployer utils.Repository `yaml:"deployer,omitempty"`
UsePlugin bool `yaml:"usePlugin,omitempty"`
UseWrapper bool `yaml:"useWrapper,omitempty"`
}
func NewConfigFile(confType utils.ProjectType, c *cli.Context) *ConfigFile {
configFile := &ConfigFile{
Version: BuildConfVersion,
ConfigType: confType.String(),
}
configFile.populateConfigFromFlags(c)
switch confType {
case utils.Maven:
configFile.populateMavenConfigFromFlags(c)
case utils.Gradle:
configFile.populateGradleConfigFromFlags(c)
case utils.Nuget, utils.Dotnet:
configFile.populateNugetConfigFromFlags(c)
}
return configFile
}
func CreateBuildConfig(c *cli.Context, confType utils.ProjectType) (err error) {
global := c.Bool(global)
projectDir, err := utils.GetProjectDir(global)
if err != nil {
return err
}
if err = fileutils.CreateDirIfNotExist(projectDir); err != nil {
return err
}
configFilePath := filepath.Join(projectDir, confType.String()+".yaml")
configFile := NewConfigFile(confType, c)
if err := configFile.VerifyConfigFile(configFilePath); err != nil {
return err
}
if configFile.Interactive {
switch confType {
case utils.Go:
err = configFile.configGo()
case utils.Pip:
err = configFile.configPip()
case utils.Yarn:
err = configFile.configYarn()
case utils.Npm:
err = configFile.configNpm()
case utils.Dotnet:
fallthrough
case utils.Nuget:
err = configFile.configDotnet()
case utils.Maven:
err = configFile.configMaven()
case utils.Gradle:
err = configFile.configGradle()
}
if err != nil {
return errorutils.CheckError(err)
}
}
if err = configFile.validateConfig(); err != nil {
return err
}
resBytes, err := yaml.Marshal(&configFile)
if err != nil {
return errorutils.CheckError(err)
}
if err = ioutil.WriteFile(configFilePath, resBytes, 0644); err != nil {
return errorutils.CheckError(err)
}
log.Info(confType.String() + " build config successfully created.")
return nil
}
func isInteractive(c *cli.Context) bool {
if strings.ToLower(os.Getenv(coreutils.CI)) == "true" {
return false
}
return !isAnyFlagSet(c, resolutionServerId, resolutionRepo, deploymentServerId, deploymentRepo)
}
func isAnyFlagSet(c *cli.Context, flagNames ...string) bool {
for _, flagName := range flagNames {
if c.IsSet(flagName) {
return true
}
}
return false
}
// Populate configuration from cli flags
func (configFile *ConfigFile) populateConfigFromFlags(c *cli.Context) {
configFile.Resolver.ServerId = c.String(resolutionServerId)
configFile.Resolver.Repo = c.String(resolutionRepo)
configFile.Deployer.ServerId = c.String(deploymentServerId)
configFile.Deployer.Repo = c.String(deploymentRepo)
configFile.Interactive = isInteractive(c)
}
// Populate Maven related configuration from cli flags
func (configFile *ConfigFile) populateMavenConfigFromFlags(c *cli.Context) {
configFile.Resolver.SnapshotRepo = c.String(resolutionSnapshotsRepo)
configFile.Resolver.ReleaseRepo = c.String(resolutionReleasesRepo)
configFile.Deployer.SnapshotRepo = c.String(deploymentSnapshotsRepo)
configFile.Deployer.ReleaseRepo = c.String(deploymentReleasesRepo)
configFile.Deployer.IncludePatterns = c.String(includePatterns)
configFile.Deployer.ExcludePatterns = c.String(excludePatterns)
configFile.Interactive = configFile.Interactive && !isAnyFlagSet(c, resolutionSnapshotsRepo, resolutionReleasesRepo,
deploymentSnapshotsRepo, deploymentReleasesRepo, includePatterns, excludePatterns)
}
// Populate Gradle related configuration from cli flags
func (configFile *ConfigFile) populateGradleConfigFromFlags(c *cli.Context) {
configFile.Deployer.DeployMavenDesc = c.BoolT(deployMavenDesc)
configFile.Deployer.DeployIvyDesc = c.BoolT(deployIvyDesc)
configFile.Deployer.IvyPattern = defaultIfNotSet(c, ivyDescPattern, "[organization]/[module]/ivy-[revision].xml")
configFile.Deployer.ArtifactsPattern = defaultIfNotSet(c, ivyArtifactsPattern, "[organization]/[module]/[revision]/[artifact]-[revision](-[classifier]).[ext]")
configFile.UsePlugin = c.Bool(usesPlugin)
configFile.UseWrapper = c.Bool(useWrapper)
configFile.Interactive = configFile.Interactive && !isAnyFlagSet(c, deployMavenDesc, deployIvyDesc, ivyDescPattern, ivyArtifactsPattern, usesPlugin, useWrapper)
}
// Populate NuGet related configuration from cli flags
func (configFile *ConfigFile) populateNugetConfigFromFlags(c *cli.Context) {
configFile.Resolver.NugetV2 = c.Bool(nugetV2)
configFile.Interactive = configFile.Interactive && !isAnyFlagSet(c, nugetV2)
}
// Verify config file doesn't exist or prompt to override it
func (configFile *ConfigFile) VerifyConfigFile(configFilePath string) error {
exists, err := fileutils.IsFileExists(configFilePath, false)
if err != nil {
return err
}
if exists {
if !configFile.Interactive {
return nil
}
override := coreutils.AskYesNo("Configuration file already exists at "+configFilePath+". Override it?", false)
if !override {
return errorutils.CheckErrorf("operation canceled")
}
return nil
}
// Create config file to make sure the path is valid
f, err := os.OpenFile(configFilePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if errorutils.CheckError(err) != nil {
return err
}
f.Close()
// The file will be written at the end of successful configuration command.
return errorutils.CheckError(os.Remove(configFilePath))
}
func (configFile *ConfigFile) configGo() error {
return configFile.setDeployerResolver()
}
func (configFile *ConfigFile) configPip() error {
return configFile.setResolver()
}
func (configFile *ConfigFile) configYarn() error {
return configFile.setResolver()
}
func (configFile *ConfigFile) configNpm() error {
return configFile.setDeployerResolver()
}
func (configFile *ConfigFile) configDotnet() error {
if err := configFile.setResolver(); err != nil {
return err
}
if configFile.Resolver.ServerId != "" {
configFile.setUseNugetV2()
}
return nil
}
func (configFile *ConfigFile) configMaven() error {
// Set resolution repositories
if err := configFile.setResolverId(); err != nil {
return err
}
if configFile.Resolver.ServerId != "" {
if err := configFile.setRepo(&configFile.Resolver.ReleaseRepo, "Set resolution repository for release dependencies", configFile.Resolver.ServerId, utils.REMOTE); err != nil {
return err
}
if err := configFile.setRepo(&configFile.Resolver.SnapshotRepo, "Set resolution repository for snapshot dependencies", configFile.Resolver.ServerId, utils.REMOTE); err != nil {
return err
}
}
// Set deployment repositories
if err := configFile.setDeployerId(); err != nil {
return err
}
if configFile.Deployer.ServerId != "" {
if err := configFile.setRepo(&configFile.Deployer.ReleaseRepo, "Set repository for release artifacts deployment", configFile.Deployer.ServerId, utils.LOCAL); err != nil {
return err
}
if err := configFile.setRepo(&configFile.Deployer.SnapshotRepo, "Set repository for snapshot artifacts deployment", configFile.Deployer.ServerId, utils.LOCAL); err != nil {
return err
}
configFile.setIncludeExcludePatterns()
}
return nil
}
func (configFile *ConfigFile) setIncludeExcludePatterns() {
if !coreutils.AskYesNo("Would you like to filter out some of the deployed artifacts?", false) {
return
}
fmt.Println("You may set multiple wildcard patterns, to match the artifacts' names you'd like to include and/or exclude from being deployed.")
includePatterns := getIncludeExcludePatterns("include")
if includePatterns != "" {
configFile.Deployer.IncludePatterns = includePatterns
}
excludePatterns := getIncludeExcludePatterns("exclude")
if excludePatterns != "" {
configFile.Deployer.ExcludePatterns = excludePatterns
}
}
func getIncludeExcludePatterns(patternType string) string {
var patterns []string
patternNum := 1
for {
newPattern := AskString("", strings.Title(patternType)+" pattern "+strconv.Itoa(patternNum)+" (leave empty to continue):", true, false)
if newPattern == "" {
return strings.Join(patterns, ", ")
}
patterns = append(patterns, newPattern)
patternNum++
}
}
func (configFile *ConfigFile) configGradle() error {
if err := configFile.setDeployerResolver(); err != nil {
return err
}
if configFile.Deployer.ServerId != "" {
configFile.setMavenIvyDescriptors()
}
configFile.readGradleGlobalConfig()
return nil
}
func (configFile *ConfigFile) readGradleGlobalConfig() {
configFile.UsePlugin = coreutils.AskYesNo("Is the Gradle Artifactory Plugin already applied in the build script?", false)
configFile.UseWrapper = coreutils.AskYesNo("Use Gradle wrapper?", false)
}
func (configFile *ConfigFile) setDeployer() error {
// Set deployer id
if err := configFile.setDeployerId(); err != nil {
return err
}
// Set deployment repository
if configFile.Deployer.ServerId != "" {
return configFile.setRepo(&configFile.Deployer.Repo, "Set repository for artifacts deployment", configFile.Deployer.ServerId, utils.LOCAL)
}
return nil
}
func (configFile *ConfigFile) setResolver() error {
// Set resolver id
if err := configFile.setResolverId(); err != nil {
return err
}
// Set resolution repository
if configFile.Resolver.ServerId != "" {
return configFile.setRepo(&configFile.Resolver.Repo, "Set repository for dependencies resolution", configFile.Resolver.ServerId, utils.REMOTE)
}
return nil
}
func (configFile *ConfigFile) setDeployerResolver() error {
if err := configFile.setResolver(); err != nil {
return err
}
return configFile.setDeployer()
}
func (configFile *ConfigFile) setResolverId() error {
return configFile.setServerId(&configFile.Resolver.ServerId, "Resolve dependencies from Artifactory?")
}
func (configFile *ConfigFile) setDeployerId() error {
return configFile.setServerId(&configFile.Deployer.ServerId, "Deploy project artifacts to Artifactory?")
}
func (configFile *ConfigFile) setServerId(serverId *string, useArtifactoryQuestion string) error {
var err error
*serverId, err = readArtifactoryServer(useArtifactoryQuestion)
return err
}
func (configFile *ConfigFile) setRepo(repo *string, message string, serverId string, repoType utils.RepoType) error {
var err error
if *repo == "" {
*repo, err = readRepo(message+PressTabMsg, serverId, repoType, utils.VIRTUAL)
}
return err
}
func (configFile *ConfigFile) setMavenIvyDescriptors() {
configFile.Deployer.DeployMavenDesc = coreutils.AskYesNo("Deploy Maven descriptors?", false)
configFile.Deployer.DeployIvyDesc = coreutils.AskYesNo("Deploy Ivy descriptors?", false)
if configFile.Deployer.DeployIvyDesc {
configFile.Deployer.IvyPattern = AskStringWithDefault("", "Set Ivy descriptor pattern", "[organization]/[module]/ivy-[revision].xml")
configFile.Deployer.ArtifactsPattern = AskStringWithDefault("", "Set Ivy artifact pattern", "[organization]/[module]/[revision]/[artifact]-[revision](-[classifier]).[ext]")
}
}
func (configFile *ConfigFile) setUseNugetV2() {
configFile.Resolver.NugetV2 = coreutils.AskYesNo("Use NuGet V2 Protocol?", false)
}
func validateRepositoryConfig(repository *utils.Repository, errorPrefix string) error {
releaseRepo := repository.ReleaseRepo
snapshotRepo := repository.SnapshotRepo
// For config commands - resolver/deployer server-id flags are optional.
// In case no server-id flag was provided we use the default configured server id.
defaultServerDetails, err := config.GetDefaultServerConf()
if err != nil {
return err
}
defaultServerId := ""
if defaultServerDetails != nil {
defaultServerId = defaultServerDetails.ServerId
}
// Server-id flag was not provided.
if repository.ServerId == "" {
// No default server was configured.
if defaultServerId == "" {
// Repositories flags were provided.
if repository.Repo != "" || releaseRepo != "" || snapshotRepo != "" {
return errorutils.CheckErrorf(errorPrefix + setServerIdError)
}
} else {
// Server-id flag wasn't provided and repositories flags were provided - the default configured global server will be chosen.
if repository.Repo != "" || releaseRepo != "" || snapshotRepo != "" {
repository.ServerId = defaultServerId
}
}
} else {
// Server-id flag was provided, but no repositories flags.
if repository.Repo == "" && releaseRepo == "" && snapshotRepo == "" {
return errorutils.CheckErrorf(errorPrefix + setRepositoryError)
}
}
// Release/snapshot repositories should be entangled to each other.
if (releaseRepo == "" && snapshotRepo != "") || (releaseRepo != "" && snapshotRepo == "") {
return errorutils.CheckErrorf(errorPrefix + setSnapshotAndReleaseError)
}
return nil
}
// Validate spec file configuration
func (configFile *ConfigFile) validateConfig() error {
err := validateRepositoryConfig(&configFile.Resolver, resolutionErrorPrefix)
if err != nil {
return err
}
return validateRepositoryConfig(&configFile.Deployer, deploymentErrorPrefix)
}
// Get Artifactory serverId from the user. If useArtifactoryQuestion is not empty, ask first whether to use artifactory.
func readArtifactoryServer(useArtifactoryQuestion string) (string, error) {
// Get all Artifactory servers
serversIds, defaultServer, err := getServersIdAndDefault()
if err != nil {
return "", err
}
if len(serversIds) == 0 {
return "", errorutils.CheckErrorf("No Artifactory servers configured. Use the 'jfrog c add' command to set the Artifactory server details.")
}
// Ask whether to use artifactory
if useArtifactoryQuestion != "" {
useArtifactory := coreutils.AskYesNo(useArtifactoryQuestion, true)
if !useArtifactory {
return "", nil
}
}
return AskFromList("", "Set Artifactory server ID", false, ConvertToSuggests(serversIds), defaultServer), nil
}
func readRepo(promptPrefix string, serverId string, repoTypes ...utils.RepoType) (string, error) {
availableRepos, err := getRepositories(serverId, repoTypes...)
if err != nil {
log.Error("failed getting repositories list: " + err.Error())
// Continue without auto complete.
availableRepos = []string{}
}
if len(availableRepos) > 0 {
return AskFromListWithMismatchConfirmation(promptPrefix, "Repository not found.", ConvertToSuggests(availableRepos)), nil
}
return AskString("", promptPrefix, false, false), nil
}
func getServersIdAndDefault() ([]string, string, error) {
allConfigs, err := config.GetAllServersConfigs()
if err != nil {
return nil, "", err
}
var defaultVal string
var serversId []string
for _, v := range allConfigs {
if v.IsDefault {
defaultVal = v.ServerId
}
serversId = append(serversId, v.ServerId)
}
return serversId, defaultVal, nil
}
func getRepositories(serverId string, repoTypes ...utils.RepoType) ([]string, error) {
artDetails, err := config.GetSpecificConfig(serverId, false, true)
if err != nil {
return nil, err
}
artAuth, err := artDetails.CreateArtAuthConfig()
if err != nil {
return nil, err
}
return utils.GetRepositories(artAuth, repoTypes...)
}
func defaultIfNotSet(c *cli.Context, flagName string, defaultValue string) string {
if c.IsSet(flagName) {
return c.String(flagName)
}
return defaultValue
}