From 56a6ed0cf71ecf55f37e94b574c41927452abc44 Mon Sep 17 00:00:00 2001 From: Robin Jarry Date: Sat, 4 Mar 2023 01:12:23 +0100 Subject: templates: add match function Add a match function that returns true if a string matches the provided regular expression. The compiled regular expressions are cached in a sync.Map to avoid repetitive compilations of the same expressions. Caveat: if the user mixes the arguments order, it may cause the cache to consume a lot of memory filled with garbage regular expression objects. Ideally, we would need to limit the size of this cache and/or use a LRU cache implementation. Maybe someday? Signed-off-by: Robin Jarry Acked-by: Tim Culverhouse --- doc/aerc-templates.7.scd | 8 ++++++++ lib/parse/match.go | 30 ++++++++++++++++++++++++++++++ lib/templates/functions.go | 2 ++ 3 files changed, 40 insertions(+) create mode 100644 lib/parse/match.go diff --git a/doc/aerc-templates.7.scd b/doc/aerc-templates.7.scd index 7d77cd0b..401c04e7 100644 --- a/doc/aerc-templates.7.scd +++ b/doc/aerc-templates.7.scd @@ -384,6 +384,14 @@ aerc provides the following additional functions: X-Mailer: aerc {{version}} ``` +*match* + Check if a string matches a regular expression. This is intended for + use in conditional control flow: + + ``` + {{if match .Subject `^(\[[\w-]+\]\s*)?\[(RFC )?PATCH`}}{{.Style .Subject "cyan"}}{{else}}{{.Subject}}{{end}} + ``` + *Function chaining* All of the template functions can be chained together if needed. diff --git a/lib/parse/match.go b/lib/parse/match.go new file mode 100644 index 00000000..ac43673e --- /dev/null +++ b/lib/parse/match.go @@ -0,0 +1,30 @@ +package parse + +import ( + "regexp" + "sync" + + "git.sr.ht/~rjarry/aerc/log" +) + +var reCache sync.Map + +// Check if a string matches the specified regular expression. +// The regexp is compiled only once and stored in a cache for future use. +func MatchCache(s, expr string) bool { + var re interface{} + var found bool + + if re, found = reCache.Load(expr); !found { + var err error + re, err = regexp.Compile(expr) + if err != nil { + log.Errorf("`%s` invalid regexp: %s", expr, err) + } + reCache.Store(expr, re) + } + if re, ok := re.(*regexp.Regexp); ok && re != nil { + return re.MatchString(s) + } + return false +} diff --git a/lib/templates/functions.go b/lib/templates/functions.go index 1cbdc85d..8bd8f37b 100644 --- a/lib/templates/functions.go +++ b/lib/templates/functions.go @@ -11,6 +11,7 @@ import ( "time" "git.sr.ht/~rjarry/aerc/lib/format" + "git.sr.ht/~rjarry/aerc/lib/parse" "github.com/emersion/go-message/mail" ) @@ -271,4 +272,5 @@ var templateFuncs = template.FuncMap{ "join": join, "trimSignature": trimSignature, "compactDir": compactDir, + "match": parse.MatchCache, } -- cgit v1.2.3-54-g00ecf