interpolate

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 8 Imported by: 14 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

interpolate

Build Status Go Reference

A Go library that expands shell-style parameters, such as $NAME and ${NAME:-default}, in strings. It implements POSIX parameter expansion and some bash extensions.

Installation

go get github.com/mfridman/interpolate@latest

Requires Go 1.25 or later.

Usage

package main

import (
	"fmt"
	"log"

	"github.com/mfridman/interpolate"
)

func main() {
	env := interpolate.NewListEnv("NAME=James")

	output, err := interpolate.Expand("Hello ${NAME}, welcome to the ${PLACE:-🏖}", env)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(output) // Hello James, welcome to the 🏖
}

Values come from an Env:

  • interpolate.LookupFunc(os.LookupEnv) reads the process environment.
  • interpolate.NewMapEnv(m) reads a map[string]string.
  • interpolate.NewListEnv("A=1", "B=2") reads NAME=value pairs, such as os.Environ()....
  • Any type with a Lookup(name string) (string, bool) method is an Env.

interpolate.Variables returns the names of the variables in a string, without repeats, and does not expand it.

Errors and strict mode

${NAME?message} and ${NAME:?message} return an *interpolate.UnsetVariableError with the variable Name and the Message. Its text is $NAME: message.

var unsetErr *interpolate.UnsetVariableError
if errors.As(err, &unsetErr) {
	fmt.Println(unsetErr.Name) // PORT
}

By default, an unset variable expands to an empty string, the same as a shell. Use interpolate.WithNoUnset() to make a reference to an unset variable an error, the same as set -u in bash. Expansions that handle an unset variable, such as ${NAME:-word}, do not change.

output, err := interpolate.Expand(input, env, interpolate.WithNoUnset())
// $TYPO -> error: $TYPO: not set

Supported expansions

Syntax Result
$NAME or ${NAME} The value of NAME, or an empty string if it is unset
${NAME:-word} word if NAME is unset or empty, otherwise the value
${NAME-word} word if NAME is unset, otherwise the value
${NAME:?message} An error if NAME is unset or empty, otherwise the value
${NAME?message} An error if NAME is unset, otherwise the value
${NAME:+word} word if NAME is set and not empty, otherwise an empty string
${NAME+word} word if NAME is set, otherwise an empty string
${#NAME} The length of the value in characters
${NAME:offset} The value from offset to the end
${NAME:offset:length} At most length characters of the value from offset
  • A name starts with a letter or an underscore, followed by letters, digits, or underscores ([A-Za-z_][A-Za-z0-9_]*).
  • A word or message can contain other expansions, such as ${NAME:-${FALLBACK:-default}}. It is expanded only when it is used. Expansions can be nested up to 1000 levels deep.
  • Without a message, the error from ? is $NAME: not set, and the error from :? is $NAME: empty or not set.
Substrings
  • Offsets and lengths count characters, not bytes. They are decimal integers; arithmetic is not supported.
  • A negative offset counts from the end. Put a space before it, as in ${NAME: -2}, because ${NAME:-2} is a default value.
  • An offset past the end, or before the start, gives an empty string.
  • A length past the end gives the rest of the value. A negative length ends that many characters before the end, so ${NAME:1:-1} removes the first and last characters.
  • A blank offset or length counts as 0, so ${NAME::2} gives the first two characters. ${NAME:} is an error.

Escaping

Input Output
$$NAME or \$NAME $NAME
$${NAME} or \${NAME} ${NAME}
\} in a word or message }
$ not followed by a letter, _, or { Kept as-is, so $1, $(command), price: $5, and a trailing $ do not change
\\ Kept as-is

A word ends at the first }, so write ${CONFIG:-{"a":1\}} to get {"a":1}. Outside of ${...}, \} is kept as-is.

A double backslash is kept as two backslashes, and it does not escape the $ after it: \\$NAME gives \\ followed by the value of NAME. You cannot put one backslash directly before a literal $. In a regular expression, write [$] instead of \$.

SQL

These rules matter when the input is SQL, for example in goose migrations with ENVSUB ON:

  • Write $$$$ for a $$ dollar-quoted string, and $$tag$$ for $tag$. Without escaping, $$ becomes $, and $tag expands as a variable.
  • Write %1$$s in format('%1$s', name), because $s is a variable.
  • Positional parameters such as $1, and a $ at the end of a regular expression such as '^abc$', are kept as-is.

Not supported

  • Pattern removal: ${NAME%word}, ${NAME%%word}, ${NAME#word}, and ${NAME##word}.
  • Assignment: ${NAME:=word} and ${NAME=word}.
  • Special and positional parameters, such as $1, $@, $*, $#, and $?. They are kept as literal text.

Acknowledgements

This project started as a fork of buildkite/interpolate. Thanks to its authors for their work.

License

MIT

Documentation

Overview

Package interpolate expands shell-style parameters, such as $NAME and ${NAME:-default}, in strings. It implements POSIX parameter expansion and some bash extensions. Expand reads values from an Env, and Variables lists the variables in a string.

Supported expansions:

$NAME or ${NAME}        the value of NAME, or an empty string if NAME is unset
${NAME:-word}           word if NAME is unset or empty
${NAME-word}            word if NAME is unset
${NAME:?message}        an error if NAME is unset or empty
${NAME?message}         an error if NAME is unset
${NAME:+word}           word if NAME is set and not empty, otherwise an empty string
${NAME+word}            word if NAME is set, otherwise an empty string
${#NAME}                the length of the value in characters
${NAME:offset}          the value from offset
${NAME:offset:length}   at most length characters of the value from offset

Write $$ or \$ for a literal dollar sign, and \} for a literal closing brace in a word. A $ that is not followed by a letter, an underscore, or { is kept as-is, so $1 and $(command) do not change.

A required expansion that fails returns an *UnsetVariableError. Use WithNoUnset to make a reference to an unset variable an error too, the same as set -u in bash.

Expand and Variables are safe for concurrent use if the Env is.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Expand added in v0.2.0

func Expand(s string, env Env, opts ...Option) (string, error)

Expand returns s with each parameter expansion replaced by its value, and each escape such as $$ replaced by its text. Values come from env. A nil env has no variables.

Expand returns an error if s is not valid, and an *UnsetVariableError if a variable that must have a value does not have one.

Example
package main

import (
	"fmt"
	"log"

	"github.com/mfridman/interpolate"
)

func main() {
	env := interpolate.NewListEnv("NAME=James")

	output, err := interpolate.Expand("Hello ${NAME}, welcome to the ${PLACE:-🏖}", env)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(output)

}
Output:
Hello James, welcome to the 🏖

func Variables added in v0.2.0

func Variables(s string) ([]string, error)

Variables returns the names of the variables that s refers to, in the order of their first use, with no repeats. It includes the variables in the words and messages of expansions, such as FALLBACK in ${NAME:-$FALLBACK}, and does not include escaped references such as $$NAME.

Variables returns an error if s is not valid.

Example
package main

import (
	"fmt"
	"log"

	"github.com/mfridman/interpolate"
)

func main() {
	names, err := interpolate.Variables("${HOST:-localhost}:${PORT:?port is required} $1 $HOST")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(names)

}
Output:
[HOST PORT]

Types

type Env

type Env interface {
	// Lookup returns the value of the variable with the given name, and whether the variable is
	// set. A variable that is set can have an empty value.
	Lookup(name string) (value string, ok bool)
}

Env is a source of variable values.

func NewListEnv added in v0.2.0

func NewListEnv(pairs ...string) Env

NewListEnv returns an Env with the variables in pairs, which use the "NAME=value" form of os.Environ. Pairs without "=" are ignored. If a name occurs more than once, the last pair wins.

On Windows, names are case insensitive.

func NewMapEnv

func NewMapEnv(m map[string]string) Env

NewMapEnv returns an Env with the variables in m. It copies m.

On Windows, names are case insensitive. If keys in m differ only in case, the last key in sorted order wins.

Example
package main

import (
	"fmt"
	"log"

	"github.com/mfridman/interpolate"
)

func main() {
	env := interpolate.NewMapEnv(map[string]string{
		"USER":  "llama",
		"EMPTY": "",
	})

	output, err := interpolate.Expand("${USER:+--user=$USER} ${EMPTY:-default} ${#USER}", env)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(output)

}
Output:
--user=llama default 5

type LookupFunc added in v0.2.0

type LookupFunc func(name string) (value string, ok bool)

LookupFunc is a function that is an Env. For example, LookupFunc(os.LookupEnv) reads the environment of the process.

Example
package main

import (
	"fmt"
	"log"
	"os"

	"github.com/mfridman/interpolate"
)

func main() {
	env := interpolate.LookupFunc(os.LookupEnv)

	output, err := interpolate.Expand("${INTERPOLATE_EXAMPLE_UNSET:-default}", env)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(output)

}
Output:
default

func (LookupFunc) Lookup added in v0.2.0

func (f LookupFunc) Lookup(name string) (string, bool)

Lookup returns f(name).

type Option added in v0.2.0

type Option interface {
	// contains filtered or unexported methods
}

Option configures Expand.

func WithNoUnset added in v0.2.0

func WithNoUnset() Option

WithNoUnset makes a reference to an unset variable an error, the same as set -u (nounset) in bash. It applies to $NAME, ${NAME}, ${#NAME}, ${NAME:offset} and ${NAME:offset:length}. Expansions that handle an unset variable, such as ${NAME:-word} and ${NAME+word}, do not change. The error is an *UnsetVariableError with the message "not set".

Example
package main

import (
	"fmt"

	"github.com/mfridman/interpolate"
)

func main() {
	env := interpolate.NewMapEnv(map[string]string{"SCHEMA": "app"})

	_, err := interpolate.Expand("CREATE TABLE $SCHEMA.users AS $body$", env, interpolate.WithNoUnset())
	fmt.Println(err)

}
Output:
$body: not set

type UnsetVariableError added in v0.2.0

type UnsetVariableError struct {
	// Name is the name of the variable.
	Name string
	// Message is the expanded message from the expansion, or a default message such as "not set".
	Message string
}

UnsetVariableError is the error for a variable that must have a value but does not. It comes from ${NAME?message}, from ${NAME:?message}, and from a reference to an unset variable with WithNoUnset.

Example
package main

import (
	"errors"
	"fmt"

	"github.com/mfridman/interpolate"
)

func main() {
	_, err := interpolate.Expand("${PORT:?port is required}", nil)

	var unsetErr *interpolate.UnsetVariableError
	if errors.As(err, &unsetErr) {
		fmt.Println(unsetErr.Name, "-", unsetErr.Message)
	}

}
Output:
PORT - port is required

func (*UnsetVariableError) Error added in v0.2.0

func (e *UnsetVariableError) Error() string

Error returns the error in the form "$NAME: message".

Jump to

Keyboard shortcuts

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