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