github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/pkg/cloudfoundry/Vars.go (about) 1 package cloudfoundry 2 3 import ( 4 "fmt" 5 "github.com/SAP/jenkins-library/pkg/piperutils" 6 "regexp" 7 ) 8 9 // VarsFilesNotFoundError ... 10 type VarsFilesNotFoundError struct { 11 Message string 12 MissingFiles []string 13 } 14 15 func (e *VarsFilesNotFoundError) Error() string { 16 return fmt.Sprintf("%s: %v", e.Message, e.MissingFiles) 17 } 18 19 var _fileUtils piperutils.FileUtils = piperutils.Files{} 20 21 // GetVarsFileOptions Returns a string array containing valid var file options, 22 // e.g.: --vars myVars.yml 23 // The options array contains all vars files which could be resolved in the file system. 24 // In case some vars files cannot be found, the missing files are reported 25 // via the error which is in this case a VarsFilesNotFoundError. In that case the options 26 // array contains nevertheless the options for all existing files. 27 func GetVarsFileOptions(varsFiles []string) ([]string, error) { 28 varsFilesOpts := []string{} 29 notFound := []string{} 30 var err error 31 for _, varsFile := range varsFiles { 32 varsFileExists, err := _fileUtils.FileExists(varsFile) 33 if err != nil { 34 return nil, fmt.Errorf("Error accessing file system: %w", err) 35 } 36 if varsFileExists { 37 varsFilesOpts = append(varsFilesOpts, "--vars-file", varsFile) 38 } else { 39 notFound = append(notFound, varsFile) 40 } 41 } 42 if len(notFound) > 0 { 43 err = &VarsFilesNotFoundError{ 44 Message: "Some vars files could not be found", 45 MissingFiles: notFound, 46 } 47 } 48 return varsFilesOpts, err 49 } 50 51 // GetVarsOptions Returns the vars as valid var option string slice 52 // InvalidVars are reported via error. 53 func GetVarsOptions(vars []string) ([]string, error) { 54 invalidVars := []string{} 55 varOptions := []string{} 56 var err error 57 for _, v := range vars { 58 valid, e := validateVar(v) 59 if e != nil { 60 return []string{}, fmt.Errorf("Cannot validate var '%s': %w", v, e) 61 } 62 if !valid { 63 invalidVars = append(invalidVars, v) 64 continue 65 } 66 varOptions = append(varOptions, "--var", v) 67 } 68 69 if len(invalidVars) > 0 { 70 return []string{}, fmt.Errorf("Invalid vars: %v", invalidVars) 71 } 72 return varOptions, err 73 } 74 75 func validateVar(v string) (bool, error) { 76 return regexp.MatchString(`\S{1,}=\S{1,}`, v) 77 }