corefunc

package
v1.5.1 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2024 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Overview

Package corefunc provides a set of functions that are useful in a variety of Terraform contexts. Provided as a Go library for use with testing frameworks like Terratest, as well as via a Terraform provider.

This allows for using the same function implementations in both places, improving convenience and consistency.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Base64Gunzip added in v1.5.0

func Base64Gunzip(input string) (string, error)

Base64Gunzip is a function that decodes a Base64-encoded string, then decompresses the result with gzip. Supports both padded and non-padded Base64 strings.

Uses the "standard" Base64 alphabet as defined in RFC 4648 §4. <https://datatracker.ietf.org/doc/html/rfc4648#section-4>

There is a data limit of 10 MiB (10485760 bytes) for the decompressed data. This is to avoid "decompression bomb" vulnerabilities.

This functionality is built into OpenTofu 1.8, but is missing in Terraform 1.9. This also provides a 1:1 implementation that can be used with Terratest or other Go code.

----

  • input (string): A string of gzipped then Base64-encoded data.
Example
output, err := Base64Gunzip(
	"H4sIAAAAAAAA/wrJSFXIL0jNUyjOLy1KTlXIzEsrSiwuKSpNLiktSlVILFZIzk9JVSjJz8/RAwQAAP//HPstqCwAAAA",
)
if err != nil {
	panic(err)
}

fmt.Println(output)
Output:

The open source infrastructure as code tool.

func CIDRContains added in v1.5.0

func CIDRContains(containingCidr, containedIPOrCidr string) (bool, error)

CIDRContains determines whether or not a given IP address, or an address prefix given in CIDR notation, is within a given IP network address prefix.

Both arguments must belong to the same address family, either IPv4 or IPv6. A family mismatch will result in an error.

This functionality is built into OpenTofu 1.8, but is missing in Terraform 1.9. This also provides a 1:1 implementation that can be used with Terratest or other Go code. This function licensed as MPL-2.0.

----

  • containingCidr (string): A CIDR range to check as a containing range.

  • containedIpOrCidr (string): An IP address or CIDR range to check as a contained range.

Example
output, err := CIDRContains("192.168.2.0/20", "192.168.2.1")
if err != nil {
	panic(err)
}

fmt.Println(output)
Output:

true

func EnvEnsure

func EnvEnsure(name string, pattern ...*regexp.Regexp) error

EnvEnsure ensures that a given environment variable is set to a non-empty value. If the environment variable is unset or if it is set to an empty string, EnvEnsure will respond with an error.

Not every Terraform provider checks to ensure that the environment variables it requires are properly set before performing work, leading to late-stage errors. This will force an error to occur early in the execution if the environment variable is not set, or if its value doesn't match the expected patttern.

----

  • name (string): The name of the environment variable to check.

  • pattern (*regexp.Regexp): The result of a call to `regexp.Compile()` or `regexp.MustCompile()`.

Example
var err error

// ---------------------------------------------------------
// Set the environment variables.

err = os.Setenv("MY_ENV_VAR_VALUE", "abcd1234")
fmt.Println(err)

err = os.Setenv("MY_ENV_VAR_EMPTY", "")
fmt.Println(err)

// ---------------------------------------------------------
// Ensure the environment variables are set.

err = EnvEnsure("MY_ENV_VAR_VALUE")
fmt.Println(err)

err = EnvEnsure("MY_ENV_VAR_EMPTY")
fmt.Println(err)

err = EnvEnsure("MY_ENV_VAR_NOT_SET")
fmt.Println(err)
Output:

<nil>
<nil>
<nil>
environment variable MY_ENV_VAR_EMPTY is not defined
environment variable MY_ENV_VAR_NOT_SET is not defined
Example (Pattern)
var err error

// ---------------------------------------------------------
// Set the environment variables.

err = os.Setenv("AWS_VAULT", "dev")
fmt.Println(err)

// ---------------------------------------------------------
// Ensure the environment variables are set.

// This will not throw an error because it is defined, and there is no pattern to match.
err = EnvEnsure("AWS_VAULT")
fmt.Println(err)

// This will throw an error because the pattern does not match.
err = EnvEnsure("AWS_VAULT", regexp.MustCompile(`(non)?prod$`))
fmt.Println(err)
Output:

<nil>
<nil>
environment variable AWS_VAULT does not match pattern (non)?prod$

func Homedir added in v1.1.0

func Homedir() (string, error)

Homedir returns the home directory for the executing user without requiring CGO for macOS.

func HomedirExpand added in v1.1.0

func HomedirExpand(path string) (string, error)

HomedirExpand expands the path to include the home directory if the path is prefixed with `~`. If it isn't prefixed with `~`, the path is returned as-is.

func IntLeftPad added in v1.1.0

func IntLeftPad(num int64, padWidth int) string

IntLeftPad pads an integer on the left side with zeroes until it reaches the desired width. Result is a string.

----

  • num (int64): The number to pad.

  • padWidth (int): The total width of the padded string. If `num` is equivalent length (base10) or longer, then no padding will be applied. If the integer is anything other than base10, it will be converted to base10.

Example
output1 := IntLeftPad(255, 5)
fmt.Println(output1)

output2 := IntLeftPad(0b11111111, 5)
fmt.Println(output2)

output3 := IntLeftPad(0xFF, 5)
fmt.Println(output3)
Output:

00255
00255
00255

func StrCamel added in v1.1.0

func StrCamel(s string, opts ...caps.Opts) string

StrCamel converts a string to `camelCase`, removing any non-alphanumeric characters.

----

  • s (string): The string to reformat.

  • opts (caps.Opts): Options to pass to the underlying `caps` library.

Example
const (
	TestStrCamelInput  = "test_with_number_123"
	TestStrCamelInput2 = "test with number -123.456e-2"
)

output1 := StrCamel(TestStrCamelInput)
fmt.Println(output1)

output2 := StrCamel(TestStrCamelInput2)
fmt.Println(output2)
Output:

testWithNumber123
testWithNumber123456e2

func StrConstant added in v1.1.0

func StrConstant(s string, opts ...caps.Opts) string

StrConstant converts a string to `CONSTANT_CASE` (aka, `SCREAMING_SNAKE_CASE`), removing any non-alphanumeric characters.

----

  • s (string): The string to reformat.

  • opts (caps.Opts): Options to pass to the underlying `caps` library.

Example
const (
	TestStrCamelInput  = "test_with_number_123"
	TestStrCamelInput2 = "test with number -123.456e-2"
)

output1 := StrConstant(TestStrCamelInput)
fmt.Println(output1)

output2 := StrConstant(TestStrCamelInput2)
fmt.Println(output2)
Output:

TEST_WITH_NUMBER_123
TEST_WITH_NUMBER_123_456E_2

func StrIterativeReplace

func StrIterativeReplace(str string, replacements []types.Replacement) string

StrIterativeReplace iterates over a list of replacements. This allows you to accept a list of replacements of unknown length from users, and apply them all in sequence. It is a wrapper around `strings.ReplaceAll()`.

----

  • str (string): The string to which we apply the replacements.

  • replacements ([]types.Replacement): A list of replacements to apply to the string, in sequence.

Example
output := StrIterativeReplace(
	"This is a string for testing replacements. New Relic. Set-up.",
	[]types.Replacement{
		{Old: ".", New: ""},
		{Old: " ", New: "_"},
		{Old: "-", New: "_"},
		{Old: "New_Relic", New: "datadog"},
		{Old: "This", New: "this"},
		{Old: "Set_up", New: "setup"},
	},
)

fmt.Println(output)
Output:

this_is_a_string_for_testing_replacements_datadog_setup

func StrKebab added in v1.1.0

func StrKebab(s string, opts ...caps.Opts) string

StrKebab converts a string to `kebab-case`, removing any non-alphanumeric characters.

----

  • s (string): The string to reformat.

  • opts (caps.Opts): Options to pass to the underlying `caps` library.

Example
const (
	TestStrCamelInput  = "test_with_number_123"
	TestStrCamelInput2 = "test with number -123.456e-2"
)

output1 := StrKebab(TestStrCamelInput)
fmt.Println(output1)

output2 := StrKebab(TestStrCamelInput2)
fmt.Println(output2)
Output:

test-with-number-123
test-with-number-123-456e-2

func StrLeftPad added in v1.1.0

func StrLeftPad(str string, padWidth int, padChar ...byte) string

StrLeftPad pads a string on the left side with a given string until it reaches the desired width.

----

  • str (string): The string to pad.

  • padWidth (int): The total width of the padded string. If `str` is equivalent length or longer, then no padding will be applied.

  • padChar (string): The string to use as padding. If unspecified, will use a single space character.

Example
output1 := StrLeftPad("foobar", 10)
fmt.Println(output1)

output2 := StrLeftPad("foobar", 10, '_')
fmt.Println(output2)
Output:

    foobar
____foobar

func StrPascal added in v1.1.0

func StrPascal(s string, acronymCaps bool, opts ...caps.Opts) string

StrPascal converts a string to `PascalCase` (aka, `StudlyCase`, `UpperCamelCase`), removing any non-alphanumeric characters.

----

  • s (string): The string to reformat.

  • acronymCaps (bool): If `true`, acronyms will be converted to initialisms (e.g., `ID` instead of `Id`).

  • opts (caps.Opts): Options to pass to the underlying `caps` library.

Example
const (
	TestStrCamelInput  = "test_with_number_123"
	TestStrCamelInput2 = "test with number -123.456e-2"
)

output1 := StrPascal(TestStrCamelInput, false)
fmt.Println(output1)

output2 := StrPascal(TestStrCamelInput2, false)
fmt.Println(output2)
Output:

TestWithNumber123
TestWithNumber123456e2

func StrSnake added in v1.1.0

func StrSnake(s string, opts ...caps.Opts) string

StrSnake converts a string to `snake_case`, removing any non-alphanumeric characters.

----

  • s (string): The string to reformat.

  • opts (caps.Opts): Options to pass to the underlying `caps` library.

Example
const (
	TestStrCamelInput  = "test_with_number_123"
	TestStrCamelInput2 = "test with number -123.456e-2"
)

output1 := StrSnake(TestStrCamelInput)
fmt.Println(output1)

output2 := StrSnake(TestStrCamelInput2)
fmt.Println(output2)
Output:

test_with_number_123
test_with_number_123_456e_2

func TruncateLabel

func TruncateLabel(maxLength int64, prefix, label string) string

TruncateLabel supports prepending a prefix to a label, while truncating them to meet the maximum length constraints. Useful when grouping labels with a kind of prefix. Both the prefix and the label will be truncated if necessary.

Uses a "balancing" algorithm between the prefix and the label, so that each section is truncated as a factor of how much space it takes up in the merged string.

DEPRECATED: This function is deprecated and will be removed in the 2.0.0 release. It's a bit too specialized to be useful in a general-purpose library.

----

  • maxLength (int64): The maximum allowed length of the combined label.

  • prefix (string): The prefix to prepend to the label.

  • label (string): The label itself.

----

The motivation for this function is in working with monitoring systems such as New Relic and Datadog where there are hundreds of applications in a monitoring "prod" account, and also hundreds of applications in a monitoring "nonprod" account. This allows us to group lists of monitors together using a shared prefix, but also truncate them appropriately to fit length constraints.

Example
length1 := TruncateLabel(1, "NW-TEST-FIRST", "Name of my monitor")
fmt.Println(length1)

length3 := TruncateLabel(3, "NW-TEST-FIRST", "Name of my monitor")
fmt.Println(length3)

length5 := TruncateLabel(5, "NW-TEST-FIRST", "Name of my monitor")
fmt.Println(length5)

length7 := TruncateLabel(7, "NW-TEST-FIRST", "Name of my monitor")
fmt.Println(length7)

length10 := TruncateLabel(10, "NW-TEST-FIRST", "Name of my monitor")
fmt.Println(length10)

length20 := TruncateLabel(20, "NW-TEST-FIRST", "Name of my monitor")
fmt.Println(length20)

length32 := TruncateLabel(32, "NW-TEST-FIRST", "Name of my monitor")
fmt.Println(length32)

length64 := TruncateLabel(64, "NW-TEST-FIRST", "Name of my monitor")
fmt.Println(length64)

length128 := TruncateLabel(128, "NW-TEST-FIRST", "Name of my monitor")
fmt.Println(length128)

length256 := TruncateLabel(256, "NW-TEST-FIRST", "Name of my monitor")
fmt.Println(length256)
Output:

…
…
…: …
…: Nam…
N…: Name…
NW-TES…: Name of my…
NW-TEST-FIRS…: Name of my monit…
NW-TEST-FIRST: Name of my monitor
NW-TEST-FIRST: Name of my monitor
NW-TEST-FIRST: Name of my monitor

func URLDecode added in v1.5.0

func URLDecode(s string) (string, error)

URLDecode decodes a URL-encoded string.

It can decode a wide range of characters, including those beyond the ASCII set. Non-ASCII characters are first interpreted as UTF-8 bytes, then percent-decoded byte-by-byte, ensuring correct decoding of multibyte characters.

This functionality is built into OpenTofu 1.8, but is missing in Terraform 1.9. This also provides a 1:1 implementation that can be used with Terratest or other Go code.

----

  • s (string): An encoded URL.
Example
output, err := URLDecode("hello%20%E4%B8%96%E7%95%8C")
if err != nil {
	panic(err)
}

fmt.Println(output)
Output:

hello 世界

func URLParse added in v1.3.0

func URLParse(rawURL string, canon ...types.URLCanonicalizer) (*url.Url, error)

URLParse is a WHATWG spec-compliant <https://url.spec.whatwg.org/#url-parsing> URL parser returns a struct representing a parsed absolute URL. Will not resolve relative URLs.

The parser is up to date as of 2023-05-24 <https://url.spec.whatwg.org/commit-snapshots/eee49fdf4f99d59f717cbeb0bce29fda930196d4/> and passes all relevant tests from web-platform-tests <https://github.com/web-platform-tests/wpt/tree/master/url>. Its API is similar to Chapter 6 in WHATWG URL Standard <https://url.spec.whatwg.org/#api>.

Google Safe Browsing is a URL canonicalizer whose rules are defined at <https://developers.google.com/safe-browsing/v4/urls-hashing#canonicalization>.

----

  • rawURL (string): An absolute URL.

  • canon (types.URLCanonicalizer): An optional parameter that allows you to specify which canonicalizer to use. If not specified, the standard canonicalizer will be used.

Example
parsedURL, err := URLParse("HTTP://u:p@example.com:80/foo?q=1#bar")
if err != nil {
	fmt.Println(err)
	return
}

fmt.Println(parsedURL.Href(false))
fmt.Println(parsedURL.Href(true))
fmt.Println(parsedURL.Protocol())
fmt.Println(parsedURL.Scheme())
fmt.Println(parsedURL.Username())
fmt.Println(parsedURL.Password())
fmt.Println(parsedURL.Host())
fmt.Println(parsedURL.Port())
fmt.Println(parsedURL.Pathname())
fmt.Println(parsedURL.Search())
fmt.Println(parsedURL.Query())
fmt.Println(parsedURL.Hash())
fmt.Println(parsedURL.Fragment())
fmt.Println(parsedURL.DecodedPort())
Output:

http://u:p@example.com/foo?q=1#bar
http://u:p@example.com/foo?q=1
http:
http
u
p
example.com

/foo
?q=1
q=1
#bar
bar
80
Example (GoogleSafeBrowsing)
// https://developers.google.com/safe-browsing/v4/urls-hashing#canonicalization
parsedURL, err := URLParse("HTTP://u:p@example.com:80/foo?q=1#bar", types.GoogleSafeBrowsing)
if err != nil {
	fmt.Println(err)
	return
}

fmt.Println("." + parsedURL.Href(false))
fmt.Println("." + parsedURL.Href(true))
fmt.Println("." + parsedURL.Protocol())
fmt.Println("." + parsedURL.Scheme())
fmt.Println("." + parsedURL.Username())
fmt.Println("." + parsedURL.Password())
fmt.Println("." + parsedURL.Host())
fmt.Println("." + parsedURL.Port())
fmt.Println("." + parsedURL.Pathname())
fmt.Println("." + parsedURL.Search())
fmt.Println("." + parsedURL.Query())
fmt.Println("." + parsedURL.Hash())
fmt.Println("." + parsedURL.Fragment())
fmt.Println("." + fmt.Sprint(parsedURL.DecodedPort()))
Output:

.http://u:p@example.com/foo?q=1
.http://u:p@example.com/foo?q=1
.http:
.http
.u
.p
.example.com
.
./foo
.?q=1
.q=1
.
.
.80

Types

This section is empty.

Directories

Path Synopsis
Package types provides a set of structs that simplify the usage of the corefunc package.
Package types provides a set of structs that simplify the usage of the corefunc package.

Jump to

Keyboard shortcuts

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