github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/conf/env/env_vars.go (about) 1 package env 2 3 import ( 4 "bytes" 5 "log" 6 "sort" 7 "strconv" 8 "strings" 9 ) 10 11 type Vars struct { 12 Prefix string 13 Values map[string]*Var 14 } 15 16 func LoadVarsFromEnviron(prefix string, envs []string) *Vars { 17 vars := NewVars(prefix) 18 for _, kv := range envs { 19 pair := strings.SplitN(kv, "=", 2) 20 if len(pair) != 2 { 21 continue 22 } 23 if !strings.HasPrefix(pair[0], prefix) { 24 continue 25 } 26 log.Println("load env", pair[0], pair[1]) 27 vars.Set(&Var{ 28 Name: strings.Replace(pair[0], prefix+"__", "", 1), 29 Value: pair[1], 30 }) 31 } 32 return vars 33 } 34 35 func NewVars(prefix string) *Vars { return &Vars{Prefix: prefix} } 36 37 func (vs *Vars) Set(v *Var) { 38 if vs.Values == nil { 39 vs.Values = map[string]*Var{} 40 } 41 vs.Values[v.Name] = v 42 } 43 44 func (vs *Vars) SetWithKeyValue(k, v string) { 45 vs.Set(&Var{ 46 Name: strings.Replace(k, vs.Prefix+"__", "", 1), 47 Value: v, 48 }) 49 } 50 51 func (vs *Vars) Get(key string) *Var { 52 if vs.Values == nil { 53 return nil 54 } 55 return vs.Values[key] 56 } 57 58 func (vs *Vars) Bytes() []byte { 59 kv := make(map[string]string) 60 for _, v := range vs.Values { 61 kv[v.Key(vs.Prefix)] = v.Value 62 } 63 return Env(kv) 64 } 65 66 func (vs *Vars) MaskBytes() []byte { 67 kv := make(map[string]string) 68 for _, v := range vs.Values { 69 if v.Mask != "" { 70 kv[v.Key(vs.Prefix)] = v.Mask 71 continue 72 } 73 kv[v.Key(vs.Prefix)] = v.Value 74 } 75 return Env(kv) 76 } 77 78 func (vs *Vars) Len(key string) int { 79 max := int64(-1) 80 for _, v := range vs.Values { 81 if !strings.HasPrefix(v.Name, key) { 82 continue 83 } 84 names := strings.TrimLeft(v.Name, key+"_") 85 parts := strings.Split(names, "_") 86 if i, e := strconv.ParseInt(parts[0], 10, 64); e == nil && i > max { 87 max = i 88 } 89 } 90 return int(max + 1) 91 } 92 93 func Env(kv map[string]string) []byte { 94 buf := bytes.NewBuffer(nil) 95 96 ks := make([]string, 0) 97 for k := range kv { 98 ks = append(ks, k) 99 } 100 sort.Strings(ks) 101 102 for _, k := range ks { 103 buf.WriteString(k) 104 buf.WriteRune('=') 105 buf.WriteString(kv[k]) 106 buf.WriteRune('\n') 107 } 108 return buf.Bytes() 109 }