From b6d59045d02d387d8f537d1853a8f4ce91ff6d86 Mon Sep 17 00:00:00 2001 From: Knut Ahlers Date: Tue, 25 May 2021 16:26:03 +0200 Subject: [PATCH] Add global variables to be used in templates Signed-off-by: Knut Ahlers --- config.go | 13 +++++++------ msgformatter.go | 29 ++++++++++++++++++----------- 2 files changed, 25 insertions(+), 17 deletions(-) diff --git a/config.go b/config.go index 3ddb94e..55e970e 100644 --- a/config.go +++ b/config.go @@ -14,12 +14,13 @@ import ( ) type configFile struct { - AutoMessages []*autoMessage `yaml:"auto_messages"` - Channels []string `yaml:"channels"` - PermitAllowModerator bool `yaml:"permit_allow_moderator"` - PermitTimeout time.Duration `yaml:"permit_timeout"` - RawLog string `yaml:"raw_log"` - Rules []*rule `yaml:"rules"` + AutoMessages []*autoMessage `yaml:"auto_messages"` + Channels []string `yaml:"channels"` + PermitAllowModerator bool `yaml:"permit_allow_moderator"` + PermitTimeout time.Duration `yaml:"permit_timeout"` + RawLog string `yaml:"raw_log"` + Rules []*rule `yaml:"rules"` + Variables map[string]interface{} `yaml:"variables"` rawLogWriter io.WriteCloser } diff --git a/msgformatter.go b/msgformatter.go index 87df4d3..5059376 100644 --- a/msgformatter.go +++ b/msgformatter.go @@ -10,34 +10,41 @@ import ( ) func formatMessage(tplString string, m *irc.Message, r *rule, fields map[string]interface{}) (string, error) { - if fields == nil { - fields = map[string]interface{}{} + compiledFields := map[string]interface{}{} + + if config != nil { + configLock.RLock() + for k, v := range config.Variables { + compiledFields[k] = v + } + compiledFields["permitTimeout"] = int64(config.PermitTimeout / time.Second) + configLock.RUnlock() + } + + for k, v := range fields { + compiledFields[k] = v } if m != nil { - fields["msg"] = m - fields["username"] = m.User + compiledFields["msg"] = m + compiledFields["username"] = m.User if m.Command == "PRIVMSG" && len(m.Params) > 0 { - fields["channel"] = m.Params[0] + compiledFields["channel"] = m.Params[0] } } - if config != nil { - fields["permitTimeout"] = int64(config.PermitTimeout / time.Second) - } - // Parse and execute template tpl, err := template. New(tplString). - Funcs(tplFuncs.GetFuncMap(m, r, fields)). + Funcs(tplFuncs.GetFuncMap(m, r, compiledFields)). Parse(tplString) if err != nil { return "", errors.Wrap(err, "parse template") } buf := new(bytes.Buffer) - err = tpl.Execute(buf, fields) + err = tpl.Execute(buf, compiledFields) return buf.String(), errors.Wrap(err, "execute template") }