github.com/swaros/contxt/module/taskrun@v0.0.0-20240305083542-3dbd4436ac40/vardata.go (about)

     1  // Copyright (c) 2020 Thomas Ziegler <thomas.zglr@googlemail.com>. All rights reserved.
     2  //
     3  // Licensed under the MIT License
     4  //
     5  //
     6  // Permission is hereby granted, free of charge, to any person obtaining a copy
     7  // of this software and associated documentation files (the "Software"), to deal
     8  // in the Software without restriction, including without limitation the rights
     9  // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    10  // copies of the Software, and to permit persons to whom the Software is
    11  // furnished to do so, subject to the following conditions:
    12  //
    13  // The above copyright notice and this permission notice shall be included in all
    14  // copies or substantial portions of the Software.
    15  //
    16  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    17  // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    18  // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    19  // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    20  // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    21  // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    22  // SOFTWARE.
    23  
    24  package taskrun
    25  
    26  import (
    27  	"encoding/json"
    28  	"errors"
    29  	"sync"
    30  
    31  	"github.com/sirupsen/logrus"
    32  	"github.com/swaros/contxt/module/yamc"
    33  	"gopkg.in/yaml.v3"
    34  
    35  	"github.com/tidwall/gjson"
    36  	"github.com/tidwall/sjson"
    37  )
    38  
    39  var dataStorage sync.Map
    40  
    41  // AddData adds a Data Map to the storage
    42  func AddData(key string, data map[string]interface{}) {
    43  	dataStorage.Store(key, data)
    44  }
    45  
    46  // ImportDataFromJSONFile imports a map from a json file and assign it to a key
    47  func ImportDataFromJSONFile(key string, filename string) error {
    48  	data, err := ImportJSONFile(filename)
    49  	if err != nil {
    50  		return err
    51  	}
    52  	GetLogger().WithFields(logrus.Fields{"key": key, "file": filename, "value": data}).Trace("variables import")
    53  	AddData(key, data)
    54  	return nil
    55  }
    56  
    57  // GetJSONPathValueString returns the value depending key and path as string
    58  func GetJSONPathValueString(key, path string) string {
    59  	ok, data := GetData(key)
    60  	if ok && data != nil {
    61  		jsonData, err := json.Marshal(data)
    62  		if err == nil {
    63  			value := gjson.Get(string(jsonData), path)
    64  			GetLogger().WithFields(logrus.Fields{"key": key, "path": path, "value": value}).Debug("placeholder: found map entrie")
    65  			return value.String()
    66  		}
    67  		GetLogger().WithField("key", key).Error("placeholder: error while marshal data")
    68  	} else {
    69  		GetLogger().WithField("key", key).Error("placeholder: error by getting data from named map")
    70  	}
    71  	return ""
    72  }
    73  
    74  func SetJSONValueByPath(key, path, value string) error {
    75  	ok, data := GetData(key)
    76  	if ok && data != nil {
    77  		jsonData, err := json.Marshal(data)
    78  		if err != nil {
    79  			return err
    80  		}
    81  		if newContent, err := sjson.Set(string(jsonData), path, value); err != nil {
    82  			return err
    83  		} else {
    84  			if err2 := AddJSON(key, newContent); err2 != nil {
    85  				return err2
    86  			}
    87  			return nil
    88  		}
    89  
    90  	}
    91  	return errors.New("error by getting data from " + key)
    92  
    93  }
    94  
    95  // GetJSONPathResult returns the value depending key and path as string
    96  func GetJSONPathResult(key, path string) (gjson.Result, bool) {
    97  	ok, data := GetData(key)
    98  	if ok && data != nil {
    99  		//mapdata := make(map[string]interface{})
   100  		jsonData, err := json.Marshal(data)
   101  		if err == nil {
   102  			value := gjson.Get(string(jsonData), path)
   103  			GetLogger().WithFields(logrus.Fields{
   104  				"key":   key,
   105  				"path":  path,
   106  				"value": value.Value()}).Debug("GetJSONPathResult: found map entrie")
   107  			return value, true
   108  		}
   109  		GetLogger().WithField("key", key).Error("GetJSONPathResult: error while marshal data")
   110  	} else {
   111  		GetLogger().WithField("key", key).Error("GetJSONPathResult: error by getting data from named map")
   112  	}
   113  	return gjson.Result{
   114  		Index: 0,
   115  	}, false
   116  }
   117  
   118  // ImportDataFromYAMLFile imports a map from a json file and assign it to a key
   119  func ImportDataFromYAMLFile(key string, filename string) error {
   120  	data, err := ImportYAMLFile(filename)
   121  	if err != nil {
   122  		return err
   123  	}
   124  
   125  	AddData(key, data)
   126  	return nil
   127  }
   128  
   129  // AddJSON imports data by a json String
   130  func AddJSON(key, jsonString string) error {
   131  	rdr := yamc.New()
   132  	if err := rdr.Parse(yamc.NewJsonReader(), []byte(jsonString)); err != nil {
   133  		return err
   134  	}
   135  	m := rdr.GetData()
   136  	AddData(key, m)
   137  	return nil
   138  }
   139  
   140  // GetData returns a data Map by the key.
   141  // or nil if nothing is stored
   142  func GetData(key string) (bool, map[string]interface{}) {
   143  	result, ok := dataStorage.Load(key)
   144  	if ok {
   145  		return ok, result.(map[string]interface{})
   146  	}
   147  	return false, nil
   148  }
   149  
   150  // GetDataAsYaml converts the map given by key infto a yaml string
   151  func GetDataAsYaml(key string) (bool, string) {
   152  	if found, data := GetData(key); found {
   153  		if outData, err := yaml.Marshal(data); err == nil {
   154  			return true, string(outData)
   155  		}
   156  	}
   157  	return false, ""
   158  }
   159  
   160  // GetDataAsJson converts the map given by key infto a yaml string
   161  func GetDataAsJson(key string) (bool, string) {
   162  	if found, data := GetData(key); found {
   163  		if outData, err := json.MarshalIndent(data, "", "  "); err == nil {
   164  			return true, string(outData)
   165  		}
   166  	}
   167  	return false, ""
   168  }
   169  
   170  // ClearAllData removes all entries
   171  func ClearAllData() {
   172  	dataStorage.Range(func(key, _ interface{}) bool {
   173  		dataStorage.Delete(key)
   174  		return true
   175  	})
   176  }
   177  
   178  // GetDataKeys returns all current keys
   179  func GetDataKeys() []string {
   180  	var keys []string
   181  	dataStorage.Range(func(key, _ interface{}) bool {
   182  		keys = append(keys, key.(string))
   183  		return true
   184  	})
   185  	return keys
   186  }