File: interpolate.go

package info (click to toggle)
golang-github-alecthomas-kong 0.2.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 620 kB
  • sloc: makefile: 2
file content (30 lines) | stat: -rw-r--r-- 710 bytes parent folder | download
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
package kong

import (
	"fmt"
	"regexp"
)

var interpolationRegex = regexp.MustCompile(`((?:\${([[:alpha:]_][[:word:]]*))(?:=([^}]+))?})|(\$)|([^$]+)`)

// Interpolate variables from vars into s for substrings in the form ${var} or ${var=default}.
func interpolate(s string, vars map[string]string) (string, error) {
	out := ""
	matches := interpolationRegex.FindAllStringSubmatch(s, -1)
	for _, match := range matches {
		if name := match[2]; name != "" {
			value, ok := vars[name]
			if !ok {
				// No default value.
				if match[3] == "" {
					return "", fmt.Errorf("undefined variable ${%s}", name)
				}
				value = match[3]
			}
			out += value
		} else {
			out += match[0]
		}
	}
	return out, nil
}