Skip to content

Commit

Permalink
✨ feat(str/text): replacer support parse env variable
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Mar 18, 2023
1 parent a188557 commit 411ef1f
Showing 1 changed file with 27 additions and 6 deletions.
33 changes: 27 additions & 6 deletions strutil/textutil/var_replacer.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"regexp"
"strings"

"github.com/gookit/goutil/internal/comfunc"
"github.com/gookit/goutil/maputil"
"github.com/gookit/goutil/strutil"
)
Expand All @@ -16,14 +17,22 @@ type VarReplacer struct {
init bool
Left, Right string
lLen, rLen int
varReg *regexp.Regexp

parseEnv bool
varReg *regexp.Regexp
}

// NewVarReplacer instance
func NewVarReplacer(format string) *VarReplacer {
return (&VarReplacer{}).WithFormat(format)
}

// WithParseEnv custom var template
func (r *VarReplacer) WithParseEnv() *VarReplacer {
r.parseEnv = true
return r
}

// WithFormat custom var template
func (r *VarReplacer) WithFormat(format string) *VarReplacer {
r.Left, r.Right = strutil.QuietCut(strutil.OrElse(format, defaultVarFormat), ",")
Expand Down Expand Up @@ -55,25 +64,37 @@ func (r *VarReplacer) Replace(s string, tplVars map[string]any) string {

varMap := make(map[string]string, len(tplVars)*2)
maputil.FlatWithFunc(tplVars, func(path string, val reflect.Value) {
varMap[path] = strutil.QuietString(val.Interface())
if val.Kind() == reflect.String {
if r.parseEnv {
varMap[path] = comfunc.ParseEnvVar(val.String(), nil)
} else {
varMap[path] = val.String()
}
} else {
varMap[path] = strutil.QuietString(val.Interface())
}
})

return r.Init().doReplace(s, varMap)
}

// ReplaceSMap string-map vars in the text contents
func (r *VarReplacer) ReplaceSMap(s string, varMap map[string]string) string {
if len(varMap) == 0 || !strings.Contains(s, r.Left) {
return s
}
return r.Init().doReplace(s, varMap)
return r.RenderSimple(s, varMap)
}

// RenderSimple string-map vars in the text contents. alias of ReplaceSMap()
func (r *VarReplacer) RenderSimple(s string, varMap map[string]string) string {
if len(varMap) == 0 || !strings.Contains(s, r.Left) {
return s
}

if r.parseEnv {
for name, val := range varMap {
varMap[name] = comfunc.ParseEnvVar(val, nil)
}
}

return r.Init().doReplace(s, varMap)
}

Expand Down

0 comments on commit 411ef1f

Please sign in to comment.