2022-12-01 21:38:49 +00:00
|
|
|
package interpolation
|
|
|
|
|
|
|
|
import (
|
2022-12-12 09:48:52 +00:00
|
|
|
"errors"
|
2022-12-01 21:38:49 +00:00
|
|
|
"fmt"
|
2023-08-15 13:50:40 +00:00
|
|
|
"slices"
|
2022-12-01 21:38:49 +00:00
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
// LookupFunction returns the value to rewrite a path expression to.
|
|
|
|
type LookupFunction func(path string, depends map[string]string) (string, error)
|
|
|
|
|
2022-12-12 09:48:52 +00:00
|
|
|
// ErrSkipInterpolation can be used to fall through from [LookupFunction].
|
|
|
|
var ErrSkipInterpolation = errors.New("skip interpolation")
|
|
|
|
|
2022-12-01 21:38:49 +00:00
|
|
|
// DefaultLookup looks up the specified path in the map.
|
|
|
|
// It returns an error if it doesn't exist.
|
|
|
|
func DefaultLookup(path string, lookup map[string]string) (string, error) {
|
|
|
|
v, ok := lookup[path]
|
|
|
|
if !ok {
|
|
|
|
return "", fmt.Errorf("expected to find value for path: %s", path)
|
|
|
|
}
|
|
|
|
return v, nil
|
|
|
|
}
|
|
|
|
|
2022-12-12 09:30:17 +00:00
|
|
|
func pathPrefixMatches(prefix []string, path string) bool {
|
|
|
|
parts := strings.Split(path, Delimiter)
|
|
|
|
return len(parts) >= len(prefix) && slices.Compare(prefix, parts[0:len(prefix)]) == 0
|
|
|
|
}
|
|
|
|
|
2022-12-01 21:38:49 +00:00
|
|
|
// ExcludeLookupsInPath is a lookup function that skips lookups for the specified path.
|
|
|
|
func ExcludeLookupsInPath(exclude ...string) LookupFunction {
|
|
|
|
return func(path string, lookup map[string]string) (string, error) {
|
2022-12-12 09:30:17 +00:00
|
|
|
if pathPrefixMatches(exclude, path) {
|
2022-12-12 09:48:52 +00:00
|
|
|
return "", ErrSkipInterpolation
|
2022-12-01 21:38:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return DefaultLookup(path, lookup)
|
|
|
|
}
|
|
|
|
}
|
2022-12-12 09:30:17 +00:00
|
|
|
|
|
|
|
// IncludeLookupsInPath is a lookup function that limits lookups to the specified path.
|
|
|
|
func IncludeLookupsInPath(include ...string) LookupFunction {
|
|
|
|
return func(path string, lookup map[string]string) (string, error) {
|
2022-12-12 09:48:52 +00:00
|
|
|
if !pathPrefixMatches(include, path) {
|
|
|
|
return "", ErrSkipInterpolation
|
2022-12-12 09:30:17 +00:00
|
|
|
}
|
|
|
|
|
2022-12-12 09:48:52 +00:00
|
|
|
return DefaultLookup(path, lookup)
|
2022-12-12 09:30:17 +00:00
|
|
|
}
|
|
|
|
}
|