functions

package
v0.9.18 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 18, 2024 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var CategoriesDefault = Categories{
	"codecs":        CategoryCodecs,
	"conversations": CategoryConversations,
	"general":       CategoryGeneral,
	"kubernetes":    CategoryKubernetes,
	"ids":           CategoryIds,
	"math":          CategoryMath,
	"path":          CategoryPath,
	"regexp":        CategoryRegexp,
	"serialization": CategorySerialization,
	"strings":       CategoryStrings,
	"templating":    CategoryTemplating,
}
View Source
var CategoryCodecs = Category{
	Functions: FuncsCodecs,
}
View Source
var CategoryConversations = Category{
	Functions: FuncsConversations,
}
View Source
var CategoryGeneral = Category{
	Functions: FuncsGeneral,
}
View Source
var CategoryIds = Category{
	Functions: FuncsIds,
}
View Source
var CategoryKubernetes = Category{
	Functions: FuncsKubernetes,
}
View Source
var CategoryMath = Category{
	Functions: FuncsMath,
}
View Source
var CategoryPath = Category{
	Functions: FuncsPath,
}
View Source
var CategoryRegexp = Category{
	Functions: FuncsRegexp,
}
View Source
var CategorySerialization = Category{
	Functions: FuncsSerialization,
}
View Source
var CategoryStrings = Category{
	Functions: FuncsStrings,
}
View Source
var CategoryTemplating = Category{
	Functions: FuncsTemplating,
}
View Source
var FuncAbbrev = Function{
	Description: `Abbreviates a string using ellipses. This will turn  the string "Now is the time for all good men" into "Now is the time for..."`,
	Parameters: Parameters{{
		Name:        "width",
		Description: "Maximum length of result string, must be at least 4",
	}, {
		Name: "in",
	}},
}.MustWithFunc(func(width int, in string) (string, error) {
	if width < 4 {
		return in, nil
	}
	return goutils.Abbreviate(in, width)
})
View Source
var FuncAbbrevFull = Function{
	Description: `AbbreviateFull abbreviates a string using ellipses. This will turn the string "Now is the time for all good men" into "...is the time for..."
This function works like Abbreviate(string, int), but allows you to specify a "left edge" offset. Note that this left edge is not
necessarily going to be the leftmost character in the result, or the first character following the ellipses, but it will appear
somewhere in the result.
In no case will it return a string of length greater than maxWidth.`,
	Parameters: Parameters{{
		Name:        "offset",
		Description: "Left edge of source string",
	}, {
		Name:        "width",
		Description: "Maximum length of result string, must be at least 4",
	}, {
		Name: "in",
	}},
}.MustWithFunc(func(offset, width int, in string) (string, error) {
	if width < 4 || offset > 0 && width < 7 {
		return in, nil
	}
	return goutils.AbbreviateFull(in, offset, width)
})
View Source
var FuncCamelCase = Function{
	Description: `Convert all lower case characters behind underscores to upper case character.`,
	Parameters: Parameters{{
		Name: "in",
	}},
}.MustWithFunc(xstrings.ToCamelCase)
View Source
var FuncCapitalize = Function{
	Description: `Capitalize capitalizes all the delimiter separated words in a string. Only the first letter of each word is changed.
To convert the rest of each word to lowercase at the same time, use CapitalizeFully(str string, delimiters ...rune).
The delimiters represent a set of characters understood to separate words. The first string character
and the first non-delimiter character after a delimiter will be capitalized. A "" input string returns "".
Capitalization uses the Unicode title case, normally equivalent to upper case.`,
	Parameters: Parameters{{
		Name: "in",
	}},
}.MustWithFunc(func(in string) string {
	return goutils.Capitalize(in)
})
View Source
var FuncCat = Function{
	Description: `Concatenates multiple strings together into one, separating them with spaces.`,
	Parameters: Parameters{{
		Name: "in",
	}},
}.MustWithFunc(func(v ...interface{}) string {
	r := strings.TrimSpace(strings.Repeat("%v ", len(v)))
	return fmt.Sprintf(r, v...)
})
View Source
var FuncCeilInt = Function{
	Description: "Returns the least int value greater than or equal to <in>.",
	Parameters: Parameters{{
		Name: "in",
	}},
}.MustWithFunc(ceilInt)
View Source
var FuncCeilInt64 = Function{
	Description: "Returns the least int64 value greater than or equal to <in>.",
	Parameters: Parameters{{
		Name: "in",
	}},
}.MustWithFunc(ceilInt64)
View Source
var FuncContains = Function{
	Description: `Checks if the given <input> contains the given <search> element. If the input is a string this will reflect a part of the string, if slice an element of the slice, if map/object a key of the map/object.`,
	Parameters: Parameters{{
		Name: "search",
	}, {
		Name: "input",
	}},
}.MustWithFunc(func(search interface{}, input interface{}) (bool, error) {
	v := reflect.ValueOf(input)
	if v.Kind() == reflect.Ptr && v.IsNil() {
		return false, nil
	}
	for v.Kind() == reflect.Ptr {
		v = v.Elem()
	}
	for v.Kind() == reflect.Interface {
		v = v.Elem()
	}
	t := v.Type()
	switch v.Kind() {
	case reflect.String:
		return strings.Contains(v.String(), fmt.Sprint(search)), nil
	case reflect.Struct:
		key := fmt.Sprint(search)
		_, ok := t.FieldByName(key)
		return ok, nil
	case reflect.Map:
		key := reflect.ValueOf(search)
		value := v.MapIndex(key)
		return value.IsValid(), nil
	case reflect.Slice, reflect.Array:
		for i := 0; i < v.Len(); i++ {
			candidate := v.Index(i)
			if candidate.IsValid() && reflect.DeepEqual(candidate.Interface(), search) {
				return true, nil
			}
		}
		return false, nil
	default:
		return false, fmt.Errorf("currently contains only supports either strings, maps, structs, arrays or slices but got: %v", reflect.TypeOf(input))
	}
})
View Source
var FuncDecodeBase64 = Function{
	Description: "Decodes base64 encoded string from given <source>.",
	Parameters: Parameters{{
		Name: "source",
	}},
	Returns: Return{
		Description: "String which was decoded from <source>.",
	},
}.MustWithFunc(func(source string) (string, error) {
	b, err := base64.StdEncoding.DecodeString(source)
	return string(b), err
})
View Source
var FuncDecodeBase64Advanced = Function{
	Description: "Decodes base64 encoded string from given <source>.",
	Parameters: Parameters{{
		Name:        "type",
		Description: "Can be either 'url' or 'standard'.",
	}, {
		Name:        "raw",
		Description: "If true raw base64 is assumed.",
	}, {
		Name: "source",
	}},
	Returns: Return{
		Description: "String which was decoded from <source>.",
	},
}.MustWithFunc(func(aType string, raw bool, source string) (string, error) {
	enc, err := base64EncodingFor(aType, raw)
	if err != nil {
		return "", err
	}
	b, err := enc.DecodeString(source)
	return string(b), err
})
View Source
var FuncDecodeHex = Function{
	Description: "Decodes hex encoded string from given <source>.",
	Parameters: Parameters{{
		Name: "source",
	}},
	Returns: Return{
		Description: "String which was decoded from <source>.",
	},
}.MustWithFunc(func(source string) (string, error) {
	b, err := hex.DecodeString(source)
	return string(b), err
})
View Source
var FuncDecodeJson = Function{
	Description: "Decodes JSON from given <source>.",
	Parameters: Parameters{{
		Name: "source",
	}},
	Returns: Return{
		Description: "Object which was decoded from <source>.",
	},
}.MustWithFunc(func(context template.ExecutionContext, source string) (interface{}, error) {
	reader := strings.NewReader(source)
	var result interface{}
	if err := json.NewDecoder(reader).Decode(&result); err != nil {
		return nil, fmt.Errorf("cannot decode json referenced in '%s': %w", context.GetTemplate().GetSource(), err)
	} else {
		return result, nil
	}
})
View Source
var FuncDecodeJsonFromFile = Function{
	Description: "Decodes JSON from given <file>.",
	Parameters: Parameters{{
		Name: "file",
	}},
	Returns: Return{
		Description: "Object which was decoded from <file>.",
	},
}.MustWithFunc(func(context template.ExecutionContext, file string) (interface{}, error) {
	if resolved, err := resolvePathOfContext(context, file); err != nil {
		return nil, err
	} else if f, err := os.Open(resolved); os.IsNotExist(err) {
		return nil, fmt.Errorf("file '%s' referenced in '%s' does not exist", resolved, context.GetTemplate().GetSource())
	} else {

		defer f.Close()
		var result interface{}
		if err := json.NewDecoder(f).Decode(&result); err != nil {
			return nil, fmt.Errorf("cannot decode yaml from '%s' referenced in '%s': %w", resolved, context.GetTemplate().GetSource(), err)
		} else {
			return result, nil
		}
	}
})
View Source
var FuncDecodeYaml = Function{
	Description: "Decodes YAML from given <source>.",
	Parameters: Parameters{{
		Name: "source",
	}},
	Returns: Return{
		Description: "Object which was decoded from <source>.",
	},
}.MustWithFunc(func(context template.ExecutionContext, source string) (interface{}, error) {
	reader := strings.NewReader(source)
	var result interface{}
	if err := yaml.NewDecoder(reader).Decode(&result); err != nil {
		return nil, fmt.Errorf("cannot decode yaml referenced in '%s': %w", context.GetTemplate().GetSource(), err)
	} else {
		return result, nil
	}
})
View Source
var FuncDecodeYamlFromFile = Function{
	Description: "Decodes YAML from given <file>.",
	Parameters: Parameters{{
		Name: "file",
	}},
	Returns: Return{
		Description: "Object which was decoded from <file>.",
	},
}.MustWithFunc(func(context template.ExecutionContext, file string) (interface{}, error) {
	if resolved, err := resolvePathOfContext(context, file); err != nil {
		return nil, err
	} else if f, err := os.Open(resolved); os.IsNotExist(err) {
		return nil, fmt.Errorf("file '%s' referenced in '%s' does not exist", resolved, context.GetTemplate().GetSource())
	} else {

		defer f.Close()
		var result interface{}
		if err := yaml.NewDecoder(f).Decode(&result); err != nil {
			return nil, fmt.Errorf("cannot decode yaml from '%s' referenced in '%s': %w", resolved, context.GetTemplate().GetSource(), err)
		} else {
			return result, nil
		}
	}
})
View Source
var FuncDefault = Function{
	Description: "If <given> is empty it will return <defaultValue>.",
	Parameters: Parameters{{
		Name: "defaultValue",
	}, {
		Name: "given",
	}},
}.MustWithFunc(func(defaultValue interface{}, given interface{}) interface{} {
	if empty(given) {
		return defaultValue
	}
	return given
})
View Source
var FuncEmpty = Function{
	Description: "Checks the given <argument> if it is empty or not.",
	Parameters: Parameters{{
		Name: "argument",
	}},
}.MustWithFunc(empty)
View Source
var FuncEncodeBase64 = Function{
	Description: "Encodes the given <source> as base64 encoded string",
	Parameters: Parameters{{
		Name: "source",
	}},
	Returns: Return{
		Description: "String which was encoded from <source>.",
	},
}.MustWithFunc(func(source string) (string, error) {
	return base64.StdEncoding.EncodeToString([]byte(source)), nil
})
View Source
var FuncEncodeBase64Advanced = Function{
	Description: "Encodes the given <source> as base64 encoded string.",
	Parameters: Parameters{{
		Name:        "type",
		Description: "Can be either 'url' or 'standard'.",
	}, {
		Name:        "raw",
		Description: "If true raw base64 is assumed.",
	}, {
		Name: "source",
	}},
	Returns: Return{
		Description: "String which was encoded from <source>.",
	},
}.MustWithFunc(func(aType string, raw bool, source string) (string, error) {
	enc, err := base64EncodingFor(aType, raw)
	if err != nil {
		return "", err
	}
	return enc.EncodeToString([]byte(source)), nil
})
View Source
var FuncEncodeHex = Function{
	Description: "Encodes the given <source> as hex encoded string",
	Parameters: Parameters{{
		Name: "source",
	}},
	Returns: Return{
		Description: "String which was encoded from <source>.",
	},
}.MustWithFunc(func(source string) (string, error) {
	return hex.EncodeToString([]byte(source)), nil
})
View Source
var FuncFileSize = Function{
	Parameters: Parameters{{
		Name: "path",
	}},
	Returns: Return{
		Description: "The size of the provided <path>. It will fail with an error if the specified file does not exist or is not a file.",
	},
}.MustWithFunc(func(context template.ExecutionContext, path string) (int64, error) {
	if fi, err := statOfContext(context, path); err != nil {
		return 0, err
	} else {
		return fi.Size(), nil
	}
})
View Source
var FuncFloorInt = Function{
	Description: "Returns the greatest int value less than or equal to <in>.",
	Parameters: Parameters{{
		Name: "in",
	}},
}.MustWithFunc(floorInt)
View Source
var FuncFloorInt64 = Function{
	Description: "Returns the greatest int64 value less than or equal to <in>.",
	Parameters: Parameters{{
		Name: "in",
	}},
}.MustWithFunc(floorInt64)
View Source
var FuncHasPrefix = Function{
	Description: `Test whether a string has a given prefix.`,
	Parameters: Parameters{{
		Name: "toSearchFor",
	}, {
		Name: "in",
	}},
}.MustWithFunc(func(toSearchFor string, in string) bool {
	return strings.HasPrefix(in, toSearchFor)
})
View Source
var FuncHasSuffix = Function{
	Description: `Test whether a string has a given suffix.`,
	Parameters: Parameters{{
		Name: "toSearchFor",
	}, {
		Name: "in",
	}},
}.MustWithFunc(func(toSearchFor string, in string) bool {
	return strings.HasSuffix(in, toSearchFor)
})
View Source
var FuncInclude = Function{
	Description: "Takes the given <file> and renders the contained template using <data> as regular Golang template.",
	Parameters: Parameters{{
		Name:        "file",
		Description: "The actual template file which should be rendered using the provided <data>.",
	}, {
		Name:        "data",
		Description: "The data that could be accessed while the rendering the content of the template of the provided <file>.",
	}},
	Returns: Return{
		Description: "The rendered content.",
	},
}.MustWithFunc(func(context template.ExecutionContext, file string, data interface{}) (string, error) {
	if resolved, err := resolvePathOfContext(context, file); err != nil {
		return "", err
	} else if tmpl, err := context.GetFactory().NewFromFile(resolved); err != nil {
		return "", fmt.Errorf("%s: cannot create parse template: %w", resolved, err)
	} else if result, err := tmpl.ExecuteToString(data); err != nil {
		return "", fmt.Errorf("%s: cannot evaluate parse template: %w", tmpl.GetSource(), err)
	} else {
		return result, nil
	}
})
View Source
var FuncIndent = Function{
	Description: `Indents every line in a given string to the specified indent width. This is useful when aligning multi-line strings.`,
	Parameters: Parameters{{
		Name: "indent",
	}, {
		Name: "str",
	}},
}.MustWithFunc(func(indent int, str string) string {
	pad := strings.Repeat(" ", indent)
	return pad + strings.Replace(str, "\n", "\n"+pad, -1)
})
View Source
var FuncInitials = Function{
	Description: "Given multiple words, take the first letter of each word and combine.",
	Parameters: Parameters{{
		Name: "in",
	}},
}.MustWithFunc(func(in string) string {
	return goutils.Initials(in)
})
View Source
var FuncIsDir = Function{
	Parameters: Parameters{{
		Name: "path",
	}},
	Returns: Return{
		Description: "<true> if provided <path> does exist and is a directory.",
	},
}.MustWithFunc(func(context template.ExecutionContext, path string) (bool, error) {
	return statCheckOfContext(context, path, func(fi os.FileInfo) bool {
		return fi.IsDir()
	})
})
View Source
var FuncIsDouble = Function{
	Description: "Will return <true> if the given string <str> is a valid float64.",
	Parameters: Parameters{{
		Name: "str",
	}},
}.MustWithFunc(isFloat)
View Source
var FuncIsFile = Function{
	Parameters: Parameters{{
		Name: "path",
	}},
	Returns: Return{
		Description: "<true> if provided <path> does exist and is a file.",
	},
}.MustWithFunc(func(context template.ExecutionContext, path string) (bool, error) {
	return statCheckOfContext(context, path, func(fi os.FileInfo) bool {
		return !fi.IsDir()
	})
})
View Source
var FuncIsFloat = Function{
	Description: "Will return <true> if the given string <str> is a valid float.",
	Parameters: Parameters{{
		Name: "str",
	}},
}.MustWithFunc(isFloat)
View Source
var FuncIsInt = Function{
	Description: "Will return <true> if the given string <str> is a valid int.",
	Parameters: Parameters{{
		Name: "str",
	}},
}.MustWithFunc(isInt)
View Source
var FuncIsInt64 = Function{
	Description: "Will return <true> if the given string <str> is a valid int64.",
	Parameters: Parameters{{
		Name: "str",
	}},
}.MustWithFunc(isInt)
View Source
var FuncIsNotEmpty = Function{
	Description: "Checks the given <argument> if it is not empty.",
	Parameters: Parameters{{
		Name: "argument",
	}},
}.MustWithFunc(func(given interface{}) bool {
	return !empty(given)
})
View Source
var FuncKebabCase = Function{
	Description: `Convert all upper case characters in a string to kebab case format.`,
	Parameters: Parameters{{
		Name: "in",
	}},
}.MustWithFunc(xstrings.ToKebabCase)
View Source
var FuncLower = Function{
	Parameters: Parameters{{
		Name: "in",
	}},
	Returns: Return{
		Description: `A copy of the string s with all Unicode letters mapped to their lower case.`,
	},
}.MustWithFunc(strings.ToLower)
View Source
var FuncMap = Function{
	Description: `Creates from the given key to value pair a new map.`,
	Parameters: Parameters{{
		Name: "input",
	}},
}.MustWithFunc(func(in ...interface{}) (map[interface{}]interface{}, error) {
	if len(in)%2 != 0 {
		return nil, fmt.Errorf("expect always a key to value pair, this means the amount of parameters needs to be dividable by two, but got: %d", len(in))
	}
	result := make(map[interface{}]interface{}, len(in)/2)
	for i := 0; i < len(in); i += 2 {
		key, value := in[i], in[i+1]
		result[key] = value
	}
	return result, nil
})
View Source
var FuncMaxDouble = Function{
	Description: "Will pick the biggest float64 of the <left> and <right>.",
	Parameters: Parameters{{
		Name: "left",
	}, {
		Name: "right",
	}},
}.MustWithFunc(maxFloat64)
View Source
var FuncMaxFloat = Function{
	Description: "Will pick the biggest float of the <left> and <right>.",
	Parameters: Parameters{{
		Name: "left",
	}, {
		Name: "right",
	}},
}.MustWithFunc(maxFloat32)
View Source
var FuncMaxInt = Function{
	Description: "Will pick the biggest int of the <left> and <right>.",
	Parameters: Parameters{{
		Name: "left",
	}, {
		Name: "right",
	}},
}.MustWithFunc(maxInt)
View Source
var FuncMaxInt64 = Function{
	Description: "Will pick the biggest int64 of the <left> and <right>.",
	Parameters: Parameters{{
		Name: "left",
	}, {
		Name: "right",
	}},
}.MustWithFunc(maxInt64)
View Source
var FuncMinDouble = Function{
	Description: "Will pick the smallest float64 of the <left> and <right>.",
	Parameters: Parameters{{
		Name: "left",
	}, {
		Name: "right",
	}},
}.MustWithFunc(minFloat64)
View Source
var FuncMinFloat = Function{
	Description: "Will pick the smallest float of the <left> and <right>.",
	Parameters: Parameters{{
		Name: "left",
	}, {
		Name: "right",
	}},
}.MustWithFunc(minFloat32)
View Source
var FuncMinInt = Function{
	Description: "Will pick the smallest int of the <left> and <right>.",
	Parameters: Parameters{{
		Name: "left",
	}, {
		Name: "right",
	}},
}.MustWithFunc(minInt)
View Source
var FuncMinInt64 = Function{
	Description: "Will pick the smallest int64 of the <left> and <right>.",
	Parameters: Parameters{{
		Name: "left",
	}, {
		Name: "right",
	}},
}.MustWithFunc(minInt64)
View Source
var FuncNormalizeLabelValue = Function{
	Description: "Takes the given string and normalize it to fit into a kubernetes label value.",
	Parameters: Parameters{{
		Name: "source",
	}},
	Returns: Return{
		Description: "Normalized string of <source>.",
	},
}.MustWithFunc(func(source string) string {
	return support.NormalizeLabelValue(source)
})
View Source
var FuncOptional = Function{
	Description: "Asks the given <holder> if a property of given <name> exists and returns it. Otherwise the result is <nil>.",
	Parameters: Parameters{{
		Name: "name",
	}, {
		Name: "holder",
	}},
}.MustWithFunc(func(name string, holder interface{}) (interface{}, error) {
	v := reflect.ValueOf(holder)
	for v.Kind() == reflect.Ptr {
		v = v.Elem()
	}
	if v.IsNil() {
		return nil, nil
	}
	for v.Kind() == reflect.Interface {
		v = v.Elem()
	}
	t := v.Type()
	switch v.Kind() {
	case reflect.Struct:
		if field, ok := t.FieldByName(name); ok {
			fieldValue := v.FieldByIndex(field.Index)
			return fieldValue.Interface(), nil
		}
		return nil, nil
	case reflect.Map:
		value := v.MapIndex(reflect.ValueOf(name))
		if !value.IsValid() {
			return nil, nil
		}
		return value.Interface(), nil
	}
	return nil, fmt.Errorf("cannot get value for '%s' because cannot handle values of type %v", name, t)
})
View Source
var FuncParseDouble = Function{
	Description: "Interprets a given string <str> as a float64 and returns the result. If this is not a valid number it will fail.",
	Parameters: Parameters{{
		Name: "str",
	}},
}.MustWithFunc(parseFloat64)
View Source
var FuncParseFloat = Function{
	Description: "Interprets a given string <str> as a float and returns the result. If this is not a valid number it will fail.",
	Parameters: Parameters{{
		Name: "str",
	}},
}.MustWithFunc(parseFloat32)
View Source
var FuncParseInt = Function{
	Description: "Interprets a given string <str> as an int and returns the result. If this is not a valid number it will fail.",
	Parameters: Parameters{{
		Name: "str",
	}},
}.MustWithFunc(parseInt)
View Source
var FuncParseInt64 = Function{
	Description: "Interprets a given string <str> as a int64 and returns the result. If this is not a valid number it will fail.",
	Parameters: Parameters{{
		Name: "str",
	}},
}.MustWithFunc(parseInt64)
View Source
var FuncPathBase = Function{
	Parameters: Parameters{{
		Name: "path",
	}},
	Returns: Return{
		Description: "The last element of path.",
	},
}.MustWithFunc(func(p string) string {
	return path.Base(p)
})
View Source
var FuncPathClean = Function{
	Parameters: Parameters{{
		Name: "path",
	}},
	Returns: Return{
		Description: "Shortest path name equivalent to path by purely lexical processing.",
	},
}.MustWithFunc(func(p string) string {
	return path.Clean(p)
})
View Source
var FuncPathDir = Function{
	Parameters: Parameters{{
		Name: "path",
	}},
	Returns: Return{
		Description: "All but the last element of path, typically the path's directory.",
	},
}.MustWithFunc(func(p string) string {
	return path.Dir(p)
})
View Source
var FuncPathExists = Function{
	Parameters: Parameters{{
		Name: "path",
	}},
	Returns: Return{
		Description: "Is <true> if provided <path> does exist.",
	},
}.MustWithFunc(func(context template.ExecutionContext, path string) (bool, error) {
	return statCheckOfContext(context, path, nil)
})
View Source
var FuncPathExt = Function{
	Parameters: Parameters{{
		Name: "path",
	}},
	Returns: Return{
		Description: "The file extension.",
	},
}.MustWithFunc(func(p string) string {
	return path.Ext(p)
})
View Source
var FuncQuote = Function{
	Description: `Wrap a string in float64 quotes.`,
	Parameters: Parameters{{
		Name: "in",
	}},
}.MustWithFunc(func(str ...interface{}) string {
	out := make([]string, len(str))
	for i, s := range str {
		out[i] = fmt.Sprintf("%q", strval(s))
	}
	return strings.Join(out, " ")
})
View Source
var FuncRandAlpha = Function{
	Description: "These four functions generate random strings, but with different base character sets of [A-Za-z].",
	Parameters: Parameters{{
		Name: "count",
	}},
}.MustWithFunc(func(count int) (string, error) {
	return goutils.RandomAlphabetic(count)
})
View Source
var FuncRandAlphaNum = Function{
	Description: "These four functions generate random strings, but with different base character sets of [0-9A-Za-z].",
	Parameters: Parameters{{
		Name: "count",
	}},
}.MustWithFunc(func(count int) (string, error) {
	return goutils.RandomAlphaNumeric(count)
})
View Source
var FuncRandNum = Function{
	Description: "These four functions generate random strings, but with different base character sets of [0-9].",
	Parameters: Parameters{{
		Name: "count",
	}},
}.MustWithFunc(func(count int) (string, error) {
	return goutils.RandomNumeric(count)
})
View Source
var FuncReadFile = Function{
	Parameters: Parameters{{
		Name: "file",
	}},
	Returns: Return{
		Description: "The content of the provided <file>.",
	},
}.MustWithFunc(func(context template.ExecutionContext, file string) (string, error) {
	if resolved, err := resolvePathOfContext(context, file); err != nil {
		return "", fmt.Errorf("cannot resolve path of '%s': %w", file, err)
	} else if b, err := os.ReadFile(resolved); err != nil {
		return "", fmt.Errorf("cannot read path '%s' (source:%s ): %w", resolved, file, err)
	} else {
		return string(b), nil
	}
})
View Source
var FuncRegexpFind = Function{
	Description: `Returns the first match of the regular expression <pattern> in the input string.
See https://golang.org/pkg/regexp/ for more details.`,
	Parameters: Parameters{{
		Name: "pattern",
	}, {
		Name: "str",
	}},
}.MustWithFunc(func(pattern string, str string) (string, error) {
	if r, err := regexp.Compile(pattern); err != nil {
		return "", err
	} else {
		return r.FindString(str), nil
	}
})
View Source
var FuncRegexpFindAll = Function{
	Description: `Returns an array of all matches of the regular expression <pattern> in the input string.
See https://golang.org/pkg/regexp/ for more details.`,
	Parameters: Parameters{{
		Name: "pattern",
	}, {
		Name:        "n",
		Description: "Limits the maximum number of matches that should be returned. If smaller then <0> it will be unlimited.",
	}, {
		Name: "str",
	}},
}.MustWithFunc(func(pattern string, n int, str string) ([]string, error) {
	if r, err := regexp.Compile(pattern); err != nil {
		return []string{}, err
	} else {
		return r.FindAllString(str, n), nil
	}
})
View Source
var FuncRegexpMatch = Function{
	Description: `Reports whether the string <str> contains any match of the regular expression <pattern>.
See https://golang.org/pkg/regexp/ for more details.`,
	Parameters: Parameters{{
		Name: "pattern",
	}, {
		Name: "str",
	}},
}.MustWithFunc(func(pattern string, str string) (bool, error) {
	return regexp.MatchString(pattern, str)
})
View Source
var FuncRegexpReplaceAll = Function{
	Description: `Returns copy of src, replacing matches of the Regexp with the replacement string repl.
Inside repl, $ signs are interpreted as in Expand, so for instance $1 represents the text of the first submatch.
See https://golang.org/pkg/regexp/ for more details.`,
	Parameters: Parameters{{
		Name: "pattern",
	}, {
		Name: "replacement",
	}, {
		Name: "str",
	}},
}.MustWithFunc(func(pattern string, replacement string, str string) (string, error) {
	if r, err := regexp.Compile(pattern); err != nil {
		return "", err
	} else {
		return r.ReplaceAllString(str, replacement), nil
	}
})
View Source
var FuncRegexpSplit = Function{
	Description: `Splits into substrings separated by the expression and returns a slice of the substrings between those expression matches.
See https://golang.org/pkg/regexp/ for more details.`,
	Parameters: Parameters{{
		Name: "pattern",
	}, {
		Name:        "n",
		Description: "Limits the maximum number of parts that should be returned. If smaller then <0> it will be unlimited.",
	}, {
		Name: "str",
	}},
}.MustWithFunc(func(pattern string, n int, str string) ([]string, error) {
	if r, err := regexp.Compile(pattern); err != nil {
		return []string{}, err
	} else {
		return r.Split(str, n), nil
	}
})
View Source
var FuncRender = Function{
	Description: "Renders the <template> using <data> as regular Golang template.",
	Parameters: Parameters{{
		Name:        "data",
		Description: "The data that could be accessed while the rendering the content of the provided <template>.",
	}, {
		Name:        "template",
		Description: "The actual template which should be rendered using the provided <data>.",
	}},
	Returns: Return{
		Description: "The rendered content.",
	},
}.MustWithFunc(func(context template.ExecutionContext, data interface{}, template string) (string, error) {
	contextTmpl := context.GetTemplate()
	if tmpl, err := context.GetFactory().New(contextTmpl.GetSourceName(), template); err != nil {
		return "", fmt.Errorf("%s: cannot create parse template: %w", contextTmpl.GetSource(), err)
	} else if result, err := tmpl.ExecuteToString(data); err != nil {
		return "", fmt.Errorf("%s: cannot evaluate parse template: %w", tmpl.GetSource(), err)
	} else {
		return result, nil
	}
})
View Source
var FuncRepeat = Function{
	Description: "Repeat a string multiple times.",
	Parameters: Parameters{{
		Name: "count",
	}, {
		Name: "in",
	}},
}.MustWithFunc(func(count int, in string) string {
	return strings.Repeat(in, count)
})
View Source
var FuncReplace = Function{
	Description: "Replaces the given <old> string with the <new> string.",
	Parameters: Parameters{{
		Name: "old",
	}, {
		Name: "new",
	}, {
		Name: "in",
	}},
}.MustWithFunc(func(old string, n string, in string) string {
	return strings.Replace(in, old, n, -1)
})
View Source
var FuncRoundDouble = Function{
	Description: "Will round the given input to a float64.",
	Parameters: Parameters{{
		Name:        "precision",
		Description: "Defines how many decimal positions should remain.",
	}, {
		Name: "in",
	}},
}.MustWithFunc(func(precision int, in interface{}) float64 {
	return roundFloat64(in, precision)
})
View Source
var FuncRoundFloat = Function{
	Description: "Will round the given input to a float.",
	Parameters: Parameters{{
		Name:        "precision",
		Description: "Defines how many decimal positions should remain.",
	}, {
		Name: "in",
	}},
}.MustWithFunc(func(precision int, in interface{}) float32 {
	return roundFloat32(in, precision)
})
View Source
var FuncRoundInt = Function{
	Description: "Will round the given input to an int.",
	Parameters: Parameters{{
		Name: "in",
	}},
}.MustWithFunc(roundInt)
View Source
var FuncRoundInt64 = Function{
	Description: "Will round the given input to a int64.",
	Parameters: Parameters{{
		Name: "in",
	}},
}.MustWithFunc(roundInt64)
View Source
var FuncSQuote = Function{
	Description: `Wrap a string in single quotes.`,
	Parameters: Parameters{{
		Name: "in",
	}},
}.MustWithFunc(func(str ...interface{}) string {
	out := make([]string, len(str))
	for i, s := range str {
		out[i] = fmt.Sprintf("'%v'", s)
	}
	return strings.Join(out, " ")
})
View Source
var FuncShuffle = Function{
	Description: `Shuffle randomizes runes in a string and returns the result.`,
	Parameters: Parameters{{
		Name: "in",
	}},
}.MustWithFunc(xstrings.Shuffle)
View Source
var FuncSlice = Function{
	Description: `Creates from the given values a new slice.`,
	Parameters: Parameters{{
		Name: "input",
	}},
}.MustWithFunc(func(in ...interface{}) ([]interface{}, error) {
	return in, nil
})
View Source
var FuncSnakeCase = Function{
	Description: `convert all upper case characters in a string to snake case format.`,
	Parameters: Parameters{{
		Name: "in",
	}},
}.MustWithFunc(xstrings.ToSnakeCase)
View Source
var FuncSourceFile = Function{
	Returns: Return{
		Description: "The filename which is the source of this rendered template if any.",
	},
}.MustWithFunc(func(context template.ExecutionContext) *string {
	return context.GetTemplate().GetSourceFile()
})
View Source
var FuncSourceName = Function{
	Returns: Return{
		Description: "The name this rendered template. Could be a short name or a filename.",
	},
}.MustWithFunc(func(context template.ExecutionContext) string {
	return context.GetTemplate().GetSourceName()
})
View Source
var FuncSubstr = Function{
	Description: "Get a substring from a string.",
	Parameters: Parameters{{
		Name: "start",
	}, {
		Name: "length",
	}, {
		Name: "in",
	}},
}.MustWithFunc(func(start int, length int, in string) string {
	if start < 0 {
		return in[:length]
	}
	if length < 0 {
		return in[start:]
	}
	return in[start:length]
})
View Source
var FuncToBool = Function{
	Description: "Will try to interpret the given <value> as a bool. If this is not possible <false> is returned.",
	Parameters: Parameters{{
		Name: "value",
	}},
}.MustWithFunc(toBool)
View Source
var FuncToDouble = Function{
	Description: "Will try to interpret the given <value> as a float64. If this is not possible <0.0> is returned.",
	Parameters: Parameters{{
		Name: "value",
	}},
}.MustWithFunc(toFloat64)
View Source
var FuncToFloat = Function{
	Description: "Will try to interpret the given <value> as a float. If this is not possible <0.0> is returned.",
	Parameters: Parameters{{
		Name: "value",
	}},
}.MustWithFunc(toFloat32)
View Source
var FuncToInt = Function{
	Description: "Will try to interpret the given <value> as an int. If this is not possible <0> is returned.",
	Parameters: Parameters{{
		Name: "value",
	}},
}.MustWithFunc(toInt)
View Source
var FuncToInt64 = Function{
	Description: "Will try to interpret the given <value> as a int64. If this is not possible <0> is returned.",
	Parameters: Parameters{{
		Name: "value",
	}},
}.MustWithFunc(toInt64)
View Source
var FuncToString = Function{
	Description: `Converts the given argument to a string.`,
	Parameters: Parameters{{
		Name: "in",
	}},
}.MustWithFunc(func(in ...interface{}) string {
	return fmt.Sprint(in)
})
View Source
var FuncTrim = Function{
	Description: "Removes space from either side of a string",
	Parameters: Parameters{{
		Name: "in",
	}},
}.MustWithFunc(strings.TrimSpace)
View Source
var FuncTrimAll = Function{
	Description: "Remove given characters from the front or back of a string.",
	Parameters: Parameters{{
		Name: "toRemove",
	}, {
		Name: "in",
	}},
}.MustWithFunc(func(toRemove string, in string) string {
	return strings.Trim(in, toRemove)
})
View Source
var FuncTrimSuffix = Function{
	Description: "Remove given characters from the back of a string.",
	Parameters: Parameters{{
		Name: "toRemove",
	}, {
		Name: "in",
	}},
}.MustWithFunc(func(toRemove string, in string) string {
	return strings.TrimSuffix(in, toRemove)
})
View Source
var FuncTrunc = Function{
	Description: "Truncate a string (and add no suffix).",
	Parameters: Parameters{{
		Name: "length",
	}, {
		Name: "in",
	}},
}.MustWithFunc(func(length int, in string) string {
	if len(in) <= length {
		return in
	}
	return in[0:length]
})
View Source
var FuncUncapitalize = Function{
	Description: `Uncapitalize uncapitalizes all the whitespace separated words in a string. Only the first letter of each word is changed.
The delimiters represent a set of characters understood to separate words. The first string character and the first non-delimiter
character after a delimiter will be uncapitalized. Whitespace is defined by unicode.IsSpace(char).`,
	Parameters: Parameters{{
		Name: "in",
	}},
}.MustWithFunc(func(in string) string {
	return goutils.Uncapitalize(in)
})
View Source
var FuncUntil = Function{
	Description: "Will return an array of numbers of <0> to <count-1>.",
	Parameters: Parameters{{
		Name: "count",
	}},
}.MustWithFunc(until)
View Source
var FuncUntilStep = Function{
	Description: "Will return an array of numbers of <start> to <stop> with the given <step> size.",
	Parameters: Parameters{{
		Name: "start",
	}, {
		Name: "stop",
	}, {
		Name: "step",
	}},
}.MustWithFunc(untilStep)
View Source
var FuncUpper = Function{
	Parameters: Parameters{{
		Name: "in",
	}},
	Returns: Return{
		Description: `A copy of the string s with all Unicode letters mapped to their upper case.`,
	},
}.MustWithFunc(strings.ToUpper)
View Source
var FuncUuid = Function{
	Description: "Creates a new, random UUID",
}.MustWithFunc(func() uuid.UUID {
	return uuid.New()
})
View Source
var FuncWarp = Function{
	Description: `Wrap wraps a single line of text, identifying words by ' '.
New lines will be separated by '\n'. Very int64 words, such as URLs will not be wrapped.
Leading spaces on a new line are stripped. Trailing spaces are not stripped.`,
	Parameters: Parameters{{
		Name: "length",
	}, {
		Name: "in",
	}},
}.MustWithFunc(func(length int, in string) string {
	return goutils.Wrap(in, length)
})
View Source
var FuncWarpCustom = Function{
	Description: `WrapCustom wraps a single line of text, identifying words by ' '.
Leading spaces on a new line are stripped. Trailing spaces are not stripped.`,
	Parameters: Parameters{{
		Name: "length",
	}, {
		Name: "newLine",
	}, {
		Name: "wrapInt64Words",
	}, {
		Name: "in",
	}},
}.MustWithFunc(func(length int, newLine string, wrapInt64Words bool, in string) string {
	return goutils.WrapCustom(in, length, newLine, wrapInt64Words)
})
View Source
var FuncsCodecs = Functions{
	"decodeBase64":    FuncDecodeBase64,
	"decodeBase64Adv": FuncDecodeBase64Advanced,
	"encodeBase64":    FuncEncodeBase64,
	"encodeBase64Adv": FuncEncodeBase64Advanced,
	"decodeHex":       FuncDecodeHex,
	"encodeHex":       FuncEncodeHex,
}
View Source
var FuncsConversations = Functions{
	"toString":     FuncToString,
	"parseInt":     FuncParseInt,
	"parseInt64":   FuncParseInt64,
	"parseFloat32": FuncParseFloat,
	"parseFloat64": FuncParseDouble,
	"isInt":        FuncIsInt,
	"isInt64":      FuncIsInt64,
	"isFloat32":    FuncIsFloat,
	"isFloat64":    FuncIsDouble,
	"toInt":        FuncToInt,
	"toInt64":      FuncToInt64,
	"toFloat32":    FuncToFloat,
	"toFloat64":    FuncToDouble,
	"toBool":       FuncToBool,
}
View Source
var FuncsGeneral = Functions{
	"optional":   FuncOptional,
	"empty":      FuncEmpty,
	"isNotEmpty": FuncIsNotEmpty,
	"default":    FuncDefault,
	"contains":   FuncContains,
	"map":        FuncMap,
	"slice":      FuncSlice,
	"array":      FuncSlice,
}
View Source
var FuncsIds = Functions{
	"uuid": FuncUuid,
}
View Source
var FuncsKubernetes = Functions{
	"normalizeLabelValue": FuncNormalizeLabelValue,
}
View Source
var FuncsMath = Functions{
	"roundFloat64": FuncRoundDouble,
	"roundFloat32": FuncRoundFloat,
	"roundInt64":   FuncRoundInt64,
	"roundInt":     FuncRoundInt,
	"untilStep":    FuncUntilStep,
	"ceilInt64":    FuncCeilInt64,
	"ceilInt":      FuncCeilInt,
	"floorInt64":   FuncFloorInt64,
	"minInt":       FuncMinInt,
	"minInt64":     FuncMinInt64,
	"maxInt":       FuncMaxInt,
	"maxInt64":     FuncMaxInt64,
	"minFloat32":   FuncMinFloat,
	"minFloat64":   FuncMinDouble,
	"maxFloat32":   FuncMaxFloat,
	"maxFloat64":   FuncMaxDouble,
	"floorInt":     FuncFloorInt,
	"until":        FuncUntil,
}
View Source
var FuncsPath = Functions{
	"readFile":   FuncReadFile,
	"fileSize":   FuncFileSize,
	"pathExists": FuncPathExists,
	"isFile":     FuncIsFile,
	"isDir":      FuncIsDir,
	"pathExt":    FuncPathExt,
	"pathBase":   FuncPathBase,
	"pathDir":    FuncPathDir,
	"pathClean":  FuncPathClean,
}
View Source
var FuncsRegexp = Functions{
	"regexpMatch":      FuncRegexpMatch,
	"regexpFindAll":    FuncRegexpFindAll,
	"regexpFind":       FuncRegexpFind,
	"regexpReplaceAll": FuncRegexpReplaceAll,
	"regexpSplit":      FuncRegexpSplit,
}
View Source
var FuncsSerialization = Functions{
	"decodeYaml":         FuncDecodeYaml,
	"decodeJson":         FuncDecodeJson,
	"decodeYamlFromFile": FuncDecodeYamlFromFile,
	"decodeJsonFromFile": FuncDecodeJsonFromFile,
}
View Source
var FuncsStrings = Functions{
	"abbrev":       FuncAbbrev,
	"abbrevFull":   FuncAbbrevFull,
	"upper":        FuncUpper,
	"lower":        FuncLower,
	"trim":         FuncTrim,
	"trimAll":      FuncTrimAll,
	"trimSuffix":   FuncTrimSuffix,
	"capitalize":   FuncCapitalize,
	"uncapitalize": FuncUncapitalize,
	"replace":      FuncReplace,
	"repeat":       FuncRepeat,
	"substr":       FuncSubstr,
	"trunc":        FuncTrunc,
	"initials":     FuncInitials,
	"randAlphaNum": FuncRandAlphaNum,
	"randAlpha":    FuncRandAlpha,
	"randNum":      FuncRandNum,
	"warp":         FuncWarp,
	"warpCustom":   FuncWarpCustom,
	"hasPrefix":    FuncHasPrefix,
	"hasSuffix":    FuncHasSuffix,
	"quote":        FuncQuote,
	"sQuote":       FuncSQuote,
	"cat":          FuncCat,
	"indent":       FuncIndent,
	"snakeCase":    FuncSnakeCase,
	"camelCase":    FuncCamelCase,
	"kebabCase":    FuncKebabCase,
	"shuffle":      FuncShuffle,
}
View Source
var FuncsTemplating = Functions{
	"render":     FuncRender,
	"include":    FuncInclude,
	"sourceFile": FuncSourceFile,
	"sourceName": FuncSourceName,
}

Functions

func DefaultTemplateFactory

func DefaultTemplateFactory() template.Factory

func NormalizeType

func NormalizeType(t reflect.Type) string

Types

type Categories

type Categories map[string]Category

func (Categories) FilterBy

func (instance Categories) FilterBy(predicate FunctionPredicate) (Categories, error)

func (Categories) GetFunctions

func (instance Categories) GetFunctions() (template.Functions, error)

func (Categories) With

func (instance Categories) With(categoryName string, category Category) Categories

func (Categories) WithFunction

func (instance Categories) WithFunction(categoryName string, functionName string, function Function) Categories

func (Categories) Without

func (instance Categories) Without(categoryName string) Categories

func (Categories) WithoutFunction

func (instance Categories) WithoutFunction(functionName string) Categories

type Category

type Category struct {
	Functions Functions
}

func (Category) FilterBy

func (instance Category) FilterBy(predicate FunctionPredicate) (Category, error)

func (Category) GetFunctions

func (instance Category) GetFunctions() (template.Functions, error)

func (Category) With

func (instance Category) With(functionName string, function Function) Category

func (Category) Without

func (instance Category) Without(functionName string) Category

type Function

type Function struct {
	Description string     `yaml:"description,omitempty" json:"description,omitempty"`
	Parameters  Parameters `yaml:"parameters,omitempty" json:"parameters,omitempty"`
	Returns     Return     `yaml:"returns" json:"returns"`
	// contains filtered or unexported fields
}

func (Function) Execute

func (instance Function) Execute(context template.ExecutionContext, args ...interface{}) (interface{}, error)

func (Function) GetDescription

func (instance Function) GetDescription() string

func (Function) GetParameters

func (instance Function) GetParameters() Parameters

func (Function) GetReturns

func (instance Function) GetReturns() Return

func (Function) MatchesFulltextSearch

func (instance Function) MatchesFulltextSearch(term *regexp.Regexp) bool

func (Function) MustWithFunc

func (instance Function) MustWithFunc(f interface{}) Function

func (Function) String

func (instance Function) String() string

func (Function) WithFunc

func (instance Function) WithFunc(f interface{}) (result Function, err error)

type FunctionPredicate

type FunctionPredicate func(candidate Function) (bool, error)

type Functions

type Functions map[string]Function

func (Functions) FilterBy

func (instance Functions) FilterBy(predicate FunctionPredicate) (Functions, error)

func (Functions) GetFunctions

func (instance Functions) GetFunctions() (template.Functions, error)

func (Functions) With

func (instance Functions) With(functionName string, function Function) Functions

func (Functions) Without

func (instance Functions) Without(functionName string) Functions

type Parameter

type Parameter struct {
	Name        string `yaml:"name" json:"name"`
	Type        string `yaml:"type" json:"type"`
	Description string `yaml:"description,omitempty" json:"description,omitempty"`
	VarArg      bool   `yaml:"varArg,omitempty" json:"varArg,omitempty"`
}

func (Parameter) GetDescription

func (instance Parameter) GetDescription() string

func (Parameter) GetName

func (instance Parameter) GetName() string

func (Parameter) GetType

func (instance Parameter) GetType() string

func (Parameter) IsVarArg

func (instance Parameter) IsVarArg() bool

func (Parameter) MatchesFulltextSearch

func (instance Parameter) MatchesFulltextSearch(term *regexp.Regexp) bool

func (Parameter) String

func (instance Parameter) String() string

type Parameters

type Parameters []Parameter

func (Parameters) MatchesFulltextSearch

func (instance Parameters) MatchesFulltextSearch(term *regexp.Regexp) bool

func (Parameters) String

func (instance Parameters) String() string

type Return

type Return struct {
	Type        string `yaml:"type" json:"type"`
	Description string `yaml:"description,omitempty" json:"description,omitempty"`
}

func (Return) GetDescription

func (instance Return) GetDescription() string

func (Return) GetType

func (instance Return) GetType() string

func (Return) MatchesFulltextSearch

func (instance Return) MatchesFulltextSearch(term *regexp.Regexp) bool

func (Return) String

func (instance Return) String() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL