github.com/jfrog/jfrog-cli-core/v2@v2.51.0/artifactory/commands/utils/templateutils.go (about) 1 package utils 2 3 import ( 4 "encoding/json" 5 "os" 6 "strings" 7 8 "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" 9 "github.com/jfrog/jfrog-cli-core/v2/utils/ioutils" 10 "github.com/jfrog/jfrog-client-go/utils/io/fileutils" 11 12 "github.com/jfrog/jfrog-client-go/utils/errorutils" 13 ) 14 15 const pathErrorSuffixMsg = " please enter a path, in which the new template file will be created" 16 17 type TemplateUserCommand interface { 18 // Returns the file path. 19 TemplatePath() string 20 // Returns vars to replace in the template content. 21 Vars() string 22 } 23 24 func ConvertTemplateToMap(tuc TemplateUserCommand) (map[string]interface{}, error) { 25 // Read the template file 26 content, err := fileutils.ReadFile(tuc.TemplatePath()) 27 if errorutils.CheckError(err) != nil { 28 return nil, err 29 } 30 // Replace vars string-by-string if needed 31 if len(tuc.Vars()) > 0 { 32 templateVars := coreutils.SpecVarsStringToMap(tuc.Vars()) 33 content = coreutils.ReplaceVars(content, templateVars) 34 } 35 // Unmarshal template to a map 36 var configMap map[string]interface{} 37 err = json.Unmarshal(content, &configMap) 38 return configMap, errorutils.CheckError(err) 39 } 40 41 func ValidateMapEntry(key string, value interface{}, writersMap map[string]ioutils.AnswerWriter) error { 42 if _, ok := writersMap[key]; !ok { 43 return errorutils.CheckErrorf("template syntax error: unknown key: \"" + key + "\".") 44 } 45 if _, ok := value.(string); !ok { 46 return errorutils.CheckErrorf("template syntax error: the value for the key: \"" + key + "\" is not a string type.") 47 } 48 return nil 49 } 50 51 func ValidateTemplatePath(templatePath string) error { 52 exists, err := fileutils.IsDirExists(templatePath, false) 53 if err != nil { 54 return errorutils.CheckError(err) 55 } 56 if exists || strings.HasSuffix(templatePath, string(os.PathSeparator)) { 57 return errorutils.CheckErrorf("path cannot be a directory," + pathErrorSuffixMsg) 58 } 59 exists, err = fileutils.IsFileExists(templatePath, false) 60 if err != nil { 61 return errorutils.CheckError(err) 62 } 63 if exists { 64 return errorutils.CheckErrorf("file already exists," + pathErrorSuffixMsg) 65 } 66 return nil 67 }