github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/pkg/piperenv/environment.go (about) 1 package piperenv 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "os" 7 "path/filepath" 8 "strings" 9 10 "github.com/SAP/jenkins-library/pkg/log" 11 "github.com/pkg/errors" 12 ) 13 14 // This file contains functions used to read/write pipeline environment data from/to disk. 15 // The content of a written file is the value. For the custom parameters this could for example also be a JSON representation of a more complex value. 16 17 // SetResourceParameter sets a resource parameter in the environment stored in the file system 18 func SetResourceParameter(path, resourceName, paramName string, value interface{}) error { 19 var content []byte 20 paramPath := filepath.Join(path, resourceName, paramName) 21 switch typedValue := value.(type) { 22 case string: 23 content = []byte(typedValue) 24 default: 25 var err error 26 paramPath += ".json" 27 content, err = json.Marshal(typedValue) 28 if err != nil { 29 return errors.Wrapf(err, "failed to marshal resource parameter value %v", typedValue) 30 } 31 } 32 return writeToDisk(paramPath, content) 33 } 34 35 // GetResourceParameter reads a resource parameter from the environment stored in the file system 36 func GetResourceParameter(path, resourceName, paramName string) string { 37 //TODO: align JSON un/marshalling, currently done in pkg/config/stepmeta.go#getParameterValue 38 39 paramPath := filepath.Join(path, resourceName, paramName) 40 return readFromDisk(paramPath) 41 } 42 43 // SetParameter sets any parameter in the pipeline environment or another environment stored in the file system 44 func SetParameter(path, name, value string) error { 45 paramPath := filepath.Join(path, name) 46 return writeToDisk(paramPath, []byte(value)) 47 } 48 49 // GetParameter reads any parameter from the pipeline environment or another environment stored in the file system 50 func GetParameter(path, name string) string { 51 paramPath := filepath.Join(path, name) 52 return readFromDisk(paramPath) 53 } 54 55 func writeToDisk(filename string, data []byte) error { 56 57 if _, err := os.Stat(filepath.Dir(filename)); os.IsNotExist(err) { 58 log.Entry().Debugf("Creating directory: %v", filepath.Dir(filename)) 59 cErr := os.MkdirAll(filepath.Dir(filename), 0777) 60 if cErr != nil { 61 return fmt.Errorf("failed to create directory %v, %w", filepath.Dir(filename), cErr) 62 } 63 } 64 65 //ToDo: make sure to not overwrite file but rather add another file? Create error if already existing? 66 if len(data) > 0 { 67 log.Entry().Debugf("Writing file to disk: %v", filename) 68 return os.WriteFile(filename, data, 0766) 69 } 70 return nil 71 } 72 73 func readFromDisk(filename string) string { 74 //ToDo: if multiple files exist, read from latest file 75 log.Entry().Debugf("Reading file from disk: %v", filename) 76 v, err := os.ReadFile(filename) 77 val := string(v) 78 if err != nil { 79 val = "" 80 } 81 return strings.TrimSpace(val) 82 }