funcs

package
v0.11.4 Latest Latest
Warning

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

Go to latest
Published: Aug 9, 2023 License: MPL-2.0 Imports: 30 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var AbsPathFunc = function.New(&function.Spec{
	Params: []function.Parameter{
		{
			Name: "path",
			Type: cty.String,
		},
	},
	Type: function.StaticReturnType(cty.String),
	Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
		absPath, err := filepath.Abs(args[0].AsString())
		return cty.StringVal(filepath.ToSlash(absPath)), err
	},
})

AbsPathFunc constructs a function that converts a filesystem path to an absolute path

View Source
var Base64DecodeFunc = function.New(&function.Spec{
	Params: []function.Parameter{
		{
			Name: "str",
			Type: cty.String,
		},
	},
	Type: function.StaticReturnType(cty.String),
	Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
		s := args[0].AsString()
		sDec, err := base64.StdEncoding.DecodeString(s)
		if err != nil {
			return cty.UnknownVal(cty.String), fmt.Errorf("failed to decode base64 data '%s'", s)
		}
		if !utf8.Valid([]byte(sDec)) {
			log.Printf("[DEBUG] the result of decoding the provided string is not valid UTF-8: %s", sDec)
			return cty.UnknownVal(cty.String), fmt.Errorf("the result of decoding the provided string is not valid UTF-8")
		}
		return cty.StringVal(string(sDec)), nil
	},
})

Base64DecodeFunc constructs a function that decodes a string containing a base64 sequence.

View Source
var Base64EncodeFunc = function.New(&function.Spec{
	Params: []function.Parameter{
		{
			Name: "str",
			Type: cty.String,
		},
	},
	Type: function.StaticReturnType(cty.String),
	Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
		return cty.StringVal(base64.StdEncoding.EncodeToString([]byte(args[0].AsString()))), nil
	},
})

Base64EncodeFunc constructs a function that encodes a string to a base64 sequence.

View Source
var Base64GzipFunc = function.New(&function.Spec{
	Params: []function.Parameter{
		{
			Name: "str",
			Type: cty.String,
		},
	},
	Type: function.StaticReturnType(cty.String),
	Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
		s := args[0].AsString()

		var b bytes.Buffer
		gz := gzip.NewWriter(&b)
		if _, err := gz.Write([]byte(s)); err != nil {
			return cty.UnknownVal(cty.String), fmt.Errorf("failed to write gzip raw data: '%s'", s)
		}
		if err := gz.Flush(); err != nil {
			return cty.UnknownVal(cty.String), fmt.Errorf("failed to flush gzip writer: '%s'", s)
		}
		if err := gz.Close(); err != nil {
			return cty.UnknownVal(cty.String), fmt.Errorf("failed to close gzip writer: '%s'", s)
		}
		return cty.StringVal(base64.StdEncoding.EncodeToString(b.Bytes())), nil
	},
})

Base64GzipFunc constructs a function that compresses a string with gzip and then encodes the result in Base64 encoding.

View Source
var BasenameFunc = function.New(&function.Spec{
	Params: []function.Parameter{
		{
			Name: "path",
			Type: cty.String,
		},
	},
	Type: function.StaticReturnType(cty.String),
	Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
		return cty.StringVal(filepath.Base(args[0].AsString())), nil
	},
})

BasenameFunc constructs a function that takes a string containing a filesystem path and removes all except the last portion from it.

View Source
var DirnameFunc = function.New(&function.Spec{
	Params: []function.Parameter{
		{
			Name: "path",
			Type: cty.String,
		},
	},
	Type: function.StaticReturnType(cty.String),
	Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
		return cty.StringVal(filepath.Dir(args[0].AsString())), nil
	},
})

DirnameFunc constructs a function that takes a string containing a filesystem path and removes the last portion from it.

View Source
var JsonnetDirFunc = function.New(&function.Spec{
	Params: []function.Parameter{
		{
			Name: "dir",
			Type: cty.String,
		},
		{
			Name: "options",
			Type: cty.DynamicPseudoType,
		},
	},
	Type: function.StaticReturnType(cty.String),
	Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
		td, err := ioutil.TempDir("", "waypoint")
		if err != nil {
			return cty.DynamicVal, err
		}

		root := args[0].AsString()
		vm, err := jsonnetVM(args[1])
		if err != nil {
			return cty.DynamicVal, err
		}
		err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
			if err != nil {
				return err
			}

			if info.IsDir() {
				return nil
			}

			dir := td

			stripped := strings.TrimPrefix(path, root)
			if len(stripped) == 0 {
				panic("empty path")
			}
			if stripped[0] == '/' || stripped[0] == '\\' {

				stripped = stripped[1:]
			}
			if v := filepath.Dir(stripped); v != "." {
				dir = filepath.Join(dir, v)
				if err := os.MkdirAll(dir, 0700); err != nil {
					return err
				}
			}

			if filepath.Ext(path) != ".jsonnet" {
				return nil
			}

			jsonStr, err := vm.EvaluateFile(path)
			if err != nil {
				return err
			}

			filename := filepath.Base(path)
			filename = strings.TrimSuffix(filename, ".jsonnet")
			filename += ".json"

			path = filepath.Join(dir, filename)
			return ioutil.WriteFile(path, []byte(jsonStr), 0600)
		})
		if err != nil {
			return cty.DynamicVal, err
		}

		return cty.StringVal(td), nil
	},
})

JsonnetDirFunc constructs a function that converts a directory of jsonnet files into standard JSON files with the same name but a "json" extension instead of the "jsonnet" extension. The converted files are stored in a temporary directory that is returned; the original files are untouched.

View Source
var JsonnetFileFunc = function.New(&function.Spec{
	Params: []function.Parameter{
		{
			Name: "path",
			Type: cty.String,
		},
		{
			Name: "options",
			Type: cty.DynamicPseudoType,
		},
	},
	Type: function.StaticReturnType(cty.String),
	Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
		td, err := ioutil.TempDir("", "waypoint")
		if err != nil {
			return cty.DynamicVal, err
		}

		path := args[0].AsString()

		vm, err := jsonnetVM(args[1])
		if err != nil {
			return cty.DynamicVal, err
		}
		jsonStr, err := vm.EvaluateFile(path)
		if err != nil {
			return cty.DynamicVal, err
		}

		filename := filepath.Base(path)
		filename = strings.TrimSuffix(filename, ".jsonnet")
		filename += ".json"

		path = filepath.Join(td, filename)
		if err := ioutil.WriteFile(path, []byte(jsonStr), 0600); err != nil {
			return cty.DynamicVal, err
		}
		return cty.StringVal(path), nil
	},
})

JsonnetFileFunc constructs a function that converts a single Jsonnet file to JSON. This returns the path to a new file with a "json" extension.

View Source
var PathExpandFunc = function.New(&function.Spec{
	Params: []function.Parameter{
		{
			Name: "path",
			Type: cty.String,
		},
	},
	Type: function.StaticReturnType(cty.String),
	Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {

		homePath, err := homedir.Expand(args[0].AsString())
		return cty.StringVal(homePath), err
	},
})

PathExpandFunc constructs a function that expands a leading ~ character to the current user's home directory.

View Source
var SelectorLookupFunc = function.New(&function.Spec{
	Params: []function.Parameter{
		{
			Name: "map",
			Type: cty.Map(cty.String),
		},
		{
			Name: "selectormap",
			Type: cty.Map(cty.DynamicPseudoType),
		},
		{
			Name: "default",
			Type: cty.DynamicPseudoType,
		},
	},
	Type: func(args []cty.Value) (ret cty.Type, err error) {
		expected := args[1].Type().ElementType()
		if !args[2].Type().Equals(expected) {
			return cty.NilType, errors.New("default value type must match types of selector map")
		}

		return expected, nil
	},
	Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
		var m map[string]string
		if err := gocty.FromCtyValue(args[0], &m); err != nil {
			return cty.UnknownVal(cty.String), err
		}

		for it := args[1].ElementIterator(); it.Next(); {
			key, val := it.Element()

			s := key.AsString()
			eval, err := bexpr.CreateEvaluator(s)
			if err != nil {
				return cty.UnknownVal(cty.String), err
			}

			result, err := eval.Evaluate(m)
			if err != nil {
				return cty.UnknownVal(cty.String), err
			}

			if result {
				return val, nil
			}
		}

		return args[2], nil
	},
})

SelectorLookupFunc constructs a function that applies a label selector to a map and returns true/false if there is a match.

View Source
var SelectorMatchFunc = function.New(&function.Spec{
	Params: []function.Parameter{
		{
			Name: "map",
			Type: cty.Map(cty.String),
		},
		{
			Name: "selector",
			Type: cty.String,
		},
	},
	Type: function.StaticReturnType(cty.Bool),
	Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
		s := args[1].AsString()
		eval, err := bexpr.CreateEvaluator(s)
		if err != nil {
			return cty.UnknownVal(cty.String), err
		}

		var m map[string]string
		if err := gocty.FromCtyValue(args[0], &m); err != nil {
			return cty.UnknownVal(cty.String), err
		}

		result, err := eval.Evaluate(m)
		if err != nil {
			return cty.UnknownVal(cty.String), err
		}

		return cty.BoolVal(result), nil
	},
})

SelectorMatchFunc constructs a function that applies a label selector to a map and returns true/false if there is a match.

View Source
var TimestampFunc = function.New(&function.Spec{
	Params: []function.Parameter{},
	Type:   function.StaticReturnType(cty.String),
	Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
		return cty.StringVal(time.Now().UTC().Format(time.RFC3339)), nil
	},
})

TimestampFunc constructs a function that returns a string representation of the current date and time.

View Source
var URLEncodeFunc = function.New(&function.Spec{
	Params: []function.Parameter{
		{
			Name: "str",
			Type: cty.String,
		},
	},
	Type: function.StaticReturnType(cty.String),
	Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
		return cty.StringVal(url.QueryEscape(args[0].AsString())), nil
	},
})

URLEncodeFunc constructs a function that applies URL encoding to a given string.

Functions

func AddEntrypointFunctions

func AddEntrypointFunctions(ctx *hcl.EvalContext)

This adds the functions that should be available to any HCL run in the entrypoint. It excludes VCS functions functions because that information is lost to be used in the entrypoint.

func AddStandardFunctions

func AddStandardFunctions(ctx *hcl.EvalContext, pwd string)

This adds the functions that should be able to any HCL run in the waypoint server and CLI context.

func Base64Decode

func Base64Decode(str cty.Value) (cty.Value, error)

Base64Decode decodes a string containing a base64 sequence.

Waypoint uses the "standard" Base64 alphabet as defined in RFC 4648 section 4.

Strings in the Waypoint language are sequences of unicode characters rather than bytes, so this function will also interpret the resulting bytes as UTF-8. If the bytes after Base64 decoding are _not_ valid UTF-8, this function produces an error.

func Base64Encode

func Base64Encode(str cty.Value) (cty.Value, error)

Base64Encode applies Base64 encoding to a string.

Waypoint uses the "standard" Base64 alphabet as defined in RFC 4648 section 4.

Strings in the Waypoint language are sequences of unicode characters rather than bytes, so this function will first encode the characters from the string as UTF-8, and then apply Base64 encoding to the result.

func Base64Gzip

func Base64Gzip(str cty.Value) (cty.Value, error)

Base64Gzip compresses a string with gzip and then encodes the result in Base64 encoding.

Waypoint uses the "standard" Base64 alphabet as defined in RFC 4648 section 4.

Strings in the Waypoint language are sequences of unicode characters rather than bytes, so this function will first encode the characters from the string as UTF-8, then apply gzip compression, and then finally apply Base64 encoding.

func Basename

func Basename(path cty.Value) (cty.Value, error)

Basename takes a string containing a filesystem path and removes all except the last portion from it.

The underlying function implementation works only with the path string and does not access the filesystem itself. It is therefore unable to take into account filesystem features such as symlinks.

If the path is empty then the result is ".", representing the current working directory.

func Datetime

func Datetime() map[string]function.Function

Stdlib are the functions provided by the HCL stdlib.

func Dirname

func Dirname(path cty.Value) (cty.Value, error)

Dirname takes a string containing a filesystem path and removes the last portion from it.

The underlying function implementation works only with the path string and does not access the filesystem itself. It is therefore unable to take into account filesystem features such as symlinks.

If the path is empty then the result is ".", representing the current working directory.

func Docs

func Docs() map[string]string

func Encoding

func Encoding() map[string]function.Function

func File

func File(path cty.Value) (cty.Value, error)

File reads the contents of the file at the given path.

The file must contain valid UTF-8 bytes, or this function will return an error.

The underlying function implementation works relative to a particular base directory, so this wrapper takes a base directory string and uses it to construct the underlying function before calling it.

func FileBase64

func FileBase64(path cty.Value) (cty.Value, error)

FileBase64 reads the contents of the file at the given path.

The bytes from the file are encoded as base64 before returning.

The underlying function implementation works relative to a particular base directory, so this wrapper takes a base directory string and uses it to construct the underlying function before calling it.

func FileExists

func FileExists(path cty.Value) (cty.Value, error)

FileExists determines whether a file exists at the given path.

The underlying function implementation works relative to a particular base directory, so this wrapper takes a base directory string and uses it to construct the underlying function before calling it.

func FileSet

func FileSet(path, pattern cty.Value) (cty.Value, error)

FileSet enumerates a set of files given a glob pattern

The underlying function implementation works relative to a particular base directory, so this wrapper takes a base directory string and uses it to construct the underlying function before calling it.

func Filesystem

func Filesystem() map[string]function.Function

func Jsonnet

func Jsonnet() map[string]function.Function

func JsonnetDir

func JsonnetDir(dir cty.Value) (cty.Value, error)

JsonnetDir converts a directory of Jsonnet files into JSON.

func JsonnetFile

func JsonnetFile(dir cty.Value) (cty.Value, error)

JsonnetFile converts a single Jsonnet file to JSON.

func MakeFileExistsFunc

func MakeFileExistsFunc() function.Function

MakeFileExistsFunc constructs a function that takes a path and determines whether a file exists at that path

func MakeFileFunc

func MakeFileFunc(encBase64 bool) function.Function

MakeFileFunc constructs a function that takes a file path and returns the contents of that file, either directly as a string (where valid UTF-8 is required) or as a string containing base64 bytes.

func MakeFileSetFunc

func MakeFileSetFunc() function.Function

MakeFileSetFunc constructs a function that takes a glob pattern and enumerates a file set from that pattern

func MakeTemplateFileFunc

func MakeTemplateFileFunc(baseDir string, funcsCb func() map[string]function.Function) function.Function

MakeTemplateFileFunc constructs a function that takes a file path and an arbitrary object of named values and attempts to render the referenced file as a template using HCL template syntax.

The template itself may recursively call other functions so a callback must be provided to get access to those functions. The template cannot, however, access any variables defined in the scope: it is restricted only to those variables provided in the second function argument, to ensure that all dependencies on other graph nodes can be seen before executing this function.

As a special exception, a referenced template file may not recursively call the templatefile function, since that would risk the same file being included into itself indefinitely.

func MakeTemplateFuncs

func MakeTemplateFuncs(hclCtx *hcl.EvalContext) map[string]function.Function

MakeTemplateFuncs adds the template functions to the function map. The template family of functions has access to the context, except they cannot call further template functions.

func Pathexpand

func Pathexpand(path cty.Value) (cty.Value, error)

Pathexpand takes a string that might begin with a `~` segment, and if so it replaces that segment with the current user's home directory path.

The underlying function implementation works only with the path string and does not access the filesystem itself. It is therefore unable to take into account filesystem features such as symlinks.

If the leading segment in the path is not `~` then the given path is returned unmodified.

func Selector

func Selector() map[string]function.Function

func SelectorLookup

func SelectorLookup(m, selector, def cty.Value) (cty.Value, error)

SelectorLookup applies a selector to a map and returns true if the selector matches. The selector should be in go-bexpr format.

func SelectorMatch

func SelectorMatch(m, selector cty.Value) (cty.Value, error)

SelectorMatch applies a selector to a map and returns true if the selector matches. The selector should be in go-bexpr format.

func Stdlib

func Stdlib() map[string]function.Function

Stdlib are the functions provided by the HCL stdlib.

func URLEncode

func URLEncode(str cty.Value) (cty.Value, error)

URLEncode applies URL encoding to a given string.

This function identifies characters in the given string that would have a special meaning when included as a query string argument in a URL and escapes them using RFC 3986 "percent encoding".

If the given string contains non-ASCII characters, these are first encoded as UTF-8 and then percent encoding is applied separately to each UTF-8 byte.

func VCSGitFuncs

func VCSGitFuncs(path string) map[string]function.Function

Types

type VCSGit

type VCSGit struct {
	// Path of the git repository. Parent directories will be searched for
	// a ".git" folder automatically.
	Path string

	// GoGitOnly forces go-git usage and disables all subprocessing to "git"
	// even if it exists.
	GoGitOnly bool
	// contains filtered or unexported fields
}

func (*VCSGit) RefHashFunc

func (s *VCSGit) RefHashFunc() function.Function

RefHashFunc returns the full hash of the HEAD ref.

waypoint:gitrefhash

func (*VCSGit) RefPrettyFunc

func (s *VCSGit) RefPrettyFunc() function.Function

RefPrettyFunc returns a string format of the current Git ref. This function takes some liberties to humanize the output: it will use a tag if the ref matches a tag, it will append "+CHANGES" to the commit if there are uncommitted changed files, etc.

You may use direct functions such as `gitrefhash` if you want the direct hash. Or `gitreftag` to get the current tag.

waypoint:gitrefpretty

func (*VCSGit) RefTagFunc

func (s *VCSGit) RefTagFunc() function.Function

RefTagFunc returns the tag of the HEAD ref or empty if not tag is found.

waypoint:gitreftag

func (*VCSGit) RemoteUrlFunc

func (s *VCSGit) RemoteUrlFunc() function.Function

RemoteUrlFunc returns the URL for the matching remote or unknown if it can't be found.

waypoint:gitremoteurl

Jump to

Keyboard shortcuts

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