github.com/lmorg/murex@v0.0.0-20240217211045-e081c89cd4ef/lang/variables_module.go (about) 1 package lang 2 3 import ( 4 "fmt" 5 "sync" 6 ) 7 8 type ModuleVars struct { 9 mutex sync.Mutex 10 vars map[string]*Variables 11 } 12 13 func NewModuleVars() *ModuleVars { 14 mod := new(ModuleVars) 15 mod.vars = make(map[string]*Variables) 16 return mod 17 } 18 19 func (mod *ModuleVars) GetValues(p *Process) interface{} { 20 m := make(map[string]interface{}) 21 v := mod.v(p) 22 23 v.mutex.Lock() 24 for name, variable := range v.vars { 25 m[name] = variable.Value 26 } 27 v.mutex.Unlock() 28 29 return m 30 } 31 32 func (mod *ModuleVars) GetDataType(p *Process, name string) (dt string) { 33 v := mod.v(p) 34 35 v.mutex.Lock() 36 variable := v.vars[name] 37 if variable != nil { 38 dt = variable.DataType 39 } 40 v.mutex.Unlock() 41 return 42 } 43 44 func (mod *ModuleVars) Set(p *Process, value interface{}, changePath []string, dataType string) (err error) { 45 if len(changePath) == 0 { 46 return fmt.Errorf("invalid use of $%s. Expecting a module variable name, eg `$%s.example`", MODULE, MODULE) 47 } 48 49 switch t := value.(type) { 50 case map[string]interface{}: 51 return mod.set(p, changePath[0], t[changePath[0]], dataType) 52 53 default: 54 return fmt.Errorf("expecting a map of module variables. Instead got a %T", t) 55 } 56 } 57 58 func (mod *ModuleVars) set(p *Process, path string, value interface{}, dataType string) error { 59 return mod.v(p).Set(p, path, value, dataType) 60 } 61 62 func (mod *ModuleVars) v(p *Process) *Variables { 63 mod.mutex.Lock() 64 v, ok := mod.vars[p.FileRef.Source.Module] 65 if !ok { 66 v = NewVariables(p) 67 mod.vars[p.FileRef.Source.Module] = v 68 } 69 mod.mutex.Unlock() 70 71 return v 72 }