File: placeholder.go

package info (click to toggle)
pat 0.19.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,228 kB
  • sloc: javascript: 3,864; sh: 147; makefile: 11
file content (41 lines) | stat: -rw-r--r-- 1,458 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package forms

import (
	"regexp"

	"github.com/la5nta/pat/internal/debug"
)

// placeholderReplacer returns a function that performs a case-insensitive search and replace.
// The placeholders are expected to be encapsulated with prefix and suffix.
// Any whitespace between prefix/suffix and key is ignored.
func placeholderReplacer(prefix, suffix string, fields map[string]string) func(string) string {
	const (
		space               = `\s*`
		caseInsensitiveFlag = `(?i)`
	)
	// compileRegexp compiles a case insensitive regular expression matching the given key.
	prefix, suffix = regexp.QuoteMeta(prefix)+space, space+regexp.QuoteMeta(suffix)
	compileRegexp := func(key string) *regexp.Regexp {
		return regexp.MustCompile(caseInsensitiveFlag + prefix + regexp.QuoteMeta(key) + suffix)
	}
	// Build a map from regexp to replacement values for all tags.
	regexps := make(map[*regexp.Regexp]string, len(fields))
	for key, newValue := range fields {
		regexps[compileRegexp(key)] = newValue
	}
	// Return a function for applying the replacements.
	return func(str string) string {
		for re, newValue := range regexps {
			str = re.ReplaceAllLiteralString(str, newValue)
		}
		if debug.Enabled() {
			// Log remaining insertion tags
			re := caseInsensitiveFlag + prefix + `[\w_-]+` + suffix
			if matches := regexp.MustCompile(re).FindAllString(str, -1); len(matches) > 0 {
				debug.Printf("Unhandled placeholder: %v", matches)
			}
		}
		return str
	}
}