2017-04-19 16:03:53 +00:00
|
|
|
package influx
|
|
|
|
|
2017-04-19 16:18:23 +00:00
|
|
|
import (
|
|
|
|
"strings"
|
2017-04-19 16:03:53 +00:00
|
|
|
|
2017-04-19 16:18:23 +00:00
|
|
|
"github.com/influxdata/chronograf"
|
|
|
|
)
|
2017-04-19 16:03:53 +00:00
|
|
|
|
|
|
|
// TemplateReplace replaces templates with values within the query string
|
2017-06-06 22:26:08 +00:00
|
|
|
func TemplateReplace(query string, templates chronograf.TemplateVars) string {
|
2017-06-13 18:42:52 +00:00
|
|
|
tvarsByPrecedence := make(map[uint]chronograf.TemplateVars, len(templates))
|
|
|
|
maxPrecedence := uint(0)
|
|
|
|
for _, tmp := range templates {
|
|
|
|
precedence := tmp.Precedence()
|
|
|
|
if precedence > maxPrecedence {
|
|
|
|
maxPrecedence = precedence
|
2017-06-08 15:31:35 +00:00
|
|
|
}
|
2017-06-13 18:42:52 +00:00
|
|
|
tvarsByPrecedence[precedence] = append(tvarsByPrecedence[precedence], tmp)
|
|
|
|
}
|
|
|
|
|
|
|
|
replaced := query
|
|
|
|
for prc := uint(0); prc <= maxPrecedence; prc++ {
|
|
|
|
replacements := []string{}
|
|
|
|
|
|
|
|
for _, v := range tvarsByPrecedence[prc] {
|
|
|
|
if evar, ok := v.(chronograf.ExecutableVar); ok {
|
|
|
|
evar.Exec(replaced)
|
|
|
|
}
|
|
|
|
newVal := v.String()
|
|
|
|
if newVal != "" {
|
|
|
|
replacements = append(replacements, v.Name(), newVal)
|
|
|
|
}
|
2017-04-19 16:03:53 +00:00
|
|
|
}
|
2017-06-13 18:42:52 +00:00
|
|
|
|
|
|
|
replacer := strings.NewReplacer(replacements...)
|
|
|
|
replaced = replacer.Replace(replaced)
|
2017-04-19 16:03:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return replaced
|
|
|
|
}
|